proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/store/BackendSessionPool.java
|
BackendSessionPool
|
detectSession
|
class BackendSessionPool {
private static final Logger LOG = Log.logger(BackendSessionPool.class);
private final HugeConfig config;
private final String name;
private final ThreadLocal<BackendSession> threadLocalSession;
private final AtomicInteger sessionCount;
private final Map<Long, BackendSession> sessions;
private final long reconnectDetectInterval;
public BackendSessionPool(HugeConfig config, String name) {
this.config = config;
this.name = name;
this.threadLocalSession = new ThreadLocal<>();
this.sessionCount = new AtomicInteger(0);
this.sessions = new ConcurrentHashMap<>();
this.reconnectDetectInterval = this.config.get(
CoreOptions.STORE_CONN_DETECT_INTERVAL);
}
public HugeConfig config() {
return this.config;
}
public final BackendSession getOrNewSession() {
BackendSession session = this.threadLocalSession.get();
if (session == null) {
session = this.newSession();
assert session != null;
this.threadLocalSession.set(session);
assert !this.sessions.containsKey(Thread.currentThread().getId());
this.sessions.put(Thread.currentThread().getId(), session);
int sessionCount = this.sessionCount.incrementAndGet();
LOG.debug("Now(after connect({})) session count is: {}",
this, sessionCount);
} else {
this.detectSession(session);
}
return session;
}
public BackendSession useSession() {
BackendSession session = this.threadLocalSession.get();
if (session != null) {
session.attach();
this.detectSession(session);
} else {
session = this.getOrNewSession();
}
return session;
}
private void detectSession(BackendSession session) {<FILL_FUNCTION_BODY>}
private Pair<Integer, Integer> closeSession() {
int sessionCount = this.sessionCount.get();
if (sessionCount <= 0) {
assert sessionCount == 0 : sessionCount;
return Pair.of(-1, -1);
}
assert sessionCount > 0 : sessionCount;
BackendSession session = this.threadLocalSession.get();
if (session == null) {
LOG.debug("Current session has ever been closed: {}", this);
return Pair.of(sessionCount, -1);
}
int ref = session.detach();
assert ref >= 0 : ref;
if (ref > 0) {
return Pair.of(sessionCount, ref);
}
// Close session when ref=0
try {
session.close();
} catch (Throwable e) {
session.attach();
throw e;
}
this.threadLocalSession.remove();
assert this.sessions.containsKey(Thread.currentThread().getId());
this.sessions.remove(Thread.currentThread().getId());
return Pair.of(this.sessionCount.decrementAndGet(), ref);
}
public void forceResetSessions() {
for (BackendSession session : this.sessions.values()) {
session.reset();
}
}
public boolean close() {
Pair<Integer, Integer> result = Pair.of(-1, -1);
try {
result = this.closeSession();
} finally {
if (result.getLeft() == 0) {
this.doClose();
}
}
LOG.debug("Now(after close({})) session count is: {}, " +
"current session reference is: {}",
this, result.getLeft(), result.getRight());
return result.getLeft() == 0;
}
public boolean closed() {
return this.sessionCount.get() == 0;
}
@Override
public String toString() {
return String.format("%s-%s@%08X", this.name,
this.getClass().getSimpleName(), this.hashCode());
}
public abstract void open() throws Exception;
protected abstract boolean opened();
public abstract BackendSession session();
protected abstract BackendSession newSession();
protected abstract void doClose();
}
|
// Reconnect if the session idle time exceed specified value
long interval = TimeUnit.SECONDS.toMillis(this.reconnectDetectInterval);
long now = System.currentTimeMillis();
if (now - session.updated() > interval) {
session.reconnectIfNeeded();
}
session.update();
| 1,097
| 85
| 1,182
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/store/BackendStoreInfo.java
|
BackendStoreInfo
|
checkVersion
|
class BackendStoreInfo {
private static final Logger LOG = Log.logger(BackendStoreInfo.class);
private final BackendStoreProvider storeProvider;
private final HugeConfig config;
public BackendStoreInfo(HugeConfig config,
BackendStoreProvider storeProvider) {
this.config = config;
this.storeProvider = storeProvider;
}
public boolean exists() {
return this.storeProvider.initialized();
}
public boolean checkVersion() {<FILL_FUNCTION_BODY>}
}
|
String driverVersion = this.storeProvider.driverVersion();
String storedVersion = this.storeProvider.loadSystemStore(this.config)
.storedVersion();
if (!driverVersion.equals(storedVersion)) {
LOG.error("The backend driver version '{}' is inconsistent with " +
"the data version '{}' of backend store for graph '{}'",
driverVersion, storedVersion, this.storeProvider.graph());
return false;
}
return true;
| 140
| 123
| 263
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/store/MetaDispatcher.java
|
MetaDispatcher
|
dispatchMetaHandler
|
class MetaDispatcher<Session extends BackendSession> {
protected final Map<String, MetaHandler<Session>> metaHandlers;
public MetaDispatcher() {
this.metaHandlers = new ConcurrentHashMap<>();
}
public void registerMetaHandler(String meta, MetaHandler<Session> handler) {
this.metaHandlers.put(meta, handler);
}
@SuppressWarnings("unchecked")
public <R> R dispatchMetaHandler(Session session,
String meta, Object[] args) {<FILL_FUNCTION_BODY>}
}
|
if (!this.metaHandlers.containsKey(meta)) {
throw new NotSupportException("metadata '%s'", meta);
}
return (R) this.metaHandlers.get(meta).handle(session, meta, args);
| 150
| 61
| 211
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/store/SystemSchemaStore.java
|
SystemSchemaStore
|
add
|
class SystemSchemaStore {
private static final int SYSTEM_SCHEMA_MAX_NUMS = 128;
private SchemaElement[] storeByIds;
private final Map<String, SchemaElement> storeByNames;
public SystemSchemaStore() {
this.storeByIds = new SchemaElement[SYSTEM_SCHEMA_MAX_NUMS];
this.storeByNames = CollectionFactory.newMap(CollectionType.EC,
SYSTEM_SCHEMA_MAX_NUMS);
}
public void add(SchemaElement schema) {<FILL_FUNCTION_BODY>}
@SuppressWarnings("unchecked")
public <T extends SchemaElement> T get(Id id) {
long idValue = id.asLong();
assert idValue < 0L;
int index = (int) Math.abs(idValue);
return (T) this.storeByIds[index];
}
@SuppressWarnings("unchecked")
public <T extends SchemaElement> T get(String name) {
return (T) this.storeByNames.get(name);
}
private void expandCapacity() {
int newLength = this.storeByIds.length << 1;
SchemaElement[] newStoreByIds = new SchemaElement[newLength];
System.arraycopy(this.storeByIds, 0, newStoreByIds, 0,
this.storeByIds.length);
this.storeByIds = newStoreByIds;
}
}
|
long idValue = schema.id().asLong();
assert idValue < 0L;
int index = (int) Math.abs(idValue);
if (index >= this.storeByIds.length) {
this.expandCapacity();
}
this.storeByIds[index] = schema;
this.storeByNames.put(schema.name(), schema);
| 383
| 95
| 478
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/store/TableDefine.java
|
TableDefine
|
column
|
class TableDefine {
private final Map<HugeKeys, String> columns;
private final List<HugeKeys> keys;
private final Map<String, String> typesMapping;
public TableDefine() {
this.columns = InsertionOrderUtil.newMap();
this.keys = InsertionOrderUtil.newList();
this.typesMapping = ImmutableMap.of();
}
public TableDefine(Map<String, String> typesMapping) {
this.columns = InsertionOrderUtil.newMap();
this.keys = InsertionOrderUtil.newList();
this.typesMapping = typesMapping;
}
public TableDefine column(HugeKeys key, String... desc) {<FILL_FUNCTION_BODY>}
public Map<HugeKeys, String> columns() {
return Collections.unmodifiableMap(this.columns);
}
public Set<HugeKeys> columnNames() {
return this.columns.keySet();
}
public Collection<String> columnTypes() {
return this.columns.values();
}
public void keys(HugeKeys... keys) {
this.keys.addAll(Arrays.asList(keys));
}
public List<HugeKeys> keys() {
return Collections.unmodifiableList(this.keys);
}
}
|
StringBuilder sb = new StringBuilder();
for (int i = 0; i < desc.length; i++) {
String type = desc[i];
// The first element of 'desc' is column data type, which may be
// mapped to actual data type supported by backend store
if (i == 0 && this.typesMapping.containsKey(type)) {
type = this.typesMapping.get(type);
}
assert type != null;
sb.append(type);
if (i != desc.length - 1) {
sb.append(" ");
}
}
this.columns.put(key, sb.toString());
return this;
| 344
| 169
| 513
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/store/memory/InMemoryDBStoreProvider.java
|
InMemoryDBStoreProvider
|
driverVersion
|
class InMemoryDBStoreProvider extends AbstractBackendStoreProvider {
public static final String TYPE = "memory";
private static Map<String, InMemoryDBStoreProvider> providers = null;
public static boolean matchType(String type) {
return TYPE.equalsIgnoreCase(type);
}
public static synchronized InMemoryDBStoreProvider instance(String graph) {
if (providers == null) {
providers = new ConcurrentHashMap<>();
}
if (!providers.containsKey(graph)) {
InMemoryDBStoreProvider p = new InMemoryDBStoreProvider(graph);
providers.putIfAbsent(graph, p);
}
return providers.get(graph);
}
private InMemoryDBStoreProvider(String graph) {
this.open(graph);
}
@Override
public void open(String graph) {
super.open(graph);
/*
* Memory store need to init some system property,
* like task related property-keys and vertex-labels.
* don't notify from store.open() due to task-tx will
* call it again and cause dead
*/
this.notifyAndWaitEvent(Events.STORE_INIT);
}
@Override
protected BackendStore newSchemaStore(HugeConfig config, String store) {
return new InMemorySchemaStore(this, this.graph(), store);
}
@Override
protected BackendStore newGraphStore(HugeConfig config, String store) {
return new InMemoryGraphStore(this, this.graph(), store);
}
@Override
protected BackendStore newSystemStore(HugeConfig config, String store) {
return new InMemorySystemStore(this, this.graph(), store);
}
@Override
public String type() {
return TYPE;
}
@Override
public String driverVersion() {<FILL_FUNCTION_BODY>}
}
|
/*
* Versions history:
* [1.0] HugeGraph-1328: supports backend table version checking
* [1.1] HugeGraph-1322: add support for full-text search
* [1.2] #296: support range sortKey feature
* [1.3] #270 & #398: support shard-index and vertex + sortkey prefix,
* also split range table to rangeInt, rangeFloat,
* rangeLong and rangeDouble
* [1.4] #746: support userdata for indexlabel
* [1.5] #820: store vertex properties in one column
* [1.6] #894: encode label id in string index
* [1.7] #1333: support read frequency for property key
* [1.8] #1533: add meta table in system store
*/
return "1.8";
| 480
| 239
| 719
|
<methods>public non-sealed void <init>() ,public void clear() throws org.apache.hugegraph.backend.BackendException,public void close() throws org.apache.hugegraph.backend.BackendException,public void createSnapshot() ,public java.lang.String graph() ,public void init() ,public boolean initialized() ,public void listen(EventListener) ,public org.apache.hugegraph.backend.store.BackendStore loadGraphStore(HugeConfig) ,public org.apache.hugegraph.backend.store.BackendStore loadSchemaStore(HugeConfig) ,public org.apache.hugegraph.backend.store.BackendStore loadSystemStore(HugeConfig) ,public void onCloneConfig(HugeConfig, java.lang.String) ,public void onDeleteConfig(HugeConfig) ,public void open(java.lang.String) ,public void resumeSnapshot() ,public EventHub storeEventHub() ,public java.lang.String storedVersion() ,public void truncate() ,public void unlisten(EventListener) ,public void waitReady(RpcServer) <variables>private static final Logger LOG,private java.lang.String graph,private final EventHub storeEventHub,protected Map<java.lang.String,org.apache.hugegraph.backend.store.BackendStore> stores
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/store/raft/RaftAddPeerJob.java
|
RaftAddPeerJob
|
execute
|
class RaftAddPeerJob extends SysJob<String> {
public static final String TASK_TYPE = "raft_add_peer";
@Override
public String type() {
return TASK_TYPE;
}
@Override
public String execute() throws Exception {<FILL_FUNCTION_BODY>}
}
|
String input = this.task().input();
E.checkArgumentNotNull(input, "The input can't be null");
@SuppressWarnings("unchecked")
Map<String, Object> map = JsonUtil.fromJson(input, Map.class);
Object value = map.get("endpoint");
E.checkArgument(value instanceof String,
"Invalid endpoint value '%s'", value);
String endpoint = (String) value;
return this.graph().raftGroupManager().addPeer(endpoint);
| 87
| 131
| 218
|
<methods>public non-sealed void <init>() ,public java.lang.String call() throws java.lang.Exception<variables>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/store/raft/RaftBackendStore.java
|
RaftBackendStore
|
clear
|
class RaftBackendStore implements BackendStore {
private static final Logger LOG = Log.logger(RaftBackendStore.class);
private final BackendStore store;
private final RaftContext context;
private final ThreadLocal<MutationBatch> mutationBatch;
private final boolean isSafeRead;
public RaftBackendStore(BackendStore store, RaftContext context) {
this.store = store;
this.context = context;
this.mutationBatch = new ThreadLocal<>();
this.isSafeRead = this.context.safeRead();
}
public BackendStore originStore() {
return this.store;
}
private RaftNode node() {
RaftNode node = this.context.node();
E.checkState(node != null, "The raft node should be initialized first");
return node;
}
@Override
public String store() {
return this.store.store();
}
@Override
public String storedVersion() {
return this.store.storedVersion();
}
@Override
public String database() {
return this.store.database();
}
@Override
public BackendStoreProvider provider() {
return this.store.provider();
}
@Override
public SystemSchemaStore systemSchemaStore() {
return this.store.systemSchemaStore();
}
@Override
public boolean isSchemaStore() {
return this.store.isSchemaStore();
}
@Override
public synchronized void open(HugeConfig config) {
this.store.open(config);
}
@Override
public void close() {
this.store.close();
}
@Override
public boolean opened() {
return this.store.opened();
}
@Override
public void init() {
// this.submitAndWait(StoreCommand.INIT);
this.store.init();
}
@Override
public void clear(boolean clearSpace) {<FILL_FUNCTION_BODY>}
@Override
public boolean initialized() {
return this.store.initialized();
}
@Override
public void truncate() {
this.submitAndWait(StoreAction.TRUNCATE, null);
}
@Override
public void mutate(BackendMutation mutation) {
if (mutation.isEmpty()) {
return;
}
// Just add to local buffer
this.getOrNewBatch().add(mutation);
}
@Override
@SuppressWarnings("unchecked")
public Iterator<BackendEntry> query(Query query) {
return (Iterator<BackendEntry>)
this.queryByRaft(query, o -> this.store.query(query));
}
@Override
public Number queryNumber(Query query) {
return (Number)
this.queryByRaft(query, o -> this.store.queryNumber(query));
}
@Override
public void beginTx() {
// Don't write raft log, commitTx(in StateMachine) will call beginTx
}
@Override
public void commitTx() {
MutationBatch batch = this.getOrNewBatch();
try {
byte[] bytes = StoreSerializer.writeMutations(batch.mutations);
this.submitAndWait(StoreAction.COMMIT_TX, bytes);
} finally {
batch.clear();
}
}
@Override
public void rollbackTx() {
this.submitAndWait(StoreAction.ROLLBACK_TX, null);
}
@Override
public <R> R metadata(HugeType type, String meta, Object[] args) {
return this.store.metadata(type, meta, args);
}
@Override
public BackendFeatures features() {
return this.store.features();
}
@Override
public void increaseCounter(HugeType type, long increment) {
IncrCounter incrCounter = new IncrCounter(type, increment);
byte[] bytes = StoreSerializer.writeIncrCounter(incrCounter);
this.submitAndWait(StoreAction.INCR_COUNTER, bytes);
}
@Override
public long getCounter(HugeType type) {
Object counter = this.queryByRaft(type, true, o -> this.store.getCounter(type));
assert counter instanceof Long;
return (Long) counter;
}
private Object submitAndWait(StoreAction action, byte[] data) {
StoreType type = this.context.storeType(this.store());
return this.submitAndWait(new StoreCommand(type, action, data));
}
private Object submitAndWait(StoreCommand command) {
RaftStoreClosure closure = new RaftStoreClosure(command);
return this.node().submitAndWait(command, closure);
}
private Object queryByRaft(Object query, Function<Object, Object> func) {
return this.queryByRaft(query, this.isSafeRead, func);
}
private Object queryByRaft(Object query, boolean safeRead,
Function<Object, Object> func) {
if (!safeRead) {
return func.apply(query);
}
RaftClosure<Object> future = new RaftClosure<>();
ReadIndexClosure readIndexClosure = new ReadIndexClosure() {
@Override
public void run(Status status, long index, byte[] reqCtx) {
if (status.isOk()) {
future.complete(status, () -> func.apply(query));
} else {
future.failure(status, new BackendException(
"Failed to do raft read-index: %s",
status));
}
}
};
this.node().readIndex(BytesUtil.EMPTY_BYTES, readIndexClosure);
try {
return future.waitFinished();
} catch (Throwable e) {
LOG.warn("Failed to execute query '{}': {}",
query, future.status(), e);
throw new BackendException("Failed to execute query: %s", e, query);
}
}
private MutationBatch getOrNewBatch() {
MutationBatch batch = this.mutationBatch.get();
if (batch == null) {
batch = new MutationBatch();
this.mutationBatch.set(batch);
}
return batch;
}
private static class MutationBatch {
// This object will stay in memory for a long time
private final List<BackendMutation> mutations;
public MutationBatch() {
this.mutations = new ArrayList<>((int) Query.COMMIT_BATCH);
}
public void add(BackendMutation mutation) {
this.mutations.add(mutation);
}
public void clear() {
this.mutations.clear();
}
}
protected static final class IncrCounter {
private HugeType type;
private long increment;
public IncrCounter(HugeType type, long increment) {
this.type = type;
this.increment = increment;
}
public HugeType type() {
return this.type;
}
public long increment() {
return this.increment;
}
}
}
|
byte value = clearSpace ? (byte) 1 : (byte) 0;
byte[] bytes = StoreCommand.wrap(value);
this.submitAndWait(StoreAction.CLEAR, bytes);
| 1,877
| 53
| 1,930
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/store/raft/RaftBackendStoreProvider.java
|
RaftBackendStoreProvider
|
init
|
class RaftBackendStoreProvider implements BackendStoreProvider {
private static final Logger LOG = Log.logger(RaftBackendStoreProvider.class);
private final BackendStoreProvider provider;
private final RaftContext context;
private RaftBackendStore schemaStore;
private RaftBackendStore graphStore;
private RaftBackendStore systemStore;
public RaftBackendStoreProvider(HugeGraphParams params,
BackendStoreProvider provider) {
this.provider = provider;
this.schemaStore = null;
this.graphStore = null;
this.systemStore = null;
this.context = new RaftContext(params);
}
public RaftGroupManager raftNodeManager() {
return this.context().raftNodeManager();
}
private RaftContext context() {
if (this.context == null) {
E.checkState(false, "Please ensure init raft context");
}
return this.context;
}
private Set<RaftBackendStore> stores() {
return ImmutableSet.of(this.schemaStore, this.graphStore,
this.systemStore);
}
private void checkOpened() {
E.checkState(this.graph() != null &&
this.schemaStore != null &&
this.graphStore != null &&
this.systemStore != null,
"The RaftBackendStoreProvider has not been opened");
}
private void checkNonSharedStore(BackendStore store) {
E.checkArgument(!store.features().supportsSharedStorage(),
"Can't enable raft mode with %s backend",
this.type());
}
@Override
public String type() {
return this.provider.type();
}
@Override
public String driverVersion() {
return this.provider.driverVersion();
}
@Override
public String storedVersion() {
return this.provider.storedVersion();
}
@Override
public String graph() {
return this.provider.graph();
}
@Override
public synchronized BackendStore loadSchemaStore(HugeConfig config) {
if (this.schemaStore == null) {
LOG.info("Init raft backend schema store");
BackendStore store = this.provider.loadSchemaStore(config);
this.checkNonSharedStore(store);
this.schemaStore = new RaftBackendStore(store, this.context());
this.context().addStore(StoreType.SCHEMA, this.schemaStore);
}
return this.schemaStore;
}
@Override
public synchronized BackendStore loadGraphStore(HugeConfig config) {
if (this.graphStore == null) {
LOG.info("Init raft backend graph store");
BackendStore store = this.provider.loadGraphStore(config);
this.checkNonSharedStore(store);
this.graphStore = new RaftBackendStore(store, this.context());
this.context().addStore(StoreType.GRAPH, this.graphStore);
}
return this.graphStore;
}
@Override
public synchronized BackendStore loadSystemStore(HugeConfig config) {
if (this.systemStore == null) {
LOG.info("Init raft backend system store");
BackendStore store = this.provider.loadSystemStore(config);
this.checkNonSharedStore(store);
this.systemStore = new RaftBackendStore(store, this.context());
this.context().addStore(StoreType.SYSTEM, this.systemStore);
}
return this.systemStore;
}
@Override
public void open(String name) {
this.provider.open(name);
}
@Override
public void waitReady(RpcServer rpcServer) {
this.context().initRaftNode(rpcServer);
LOG.info("The raft node is initialized");
this.context().waitRaftNodeStarted();
LOG.info("The raft store is started");
}
@Override
public void close() {
this.provider.close();
if (this.context != null) {
this.context.close();
}
}
@Override
public void init() {<FILL_FUNCTION_BODY>}
@Override
public void clear() {
this.checkOpened();
for (RaftBackendStore store : this.stores()) {
// Just clear tables of store, not clear space
store.clear(false);
}
for (RaftBackendStore store : this.stores()) {
// Only clear space of store
store.clear(true);
}
this.notifyAndWaitEvent(Events.STORE_CLEAR);
LOG.debug("Graph '{}' store has been cleared", this.graph());
}
@Override
public void truncate() {
this.checkOpened();
for (RaftBackendStore store : this.stores()) {
store.truncate();
}
this.notifyAndWaitEvent(Events.STORE_TRUNCATE);
LOG.debug("Graph '{}' store has been truncated", this.graph());
/*
* Take the initiative to generate a snapshot, it can avoid this
* situation: when the server restart need to read the database
* (such as checkBackendVersionInfo), it happens that raft replays
* the truncate log, at the same time, the store has been cleared
* (truncate) but init-store has not been completed, which will
* cause reading errors.
* When restarting, load the snapshot first and then read backend,
* will not encounter such an intermediate state.
*/
this.createSnapshot();
}
@Override
public boolean initialized() {
return this.provider.initialized() && this.context != null;
}
@Override
public void createSnapshot() {
// TODO: snapshot for StoreType.ALL instead of StoreType.GRAPH
StoreCommand command = new StoreCommand(StoreType.GRAPH,
StoreAction.SNAPSHOT, null);
RaftStoreClosure closure = new RaftStoreClosure(command);
RaftClosure<?> future = this.context().node().submitAndWait(command,
closure);
E.checkState(future != null, "The snapshot future can't be null");
try {
future.waitFinished();
LOG.debug("Graph '{}' has writed snapshot", this.graph());
} catch (Throwable e) {
throw new BackendException("Failed to create snapshot", e);
}
}
@Override
public void onCloneConfig(HugeConfig config, String newGraph) {
this.provider.onCloneConfig(config, newGraph);
}
@Override
public void onDeleteConfig(HugeConfig config) {
this.provider.onDeleteConfig(config);
}
@Override
public void resumeSnapshot() {
// Jraft doesn't expose API to load snapshot
throw new UnsupportedOperationException("resumeSnapshot");
}
@Override
public void listen(EventListener listener) {
this.provider.listen(listener);
}
@Override
public void unlisten(EventListener listener) {
this.provider.unlisten(listener);
}
@Override
public EventHub storeEventHub() {
return this.provider.storeEventHub();
}
protected final void notifyAndWaitEvent(String event) {
Future<?> future = this.storeEventHub().notify(event, this);
try {
future.get();
} catch (Throwable e) {
LOG.warn("Error when waiting for event execution: {}", event, e);
}
}
}
|
this.checkOpened();
for (RaftBackendStore store : this.stores()) {
store.init();
}
this.notifyAndWaitEvent(Events.STORE_INIT);
LOG.debug("Graph '{}' store has been initialized", this.graph());
| 1,968
| 75
| 2,043
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/store/raft/RaftClosure.java
|
RaftClosure
|
get
|
class RaftClosure<T> implements Closure {
private static final Logger LOG = Log.logger(RaftStoreClosure.class);
private final CompletableFuture<RaftResult<T>> future;
public RaftClosure() {
this.future = new CompletableFuture<>();
}
public T waitFinished() throws Throwable {
RaftResult<T> result = this.get();
if (result.status().isOk()) {
return result.callback().get();
} else {
throw result.exception();
}
}
public Status status() {
return this.get().status();
}
private RaftResult<T> get() {<FILL_FUNCTION_BODY>}
public void complete(Status status) {
this.future.complete(new RaftResult<>(status));
}
public void complete(Status status, Supplier<T> callback) {
// This callback is called by consumer thread(like grizzly)
this.future.complete(new RaftResult<>(status, callback));
}
public void failure(Status status, Throwable exception) {
this.future.complete(new RaftResult<>(status, exception));
}
@Override
public void run(Status status) {
if (status.isOk()) {
this.complete(status);
} else {
LOG.error("Failed to apply command: {}", status);
String msg = "Failed to apply command in raft node with error: " +
status.getErrorMsg();
this.failure(status, new BackendException(msg));
}
}
}
|
try {
return this.future.get(RaftContext.WAIT_RAFTLOG_TIMEOUT,
TimeUnit.MILLISECONDS);
} catch (ExecutionException e) {
throw new BackendException("ExecutionException", e);
} catch (InterruptedException e) {
throw new BackendException("InterruptedException", e);
} catch (TimeoutException e) {
throw new BackendException("Wait closure timeout");
}
| 420
| 114
| 534
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/store/raft/RaftGroupManagerImpl.java
|
RaftGroupManagerImpl
|
setLeader
|
class RaftGroupManagerImpl implements RaftGroupManager {
private final String group;
private final RaftNode raftNode;
private final RpcForwarder rpcForwarder;
public RaftGroupManagerImpl(RaftContext context) {
this.group = context.group();
this.raftNode = context.node();
this.rpcForwarder = context.rpcForwarder();
}
@Override
public String group() {
return this.group;
}
@Override
public List<String> listPeers() {
if (this.raftNode.selfIsLeader()) {
List<PeerId> peerIds = this.raftNode.node().listPeers();
return peerIds.stream().map(PeerId::toString)
.collect(Collectors.toList());
}
// If current node is not leader, forward request to leader
ListPeersRequest request = ListPeersRequest.getDefaultInstance();
try {
RaftClosure<ListPeersResponse> future;
future = this.forwardToLeader(request);
ListPeersResponse response = future.waitFinished();
return response.getEndpointsList();
} catch (Throwable e) {
throw new BackendException("Failed to list peers", e);
}
}
@Override
public String getLeader() {
PeerId leaderId = this.raftNode.leaderId();
E.checkState(leaderId != null,
"There is no leader for raft group '%s'", this.group);
return leaderId.toString();
}
@Override
public String transferLeaderTo(String endpoint) {
PeerId peerId = PeerId.parsePeer(endpoint);
Status status = this.raftNode.node().transferLeadershipTo(peerId);
if (!status.isOk()) {
throw new BackendException(
"Failed to transfer leader to '%s', raft error: %s",
endpoint, status.getErrorMsg());
}
return peerId.toString();
}
@Override
public String setLeader(String endpoint) {<FILL_FUNCTION_BODY>}
@Override
public String addPeer(String endpoint) {
PeerId peerId = PeerId.parsePeer(endpoint);
try {
RaftClosure<?> future = new RaftClosure<>();
if (this.raftNode.selfIsLeader()) {
this.raftNode.node().addPeer(peerId, future);
} else {
AddPeerRequest request = AddPeerRequest.newBuilder()
.setEndpoint(endpoint)
.build();
future = this.forwardToLeader(request);
}
future.waitFinished();
} catch (Throwable e) {
throw new BackendException("Failed to add peer '%s'", e, endpoint);
}
return peerId.toString();
}
@Override
public String removePeer(String endpoint) {
PeerId peerId = PeerId.parsePeer(endpoint);
try {
RaftClosure<?> future = new RaftClosure<>();
if (this.raftNode.selfIsLeader()) {
this.raftNode.node().removePeer(peerId, future);
} else {
RemovePeerRequest request = RemovePeerRequest.newBuilder()
.setEndpoint(endpoint)
.build();
future = this.forwardToLeader(request);
}
future.waitFinished();
} catch (Throwable e) {
throw new BackendException("Failed to remove peer '%s'", e, endpoint);
}
return peerId.toString();
}
private <T extends Message> RaftClosure<T> forwardToLeader(Message request) {
PeerId leaderId = this.raftNode.leaderId();
return this.rpcForwarder.forwardToLeader(leaderId, request);
}
}
|
PeerId newLeaderId = PeerId.parsePeer(endpoint);
Node node = this.raftNode.node();
// If expected endpoint has already been raft leader
if (node.getLeaderId().equals(newLeaderId)) {
return newLeaderId.toString();
}
if (this.raftNode.selfIsLeader()) {
// If current node is the leader, transfer directly
this.transferLeaderTo(endpoint);
} else {
// If current node is not leader, forward request to leader
SetLeaderRequest request = SetLeaderRequest.newBuilder()
.setEndpoint(endpoint)
.build();
try {
RaftClosure<SetLeaderResponse> future;
future = this.forwardToLeader(request);
future.waitFinished();
} catch (Throwable e) {
throw new BackendException("Failed to set leader to '%s'",
e, endpoint);
}
}
return newLeaderId.toString();
| 1,020
| 261
| 1,281
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/store/raft/RaftRemovePeerJob.java
|
RaftRemovePeerJob
|
execute
|
class RaftRemovePeerJob extends SysJob<String> {
public static final String TASK_TYPE = "raft_remove_peer";
@Override
public String type() {
return TASK_TYPE;
}
@Override
public String execute() throws Exception {<FILL_FUNCTION_BODY>}
}
|
String input = this.task().input();
E.checkArgumentNotNull(input, "The input can't be null");
@SuppressWarnings("unchecked")
Map<String, Object> map = JsonUtil.fromJson(input, Map.class);
Object value = map.get("endpoint");
E.checkArgument(value instanceof String,
"Invalid endpoint value '%s'", value);
String endpoint = (String) value;
return this.graph().raftGroupManager().removePeer(endpoint);
| 87
| 131
| 218
|
<methods>public non-sealed void <init>() ,public java.lang.String call() throws java.lang.Exception<variables>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/store/raft/StoreCommand.java
|
StoreCommand
|
fromBytes
|
class StoreCommand {
public static final int HEADER_SIZE = 2;
private final StoreType type;
private final StoreAction action;
private final byte[] data;
private final boolean forwarded;
public StoreCommand(StoreType type, StoreAction action, byte[] data) {
this(type, action, data, false);
}
public StoreCommand(StoreType type, StoreAction action,
byte[] data, boolean forwarded) {
this.type = type;
this.action = action;
if (data == null) {
this.data = new byte[HEADER_SIZE];
} else {
assert data.length >= HEADER_SIZE;
this.data = data;
}
this.data[0] = (byte) this.type.getNumber();
this.data[1] = (byte) this.action.getNumber();
this.forwarded = forwarded;
}
public StoreType type() {
return this.type;
}
public StoreAction action() {
return this.action;
}
public byte[] data() {
return this.data;
}
public boolean forwarded() {
return this.forwarded;
}
public static void writeHeader(BytesBuffer buffer) {
buffer.write((byte) 0);
buffer.write((byte) 0);
}
public static byte[] wrap(byte value) {
byte[] bytes = new byte[HEADER_SIZE + 1];
bytes[2] = value;
return bytes;
}
public static StoreCommand fromBytes(byte[] bytes) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return String.format("StoreCommand{type=%s,action=%s}",
this.type.name(), this.action.name());
}
}
|
StoreType type = StoreType.valueOf(bytes[0]);
StoreAction action = StoreAction.valueOf(bytes[1]);
return new StoreCommand(type, action, bytes);
| 475
| 48
| 523
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/store/raft/StoreSerializer.java
|
StoreSerializer
|
writeMutations
|
class StoreSerializer {
private static final int MUTATION_SIZE = (int) (1 * Bytes.MB);
public static byte[] writeMutations(List<BackendMutation> mutations) {<FILL_FUNCTION_BODY>}
public static List<BackendMutation> readMutations(BytesBuffer buffer) {
int size = buffer.readVInt();
List<BackendMutation> mutations = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
BytesBuffer buf = BytesBuffer.wrap(buffer.readBigBytes());
mutations.add(readMutation(buf));
}
return mutations;
}
public static byte[] writeMutation(BackendMutation mutation) {
BytesBuffer buffer = BytesBuffer.allocate(MUTATION_SIZE);
// write mutation size
buffer.writeVInt(mutation.size());
for (Iterator<BackendAction> items = mutation.mutation();
items.hasNext(); ) {
BackendAction item = items.next();
// write Action
buffer.write(item.action().code());
BackendEntry entry = item.entry();
// write HugeType
buffer.write(entry.type().code());
// write id
buffer.writeBytes(entry.id().asBytes());
// write subId
if (entry.subId() != null) {
buffer.writeId(entry.subId());
} else {
buffer.writeId(IdGenerator.ZERO);
}
// write ttl
buffer.writeVLong(entry.ttl());
// write columns
buffer.writeVInt(entry.columns().size());
for (BackendColumn column : entry.columns()) {
buffer.writeBytes(column.name);
buffer.writeBytes(column.value);
}
}
return buffer.bytes();
}
public static BackendMutation readMutation(BytesBuffer buffer) {
int size = buffer.readVInt();
BackendMutation mutation = new BackendMutation(size);
for (int i = 0; i < size; i++) {
// read action
Action action = Action.fromCode(buffer.read());
// read HugeType
HugeType type = SerialEnum.fromCode(HugeType.class, buffer.read());
// read id
byte[] idBytes = buffer.readBytes();
// read subId
Id subId = buffer.readId();
if (subId.equals(IdGenerator.ZERO)) {
subId = null;
}
// read ttl
long ttl = buffer.readVLong();
BinaryBackendEntry entry = new BinaryBackendEntry(type, idBytes);
entry.subId(subId);
entry.ttl(ttl);
// read columns
int columnsSize = buffer.readVInt();
for (int c = 0; c < columnsSize; c++) {
byte[] name = buffer.readBytes();
byte[] value = buffer.readBytes();
entry.column(BackendColumn.of(name, value));
}
mutation.put(entry, action);
}
return mutation;
}
public static byte[] writeIncrCounter(IncrCounter incrCounter) {
// The first two bytes are reserved for StoreType and StoreAction
BytesBuffer buffer = BytesBuffer.allocate(StoreCommand.HEADER_SIZE +
1 + BytesBuffer.LONG_LEN);
StoreCommand.writeHeader(buffer);
buffer.write(incrCounter.type().code());
buffer.writeVLong(incrCounter.increment());
return buffer.bytes();
}
public static IncrCounter readIncrCounter(BytesBuffer buffer) {
HugeType type = SerialEnum.fromCode(HugeType.class, buffer.read());
long increment = buffer.readVLong();
return new IncrCounter(type, increment);
}
}
|
int estimateSize = mutations.size() * MUTATION_SIZE;
// The first two bytes are reserved for StoreType and StoreAction
BytesBuffer buffer = BytesBuffer.allocate(StoreCommand.HEADER_SIZE +
4 + estimateSize);
StoreCommand.writeHeader(buffer);
buffer.writeVInt(mutations.size());
for (BackendMutation mutation : mutations) {
buffer.writeBigBytes(writeMutation(mutation));
}
return buffer.bytes();
| 1,005
| 130
| 1,135
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/store/raft/StoreStateMachine.java
|
StoreStateMachine
|
onApplyLeader
|
class StoreStateMachine extends StateMachineAdapter {
private static final Logger LOG = Log.logger(StoreStateMachine.class);
private final RaftContext context;
private final StoreSnapshotFile snapshotFile;
public StoreStateMachine(RaftContext context) {
this.context = context;
this.snapshotFile = new StoreSnapshotFile(context.stores());
}
private BackendStore store(StoreType type) {
return this.context.originStore(type);
}
private RaftNode node() {
return this.context.node();
}
@Override
public void onApply(Iterator iter) {
LOG.debug("Node role: {}", this.node().selfIsLeader() ?
"leader" : "follower");
List<Future<?>> futures = new ArrayList<>(64);
try {
// Apply all the logs
while (iter.hasNext()) {
RaftStoreClosure closure = (RaftStoreClosure) iter.done();
if (closure != null) {
futures.add(this.onApplyLeader(closure));
} else {
futures.add(this.onApplyFollower(iter.getData()));
}
iter.next();
}
// Wait for all tasks finished
for (Future<?> future : futures) {
future.get();
}
} catch (Throwable e) {
String title = "StateMachine occurred critical error";
LOG.error("{}", title, e);
Status status = new Status(RaftError.ESTATEMACHINE,
"%s: %s", title, e.getMessage());
// Will cause current node inactive
// TODO: rollback to correct index
iter.setErrorAndRollback(1L, status);
}
}
private Future<?> onApplyLeader(RaftStoreClosure closure) {<FILL_FUNCTION_BODY>}
private Future<?> onApplyFollower(ByteBuffer data) {
// Follower need to read mutation data
byte[] bytes = data.array();
// Let the backend thread do it directly
return this.context.backendExecutor().submit(() -> {
BytesBuffer buffer = LZ4Util.decompress(bytes,
RaftContext.BLOCK_SIZE);
buffer.forReadWritten();
StoreType type = StoreType.valueOf(buffer.read());
StoreAction action = StoreAction.valueOf(buffer.read());
try {
return this.applyCommand(type, action, buffer, false);
} catch (Throwable e) {
String title = "Failed to execute backend command";
LOG.error("{}: {}", title, action, e);
throw new BackendException(title, e);
}
});
}
private Object applyCommand(StoreType type, StoreAction action,
BytesBuffer buffer, boolean forwarded) {
E.checkState(type != StoreType.ALL,
"Can't apply command for all store at one time");
BackendStore store = this.store(type);
switch (action) {
case CLEAR:
boolean clearSpace = buffer.read() > 0;
store.clear(clearSpace);
this.context.clearCache();
break;
case TRUNCATE:
store.truncate();
this.context.clearCache();
break;
case SNAPSHOT:
assert store == null;
return this.node().snapshot();
case BEGIN_TX:
store.beginTx();
break;
case COMMIT_TX:
List<BackendMutation> mutations = StoreSerializer.readMutations(
buffer);
// RaftBackendStore doesn't write raft log for beginTx
store.beginTx();
for (BackendMutation mutation : mutations) {
store.mutate(mutation);
this.context.updateCacheIfNeeded(mutation, forwarded);
}
store.commitTx();
break;
case ROLLBACK_TX:
store.rollbackTx();
break;
case INCR_COUNTER:
// Do increase counter
IncrCounter counter = StoreSerializer.readIncrCounter(buffer);
store.increaseCounter(counter.type(), counter.increment());
break;
default:
throw new IllegalArgumentException("Invalid action " + action);
}
return null;
}
@Override
public void onSnapshotSave(SnapshotWriter writer, Closure done) {
LOG.info("The node {} start snapshot saving", this.node().nodeId());
this.snapshotFile.save(writer, done, this.context.snapshotExecutor());
}
@Override
public boolean onSnapshotLoad(SnapshotReader reader) {
if (this.node() != null && this.node().selfIsLeader()) {
LOG.warn("Leader is not supposed to load snapshot.");
return false;
}
/*
* Snapshot load occurred in RaftNode constructor, specifically at step
* `this.node = this.initRaftNode()`, at this time the NodeImpl is null
* in RaftNode so we can't call `this.node().nodeId()`
*/
LOG.info("The node {} start snapshot loading", this.context.endpoint());
return this.snapshotFile.load(reader);
}
@Override
public void onLeaderStart(long term) {
LOG.info("The node {} become to leader", this.context.endpoint());
this.node().onLeaderInfoChange(this.context.endpoint(), true);
super.onLeaderStart(term);
}
@Override
public void onLeaderStop(Status status) {
LOG.info("The node {} abdicated from leader", this.node().nodeId());
this.node().onLeaderInfoChange(null, false);
super.onLeaderStop(status);
}
@Override
public void onStartFollowing(LeaderChangeContext ctx) {
LOG.info("The node {} become to follower", this.node().nodeId());
this.node().onLeaderInfoChange(ctx.getLeaderId(), false);
super.onStartFollowing(ctx);
}
@Override
public void onStopFollowing(LeaderChangeContext ctx) {
LOG.info("The node {} abdicated from follower", this.node().nodeId());
this.node().onLeaderInfoChange(null, false);
super.onStopFollowing(ctx);
}
@Override
public void onConfigurationCommitted(Configuration conf) {
super.onConfigurationCommitted(conf);
}
@Override
public void onError(final RaftException e) {
LOG.error("Raft error: {}", e.getMessage(), e);
}
}
|
// Leader just take the command out from the closure
StoreCommand command = closure.command();
BytesBuffer buffer = BytesBuffer.wrap(command.data());
// The first two bytes are StoreType and StoreAction
StoreType type = StoreType.valueOf(buffer.read());
StoreAction action = StoreAction.valueOf(buffer.read());
boolean forwarded = command.forwarded();
// Let the producer thread to handle it, and wait for it
CompletableFuture<Object> future = new CompletableFuture<>();
closure.complete(Status.OK(), () -> {
Object result;
try {
result = this.applyCommand(type, action, buffer, forwarded);
} catch (Throwable e) {
future.completeExceptionally(e);
throw e;
}
future.complete(result);
return result;
});
return future;
| 1,713
| 220
| 1,933
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/store/raft/compress/CompressStrategyManager.java
|
CompressStrategyManager
|
addCompressStrategy
|
class CompressStrategyManager {
private static byte DEFAULT_STRATEGY = 1;
public static final byte SERIAL_STRATEGY = 1;
public static final byte PARALLEL_STRATEGY = 2;
public static final byte MAX_STRATEGY = 5;
private static CompressStrategy[] compressStrategies = new CompressStrategy[MAX_STRATEGY];
static {
addCompressStrategy(SERIAL_STRATEGY, new SerialCompressStrategy());
}
private CompressStrategyManager() {
}
public static void addCompressStrategy(int index, CompressStrategy compressStrategy) {<FILL_FUNCTION_BODY>}
public static CompressStrategy getDefault() {
return compressStrategies[DEFAULT_STRATEGY];
}
public static void init(final HugeConfig config) {
if (!config.get(CoreOptions.RAFT_SNAPSHOT_PARALLEL_COMPRESS)) {
return;
}
// add parallel compress strategy
if (compressStrategies[PARALLEL_STRATEGY] == null) {
CompressStrategy compressStrategy = new ParallelCompressStrategy(
config.get(CoreOptions.RAFT_SNAPSHOT_COMPRESS_THREADS),
config.get(CoreOptions.RAFT_SNAPSHOT_DECOMPRESS_THREADS));
CompressStrategyManager.addCompressStrategy(
CompressStrategyManager.PARALLEL_STRATEGY, compressStrategy);
DEFAULT_STRATEGY = PARALLEL_STRATEGY;
}
}
}
|
if (compressStrategies.length <= index) {
CompressStrategy[] newCompressStrategies = new CompressStrategy[index + MAX_STRATEGY];
System.arraycopy(compressStrategies, 0, newCompressStrategies, 0,
compressStrategies.length);
compressStrategies = newCompressStrategies;
}
compressStrategies[index] = compressStrategy;
| 405
| 110
| 515
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/store/raft/compress/ParallelCompressStrategy.java
|
ZipArchiveScatterOutputStream
|
compressDirectoryToZipFile
|
class ZipArchiveScatterOutputStream {
private final ParallelScatterZipCreator creator;
public ZipArchiveScatterOutputStream(ExecutorService executorService) {
this.creator = new ParallelScatterZipCreator(executorService);
}
public void addEntry(ZipArchiveEntry entry, InputStreamSupplier supplier) {
creator.addArchiveEntry(entry, supplier);
}
public void writeTo(ZipArchiveOutputStream archiveOutput) throws Exception {
creator.writeTo(archiveOutput);
}
}
@Override
public void compressZip(String rootDir, String sourceDir, String outputZipFile,
Checksum checksum) throws Throwable {
File rootFile = new File(Paths.get(rootDir, sourceDir).toString());
File zipFile = new File(outputZipFile);
LOG.info("Start to compress snapshot in parallel mode");
FileUtils.forceMkdir(zipFile.getParentFile());
ExecutorService compressExecutor =
newFixedPool(compressThreads, compressThreads, "raft-snapshot-compress-executor",
new ThreadPoolExecutor.CallerRunsPolicy());
ZipArchiveScatterOutputStream scatterOutput =
new ZipArchiveScatterOutputStream(compressExecutor);
compressDirectoryToZipFile(rootFile, scatterOutput, sourceDir, ZipEntry.DEFLATED);
try (FileOutputStream fos = new FileOutputStream(zipFile);
BufferedOutputStream bos = new BufferedOutputStream(fos);
CheckedOutputStream cos = new CheckedOutputStream(bos, checksum);
ZipArchiveOutputStream archiveOutputStream = new ZipArchiveOutputStream(cos)) {
scatterOutput.writeTo(archiveOutputStream);
archiveOutputStream.flush();
fos.getFD().sync();
}
ExecutorServiceHelper.shutdownAndAwaitTermination(compressExecutor);
}
@Override
public void decompressZip(String sourceZipFile, String outputDir,
Checksum checksum) throws Throwable {
LOG.info("Start to decompress snapshot in parallel mode");
ExecutorService decompressExecutor =
newFixedPool(decompressThreads, decompressThreads,
"raft-snapshot-decompress-executor",
new ThreadPoolExecutor.CallerRunsPolicy());
// compute the checksum in a single thread
Future<Boolean> checksumFuture = decompressExecutor.submit(() -> {
computeZipFileChecksumValue(sourceZipFile, checksum);
return true;
});
try (ZipFile zipFile = new ZipFile(sourceZipFile)) {
List<Future<Boolean>> futures = Lists.newArrayList();
for (Enumeration<ZipArchiveEntry> e = zipFile.getEntries();
e.hasMoreElements(); ) {
ZipArchiveEntry zipEntry = e.nextElement();
Future<Boolean> future = decompressExecutor.submit(() -> {
unZipFile(zipFile, zipEntry, outputDir);
return true;
});
futures.add(future);
}
// blocking and caching exception
for (Future<Boolean> future : futures) {
future.get();
}
}
// wait for checksum to be calculated
checksumFuture.get();
ExecutorServiceHelper.shutdownAndAwaitTermination(decompressExecutor);
}
private void compressDirectoryToZipFile(File dir, ZipArchiveScatterOutputStream scatterOutput,
String sourceDir, int method) {<FILL_FUNCTION_BODY>
|
if (dir == null) {
return;
}
if (dir.isFile()) {
addEntry(sourceDir, dir, scatterOutput, method);
return;
}
File[] files = Requires.requireNonNull(Objects.requireNonNull(dir.listFiles()), "files");
for (File file : files) {
String child = Paths.get(sourceDir, file.getName()).toString();
if (file.isDirectory()) {
compressDirectoryToZipFile(file, scatterOutput, child, method);
} else {
addEntry(child, file, scatterOutput, method);
}
}
| 903
| 163
| 1,066
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/store/raft/compress/SerialCompressStrategy.java
|
SerialCompressStrategy
|
compressZip
|
class SerialCompressStrategy implements CompressStrategy {
private static final Logger LOG = LoggerFactory.getLogger(SerialCompressStrategy.class);
@Override
public void compressZip(String rootDir, String sourceDir, String outputZipFile,
Checksum checksum) throws Throwable {<FILL_FUNCTION_BODY>}
@Override
public void decompressZip(String sourceZipFile, String outputDir,
Checksum checksum) throws Throwable {
LOG.info("Start to decompress snapshot in serial strategy");
CompressUtil.decompressZip(sourceZipFile, outputDir, checksum);
}
}
|
LOG.info("Start to compress snapshot in serial strategy");
CompressUtil.compressZip(rootDir, sourceDir, outputZipFile, checksum);
| 167
| 42
| 209
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/store/raft/rpc/AddPeerProcessor.java
|
AddPeerProcessor
|
processRequest
|
class AddPeerProcessor
extends RpcRequestProcessor<AddPeerRequest> {
private static final Logger LOG = Log.logger(AddPeerProcessor.class);
private final RaftContext context;
public AddPeerProcessor(RaftContext context) {
super(null, null);
this.context = context;
}
@Override
public Message processRequest(AddPeerRequest request,
RpcRequestClosure done) {<FILL_FUNCTION_BODY>}
@Override
public String interest() {
return AddPeerRequest.class.getName();
}
}
|
LOG.debug("Processing AddPeerRequest {}", request.getClass());
RaftGroupManager nodeManager = this.context.raftNodeManager();
try {
nodeManager.addPeer(request.getEndpoint());
CommonResponse common = CommonResponse.newBuilder()
.setStatus(true)
.build();
return AddPeerResponse.newBuilder().setCommon(common).build();
} catch (Throwable e) {
CommonResponse common = CommonResponse.newBuilder()
.setStatus(false)
.setMessage(e.toString())
.build();
return AddPeerResponse.newBuilder().setCommon(common).build();
}
| 155
| 171
| 326
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/store/raft/rpc/ListPeersProcessor.java
|
ListPeersProcessor
|
processRequest
|
class ListPeersProcessor
extends RpcRequestProcessor<ListPeersRequest> {
private static final Logger LOG = Log.logger(ListPeersProcessor.class);
private final RaftContext context;
public ListPeersProcessor(RaftContext context) {
super(null, null);
this.context = context;
}
@Override
public Message processRequest(ListPeersRequest request,
RpcRequestClosure done) {<FILL_FUNCTION_BODY>}
@Override
public String interest() {
return ListPeersRequest.class.getName();
}
}
|
LOG.debug("Processing ListPeersRequest {}", request.getClass());
RaftGroupManager nodeManager = this.context.raftNodeManager();
try {
CommonResponse common = CommonResponse.newBuilder()
.setStatus(true)
.build();
return ListPeersResponse.newBuilder()
.setCommon(common)
.addAllEndpoints(nodeManager.listPeers())
.build();
} catch (Throwable e) {
CommonResponse common = CommonResponse.newBuilder()
.setStatus(false)
.setMessage(e.toString())
.build();
return ListPeersResponse.newBuilder()
.setCommon(common)
.addAllEndpoints(ImmutableList.of())
.build();
}
| 155
| 198
| 353
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/store/raft/rpc/RemovePeerProcessor.java
|
RemovePeerProcessor
|
processRequest
|
class RemovePeerProcessor
extends RpcRequestProcessor<RemovePeerRequest> {
private static final Logger LOG = Log.logger(RemovePeerProcessor.class);
private final RaftContext context;
public RemovePeerProcessor(RaftContext context) {
super(null, null);
this.context = context;
}
@Override
public Message processRequest(RemovePeerRequest request,
RpcRequestClosure done) {<FILL_FUNCTION_BODY>}
@Override
public String interest() {
return RemovePeerRequest.class.getName();
}
}
|
LOG.debug("Processing RemovePeerRequest {}", request.getClass());
RaftGroupManager nodeManager = this.context.raftNodeManager();
try {
nodeManager.removePeer(request.getEndpoint());
CommonResponse common = CommonResponse.newBuilder()
.setStatus(true)
.build();
return RemovePeerResponse.newBuilder().setCommon(common).build();
} catch (Throwable e) {
CommonResponse common = CommonResponse.newBuilder()
.setStatus(false)
.setMessage(e.toString())
.build();
return RemovePeerResponse.newBuilder().setCommon(common).build();
}
| 155
| 171
| 326
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/store/raft/rpc/RpcForwarder.java
|
RpcForwarder
|
forwardToLeader
|
class RpcForwarder {
private static final Logger LOG = Log.logger(RpcForwarder.class);
private final PeerId nodeId;
private final RaftClientService rpcClient;
public RpcForwarder(Node node) {
this.nodeId = node.getNodeId().getPeerId();
this.rpcClient = ((NodeImpl) node).getRpcService();
E.checkNotNull(this.rpcClient, "rpc client");
}
public void forwardToLeader(PeerId leaderId, StoreCommand command,
RaftStoreClosure future) {<FILL_FUNCTION_BODY>}
public <T extends Message> RaftClosure<T> forwardToLeader(PeerId leaderId,
Message request) {
E.checkNotNull(leaderId, "leader id");
E.checkState(!leaderId.equals(this.nodeId),
"Invalid state: current node is the leader, there is " +
"no need to forward the request");
LOG.debug("The node '{}' forward request to leader '{}'",
this.nodeId, leaderId);
RaftClosure<T> future = new RaftClosure<>();
RpcResponseClosure<T> responseDone = new RpcResponseClosure<T>() {
@Override
public void setResponse(T response) {
FieldDescriptor fd = response.getDescriptorForType()
.findFieldByName("common");
Object object = response.getField(fd);
E.checkState(object instanceof CommonResponse,
"The common field must be instance of " +
"CommonResponse, actual is '%s'",
object != null ? object.getClass() : null);
CommonResponse commonResponse = (CommonResponse) object;
if (commonResponse.getStatus()) {
future.complete(Status.OK(), () -> response);
} else {
Status status = new Status(RaftError.UNKNOWN,
"fowared request failed");
BackendException e = new BackendException(
"Current node isn't leader, leader " +
"is [%s], failed to forward request " +
"to leader: %s",
leaderId, commonResponse.getMessage());
future.failure(status, e);
}
}
@Override
public void run(Status status) {
future.run(status);
}
};
this.waitRpc(leaderId.getEndpoint(), request, responseDone);
return future;
}
private <T extends Message> void waitRpc(Endpoint endpoint, Message request,
RpcResponseClosure<T> done) {
E.checkNotNull(endpoint, "leader endpoint");
try {
this.rpcClient.invokeWithDone(endpoint, request, done,
RaftContext.WAIT_RPC_TIMEOUT)
.get();
} catch (InterruptedException e) {
throw new BackendException("Invoke rpc request was interrupted, " +
"please try again later", e);
} catch (ExecutionException e) {
throw new BackendException("Failed to invoke rpc request", e);
}
}
}
|
E.checkNotNull(leaderId, "leader id");
E.checkState(!leaderId.equals(this.nodeId),
"Invalid state: current node is the leader, there is " +
"no need to forward the request");
LOG.debug("The node {} forward request to leader {}",
this.nodeId, leaderId);
StoreCommandRequest.Builder builder = StoreCommandRequest.newBuilder();
builder.setType(command.type());
builder.setAction(command.action());
builder.setData(ZeroByteStringHelper.wrap(command.data()));
StoreCommandRequest request = builder.build();
RpcResponseClosure<StoreCommandResponse> responseClosure;
responseClosure = new RpcResponseClosure<StoreCommandResponse>() {
@Override
public void setResponse(StoreCommandResponse response) {
if (response.getStatus()) {
LOG.debug("StoreCommandResponse status ok");
// This code forwards the request to the Raft leader and considers the
// operation successful
// if it's forwarded successfully. It returns a RaftClosure because the calling
// logic expects a RaftClosure result. Specifically, if the current instance
// is the Raft leader,
// it executes the corresponding logic locally and notifies the calling logic
// asynchronously
// via RaftClosure. Therefore, the result is returned as a RaftClosure here.
RaftClosure<Status> supplierFuture = new RaftClosure<>();
supplierFuture.complete(Status.OK());
future.complete(Status.OK(), () -> supplierFuture);
} else {
LOG.debug("StoreCommandResponse status error");
Status status = new Status(RaftError.UNKNOWN,
"fowared request failed");
BackendException e = new BackendException(
"Current node isn't leader, leader " +
"is [%s], failed to forward request " +
"to leader: %s",
leaderId, response.getMessage());
future.failure(status, e);
}
}
@Override
public void run(Status status) {
future.run(status);
}
};
this.waitRpc(leaderId.getEndpoint(), request, responseClosure);
| 809
| 571
| 1,380
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/store/raft/rpc/SetLeaderProcessor.java
|
SetLeaderProcessor
|
processRequest
|
class SetLeaderProcessor
extends RpcRequestProcessor<SetLeaderRequest> {
private static final Logger LOG = Log.logger(SetLeaderProcessor.class);
private final RaftContext context;
public SetLeaderProcessor(RaftContext context) {
super(null, null);
this.context = context;
}
@Override
public Message processRequest(SetLeaderRequest request,
RpcRequestClosure done) {<FILL_FUNCTION_BODY>}
@Override
public String interest() {
return SetLeaderRequest.class.getName();
}
}
|
LOG.debug("Processing SetLeaderRequest {}", request.getClass());
RaftGroupManager nodeManager = this.context.raftNodeManager();
try {
nodeManager.setLeader(request.getEndpoint());
CommonResponse common = CommonResponse.newBuilder()
.setStatus(true)
.build();
return SetLeaderResponse.newBuilder().setCommon(common).build();
} catch (Throwable e) {
CommonResponse common = CommonResponse.newBuilder()
.setStatus(false)
.setMessage(e.toString())
.build();
return SetLeaderResponse.newBuilder().setCommon(common).build();
}
| 155
| 171
| 326
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/store/raft/rpc/StoreCommandProcessor.java
|
StoreCommandProcessor
|
processRequest
|
class StoreCommandProcessor
extends RpcRequestProcessor<StoreCommandRequest> {
private static final Logger LOG = Log.logger(
StoreCommandProcessor.class);
private final RaftContext context;
public StoreCommandProcessor(RaftContext context) {
super(null, null);
this.context = context;
}
@Override
public Message processRequest(StoreCommandRequest request,
RpcRequestClosure done) {<FILL_FUNCTION_BODY>}
@Override
public String interest() {
return StoreCommandRequest.class.getName();
}
private StoreCommand parseStoreCommand(StoreCommandRequest request) {
StoreType type = request.getType();
StoreAction action = request.getAction();
byte[] data = request.getData().toByteArray();
return new StoreCommand(type, action, data, true);
}
}
|
LOG.debug("Processing StoreCommandRequest: {}", request.getAction());
RaftNode node = this.context.node();
try {
StoreCommand command = this.parseStoreCommand(request);
RaftStoreClosure closure = new RaftStoreClosure(command);
node.submitAndWait(command, closure);
// TODO: return the submitAndWait() result to rpc client
return StoreCommandResponse.newBuilder().setStatus(true).build();
} catch (Throwable e) {
LOG.warn("Failed to process StoreCommandRequest: {}",
request.getAction(), e);
StoreCommandResponse.Builder builder = StoreCommandResponse
.newBuilder()
.setStatus(false);
if (e.getMessage() != null) {
builder.setMessage(e.getMessage());
}
return builder.build();
}
| 222
| 215
| 437
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/store/ram/IntIntMap.java
|
IntIntMap
|
readFrom
|
class IntIntMap implements RamMap {
// TODO: use com.carrotsearch.hppc.IntIntHashMap instead
private final int[] array;
public IntIntMap(int capacity) {
this.array = new int[capacity];
}
public void put(long key, int value) {
assert 0 <= key && key < Integer.MAX_VALUE;
this.array[(int) key] = value;
}
public int get(long key) {
assert 0 <= key && key < Integer.MAX_VALUE;
return this.array[(int) key];
}
@Override
public void clear() {
Arrays.fill(this.array, 0);
}
@Override
public long size() {
return this.array.length;
}
@Override
public void writeTo(DataOutputStream buffer) throws IOException {
buffer.writeInt(this.array.length);
for (int value : this.array) {
buffer.writeInt(value);
}
}
@Override
public void readFrom(DataInputStream buffer) throws IOException {<FILL_FUNCTION_BODY>}
}
|
int size = buffer.readInt();
if (size > this.array.length) {
throw new HugeException("Invalid size %s, expect < %s",
size, this.array.length);
}
for (int i = 0; i < size; i++) {
int value = buffer.readInt();
this.array[i] = value;
}
| 297
| 98
| 395
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/store/ram/IntLongMap.java
|
IntLongMap
|
readFrom
|
class IntLongMap implements RamMap {
// TODO: use com.carrotsearch.hppc.IntLongHashMap instead
private final long[] array;
private int size;
public IntLongMap(int capacity) {
this.array = new long[capacity];
this.size = 0;
}
public void put(int key, long value) {
if (key >= this.size || key < 0) {
throw new HugeException("Invalid key %s", key);
}
this.array[key] = value;
}
public int add(long value) {
if (this.size == Integer.MAX_VALUE) {
throw new HugeException("Too many edges %s", this.size);
}
int index = this.size;
this.array[index] = value;
this.size++;
return index;
}
public long get(int key) {
if (key >= this.size || key < 0) {
throw new HugeException("Invalid key %s", key);
}
return this.array[key];
}
@Override
public void clear() {
Arrays.fill(this.array, 0L);
this.size = 0;
}
@Override
public long size() {
return this.size;
}
@Override
public void writeTo(DataOutputStream buffer) throws IOException {
buffer.writeInt(this.array.length);
for (long value : this.array) {
buffer.writeLong(value);
}
}
@Override
public void readFrom(DataInputStream buffer) throws IOException {<FILL_FUNCTION_BODY>}
}
|
int size = buffer.readInt();
if (size > this.array.length) {
throw new HugeException("Invalid size %s, expect < %s",
size, this.array.length);
}
for (int i = 0; i < size; i++) {
long value = buffer.readLong();
this.array[i] = value;
}
this.size = size;
| 431
| 106
| 537
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/store/ram/IntObjectMap.java
|
IntObjectMap
|
set
|
class IntObjectMap<V> implements RamMap {
private static final float DEFAULT_INITIAL_FACTOR = 0.25f;
private final int maxSize;
private volatile int currentSize;
private volatile Object[] array;
public IntObjectMap(int size) {
this.maxSize = size;
this.currentSize = (int) (size * DEFAULT_INITIAL_FACTOR);
this.array = new Object[this.currentSize];
}
@SuppressWarnings("unchecked")
public V get(int key) {
if (key >= this.currentSize) {
return null;
}
return (V) this.array[key];
}
public void set(int key, V value) {<FILL_FUNCTION_BODY>}
@Override
public void clear() {
Arrays.fill(this.array, null);
}
@Override
public long size() {
return this.maxSize;
}
@Override
public void writeTo(DataOutputStream buffer) throws IOException {
throw new NotSupportException("IntObjectMap.writeTo");
}
@Override
public void readFrom(DataInputStream buffer) throws IOException {
throw new NotSupportException("IntObjectMap.readFrom");
}
private synchronized void expandCapacity() {
if (this.currentSize == this.maxSize) {
return;
}
int newSize = Math.min(this.currentSize * 2, this.maxSize);
Object[] newArray = new Object[newSize];
System.arraycopy(this.array, 0, newArray, 0, this.array.length);
this.clear();
this.array = newArray;
this.currentSize = newSize;
}
}
|
if (key >= this.currentSize) {
this.expandCapacity();
}
this.array[key] = value;
| 457
| 38
| 495
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/tx/IndexableTransaction.java
|
IndexableTransaction
|
reset
|
class IndexableTransaction extends AbstractTransaction {
public IndexableTransaction(HugeGraphParams graph, BackendStore store) {
super(graph, store);
}
@Override
public boolean hasUpdate() {
AbstractTransaction indexTx = this.indexTransaction();
boolean indexTxChanged = (indexTx != null && indexTx.hasUpdate());
return indexTxChanged || super.hasUpdate();
}
@Override
protected void reset() {<FILL_FUNCTION_BODY>}
@Override
protected void commit2Backend() {
BackendMutation mutation = this.prepareCommit();
BackendMutation idxMutation = this.indexTransaction().prepareCommit();
assert !mutation.isEmpty() || !idxMutation.isEmpty();
// Commit graph/schema updates and index updates with graph/schema tx
this.commitMutation2Backend(mutation, idxMutation);
}
@Override
public void commitIfGtSize(int size) throws BackendException {
int totalSize = this.mutationSize() +
this.indexTransaction().mutationSize();
if (totalSize >= size) {
this.commit();
}
}
@Override
public void rollback() throws BackendException {
try {
super.rollback();
} finally {
this.indexTransaction().rollback();
}
}
@Override
public void close() {
try {
this.indexTransaction().close();
} finally {
super.close();
}
}
protected abstract AbstractTransaction indexTransaction();
}
|
super.reset();
// It's null when called by super AbstractTransaction()
AbstractTransaction indexTx = this.indexTransaction();
if (indexTx != null) {
indexTx.reset();
}
| 399
| 57
| 456
|
<methods>public void <init>(org.apache.hugegraph.HugeGraphParams, org.apache.hugegraph.backend.store.BackendStore) ,public boolean autoCommit() ,public void close() ,public void commit() throws org.apache.hugegraph.backend.BackendException,public void commitIfGtSize(int) throws org.apache.hugegraph.backend.BackendException,public void commitOrRollback() ,public void doAppend(org.apache.hugegraph.backend.store.BackendEntry) ,public void doEliminate(org.apache.hugegraph.backend.store.BackendEntry) ,public void doInsert(org.apache.hugegraph.backend.store.BackendEntry) ,public void doRemove(org.apache.hugegraph.backend.store.BackendEntry) ,public void doUpdateIfAbsent(org.apache.hugegraph.backend.store.BackendEntry) ,public void doUpdateIfPresent(org.apache.hugegraph.backend.store.BackendEntry) ,public org.apache.hugegraph.backend.store.BackendEntry get(org.apache.hugegraph.type.HugeType, org.apache.hugegraph.backend.id.Id) ,public org.apache.hugegraph.HugeGraph graph() ,public org.apache.hugegraph.type.define.GraphMode graphMode() ,public java.lang.String graphName() ,public boolean hasUpdate() ,public boolean hasUpdate(org.apache.hugegraph.type.HugeType, org.apache.hugegraph.type.define.Action) ,public transient R metadata(org.apache.hugegraph.type.HugeType, java.lang.String, java.lang.Object[]) ,public int mutationSize() ,public QueryResults<org.apache.hugegraph.backend.store.BackendEntry> query(org.apache.hugegraph.backend.query.Query) ,public org.apache.hugegraph.backend.store.BackendEntry query(org.apache.hugegraph.type.HugeType, org.apache.hugegraph.backend.id.Id) ,public java.lang.Number queryNumber(org.apache.hugegraph.backend.query.Query) ,public void rollback() throws org.apache.hugegraph.backend.BackendException,public org.apache.hugegraph.backend.store.BackendFeatures storeFeatures() ,public boolean storeInitialized() <variables>protected static final Logger LOG,private boolean autoCommit,private boolean closed,private boolean committing,private boolean committing2Backend,private final non-sealed org.apache.hugegraph.HugeGraphParams graph,private org.apache.hugegraph.backend.store.BackendMutation mutation,private final java.lang.Thread ownerThread,protected final non-sealed org.apache.hugegraph.backend.serializer.AbstractSerializer serializer,private final non-sealed org.apache.hugegraph.backend.store.BackendStore store
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/tx/SchemaIndexTransaction.java
|
SchemaIndexTransaction
|
queryByName
|
class SchemaIndexTransaction extends AbstractTransaction {
public SchemaIndexTransaction(HugeGraphParams graph, BackendStore store) {
super(graph, store);
}
@Watched(prefix = "index")
public void updateNameIndex(SchemaElement element, boolean removed) {
if (!this.needIndexForName()) {
return;
}
IndexLabel indexLabel = IndexLabel.label(element.type());
// Update name index if backend store not supports name-query
HugeIndex index = new HugeIndex(this.graph(), indexLabel);
index.fieldValues(element.name());
index.elementIds(element.id());
if (removed) {
this.doEliminate(this.serializer.writeIndex(index));
} else {
this.doAppend(this.serializer.writeIndex(index));
}
}
private boolean needIndexForName() {
return !this.store().features().supportsQuerySchemaByName();
}
@Watched(prefix = "index")
@Override
public QueryResults<BackendEntry> query(Query query) {
if (query instanceof ConditionQuery) {
ConditionQuery q = (ConditionQuery) query;
if (q.allSysprop() && q.conditionsSize() == 1 &&
q.containsCondition(HugeKeys.NAME)) {
return this.queryByName(q);
}
}
return super.query(query);
}
@Watched(prefix = "index")
private QueryResults<BackendEntry> queryByName(ConditionQuery query) {<FILL_FUNCTION_BODY>}
}
|
if (!this.needIndexForName()) {
return super.query(query);
}
IndexLabel il = IndexLabel.label(query.resultType());
String name = query.condition(HugeKeys.NAME);
E.checkState(name != null, "The name in condition can't be null " +
"when querying schema by name");
ConditionQuery indexQuery;
indexQuery = new ConditionQuery(HugeType.SECONDARY_INDEX, query);
indexQuery.eq(HugeKeys.FIELD_VALUES, name);
indexQuery.eq(HugeKeys.INDEX_LABEL_ID, il.id());
IdQuery idQuery = new IdQuery(query.resultType(), query);
Iterator<BackendEntry> entries = super.query(indexQuery).iterator();
try {
while (entries.hasNext()) {
HugeIndex index = this.serializer.readIndex(graph(), indexQuery,
entries.next());
idQuery.query(index.elementIds());
Query.checkForceCapacity(idQuery.idsSize());
}
} finally {
CloseableIterator.closeIterator(entries);
}
if (idQuery.ids().isEmpty()) {
return QueryResults.empty();
}
assert idQuery.idsSize() == 1 : idQuery.ids();
if (idQuery.idsSize() > 1) {
LOG.warn("Multiple ids are found with same name '{}': {}",
name, idQuery.ids());
}
return super.query(idQuery);
| 413
| 392
| 805
|
<methods>public void <init>(org.apache.hugegraph.HugeGraphParams, org.apache.hugegraph.backend.store.BackendStore) ,public boolean autoCommit() ,public void close() ,public void commit() throws org.apache.hugegraph.backend.BackendException,public void commitIfGtSize(int) throws org.apache.hugegraph.backend.BackendException,public void commitOrRollback() ,public void doAppend(org.apache.hugegraph.backend.store.BackendEntry) ,public void doEliminate(org.apache.hugegraph.backend.store.BackendEntry) ,public void doInsert(org.apache.hugegraph.backend.store.BackendEntry) ,public void doRemove(org.apache.hugegraph.backend.store.BackendEntry) ,public void doUpdateIfAbsent(org.apache.hugegraph.backend.store.BackendEntry) ,public void doUpdateIfPresent(org.apache.hugegraph.backend.store.BackendEntry) ,public org.apache.hugegraph.backend.store.BackendEntry get(org.apache.hugegraph.type.HugeType, org.apache.hugegraph.backend.id.Id) ,public org.apache.hugegraph.HugeGraph graph() ,public org.apache.hugegraph.type.define.GraphMode graphMode() ,public java.lang.String graphName() ,public boolean hasUpdate() ,public boolean hasUpdate(org.apache.hugegraph.type.HugeType, org.apache.hugegraph.type.define.Action) ,public transient R metadata(org.apache.hugegraph.type.HugeType, java.lang.String, java.lang.Object[]) ,public int mutationSize() ,public QueryResults<org.apache.hugegraph.backend.store.BackendEntry> query(org.apache.hugegraph.backend.query.Query) ,public org.apache.hugegraph.backend.store.BackendEntry query(org.apache.hugegraph.type.HugeType, org.apache.hugegraph.backend.id.Id) ,public java.lang.Number queryNumber(org.apache.hugegraph.backend.query.Query) ,public void rollback() throws org.apache.hugegraph.backend.BackendException,public org.apache.hugegraph.backend.store.BackendFeatures storeFeatures() ,public boolean storeInitialized() <variables>protected static final Logger LOG,private boolean autoCommit,private boolean closed,private boolean committing,private boolean committing2Backend,private final non-sealed org.apache.hugegraph.HugeGraphParams graph,private org.apache.hugegraph.backend.store.BackendMutation mutation,private final java.lang.Thread ownerThread,protected final non-sealed org.apache.hugegraph.backend.serializer.AbstractSerializer serializer,private final non-sealed org.apache.hugegraph.backend.store.BackendStore store
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/config/AuthOptions.java
|
AuthOptions
|
instance
|
class AuthOptions extends OptionHolder {
private AuthOptions() {
super();
}
private static volatile AuthOptions instance;
public static synchronized AuthOptions instance() {<FILL_FUNCTION_BODY>}
public static final ConfigOption<String> AUTHENTICATOR =
new ConfigOption<>(
"auth.authenticator",
"The class path of authenticator implementation. " +
"e.g., org.apache.hugegraph.auth.StandardAuthenticator, " +
"or org.apache.hugegraph.auth.ConfigAuthenticator.",
null,
""
);
public static final ConfigOption<String> AUTH_GRAPH_STORE =
new ConfigOption<>(
"auth.graph_store",
"The name of graph used to store authentication information, " +
"like users, only for org.apache.hugegraph.auth.StandardAuthenticator.",
disallowEmpty(),
"hugegraph"
);
public static final ConfigOption<String> AUTH_ADMIN_TOKEN =
new ConfigOption<>(
"auth.admin_token",
"Token for administrator operations, " +
"only for org.apache.hugegraph.auth.ConfigAuthenticator.",
disallowEmpty(),
"162f7848-0b6d-4faf-b557-3a0797869c55"
);
public static final ConfigListOption<String> AUTH_USER_TOKENS =
new ConfigListOption<>(
"auth.user_tokens",
"The map of user tokens with name and password, " +
"only for org.apache.hugegraph.auth.ConfigAuthenticator.",
disallowEmpty(),
"hugegraph:9fd95c9c-711b-415b-b85f-d4df46ba5c31"
);
public static final ConfigOption<String> AUTH_REMOTE_URL =
new ConfigOption<>(
"auth.remote_url",
"If the address is empty, it provide auth service, " +
"otherwise it is auth client and also provide auth service " +
"through rpc forwarding. The remote url can be set to " +
"multiple addresses, which are concat by ','.",
null,
""
);
public static final ConfigOption<String> AUTH_TOKEN_SECRET =
new ConfigOption<>(
"auth.token_secret",
"Secret key of HS256 algorithm.",
disallowEmpty(),
"FXQXbJtbCLxODc6tGci732pkH1cyf8Qg"
);
public static final ConfigOption<Double> AUTH_AUDIT_LOG_RATE =
new ConfigOption<>(
"auth.audit_log_rate",
"The max rate of audit log output per user, " +
"default value is 1000 records per second.",
rangeDouble(0.0, Double.MAX_VALUE),
1000.0
);
public static final ConfigOption<Long> AUTH_CACHE_EXPIRE =
new ConfigOption<>(
"auth.cache_expire",
"The expiration time in seconds of auth cache in " +
"auth client and auth server.",
rangeInt(0L, Long.MAX_VALUE),
(60 * 10L)
);
public static final ConfigOption<Long> AUTH_CACHE_CAPACITY =
new ConfigOption<>(
"auth.cache_capacity",
"The max cache capacity of each auth cache item.",
rangeInt(0L, Long.MAX_VALUE),
(1024 * 10L)
);
public static final ConfigOption<Long> AUTH_TOKEN_EXPIRE =
new ConfigOption<>(
"auth.token_expire",
"The expiration time in seconds after token created",
rangeInt(0L, Long.MAX_VALUE),
(3600 * 24L)
);
}
|
if (instance == null) {
instance = new AuthOptions();
instance.registerOptions();
}
return instance;
| 1,044
| 35
| 1,079
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/io/GraphSONSchemaSerializer.java
|
GraphSONSchemaSerializer
|
writePropertyKey
|
class GraphSONSchemaSerializer {
public Map<HugeKeys, Object> writeVertexLabel(VertexLabel vertexLabel) {
HugeGraph graph = vertexLabel.graph();
assert graph != null;
Map<HugeKeys, Object> map = new LinkedHashMap<>();
map.put(HugeKeys.ID, vertexLabel.id().asLong());
map.put(HugeKeys.NAME, vertexLabel.name());
map.put(HugeKeys.ID_STRATEGY, vertexLabel.idStrategy());
map.put(HugeKeys.PRIMARY_KEYS,
graph.mapPkId2Name(vertexLabel.primaryKeys()));
map.put(HugeKeys.NULLABLE_KEYS,
graph.mapPkId2Name(vertexLabel.nullableKeys()));
map.put(HugeKeys.INDEX_LABELS,
graph.mapIlId2Name(vertexLabel.indexLabels()));
map.put(HugeKeys.PROPERTIES,
graph.mapPkId2Name(vertexLabel.properties()));
map.put(HugeKeys.STATUS, vertexLabel.status());
map.put(HugeKeys.TTL, vertexLabel.ttl());
String ttlStartTimeName = vertexLabel.ttlStartTimeName();
if (ttlStartTimeName != null) {
map.put(HugeKeys.TTL_START_TIME, ttlStartTimeName);
}
map.put(HugeKeys.ENABLE_LABEL_INDEX, vertexLabel.enableLabelIndex());
map.put(HugeKeys.USER_DATA, vertexLabel.userdata());
return map;
}
public Map<HugeKeys, Object> writeEdgeLabel(EdgeLabel edgeLabel) {
HugeGraph graph = edgeLabel.graph();
assert graph != null;
Map<HugeKeys, Object> map = new LinkedHashMap<>();
map.put(HugeKeys.ID, edgeLabel.id().asLong());
map.put(HugeKeys.NAME, edgeLabel.name());
map.put(HugeKeys.SOURCE_LABEL, edgeLabel.sourceLabelName());
map.put(HugeKeys.TARGET_LABEL, edgeLabel.targetLabelName());
map.put(HugeKeys.FREQUENCY, edgeLabel.frequency());
map.put(HugeKeys.SORT_KEYS,
graph.mapPkId2Name(edgeLabel.sortKeys()));
map.put(HugeKeys.NULLABLE_KEYS,
graph.mapPkId2Name(edgeLabel.nullableKeys()));
map.put(HugeKeys.INDEX_LABELS,
graph.mapIlId2Name(edgeLabel.indexLabels()));
map.put(HugeKeys.PROPERTIES,
graph.mapPkId2Name(edgeLabel.properties()));
map.put(HugeKeys.STATUS, edgeLabel.status());
map.put(HugeKeys.TTL, edgeLabel.ttl());
String ttlStartTimeName = edgeLabel.ttlStartTimeName();
if (ttlStartTimeName != null) {
map.put(HugeKeys.TTL_START_TIME, ttlStartTimeName);
}
map.put(HugeKeys.ENABLE_LABEL_INDEX, edgeLabel.enableLabelIndex());
map.put(HugeKeys.USER_DATA, edgeLabel.userdata());
return map;
}
public Map<HugeKeys, Object> writePropertyKey(PropertyKey propertyKey) {<FILL_FUNCTION_BODY>}
public Map<HugeKeys, Object> writeIndexLabel(IndexLabel indexLabel) {
HugeGraph graph = indexLabel.graph();
assert graph != null;
Map<HugeKeys, Object> map = new LinkedHashMap<>();
map.put(HugeKeys.ID, indexLabel.id().asLong());
map.put(HugeKeys.NAME, indexLabel.name());
map.put(HugeKeys.BASE_TYPE, indexLabel.baseType());
if (indexLabel.baseType() == HugeType.VERTEX_LABEL) {
map.put(HugeKeys.BASE_VALUE,
graph.vertexLabel(indexLabel.baseValue()).name());
} else {
assert indexLabel.baseType() == HugeType.EDGE_LABEL;
map.put(HugeKeys.BASE_VALUE,
graph.edgeLabel(indexLabel.baseValue()).name());
}
map.put(HugeKeys.INDEX_TYPE, indexLabel.indexType());
map.put(HugeKeys.FIELDS, graph.mapPkId2Name(indexLabel.indexFields()));
map.put(HugeKeys.STATUS, indexLabel.status());
map.put(HugeKeys.USER_DATA, indexLabel.userdata());
return map;
}
}
|
HugeGraph graph = propertyKey.graph();
assert graph != null;
Map<HugeKeys, Object> map = new LinkedHashMap<>();
map.put(HugeKeys.ID, propertyKey.id().asLong());
map.put(HugeKeys.NAME, propertyKey.name());
map.put(HugeKeys.DATA_TYPE, propertyKey.dataType());
map.put(HugeKeys.CARDINALITY, propertyKey.cardinality());
map.put(HugeKeys.AGGREGATE_TYPE, propertyKey.aggregateType());
map.put(HugeKeys.WRITE_TYPE, propertyKey.writeType());
map.put(HugeKeys.PROPERTIES,
graph.mapPkId2Name(propertyKey.properties()));
map.put(HugeKeys.STATUS, propertyKey.status());
map.put(HugeKeys.USER_DATA, propertyKey.userdata());
return map;
| 1,211
| 240
| 1,451
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/io/HugeGraphSONModule.java
|
HugeElementSerializer
|
writePropertiesField
|
class HugeElementSerializer<T extends HugeElement>
extends StdSerializer<T> {
public HugeElementSerializer(Class<T> clazz) {
super(clazz);
}
public void writeIdField(String fieldName, Id id,
JsonGenerator generator)
throws IOException {
generator.writeFieldName(fieldName);
if (id.number()) {
generator.writeNumber(id.asLong());
} else {
generator.writeString(id.asString());
}
}
public void writePropertiesField(Collection<HugeProperty<?>> properties,
JsonGenerator generator,
SerializerProvider provider)
throws IOException {<FILL_FUNCTION_BODY>}
}
|
// Start write properties
generator.writeFieldName("properties");
generator.writeStartObject();
for (HugeProperty<?> property : properties) {
String key = property.key();
Object val = property.value();
try {
generator.writeFieldName(key);
if (val != null) {
JsonSerializer<Object> serializer =
provider.findValueSerializer(val.getClass());
serializer.serialize(val, generator, provider);
} else {
generator.writeNull();
}
} catch (IOException e) {
throw new HugeException(
"Failed to serialize property(%s: %s) " +
"for vertex '%s'", key, val, property.element());
}
}
// End write properties
generator.writeEndObject();
| 184
| 208
| 392
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/io/HugeGryoModule.java
|
EdgeIdSerializer
|
writeEntry
|
class EdgeIdSerializer extends Serializer<EdgeId> {
@Override
public void write(Kryo kryo, Output output, EdgeId edgeId) {
byte[] idBytes = edgeId.asBytes();
output.write(idBytes.length);
output.writeBytes(edgeId.asBytes());
}
@Override
public EdgeId read(Kryo kryo, Input input, Class<EdgeId> clazz) {
int length = input.read();
byte[] idBytes = input.readBytes(length);
return EdgeId.parse(StringEncoding.decode(idBytes));
}
}
private static void writeEntry(Kryo kryo,
Output output,
Map<HugeKeys, Object> schema) {<FILL_FUNCTION_BODY>
|
/* Write columns size and data */
output.writeInt(schema.keySet().size());
for (Map.Entry<HugeKeys, Object> entry : schema.entrySet()) {
kryo.writeObject(output, entry.getKey());
kryo.writeClassAndObject(output, entry.getValue());
}
| 201
| 84
| 285
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/AlgorithmJob.java
|
AlgorithmJob
|
execute
|
class AlgorithmJob extends UserJob<Object> {
public static final String TASK_TYPE = "algorithm";
public static boolean check(String name, Map<String, Object> parameters) {
Algorithm algorithm = AlgorithmPool.instance().find(name);
if (algorithm == null) {
return false;
}
algorithm.checkParameters(parameters);
return true;
}
@Override
public String type() {
return TASK_TYPE;
}
@Override
public Object execute() throws Exception {<FILL_FUNCTION_BODY>}
}
|
String input = this.task().input();
E.checkArgumentNotNull(input, "The input can't be null");
@SuppressWarnings("unchecked")
Map<String, Object> map = JsonUtil.fromJson(input, Map.class);
Object value = map.get("algorithm");
E.checkArgument(value instanceof String,
"Invalid algorithm name '%s'", value);
String name = (String) value;
value = map.get("parameters");
E.checkArgument(value instanceof Map,
"Invalid algorithm parameters '%s'", value);
@SuppressWarnings("unchecked")
Map<String, Object> parameters = (Map<String, Object>) value;
AlgorithmPool pool = AlgorithmPool.instance();
Algorithm algorithm = pool.find(name);
E.checkArgument(algorithm != null,
"There is no algorithm named '%s'", name);
return algorithm.call(this, parameters);
| 145
| 238
| 383
|
<methods>public non-sealed void <init>() ,public java.lang.Object call() throws java.lang.Exception<variables>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/ComputerJob.java
|
ComputerJob
|
execute
|
class ComputerJob extends SysJob<Object> {
public static final String COMPUTER = "computer";
public static boolean check(String name, Map<String, Object> parameters) {
Computer computer = ComputerPool.instance().find(name);
if (computer == null) {
return false;
}
computer.checkParameters(parameters);
return true;
}
public String computerConfigPath() {
return this.params().configuration().get(CoreOptions.COMPUTER_CONFIG);
}
@Override
public String type() {
return COMPUTER;
}
@Override
public Object execute() throws Exception {<FILL_FUNCTION_BODY>}
}
|
String input = this.task().input();
E.checkArgumentNotNull(input, "The input can't be null");
@SuppressWarnings("unchecked")
Map<String, Object> map = JsonUtil.fromJson(input, Map.class);
Object value = map.get("computer");
E.checkArgument(value instanceof String,
"Invalid computer name '%s'", value);
String name = (String) value;
value = map.get("parameters");
E.checkArgument(value instanceof Map,
"Invalid computer parameters '%s'", value);
@SuppressWarnings("unchecked")
Map<String, Object> parameters = (Map<String, Object>) value;
ComputerPool pool = ComputerPool.instance();
Computer computer = pool.find(name);
E.checkArgument(computer != null,
"There is no computer method named '%s'", name);
return computer.call(this, parameters);
| 179
| 241
| 420
|
<methods>public non-sealed void <init>() ,public java.lang.Object call() throws java.lang.Exception<variables>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/EphemeralJobBuilder.java
|
EphemeralJobBuilder
|
schedule
|
class EphemeralJobBuilder<V> {
private final HugeGraph graph;
private String name;
private String input;
private EphemeralJob<V> job;
// Use negative task id for ephemeral task
private static int ephemeralTaskId = -1;
public static <T> EphemeralJobBuilder<T> of(final HugeGraph graph) {
return new EphemeralJobBuilder<>(graph);
}
public EphemeralJobBuilder(final HugeGraph graph) {
this.graph = graph;
}
public EphemeralJobBuilder<V> name(String name) {
this.name = name;
return this;
}
public EphemeralJobBuilder<V> input(String input) {
this.input = input;
return this;
}
public EphemeralJobBuilder<V> job(EphemeralJob<V> job) {
this.job = job;
return this;
}
public HugeTask<V> schedule() {<FILL_FUNCTION_BODY>}
private Id genTaskId() {
if (ephemeralTaskId >= 0) {
ephemeralTaskId = -1;
}
return IdGenerator.of(ephemeralTaskId--);
}
}
|
E.checkArgumentNotNull(this.name, "Job name can't be null");
E.checkArgumentNotNull(this.job, "Job can't be null");
HugeTask<V> task = new HugeTask<>(this.genTaskId(), null, this.job);
task.type(this.job.type());
task.name(this.name);
if (this.input != null) {
task.input(this.input);
}
TaskScheduler scheduler = this.graph.taskScheduler();
scheduler.schedule(task);
return task;
| 346
| 153
| 499
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/GremlinJob.java
|
GremlinJob
|
execute
|
class GremlinJob extends UserJob<Object> {
public static final String TASK_TYPE = "gremlin";
public static final String TASK_BIND_NAME = "gremlinJob";
public static final int TASK_RESULTS_MAX_SIZE = (int) Query.DEFAULT_CAPACITY;
@Override
public String type() {
return TASK_TYPE;
}
@Override
public Object execute() throws Exception {<FILL_FUNCTION_BODY>}
private void checkResultsSize(Object results) {
int size = 0;
if (results instanceof Collection) {
size = ((Collection<?>) results).size();
}
if (size > TASK_RESULTS_MAX_SIZE) {
throw new LimitExceedException(
"Job results size %s has exceeded the max limit %s",
size, TASK_RESULTS_MAX_SIZE);
}
}
/**
* Used by gremlin script
*/
@SuppressWarnings("unused")
private class GremlinJobProxy {
public void setMinSaveInterval(long seconds) {
GremlinJob.this.setMinSaveInterval(seconds);
}
public void updateProgress(int progress) {
GremlinJob.this.updateProgress(progress);
}
public int progress() {
return GremlinJob.this.progress();
}
}
}
|
String input = this.task().input();
E.checkArgumentNotNull(input, "The input can't be null");
@SuppressWarnings("unchecked")
Map<String, Object> map = JsonUtil.fromJson(input, Map.class);
Object value = map.get("gremlin");
E.checkArgument(value instanceof String,
"Invalid gremlin value '%s'", value);
String gremlin = (String) value;
value = map.get("bindings");
E.checkArgument(value instanceof Map,
"Invalid bindings value '%s'", value);
@SuppressWarnings("unchecked")
Map<String, Object> bindings = (Map<String, Object>) value;
value = map.get("language");
E.checkArgument(value instanceof String,
"Invalid language value '%s'", value);
String language = (String) value;
value = map.get("aliases");
E.checkArgument(value instanceof Map,
"Invalid aliases value '%s'", value);
@SuppressWarnings("unchecked")
Map<String, String> aliases = (Map<String, String>) value;
bindings.put(TASK_BIND_NAME, new GremlinJobProxy());
HugeScriptTraversal<?, ?> traversal = new HugeScriptTraversal<>(
this.graph().traversal(),
language, gremlin,
bindings, aliases);
List<Object> results = new ArrayList<>();
long capacity = Query.defaultCapacity(Query.NO_CAPACITY);
try {
while (traversal.hasNext()) {
Object result = traversal.next();
results.add(result);
checkResultsSize(results);
Thread.yield();
}
} finally {
Query.defaultCapacity(capacity);
traversal.close();
this.graph().tx().commit();
}
Object result = traversal.result();
if (result != null) {
checkResultsSize(result);
return result;
} else {
return results;
}
| 367
| 544
| 911
|
<methods>public non-sealed void <init>() ,public java.lang.Object call() throws java.lang.Exception<variables>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/JobBuilder.java
|
JobBuilder
|
schedule
|
class JobBuilder<V> {
private final HugeGraph graph;
private String name;
private String input;
private Job<V> job;
private Set<Id> dependencies;
public static <T> JobBuilder<T> of(final HugeGraph graph) {
return new JobBuilder<>(graph);
}
public JobBuilder(final HugeGraph graph) {
this.graph = graph;
}
public JobBuilder<V> name(String name) {
this.name = name;
return this;
}
public JobBuilder<V> input(String input) {
this.input = input;
return this;
}
public JobBuilder<V> job(Job<V> job) {
this.job = job;
return this;
}
public JobBuilder<V> dependencies(Set<Id> dependencies) {
this.dependencies = dependencies;
return this;
}
public HugeTask<V> schedule() {<FILL_FUNCTION_BODY>}
private Id genTaskId() {
return this.graph.getNextId(HugeType.TASK);
}
}
|
E.checkArgumentNotNull(this.name, "Job name can't be null");
E.checkArgumentNotNull(this.job, "Job callable can't be null");
E.checkArgument(this.job instanceof TaskCallable,
"Job must be instance of TaskCallable");
this.graph.taskScheduler().checkRequirement("schedule");
@SuppressWarnings("unchecked")
TaskCallable<V> job = (TaskCallable<V>) this.job;
HugeTask<V> task = new HugeTask<>(this.genTaskId(), null, job);
task.type(this.job.type());
task.name(this.name);
if (this.input != null) {
task.input(this.input);
}
if (this.dependencies != null && !this.dependencies.isEmpty()) {
for (Id depend : this.dependencies) {
task.depends(depend);
}
}
TaskScheduler scheduler = this.graph.taskScheduler();
scheduler.schedule(task);
return task;
| 298
| 282
| 580
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/algorithm/AbstractAlgorithm.java
|
TopMap
|
shrinkIfNeeded
|
class TopMap<K> {
private final long topN;
private Map<K, MutableLong> tops;
public TopMap(long topN) {
this.topN = topN;
this.tops = new HashMap<>();
}
public int size() {
return this.tops.size();
}
public MutableLong get(K key) {
return this.tops.get(key);
}
public void add(K key, long value) {
MutableLong mlong = this.tops.get(key);
if (mlong == null) {
mlong = new MutableLong(value);
this.tops.put(key, mlong);
}
mlong.add(value);
}
public void put(K key, long value) {
assert this.topN != 0L;
this.tops.put(key, new MutableLong(value));
// keep 2x buffer
if (this.tops.size() > this.topN * 2 &&
this.topN != HugeTraverser.NO_LIMIT) {
this.shrinkIfNeeded(this.topN);
}
}
public Set<Map.Entry<K, MutableLong>> entrySet() {
if (this.tops.size() <= this.topN) {
this.tops = CollectionUtil.sortByValue(this.tops, false);
} else {
this.shrinkIfNeeded(this.topN);
}
return this.tops.entrySet();
}
private void shrinkIfNeeded(long limit) {<FILL_FUNCTION_BODY>}
}
|
assert limit != 0L;
if (this.tops.size() >= limit &&
(limit > 0L || limit == HugeTraverser.NO_LIMIT)) {
// Just do sort if limit=NO_LIMIT, else do sort and shrink
this.tops = HugeTraverser.topN(this.tops, true, limit);
}
| 438
| 95
| 533
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/algorithm/AlgorithmPool.java
|
AlgorithmPool
|
get
|
class AlgorithmPool {
private static final AlgorithmPool INSTANCE = new AlgorithmPool();
static {
INSTANCE.register(new CountVertexAlgorithm());
INSTANCE.register(new CountEdgeAlgorithm());
INSTANCE.register(new DegreeCentralityAlgorithm());
INSTANCE.register(new StressCentralityAlgorithm());
INSTANCE.register(new BetweennessCentralityAlgorithm());
INSTANCE.register(new ClosenessCentralityAlgorithm());
INSTANCE.register(new EigenvectorCentralityAlgorithm());
INSTANCE.register(new TriangleCountAlgorithm());
INSTANCE.register(new ClusterCoefficientAlgorithm());
INSTANCE.register(new LpaAlgorithm());
INSTANCE.register(new LouvainAlgorithm());
INSTANCE.register(new WeakConnectedComponent());
INSTANCE.register(new FusiformSimilarityAlgorithm());
INSTANCE.register(new RingsDetectAlgorithm());
INSTANCE.register(new KCoreAlgorithm());
INSTANCE.register(new PageRankAlgorithm());
INSTANCE.register(new SubgraphStatAlgorithm());
INSTANCE.register(new StressCentralityAlgorithmV2());
INSTANCE.register(new BetweennessCentralityAlgorithmV2());
INSTANCE.register(new ClosenessCentralityAlgorithmV2());
}
private final Map<String, Algorithm> algorithms;
public AlgorithmPool() {
this.algorithms = new ConcurrentHashMap<>();
}
public Algorithm register(Algorithm algo) {
assert !this.algorithms.containsKey(algo.name());
return this.algorithms.put(algo.name(), algo);
}
public Algorithm find(String name) {
return this.algorithms.get(name);
}
public Algorithm get(String name) {<FILL_FUNCTION_BODY>}
public static AlgorithmPool instance() {
return INSTANCE;
}
}
|
Algorithm algorithm = this.algorithms.get(name);
E.checkArgument(algorithm != null,
"Not found algorithm '%s'", name);
return algorithm;
| 519
| 46
| 565
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/algorithm/BfsTraverser.java
|
Node
|
addParent
|
class Node {
private Id[] parents;
private int pathCount;
private final int distance;
public Node(Node parentNode) {
this(0, parentNode.distance + 1);
}
public Node(int pathCount, int distance) {
this.pathCount = pathCount;
this.distance = distance;
this.parents = new Id[0];
}
public int distance() {
return this.distance;
}
public Id[] parents() {
return this.parents;
}
public void addParent(Id parentId) {<FILL_FUNCTION_BODY>}
public void addParentNode(Node node, Id parentId) {
this.pathCount += node.pathCount;
this.addParent(parentId);
}
protected int pathCount() {
return this.pathCount;
}
}
|
// TODO: test if need to allocate more memory in advance
Id[] newParents = new Id[this.parents.length + 1];
System.arraycopy(this.parents, 0, newParents, 0,
this.parents.length);
newParents[newParents.length - 1] = parentId;
this.parents = newParents;
| 226
| 95
| 321
|
<methods>public void <init>(UserJob<java.lang.Object>) ,public void close() ,public org.apache.hugegraph.backend.id.Id jobId() ,public void updateProgress(long) <variables>protected final non-sealed java.util.concurrent.ExecutorService executor,private final non-sealed UserJob<java.lang.Object> job,protected long progress
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/algorithm/Consumers.java
|
Consumers
|
consume
|
class Consumers<V> {
public static final int CPUS = Runtime.getRuntime().availableProcessors();
public static final int THREADS = 4 + CPUS / 4;
public static final int QUEUE_WORKER_SIZE = 1000;
private static final Logger LOG = Log.logger(Consumers.class);
private final ExecutorService executor;
private final Consumer<V> consumer;
private final Runnable done;
private final int workers;
private final int queueSize;
private final CountDownLatch latch;
private final BlockingQueue<V> queue;
private volatile boolean ending = false;
private volatile Throwable exception = null;
public Consumers(ExecutorService executor, Consumer<V> consumer) {
this(executor, consumer, null);
}
public Consumers(ExecutorService executor,
Consumer<V> consumer, Runnable done) {
this.executor = executor;
this.consumer = consumer;
this.done = done;
int workers = THREADS;
if (this.executor instanceof ThreadPoolExecutor) {
workers = ((ThreadPoolExecutor) this.executor).getCorePoolSize();
}
this.workers = workers;
this.queueSize = QUEUE_WORKER_SIZE * workers;
this.latch = new CountDownLatch(workers);
this.queue = new ArrayBlockingQueue<>(this.queueSize);
}
public void start(String name) {
this.ending = false;
this.exception = null;
if (this.executor == null) {
return;
}
LOG.info("Starting {} workers[{}] with queue size {}...",
this.workers, name, this.queueSize);
for (int i = 0; i < this.workers; i++) {
this.executor.submit(new ContextCallable<>(this::runAndDone));
}
}
private Void runAndDone() {
try {
this.run();
this.done();
} catch (Throwable e) {
// Only the first exception to one thread can be stored
this.exception = e;
if (!(e instanceof StopExecution)) {
LOG.error("Error when running task", e);
}
this.done();
} finally {
this.latch.countDown();
}
return null;
}
private void run() {
LOG.debug("Start to work...");
while (!this.ending) {
this.consume();
}
assert this.ending;
while (this.consume()) {
}
LOG.debug("Worker finished");
}
private boolean consume() {<FILL_FUNCTION_BODY>}
private void done() {
if (this.done != null) {
this.done.run();
}
}
public void provide(V v) throws Throwable {
if (this.executor == null) {
assert this.exception == null;
// do job directly if without thread pool
this.consumer.accept(v);
} else if (this.exception != null) {
throw this.exception;
} else {
try {
this.queue.put(v);
} catch (InterruptedException e) {
LOG.warn("Interrupted", e);
}
}
}
public void await() {
this.ending = true;
if (this.executor == null) {
// call done() directly if without thread pool
this.done();
} else {
try {
this.latch.await();
} catch (InterruptedException e) {
LOG.warn("Interrupted", e);
}
}
}
public static ExecutorService newThreadPool(String prefix, int workers) {
if (workers == 0) {
return null;
} else {
if (workers < 0) {
assert workers == -1;
workers = Consumers.THREADS;
} else if (workers > Consumers.CPUS * 2) {
workers = Consumers.CPUS * 2;
}
String name = prefix + "-worker-%d";
return ExecutorUtil.newFixedThreadPool(workers, name);
}
}
public static RuntimeException wrapException(Throwable e) {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new HugeException("Error when running task: %s",
HugeException.rootCause(e).getMessage(), e);
}
public static class StopExecution extends HugeException {
private static final long serialVersionUID = -371829356182454517L;
public StopExecution(String message) {
super(message);
}
public StopExecution(String message, Object... args) {
super(message, args);
}
}
}
|
V elem;
try {
elem = this.queue.poll(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// ignore
return true;
}
if (elem == null) {
return false;
}
// do job
this.consumer.accept(elem);
return true;
| 1,281
| 93
| 1,374
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/algorithm/CountEdgeAlgorithm.java
|
Traverser
|
count
|
class Traverser extends AlgoTraverser {
public Traverser(UserJob<Object> job) {
super(job);
}
public Object count() {<FILL_FUNCTION_BODY>}
}
|
Iterator<Edge> edges = this.edges(null);
Map<String, MutableLong> counts = new HashMap<>();
long total = 0L;
while (edges.hasNext()) {
Edge edge = edges.next();
String label = edge.label();
MutableLong count = counts.get(label);
if (count != null) {
count.increment();
} else {
counts.put(label, new MutableLong(1L));
}
total++;
this.updateProgress(total);
}
counts.put("*", new MutableLong(total));
return JsonUtil.asJson(counts);
| 60
| 174
| 234
|
<methods>public non-sealed void <init>() ,public void checkParameters(Map<java.lang.String,java.lang.Object>) <variables>public static final int BATCH,public static final java.lang.String CATEGORY_AGGR,public static final java.lang.String CATEGORY_CENT,public static final java.lang.String CATEGORY_COMM,public static final java.lang.String CATEGORY_PATH,public static final java.lang.String CATEGORY_RANK,public static final java.lang.String CATEGORY_SIMI,public static final java.lang.String C_LABEL,public static final double DEFAULT_ALPHA,public static final long DEFAULT_CAPACITY,public static final long DEFAULT_DEGREE,public static final long DEFAULT_EACH_LIMIT,public static final long DEFAULT_LIMIT,public static final double DEFAULT_PRECISION,public static final long DEFAULT_SAMPLE,public static final long DEFAULT_STABLE_TIMES,public static final long DEFAULT_TIMES,public static final java.lang.String EXPORT_PATH,public static final java.lang.String KEY_ALPHA,public static final java.lang.String KEY_CAPACITY,public static final java.lang.String KEY_CLEAR,public static final java.lang.String KEY_DEGREE,public static final java.lang.String KEY_DEPTH,public static final java.lang.String KEY_DIRECTION,public static final java.lang.String KEY_EACH_LIMIT,public static final java.lang.String KEY_EXPORT_COMM,public static final java.lang.String KEY_LABEL,public static final java.lang.String KEY_LIMIT,public static final java.lang.String KEY_PRECISION,public static final java.lang.String KEY_SAMPLE,public static final java.lang.String KEY_SHOW_COMM,public static final java.lang.String KEY_SHOW_MOD,public static final java.lang.String KEY_SKIP_ISOLATED,public static final java.lang.String KEY_SOURCE_CLABEL,public static final java.lang.String KEY_SOURCE_LABEL,public static final java.lang.String KEY_SOURCE_SAMPLE,public static final java.lang.String KEY_STABLE_TIMES,public static final java.lang.String KEY_TIMES,public static final java.lang.String KEY_TOP,public static final java.lang.String KEY_WORKERS,public static final long MAX_CAPACITY,public static final long MAX_QUERY_LIMIT,public static final long MAX_RESULT_SIZE,public static final java.lang.String R_RANK,public static final java.lang.String USER_DIR
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/algorithm/CountVertexAlgorithm.java
|
Traverser
|
count
|
class Traverser extends AlgoTraverser {
public Traverser(UserJob<Object> job) {
super(job);
}
public Object count() {<FILL_FUNCTION_BODY>}
}
|
Iterator<Vertex> vertices = this.vertices();
Map<String, MutableLong> counts = new HashMap<>();
long total = 0L;
while (vertices.hasNext()) {
Vertex vertex = vertices.next();
String label = vertex.label();
MutableLong count = counts.get(label);
if (count != null) {
count.increment();
} else {
counts.put(label, new MutableLong(1L));
}
total++;
this.updateProgress(total);
}
counts.put("*", new MutableLong(total));
return JsonUtil.asJson(counts);
| 60
| 173
| 233
|
<methods>public non-sealed void <init>() ,public void checkParameters(Map<java.lang.String,java.lang.Object>) <variables>public static final int BATCH,public static final java.lang.String CATEGORY_AGGR,public static final java.lang.String CATEGORY_CENT,public static final java.lang.String CATEGORY_COMM,public static final java.lang.String CATEGORY_PATH,public static final java.lang.String CATEGORY_RANK,public static final java.lang.String CATEGORY_SIMI,public static final java.lang.String C_LABEL,public static final double DEFAULT_ALPHA,public static final long DEFAULT_CAPACITY,public static final long DEFAULT_DEGREE,public static final long DEFAULT_EACH_LIMIT,public static final long DEFAULT_LIMIT,public static final double DEFAULT_PRECISION,public static final long DEFAULT_SAMPLE,public static final long DEFAULT_STABLE_TIMES,public static final long DEFAULT_TIMES,public static final java.lang.String EXPORT_PATH,public static final java.lang.String KEY_ALPHA,public static final java.lang.String KEY_CAPACITY,public static final java.lang.String KEY_CLEAR,public static final java.lang.String KEY_DEGREE,public static final java.lang.String KEY_DEPTH,public static final java.lang.String KEY_DIRECTION,public static final java.lang.String KEY_EACH_LIMIT,public static final java.lang.String KEY_EXPORT_COMM,public static final java.lang.String KEY_LABEL,public static final java.lang.String KEY_LIMIT,public static final java.lang.String KEY_PRECISION,public static final java.lang.String KEY_SAMPLE,public static final java.lang.String KEY_SHOW_COMM,public static final java.lang.String KEY_SHOW_MOD,public static final java.lang.String KEY_SKIP_ISOLATED,public static final java.lang.String KEY_SOURCE_CLABEL,public static final java.lang.String KEY_SOURCE_LABEL,public static final java.lang.String KEY_SOURCE_SAMPLE,public static final java.lang.String KEY_STABLE_TIMES,public static final java.lang.String KEY_TIMES,public static final java.lang.String KEY_TOP,public static final java.lang.String KEY_WORKERS,public static final long MAX_CAPACITY,public static final long MAX_QUERY_LIMIT,public static final long MAX_RESULT_SIZE,public static final java.lang.String R_RANK,public static final java.lang.String USER_DIR
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/algorithm/SubgraphStatAlgorithm.java
|
SubgraphStatAlgorithm
|
call
|
class SubgraphStatAlgorithm extends AbstractAlgorithm {
public static final String KEY_SUBGRAPH = "subgraph";
public static final String KEY_COPY_SCHEMA = "copy_schema";
private static final Logger LOG = Log.logger(SubgraphStatAlgorithm.class);
@Override
public String name() {
return "subgraph_stat";
}
@Override
public String category() {
return CATEGORY_AGGR;
}
@Override
public void checkParameters(Map<String, Object> parameters) {
subgraph(parameters);
}
@Override
public Object call(UserJob<Object> job, Map<String, Object> parameters) {<FILL_FUNCTION_BODY>}
private HugeGraph createTempGraph(UserJob<Object> job) {
Id id = job.task().id();
String name = "tmp_" + id;
PropertiesConfiguration config = new PropertiesConfiguration();
config.setProperty(CoreOptions.BACKEND.name(), "memory");
config.setProperty(CoreOptions.STORE.name(), name);
/*
* NOTE: this temp graph don't need to init backend because no task info
* required, also not set started because no task to be scheduled.
*/
return new StandardHugeGraph(new HugeConfig(config));
}
@SuppressWarnings("resource")
private void initGraph(HugeGraph parent, HugeGraph graph,
String script, boolean copySchema) {
if (copySchema) {
graph.schema().copyFrom(parent.schema());
}
new HugeScriptTraversal<>(graph.traversal(), "gremlin-groovy",
script, ImmutableMap.of(),
ImmutableMap.of()).iterate();
graph.tx().commit();
}
protected static String subgraph(Map<String, Object> parameters) {
Object subgraph = parameters.get(KEY_SUBGRAPH);
E.checkArgument(subgraph != null,
"Must pass parameter '%s'", KEY_SUBGRAPH);
E.checkArgument(subgraph instanceof String,
"Invalid parameter '%s', expect a String, but got %s",
KEY_SUBGRAPH, subgraph.getClass().getSimpleName());
return (String) subgraph;
}
protected static boolean copySchema(Map<String, Object> parameters) {
if (!parameters.containsKey(KEY_COPY_SCHEMA)) {
return false;
}
return ParameterUtil.parameterBoolean(parameters, KEY_COPY_SCHEMA);
}
private static class Traverser extends AlgoTraverser {
private static final Map<String, Object> PARAMS = ImmutableMap.of("depth", 10L,
"degree", -1L,
"sample", -1L,
"top", -1L /* sorted */,
"workers", 0);
public Traverser(UserJob<Object> job) {
super(job);
}
public Object subgraphStat(UserJob<Object> job) {
AlgorithmPool pool = AlgorithmPool.instance();
Map<String, Object> results = InsertionOrderUtil.newMap();
GraphTraversalSource g = job.graph().traversal();
results.put("vertices_count", g.V().count().next());
results.put("edges_count", g.E().count().next());
Algorithm algo = pool.get("degree_centrality");
Map<String, Object> parameters = ImmutableMap.copyOf(PARAMS);
results.put("degrees", algo.call(job, parameters));
algo = pool.get("stress_centrality");
results.put("stress", algo.call(job, parameters));
algo = pool.get("betweenness_centrality");
results.put("betweenness", algo.call(job, parameters));
algo = pool.get("eigenvector_centrality");
results.put("eigenvectors", algo.call(job, parameters));
algo = pool.get("closeness_centrality");
results.put("closeness", algo.call(job, parameters));
results.put("page_ranks", pageRanks(job));
algo = pool.get("cluster_coefficient");
results.put("cluster_coefficient", algo.call(job, parameters));
algo = pool.get("rings");
parameters = ImmutableMap.<String, Object>builder()
.putAll(PARAMS)
.put("count_only", true)
.put("each_limit", NO_LIMIT)
.put("limit", NO_LIMIT)
.build();
results.put("rings", algo.call(job, parameters));
return results;
}
private Map<Object, Double> pageRanks(UserJob<Object> job) {
Algorithm algo = AlgorithmPool.instance().get("page_rank");
algo.call(job, ImmutableMap.of("alpha", 0.15));
// Collect page ranks
Map<Object, Double> ranks = InsertionOrderUtil.newMap();
Iterator<Vertex> vertices = job.graph().vertices();
while (vertices.hasNext()) {
Vertex vertex = vertices.next();
ranks.put(vertex.id(), vertex.value(R_RANK));
}
ranks = HugeTraverser.topN(ranks, true, NO_LIMIT);
return ranks;
}
}
private static class TempJob<V> extends UserJob<V> {
private final UserJob<V> parent;
public TempJob(HugeGraph graph, UserJob<V> job, HugeTask<V> task) {
this.graph(graph);
this.task(task);
this.parent = job;
}
@Override
public String type() {
return "temp";
}
@Override
public V execute() throws Exception {
return null;
}
@Override
public void updateProgress(int progress) {
this.parent.updateProgress(progress);
}
}
}
|
HugeGraph graph = this.createTempGraph(job);
try (Traverser traverser = new Traverser(job)) {
this.initGraph(job.graph(), graph,
subgraph(parameters), copySchema(parameters));
UserJob<Object> tmpJob = new TempJob<>(graph, job, job.task());
return traverser.subgraphStat(tmpJob);
} finally {
// Use clearBackend instead of truncateBackend due to no server-id
graph.clearBackend();
try {
graph.close();
} catch (Throwable e) {
LOG.warn("Can't close subgraph_stat temp graph {}: {}",
graph, e.getMessage(), e);
}
}
| 1,561
| 188
| 1,749
|
<methods>public non-sealed void <init>() ,public void checkParameters(Map<java.lang.String,java.lang.Object>) <variables>public static final int BATCH,public static final java.lang.String CATEGORY_AGGR,public static final java.lang.String CATEGORY_CENT,public static final java.lang.String CATEGORY_COMM,public static final java.lang.String CATEGORY_PATH,public static final java.lang.String CATEGORY_RANK,public static final java.lang.String CATEGORY_SIMI,public static final java.lang.String C_LABEL,public static final double DEFAULT_ALPHA,public static final long DEFAULT_CAPACITY,public static final long DEFAULT_DEGREE,public static final long DEFAULT_EACH_LIMIT,public static final long DEFAULT_LIMIT,public static final double DEFAULT_PRECISION,public static final long DEFAULT_SAMPLE,public static final long DEFAULT_STABLE_TIMES,public static final long DEFAULT_TIMES,public static final java.lang.String EXPORT_PATH,public static final java.lang.String KEY_ALPHA,public static final java.lang.String KEY_CAPACITY,public static final java.lang.String KEY_CLEAR,public static final java.lang.String KEY_DEGREE,public static final java.lang.String KEY_DEPTH,public static final java.lang.String KEY_DIRECTION,public static final java.lang.String KEY_EACH_LIMIT,public static final java.lang.String KEY_EXPORT_COMM,public static final java.lang.String KEY_LABEL,public static final java.lang.String KEY_LIMIT,public static final java.lang.String KEY_PRECISION,public static final java.lang.String KEY_SAMPLE,public static final java.lang.String KEY_SHOW_COMM,public static final java.lang.String KEY_SHOW_MOD,public static final java.lang.String KEY_SKIP_ISOLATED,public static final java.lang.String KEY_SOURCE_CLABEL,public static final java.lang.String KEY_SOURCE_LABEL,public static final java.lang.String KEY_SOURCE_SAMPLE,public static final java.lang.String KEY_STABLE_TIMES,public static final java.lang.String KEY_TIMES,public static final java.lang.String KEY_TOP,public static final java.lang.String KEY_WORKERS,public static final long MAX_CAPACITY,public static final long MAX_QUERY_LIMIT,public static final long MAX_RESULT_SIZE,public static final java.lang.String R_RANK,public static final java.lang.String USER_DIR
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/algorithm/cent/AbstractCentAlgorithm.java
|
Traverser
|
substractPath
|
class Traverser extends AlgoTraverser {
public Traverser(UserJob<Object> job) {
super(job);
}
protected GraphTraversal<Vertex, Vertex> constructSource(
String sourceLabel,
long sourceSample,
String sourceCLabel) {
GraphTraversal<Vertex, Vertex> t = this.graph().traversal()
.withSack(1f).V();
if (sourceLabel != null) {
t = t.hasLabel(sourceLabel);
}
t = t.filter(it -> {
this.updateProgress(++this.progress);
return sourceCLabel == null || match(it.get(), sourceCLabel);
});
if (sourceSample > 0L) {
t = t.sample((int) sourceSample);
}
return t;
}
protected GraphTraversal<Vertex, Vertex> constructPath(
GraphTraversal<Vertex, Vertex> t, Directions dir,
String label, long degree, long sample,
String sourceLabel, String sourceCLabel) {
GraphTraversal<?, Vertex> unit = constructPathUnit(dir, label,
degree, sample,
sourceLabel,
sourceCLabel);
t = t.as("v").repeat(__.local(unit).simplePath().as("v"));
return t;
}
protected GraphTraversal<Vertex, Vertex> constructPathUnit(
Directions dir, String label,
long degree, long sample,
String sourceLabel,
String sourceCLabel) {
if (dir == null) {
dir = Directions.BOTH;
}
Direction direction = dir.direction();
String[] labels = {};
if (label != null) {
labels = new String[]{label};
}
GraphTraversal<Vertex, Vertex> unit = __.to(direction, labels);
if (sourceLabel != null) {
unit = unit.hasLabel(sourceLabel);
}
if (sourceCLabel != null) {
unit = unit.has(C_LABEL, sourceCLabel);
}
if (degree != NO_LIMIT) {
unit = unit.limit(degree);
}
if (sample > 0L) {
unit = unit.sample((int) sample);
}
return unit;
}
protected <V> GraphTraversal<V, V> filterNonShortestPath(
GraphTraversal<V, V> t,
boolean keepOneShortestPath) {
long size = this.graph().traversal().V().limit(100000L)
.count().next();
Map<Pair<Id, Id>, Integer> triples = new HashMap<>((int) size);
return t.filter(it -> {
Id start = it.<HugeElement>path(Pop.first, "v").id();
Id end = it.<HugeElement>path(Pop.last, "v").id();
int len = it.path().size();
assert len == it.<List<?>>path(Pop.all, "v").size();
Pair<Id, Id> key = Pair.of(start, end);
Integer shortest = triples.get(key);
if (shortest != null && len > shortest) {
// ignore non shortest path
return false;
}
// TODO: len may be smaller than shortest
if (shortest == null) {
triples.put(key, len);
} else {
assert len == shortest;
return !keepOneShortestPath;
}
return true;
});
}
protected GraphTraversal<Vertex, Id> substractPath(
GraphTraversal<Vertex, Vertex> t,
boolean withBoundary) {<FILL_FUNCTION_BODY>}
protected GraphTraversal<Vertex, ?> topN(GraphTraversal<Vertex, ?> t,
long topN) {
if (topN > 0L || topN == NO_LIMIT) {
t = t.order(Scope.local).by(Column.values, Order.desc);
if (topN > 0L) {
assert topN != NO_LIMIT;
t = t.limit(Scope.local, topN);
}
}
return t;
}
}
|
// t.select(Pop.all, "v").unfold().id()
return t.select(Pop.all, "v").flatMap(it -> {
List<?> path = (List<?>) it.get();
if (withBoundary) {
@SuppressWarnings("unchecked")
Iterator<HugeVertex> items = (Iterator<HugeVertex>)
path.iterator();
return new MapperIterator<>(items, HugeVertex::id);
}
int len = path.size();
if (len < 3) {
return Collections.emptyIterator();
}
LOG.debug("CentAlgorithm substract path: {}", path);
path.remove(path.size() - 1);
path.remove(0);
@SuppressWarnings("unchecked")
Iterator<HugeVertex> items = (Iterator<HugeVertex>)
path.iterator();
return new MapperIterator<>(items, HugeVertex::id);
});
| 1,119
| 254
| 1,373
|
<methods>public non-sealed void <init>() ,public void checkParameters(Map<java.lang.String,java.lang.Object>) <variables>public static final int BATCH,public static final java.lang.String CATEGORY_AGGR,public static final java.lang.String CATEGORY_CENT,public static final java.lang.String CATEGORY_COMM,public static final java.lang.String CATEGORY_PATH,public static final java.lang.String CATEGORY_RANK,public static final java.lang.String CATEGORY_SIMI,public static final java.lang.String C_LABEL,public static final double DEFAULT_ALPHA,public static final long DEFAULT_CAPACITY,public static final long DEFAULT_DEGREE,public static final long DEFAULT_EACH_LIMIT,public static final long DEFAULT_LIMIT,public static final double DEFAULT_PRECISION,public static final long DEFAULT_SAMPLE,public static final long DEFAULT_STABLE_TIMES,public static final long DEFAULT_TIMES,public static final java.lang.String EXPORT_PATH,public static final java.lang.String KEY_ALPHA,public static final java.lang.String KEY_CAPACITY,public static final java.lang.String KEY_CLEAR,public static final java.lang.String KEY_DEGREE,public static final java.lang.String KEY_DEPTH,public static final java.lang.String KEY_DIRECTION,public static final java.lang.String KEY_EACH_LIMIT,public static final java.lang.String KEY_EXPORT_COMM,public static final java.lang.String KEY_LABEL,public static final java.lang.String KEY_LIMIT,public static final java.lang.String KEY_PRECISION,public static final java.lang.String KEY_SAMPLE,public static final java.lang.String KEY_SHOW_COMM,public static final java.lang.String KEY_SHOW_MOD,public static final java.lang.String KEY_SKIP_ISOLATED,public static final java.lang.String KEY_SOURCE_CLABEL,public static final java.lang.String KEY_SOURCE_LABEL,public static final java.lang.String KEY_SOURCE_SAMPLE,public static final java.lang.String KEY_STABLE_TIMES,public static final java.lang.String KEY_TIMES,public static final java.lang.String KEY_TOP,public static final java.lang.String KEY_WORKERS,public static final long MAX_CAPACITY,public static final long MAX_QUERY_LIMIT,public static final long MAX_RESULT_SIZE,public static final java.lang.String R_RANK,public static final java.lang.String USER_DIR
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/algorithm/cent/BetweennessCentralityAlgorithm.java
|
Traverser
|
computeBetweenness
|
class Traverser extends AbstractCentAlgorithm.Traverser {
public Traverser(UserJob<Object> job) {
super(job);
}
public Object betweennessCentrality(Directions direction,
String label,
int depth,
long degree,
long sample,
String sourceLabel,
long sourceSample,
String sourceCLabel,
long topN) {
assert depth > 0;
assert degree > 0L || degree == NO_LIMIT;
assert topN >= 0L || topN == NO_LIMIT;
GraphTraversal<Vertex, Vertex> t = constructSource(sourceLabel,
sourceSample,
sourceCLabel);
t = constructPath(t, direction, label, degree, sample,
sourceLabel, sourceCLabel);
t = t.emit().until(__.loops().is(P.gte(depth)));
t = filterNonShortestPath(t, false);
GraphTraversal<Vertex, ?> tg = this.groupPathByEndpoints(t);
tg = this.computeBetweenness(tg);
GraphTraversal<Vertex, ?> tLimit = topN(tg, topN);
return this.execute(tLimit, tLimit::next);
}
protected GraphTraversal<Vertex, ?> groupPathByEndpoints(
GraphTraversal<Vertex, Vertex> t) {
return t.map(it -> {
// t.select(Pop.all, "v").unfold().id()
List<HugeElement> path = it.path(Pop.all, "v");
List<Id> pathById = new ArrayList<>(path.size());
for (HugeElement v : path) {
pathById.add(v.id());
}
return pathById;
}).group().by(it -> {
// group by the first and last vertex
@SuppressWarnings("unchecked")
List<Id> path = (List<Id>) it;
assert path.size() >= 2;
String first = path.get(0).toString();
String last = path.get(path.size() - 1).toString();
return SplicingIdGenerator.concat(first, last);
}).unfold();
}
protected GraphTraversal<Vertex, ?> computeBetweenness(
GraphTraversal<Vertex, ?> t) {<FILL_FUNCTION_BODY>}
}
|
return t.fold(new HashMap<Id, MutableFloat>(), (results, it) -> {
@SuppressWarnings("unchecked")
Map.Entry<Id, List<?>> entry = (Map.Entry<Id, List<?>>) it;
@SuppressWarnings("unchecked")
List<List<Id>> paths = (List<List<Id>>) entry.getValue();
for (List<Id> path : paths) {
int len = path.size();
if (len <= 2) {
// only two vertex, no betweenness vertex
continue;
}
// skip the first and last vertex
for (int i = 1; i < len - 1; i++) {
Id vertex = path.get(i);
MutableFloat value = results.get(vertex);
if (value == null) {
value = new MutableFloat();
results.put(vertex, value);
}
value.add(1.0f / paths.size());
}
}
return results;
});
| 618
| 265
| 883
|
<methods>public non-sealed void <init>() ,public java.lang.String category() ,public void checkParameters(Map<java.lang.String,java.lang.Object>) <variables>private static final Logger LOG
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/algorithm/cent/BetweennessCentralityAlgorithmV2.java
|
Traverser
|
betweenessCentrality
|
class Traverser extends BfsTraverser<BetweennessNode> {
private Map<Id, MutableFloat> globalBetweennesses;
private Traverser(UserJob<Object> job) {
super(job);
}
private Object betweenessCentrality(Directions direction,
String label,
int depth,
long degree,
long sample,
String sourceLabel,
long sourceSample,
String sourceCLabel,
long topN) {<FILL_FUNCTION_BODY>}
@Override
protected BetweennessNode createNode(BetweennessNode parentNode) {
return new BetweennessNode(parentNode);
}
@Override
protected void meetNode(Id currentVertex, BetweennessNode currentNode,
Id parentVertex, BetweennessNode parentNode,
boolean firstTime) {
currentNode.addParentNode(parentNode, parentVertex);
}
@Override
protected BetweennessNode createStartNode() {
return new BetweennessNode(1, 0);
}
@Override
protected void backtrack(Id startVertex, Id currentVertex,
Map<Id, BetweennessNode> localNodes) {
if (startVertex.equals(currentVertex)) {
return;
}
MutableFloat betweenness = this.globalBetweennesses.get(
currentVertex);
if (betweenness == null) {
betweenness = new MutableFloat(0.0F);
this.globalBetweennesses.put(currentVertex, betweenness);
}
BetweennessNode node = localNodes.get(currentVertex);
betweenness.add(node.betweenness());
// Contribute to parents
for (Id v : node.parents()) {
BetweennessNode parentNode = localNodes.get(v);
parentNode.increaseBetweenness(node);
}
}
}
|
assert depth > 0;
assert degree > 0L || degree == NO_LIMIT;
assert topN >= 0L || topN == NO_LIMIT;
this.globalBetweennesses = new HashMap<>();
Id edgeLabelId = this.getEdgeLabelIdOrNull(label);
// TODO: sample the startVertices
Iterator<Vertex> startVertices = this.vertices(sourceLabel,
sourceCLabel,
Query.NO_LIMIT);
while (startVertices.hasNext()) {
Id startVertex = ((HugeVertex) startVertices.next()).id();
this.globalBetweennesses.putIfAbsent(startVertex,
new MutableFloat());
this.compute(startVertex, direction, edgeLabelId,
degree, depth);
}
if (topN > 0L || topN == NO_LIMIT) {
return HugeTraverser.topN(this.globalBetweennesses,
true, topN);
} else {
return this.globalBetweennesses;
}
| 469
| 269
| 738
|
<methods>public non-sealed void <init>() ,public java.lang.String category() ,public void checkParameters(Map<java.lang.String,java.lang.Object>) <variables>private static final Logger LOG
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/algorithm/cent/ClosenessCentralityAlgorithm.java
|
Traverser
|
closenessCentrality
|
class Traverser extends AbstractCentAlgorithm.Traverser {
public Traverser(UserJob<Object> job) {
super(job);
}
public Object closenessCentrality(Directions direction,
String label,
int depth,
long degree,
long sample,
String sourceLabel,
long sourceSample,
String sourceCLabel,
long topN) {<FILL_FUNCTION_BODY>}
}
|
assert depth > 0;
assert degree > 0L || degree == NO_LIMIT;
assert topN >= 0L || topN == NO_LIMIT;
GraphTraversal<Vertex, Vertex> t = constructSource(sourceLabel,
sourceSample,
sourceCLabel);
t = constructPath(t, direction, label, degree, sample,
sourceLabel, sourceCLabel);
t = t.emit().until(__.loops().is(P.gte(depth)));
t = filterNonShortestPath(t, true);
/*
* We use Marchiori's algorithm(sum of reciprocal of distances):
* .math("_-1").sack(Operator.div).sack().sum()
* for Bavelas's algorithm:
* .math("_-1").sum().sack(Operator.div).sack()
* see https://en.wikipedia.org/wiki/Closeness_centrality
*/
GraphTraversal<Vertex, ?> tg;
tg = t.group().by(__.select(Pop.first, "v").id())
.by(__.select(Pop.all, "v").count(Scope.local)
.math("_-1").sack(Operator.div).sack().sum());
GraphTraversal<Vertex, ?> tLimit = topN(tg, topN);
return this.execute(tLimit, tLimit::next);
| 117
| 360
| 477
|
<methods>public non-sealed void <init>() ,public java.lang.String category() ,public void checkParameters(Map<java.lang.String,java.lang.Object>) <variables>private static final Logger LOG
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/algorithm/cent/ClosenessCentralityAlgorithmV2.java
|
Traverser
|
closenessCentrality
|
class Traverser extends BfsTraverser<BfsTraverser.Node> {
private final Map<Id, Float> globalCloseness;
private float startVertexCloseness;
private Traverser(UserJob<Object> job) {
super(job);
this.globalCloseness = new HashMap<>();
}
private Object closenessCentrality(Directions direction,
String label,
int depth,
long degree,
long sample,
String sourceLabel,
long sourceSample,
String sourceCLabel,
long topN) {<FILL_FUNCTION_BODY>}
@Override
protected Node createStartNode() {
return new Node(1, 0);
}
@Override
protected Node createNode(Node parentNode) {
return new Node(parentNode);
}
@Override
protected void meetNode(Id currentVertex, Node currentNode,
Id parentVertex, Node parentNode,
boolean firstTime) {
if (firstTime) {
this.startVertexCloseness += 1.0F / currentNode.distance();
}
}
@Override
protected void backtrack(Id startVertex, Id currentVertex,
Map<Id, Node> localNodes) {
throw new NotSupportException("backtrack()");
}
}
|
assert depth > 0;
assert degree > 0L || degree == NO_LIMIT;
assert topN >= 0L || topN == NO_LIMIT;
Id edgeLabelId = this.getEdgeLabelIdOrNull(label);
// TODO: sample the startVertices
Iterator<Vertex> startVertices = this.vertices(sourceLabel,
sourceCLabel,
Query.NO_LIMIT);
while (startVertices.hasNext()) {
this.startVertexCloseness = 0.0F;
Id startVertex = ((HugeVertex) startVertices.next()).id();
this.traverse(startVertex, direction, edgeLabelId,
degree, depth);
this.globalCloseness.put(startVertex,
this.startVertexCloseness);
}
if (topN > 0L || topN == NO_LIMIT) {
return HugeTraverser.topN(this.globalCloseness, true, topN);
} else {
return this.globalCloseness;
}
| 348
| 264
| 612
|
<methods>public non-sealed void <init>() ,public java.lang.String category() ,public void checkParameters(Map<java.lang.String,java.lang.Object>) <variables>private static final Logger LOG
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/algorithm/cent/DegreeCentralityAlgorithm.java
|
Traverser
|
degreeCentrality
|
class Traverser extends AlgoTraverser {
public Traverser(UserJob<Object> job) {
super(job);
}
public Object degreeCentrality(Directions direction,
String label,
long topN) {<FILL_FUNCTION_BODY>}
protected Object degreeCentralityForBothDir(String label, long topN) {
assert topN >= 0L || topN == NO_LIMIT;
long totalVertices = 0L;
JsonMap degrees = new JsonMap();
TopMap<Id> tops = new TopMap<>(topN);
Iterator<Vertex> vertices = this.vertices();
degrees.startObject();
while (vertices.hasNext()) {
Id source = (Id) vertices.next().id();
this.updateProgress(++totalVertices);
long degree = this.degree(source, label);
if (degree > 0L) {
if (topN <= 0L && topN != NO_LIMIT) {
degrees.append(source, degree);
} else {
tops.put(source, degree);
}
}
}
if (tops.size() > 0) {
degrees.append(tops.entrySet());
}
degrees.endObject();
return degrees.asJson();
}
private long degree(Id source, String label) {
List<String> labels = label == null ? null : Collections.singletonList(label);
EdgeStep step = new EdgeStep(this.graph(), Directions.BOTH,
labels, null, NO_LIMIT, 0);
return this.edgesCount(source, step);
}
}
|
if (direction == null || direction == Directions.BOTH) {
return this.degreeCentralityForBothDir(label, topN);
}
assert direction == Directions.OUT || direction == Directions.IN;
assert topN >= 0L || topN == NO_LIMIT;
Iterator<Edge> edges = this.edges(direction);
JsonMap degrees = new JsonMap();
TopMap<Id> tops = new TopMap<>(topN);
Id vertex = null;
Id labelId = this.getEdgeLabelIdOrNull(label);
long degree = 0L;
long totalEdges = 0L;
degrees.startObject();
while (edges.hasNext()) {
HugeEdge edge = (HugeEdge) edges.next();
this.updateProgress(++totalEdges);
Id schemaLabel = edge.schemaLabel().id();
if (labelId != null && !labelId.equals(schemaLabel)) {
continue;
}
Id source = edge.ownerVertex().id();
if (source.equals(vertex)) {
// edges belong to same source vertex
degree++;
continue;
}
if (vertex != null) {
// next vertex found
if (topN <= 0L && topN != NO_LIMIT) {
degrees.append(vertex, degree);
} else {
tops.put(vertex, degree);
}
}
vertex = source;
degree = 1L;
}
if (vertex != null) {
if (topN <= 0L && topN != NO_LIMIT) {
degrees.append(vertex, degree);
} else {
tops.put(vertex, degree);
degrees.append(tops.entrySet());
}
}
degrees.endObject();
return degrees.asJson();
| 429
| 474
| 903
|
<methods>public non-sealed void <init>() ,public java.lang.String category() ,public void checkParameters(Map<java.lang.String,java.lang.Object>) <variables>private static final Logger LOG
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/algorithm/cent/EigenvectorCentralityAlgorithm.java
|
Traverser
|
eigenvectorCentrality
|
class Traverser extends AbstractCentAlgorithm.Traverser {
public Traverser(UserJob<Object> job) {
super(job);
}
public Object eigenvectorCentrality(Directions direction,
String label,
int depth,
long degree,
long sample,
String sourceLabel,
long sourceSample,
String sourceCLabel,
long topN) {<FILL_FUNCTION_BODY>}
}
|
assert depth > 0;
assert degree > 0L || degree == NO_LIMIT;
assert topN >= 0L || topN == NO_LIMIT;
// TODO: support parameters: Directions dir, String label
/*
* g.V().repeat(groupCount('m').by(id)
* .local(both().limit(50).sample(1))
* .simplePath())
* .times(4).cap('m')
* .order(local).by(values, desc)
* .limit(local, 100)
*/
GraphTraversal<Vertex, Vertex> t = constructSource(sourceLabel,
sourceSample,
sourceCLabel);
GraphTraversal<?, Vertex> unit = constructPathUnit(direction, label,
degree, sample,
sourceLabel,
sourceCLabel);
t = t.repeat(__.groupCount("m").by(T.id)
.local(unit).simplePath()).times(depth);
GraphTraversal<Vertex, Object> tCap = t.cap("m");
GraphTraversal<Vertex, ?> tLimit = topN(tCap, topN);
return this.execute(tLimit, tLimit::next);
| 117
| 319
| 436
|
<methods>public non-sealed void <init>() ,public java.lang.String category() ,public void checkParameters(Map<java.lang.String,java.lang.Object>) <variables>private static final Logger LOG
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/algorithm/cent/StressCentralityAlgorithm.java
|
StressCentralityAlgorithm
|
withBoundary
|
class StressCentralityAlgorithm extends AbstractCentAlgorithm {
public static final String KEY_WITH_BOUNDARY = "with_boundary";
@Override
public String name() {
return "stress_centrality";
}
@Override
public void checkParameters(Map<String, Object> parameters) {
super.checkParameters(parameters);
withBoundary(parameters);
}
@Override
public Object call(UserJob<Object> job, Map<String, Object> parameters) {
try (Traverser traverser = new Traverser(job)) {
return traverser.stressCentrality(direction(parameters),
edgeLabel(parameters),
depth(parameters),
degree(parameters),
sample(parameters),
withBoundary(parameters),
sourceLabel(parameters),
sourceSample(parameters),
sourceCLabel(parameters),
top(parameters));
}
}
protected static boolean withBoundary(Map<String, Object> parameters) {<FILL_FUNCTION_BODY>}
private static class Traverser extends AbstractCentAlgorithm.Traverser {
public Traverser(UserJob<Object> job) {
super(job);
}
public Object stressCentrality(Directions direction,
String label,
int depth,
long degree,
long sample,
boolean withBoundary,
String sourceLabel,
long sourceSample,
String sourceCLabel,
long topN) {
assert depth > 0;
assert degree > 0L || degree == NO_LIMIT;
assert topN >= 0L || topN == NO_LIMIT;
GraphTraversal<Vertex, Vertex> t = constructSource(sourceLabel,
sourceSample,
sourceCLabel);
t = constructPath(t, direction, label, degree, sample,
sourceLabel, sourceCLabel);
t = t.emit().until(__.loops().is(P.gte(depth)));
t = filterNonShortestPath(t, false);
GraphTraversal<Vertex, ?> tg = this.substractPath(t, withBoundary)
.groupCount();
GraphTraversal<Vertex, ?> tLimit = topN(tg, topN);
return this.execute(tLimit, tLimit::next);
}
}
}
|
if (!parameters.containsKey(KEY_WITH_BOUNDARY)) {
return false;
}
return ParameterUtil.parameterBoolean(parameters, KEY_WITH_BOUNDARY);
| 602
| 49
| 651
|
<methods>public non-sealed void <init>() ,public java.lang.String category() ,public void checkParameters(Map<java.lang.String,java.lang.Object>) <variables>private static final Logger LOG
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/algorithm/cent/StressCentralityAlgorithmV2.java
|
Traverser
|
stressCentrality
|
class Traverser extends BfsTraverser<StressNode> {
private final Map<Id, MutableLong> globalStresses;
private Traverser(UserJob<Object> job) {
super(job);
this.globalStresses = new HashMap<>();
}
private Object stressCentrality(Directions direction,
String label,
int depth,
long degree,
long sample,
String sourceLabel,
long sourceSample,
String sourceCLabel,
long topN) {<FILL_FUNCTION_BODY>}
@Override
protected StressNode createStartNode() {
return new StressNode(1, 0);
}
@Override
protected StressNode createNode(StressNode parentNode) {
return new StressNode(parentNode);
}
@Override
protected void meetNode(Id currentVertex, StressNode currentNode,
Id parentVertex, StressNode parentNode,
boolean firstTime) {
currentNode.addParentNode(parentNode, parentVertex);
}
@Override
protected void backtrack(Id startVertex, Id currentVertex,
Map<Id, StressNode> localNodes) {
if (startVertex.equals(currentVertex)) {
return;
}
StressNode currentNode = localNodes.get(currentVertex);
// Add local stresses to global stresses
MutableLong stress = this.globalStresses.get(currentVertex);
if (stress == null) {
stress = new MutableLong(0L);
this.globalStresses.put(currentVertex, stress);
}
stress.add(currentNode.stress());
// Contribute to parents
for (Id v : currentNode.parents()) {
StressNode parentNode = localNodes.get(v);
parentNode.increaseStress(currentNode);
}
}
}
|
assert depth > 0;
assert degree > 0L || degree == NO_LIMIT;
assert topN >= 0L || topN == NO_LIMIT;
Id edgeLabelId = this.getEdgeLabelIdOrNull(label);
// TODO: sample the startVertices
Iterator<Vertex> startVertices = this.vertices(sourceLabel,
sourceCLabel,
Query.NO_LIMIT);
while (startVertices.hasNext()) {
Id startVertex = ((HugeVertex) startVertices.next()).id();
this.globalStresses.putIfAbsent(startVertex, new MutableLong(0L));
this.compute(startVertex, direction, edgeLabelId,
degree, depth);
}
if (topN > 0L || topN == NO_LIMIT) {
return HugeTraverser.topN(this.globalStresses, true, topN);
} else {
return this.globalStresses;
}
| 481
| 246
| 727
|
<methods>public non-sealed void <init>() ,public java.lang.String category() ,public void checkParameters(Map<java.lang.String,java.lang.Object>) <variables>private static final Logger LOG
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/algorithm/comm/AbstractCommAlgorithm.java
|
AbstractCommAlgorithm
|
stableTimes
|
class AbstractCommAlgorithm extends AbstractAlgorithm {
private static final int MAX_TIMES = 2048;
@Override
public String category() {
return CATEGORY_COMM;
}
protected static int times(Map<String, Object> parameters) {
if (!parameters.containsKey(KEY_TIMES)) {
return (int) DEFAULT_TIMES;
}
int times = ParameterUtil.parameterInt(parameters, KEY_TIMES);
HugeTraverser.checkPositiveOrNoLimit(times, KEY_TIMES);
E.checkArgument(times <= MAX_TIMES,
"The maximum number of iterations is %s, but got %s",
MAX_TIMES, times);
return times;
}
protected static int stableTimes(Map<String, Object> parameters) {<FILL_FUNCTION_BODY>}
protected static double precision(Map<String, Object> parameters) {
if (!parameters.containsKey(KEY_PRECISION)) {
return DEFAULT_PRECISION;
}
double precision = ParameterUtil.parameterDouble(parameters,
KEY_PRECISION);
E.checkArgument(0d < precision && precision < 1d,
"The %s parameter must be in range(0,1), but got: %s",
KEY_PRECISION, precision);
return precision;
}
protected static String showCommunity(Map<String, Object> parameters) {
if (!parameters.containsKey(KEY_SHOW_COMM)) {
return null;
}
return ParameterUtil.parameterString(parameters, KEY_SHOW_COMM);
}
}
|
if (!parameters.containsKey(KEY_STABLE_TIMES)) {
return (int) DEFAULT_STABLE_TIMES;
}
int times = ParameterUtil.parameterInt(parameters, KEY_STABLE_TIMES);
HugeTraverser.checkPositiveOrNoLimit(times, KEY_STABLE_TIMES);
E.checkArgument(times <= MAX_TIMES,
"The maximum number of stable iterations is %s, " +
"but got %s", MAX_TIMES, times);
return times;
| 422
| 140
| 562
|
<methods>public non-sealed void <init>() ,public void checkParameters(Map<java.lang.String,java.lang.Object>) <variables>public static final int BATCH,public static final java.lang.String CATEGORY_AGGR,public static final java.lang.String CATEGORY_CENT,public static final java.lang.String CATEGORY_COMM,public static final java.lang.String CATEGORY_PATH,public static final java.lang.String CATEGORY_RANK,public static final java.lang.String CATEGORY_SIMI,public static final java.lang.String C_LABEL,public static final double DEFAULT_ALPHA,public static final long DEFAULT_CAPACITY,public static final long DEFAULT_DEGREE,public static final long DEFAULT_EACH_LIMIT,public static final long DEFAULT_LIMIT,public static final double DEFAULT_PRECISION,public static final long DEFAULT_SAMPLE,public static final long DEFAULT_STABLE_TIMES,public static final long DEFAULT_TIMES,public static final java.lang.String EXPORT_PATH,public static final java.lang.String KEY_ALPHA,public static final java.lang.String KEY_CAPACITY,public static final java.lang.String KEY_CLEAR,public static final java.lang.String KEY_DEGREE,public static final java.lang.String KEY_DEPTH,public static final java.lang.String KEY_DIRECTION,public static final java.lang.String KEY_EACH_LIMIT,public static final java.lang.String KEY_EXPORT_COMM,public static final java.lang.String KEY_LABEL,public static final java.lang.String KEY_LIMIT,public static final java.lang.String KEY_PRECISION,public static final java.lang.String KEY_SAMPLE,public static final java.lang.String KEY_SHOW_COMM,public static final java.lang.String KEY_SHOW_MOD,public static final java.lang.String KEY_SKIP_ISOLATED,public static final java.lang.String KEY_SOURCE_CLABEL,public static final java.lang.String KEY_SOURCE_LABEL,public static final java.lang.String KEY_SOURCE_SAMPLE,public static final java.lang.String KEY_STABLE_TIMES,public static final java.lang.String KEY_TIMES,public static final java.lang.String KEY_TOP,public static final java.lang.String KEY_WORKERS,public static final long MAX_CAPACITY,public static final long MAX_QUERY_LIMIT,public static final long MAX_RESULT_SIZE,public static final java.lang.String R_RANK,public static final java.lang.String USER_DIR
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/algorithm/comm/ClusterCoefficientAlgorithm.java
|
ClusterCoefficientAlgorithm
|
workersWhenBoth
|
class ClusterCoefficientAlgorithm extends AbstractCommAlgorithm {
public static final String ALGO_NAME = "cluster_coefficient";
@Override
public String name() {
return ALGO_NAME;
}
@Override
public void checkParameters(Map<String, Object> parameters) {
direction(parameters);
degree(parameters);
workersWhenBoth(parameters);
}
@Override
public Object call(UserJob<Object> job, Map<String, Object> parameters) {
int workers = workersWhenBoth(parameters);
try (Traverser traverser = new Traverser(job, workers)) {
return traverser.clusterCoefficient(direction(parameters), degree(parameters));
}
}
protected static int workersWhenBoth(Map<String, Object> parameters) {<FILL_FUNCTION_BODY>}
private static class Traverser extends TriangleCountAlgorithm.Traverser {
public Traverser(UserJob<Object> job, int workers) {
super(job, ALGO_NAME, workers);
}
public Object clusterCoefficient(Directions direction, long degree) {
Map<String, Long> results = this.triangles(direction, degree);
results = InsertionOrderUtil.newMap(results);
long triangles = results.remove(KEY_TRIANGLES);
long triads = results.remove(KEY_TRIADS);
assert triangles <= triads;
double coefficient = triads == 0L ? 0d : 1d * triangles / triads;
@SuppressWarnings({"unchecked", "rawtypes"})
Map<String, Double> converted = (Map) results;
converted.put("cluster_coefficient", coefficient);
return results;
}
}
}
|
Directions direction = direction(parameters);
int workers = workers(parameters);
E.checkArgument(direction == Directions.BOTH || workers <= 0,
"The workers must be not set when direction!=BOTH, " +
"but got workers=%s and direction=%s",
workers, direction);
return workers;
| 454
| 89
| 543
|
<methods>public non-sealed void <init>() ,public java.lang.String category() <variables>private static final int MAX_TIMES
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/algorithm/comm/KCoreAlgorithm.java
|
Traverser
|
kcore
|
class Traverser extends AlgoTraverser {
public Traverser(UserJob<Object> job, int workers) {
super(job, ALGO_NAME, workers);
}
public Object kcore(String sourceLabel, String sourceCLabel,
Directions dir, String label, int k, double alpha,
long degree, boolean merged) {<FILL_FUNCTION_BODY>}
private static void mergeKcores(Set<Set<Id>> kcores, Set<Id> kcore) {
boolean merged = false;
/*
* Iterate to collect merging kcores firstly, because merging
* kcores will be removed from all kcores.
* Besides one new kcore may connect to multiple existing kcores.
*/
Set<Set<Id>> mergingKcores = new HashSet<>();
for (Set<Id> existedKcore : kcores) {
if (CollectionUtil.hasIntersection(existedKcore, kcore)) {
mergingKcores.add(existedKcore);
merged = true;
}
}
if (merged) {
for (Set<Id> mergingKcore : mergingKcores) {
kcores.remove(mergingKcore);
kcore.addAll(mergingKcore);
}
}
kcores.add(kcore);
}
}
|
HugeGraph graph = this.graph();
KcoreTraverser traverser = new KcoreTraverser(graph);
JsonMap kcoresJson = new JsonMap();
kcoresJson.startObject();
kcoresJson.appendKey("kcores");
kcoresJson.startList();
Set<Set<Id>> kcores = new HashSet<>();
this.traverse(sourceLabel, sourceCLabel, v -> {
Set<Id> kcore = traverser.kcore(IteratorUtils.of(v),
dir, label, k, alpha, degree);
if (kcore.isEmpty()) {
return;
}
if (merged) {
synchronized (kcores) {
mergeKcores(kcores, kcore);
}
} else {
String json = JsonUtil.toJson(kcore);
synchronized (kcoresJson) {
kcoresJson.appendRaw(json);
}
}
});
if (merged) {
for (Set<Id> kcore : kcores) {
kcoresJson.appendRaw(JsonUtil.toJson(kcore));
}
}
kcoresJson.endList();
kcoresJson.endObject();
return kcoresJson.asJson();
| 353
| 340
| 693
|
<methods>public non-sealed void <init>() ,public java.lang.String category() <variables>private static final int MAX_TIMES
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/algorithm/comm/LouvainAlgorithm.java
|
LouvainAlgorithm
|
call
|
class LouvainAlgorithm extends AbstractCommAlgorithm {
public static final String ALGO_NAME = "louvain";
@Override
public String name() {
return ALGO_NAME;
}
@Override
public void checkParameters(Map<String, Object> parameters) {
times(parameters);
stableTimes(parameters);
precision(parameters);
degree(parameters);
sourceLabel(parameters);
sourceCLabel(parameters);
showModularity(parameters);
showCommunity(parameters);
exportCommunity(parameters);
skipIsolated(parameters);
clearPass(parameters);
workers(parameters);
}
@Override
public Object call(UserJob<Object> job, Map<String, Object> parameters) {<FILL_FUNCTION_BODY>}
protected static Long clearPass(Map<String, Object> parameters) {
if (!parameters.containsKey(KEY_CLEAR)) {
return null;
}
long pass = ParameterUtil.parameterLong(parameters, KEY_CLEAR);
HugeTraverser.checkNonNegativeOrNoLimit(pass, KEY_CLEAR);
return pass;
}
protected static Long showModularity(Map<String, Object> parameters) {
if (!parameters.containsKey(KEY_SHOW_MOD)) {
return null;
}
long pass = ParameterUtil.parameterLong(parameters, KEY_SHOW_MOD);
HugeTraverser.checkNonNegative(pass, KEY_SHOW_MOD);
return pass;
}
protected static Long exportCommunity(Map<String, Object> parameters) {
if (!parameters.containsKey(KEY_EXPORT_COMM)) {
return null;
}
long pass = ParameterUtil.parameterLong(parameters, KEY_EXPORT_COMM);
HugeTraverser.checkNonNegative(pass, KEY_EXPORT_COMM);
return pass;
}
protected static boolean skipIsolated(Map<String, Object> parameters) {
if (!parameters.containsKey(KEY_SKIP_ISOLATED)) {
return true;
}
return ParameterUtil.parameterBoolean(parameters, KEY_SKIP_ISOLATED);
}
}
|
String label = sourceLabel(parameters);
String clabel = sourceCLabel(parameters);
long degree = degree(parameters);
boolean skipIsolated = skipIsolated(parameters);
int workers = workers(parameters);
Long clearPass = clearPass(parameters);
Long modPass = showModularity(parameters);
String showComm = showCommunity(parameters);
Long exportPass = exportCommunity(parameters);
try (LouvainTraverser traverser = new LouvainTraverser(
job, workers, degree,
label, clabel, skipIsolated)) {
if (clearPass != null) {
return traverser.clearPass(clearPass.intValue());
} else if (modPass != null) {
return traverser.modularity(modPass.intValue());
} else if (exportPass != null) {
boolean vertexFirst = showComm == null;
int pass = exportPass.intValue();
return traverser.exportCommunity(pass, vertexFirst);
} else if (showComm != null) {
return traverser.showCommunity(showComm);
} else {
return traverser.louvain(times(parameters),
stableTimes(parameters),
precision(parameters));
}
} catch (Throwable e) {
job.graph().tx().rollback();
throw e;
}
| 562
| 352
| 914
|
<methods>public non-sealed void <init>() ,public java.lang.String category() <variables>private static final int MAX_TIMES
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/algorithm/comm/LouvainTraverser.java
|
Community
|
equals
|
class Community {
// community id (stored as a backend vertex)
private final Id cid;
// community members size of last pass [just for skip large community]
private int size = 0;
// community members size of origin vertex [just for debug members lost]
private float weight = 0f;
/*
* weight of all edges in community(2X), sum of kin of new members
* [each is from the last pass, stored in backend vertex]
*/
private int kin = 0;
/*
* weight of all edges between communities, sum of kout of new members
* [each is last pass, calculated in real time by neighbors]
*/
private float kout = 0f;
public Community(Id cid) {
this.cid = cid;
}
public boolean empty() {
return this.size <= 0;
}
public int size() {
return this.size;
}
public float weight() {
return this.weight;
}
public synchronized void add(LouvainTraverser t,
Vertex v, List<Edge> nbs) {
this.size++;
this.weight += t.cweightOfVertex(v);
this.kin += t.kinOfVertex(v);
this.kout += t.weightOfVertex(v, nbs);
}
public synchronized void remove(LouvainTraverser t,
Vertex v, List<Edge> nbs) {
this.size--;
this.weight -= t.cweightOfVertex(v);
this.kin -= t.kinOfVertex(v);
this.kout -= t.weightOfVertex(v, nbs);
}
public synchronized int kin() {
return this.kin;
}
public synchronized float kout() {
return this.kout;
}
@Override
public boolean equals(Object object) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return String.format("[%s](size=%s weight=%s kin=%s kout=%s)",
this.cid, this.size, this.weight,
this.kin, this.kout);
}
}
|
if (!(object instanceof Community)) {
return false;
}
Community other = (Community) object;
return Objects.equals(this.cid, other.cid);
| 574
| 48
| 622
|
<methods>public void <init>(UserJob<java.lang.Object>) ,public void close() ,public org.apache.hugegraph.backend.id.Id jobId() ,public void updateProgress(long) <variables>protected final non-sealed java.util.concurrent.ExecutorService executor,private final non-sealed UserJob<java.lang.Object> job,protected long progress
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/algorithm/comm/LpaAlgorithm.java
|
Traverser
|
lpa
|
class Traverser extends AlgoTraverser {
private static final long LIMIT = MAX_QUERY_LIMIT;
private final Random R = new Random();
public Traverser(UserJob<Object> job, int workers) {
super(job, ALGO_NAME, workers);
}
public Object lpa(String sourceLabel, String edgeLabel,
Directions dir, long degree,
int maxTimes, double precision) {<FILL_FUNCTION_BODY>}
public Object showCommunity(String clabel) {
E.checkNotNull(clabel, "clabel");
// all vertices with specified c-label
Iterator<Vertex> vertices = this.vertices(null, clabel, LIMIT);
JsonMap json = new JsonMap();
json.startList();
while (vertices.hasNext()) {
this.updateProgress(++this.progress);
json.append(vertices.next().id().toString());
}
json.endList();
return json.asJson();
}
private double detectCommunities(String sourceLabel, String edgeLabel,
Directions dir, long degree) {
// shuffle: r.order().by(shuffle)
// r = this.graph().traversal().V().sample((int) LIMIT);
// detect all vertices
AtomicLong changed = new AtomicLong(0L);
long total = this.traverse(sourceLabel, null, v -> {
// called by multi-threads
if (this.voteCommunityAndUpdate(v, edgeLabel, dir, degree)) {
changed.incrementAndGet();
}
}, () -> {
// commit when finished
this.graph().tx().commit();
});
return total == 0L ? 0d : changed.doubleValue() / total;
}
private boolean voteCommunityAndUpdate(Vertex vertex, String edgeLabel,
Directions dir, long degree) {
String label = this.voteCommunityOfVertex(vertex, edgeLabel,
dir, degree);
// update label if it's absent or changed
if (!labelPresent(vertex) || !label.equals(labelOfVertex(vertex))) {
this.updateLabelOfVertex(vertex, label);
return true;
}
return false;
}
private String voteCommunityOfVertex(Vertex vertex, String edgeLabel,
Directions dir, long degree) {
// neighbors of source vertex v
Id source = (Id) vertex.id();
Id labelId = this.getEdgeLabelIdOrNull(edgeLabel);
Iterator<Id> neighbors = this.adjacentVertices(source, dir,
labelId, degree);
// whether include vertex itself, greatly affects the result.
// get a larger number of small communities if include itself
//neighbors.inject(v);
// calculate label frequency
Map<String, MutableInt> labels = new HashMap<>();
while (neighbors.hasNext()) {
String label = this.labelOfVertex(neighbors.next());
if (label == null) {
// ignore invalid or not-exist vertex
continue;
}
MutableInt labelCount = labels.get(label);
if (labelCount != null) {
labelCount.increment();
} else {
labels.put(label, new MutableInt(1));
}
}
// isolated vertex
if (labels.isEmpty()) {
return this.labelOfVertex(vertex);
}
// get the labels with maximum frequency
List<String> maxLabels = new ArrayList<>();
int maxFreq = 1;
for (Map.Entry<String, MutableInt> e : labels.entrySet()) {
int value = e.getValue().intValue();
if (value > maxFreq) {
maxFreq = value;
maxLabels.clear();
}
if (value == maxFreq) {
maxLabels.add(e.getKey());
}
}
/*
* TODO:
* keep origin label with probability to prevent monster communities
*/
// random choice
int selected = this.R.nextInt(maxLabels.size());
return maxLabels.get(selected);
}
private boolean labelPresent(Vertex vertex) {
return vertex.property(C_LABEL).isPresent();
}
private String labelOfVertex(Vertex vertex) {
if (!labelPresent(vertex)) {
return vertex.id().toString();
}
return vertex.value(C_LABEL);
}
private String labelOfVertex(Id vid) {
// TODO: cache with Map<Id, String>
Vertex vertex = this.vertex(vid);
if (vertex == null) {
return null;
}
return this.labelOfVertex(vertex);
}
private void updateLabelOfVertex(Vertex v, String label) {
// TODO: cache with Map<Id, String>
v.property(C_LABEL, label);
this.commitIfNeeded();
}
private void initSchema() {
String cl = C_LABEL;
SchemaManager schema = this.graph().schema();
schema.propertyKey(cl).asText().ifNotExist().create();
for (VertexLabel vl : schema.getVertexLabels()) {
schema.vertexLabel(vl.name())
.properties(cl).nullableKeys(cl)
.append();
}
}
}
|
assert maxTimes > 0;
assert precision > 0d;
this.initSchema();
int times = maxTimes;
double changedPercent = 0d;
/*
* Iterate until:
* 1.it has stabilized
* 2.or the maximum number of times is reached
*/
for (int i = 0; i < maxTimes; i++) {
changedPercent = this.detectCommunities(sourceLabel, edgeLabel,
dir, degree);
if (changedPercent <= precision) {
times = i + 1;
break;
}
}
Number communities = tryNext(this.graph().traversal().V()
.filter(__.properties(C_LABEL))
.groupCount().by(C_LABEL)
.count(Scope.local));
return ImmutableMap.of("iteration_times", times,
"last_precision", changedPercent,
"times", maxTimes,
"communities", communities);
| 1,384
| 257
| 1,641
|
<methods>public non-sealed void <init>() ,public java.lang.String category() <variables>private static final int MAX_TIMES
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/algorithm/comm/TriangleCountAlgorithm.java
|
Traverser
|
intersect
|
class Traverser extends AlgoTraverser {
protected static final String KEY_TRIANGLES = "triangles";
protected static final String KEY_TRIADS = "triads";
public Traverser(UserJob<Object> job, int workers) {
super(job, ALGO_NAME, workers);
}
protected Traverser(UserJob<Object> job, String name, int workers) {
super(job, name, workers);
}
protected static <V> Set<V> newOrderedSet() {
return new TreeSet<>();
}
public Object triangleCount(Directions direction, long degree) {
Map<String, Long> results = triangles(direction, degree);
results = InsertionOrderUtil.newMap(results);
results.remove(KEY_TRIADS);
return results;
}
protected Map<String, Long> triangles(Directions direction,
long degree) {
if (direction == null || direction == Directions.BOTH) {
return this.trianglesForBothDir(degree);
}
assert direction == Directions.OUT || direction == Directions.IN;
Iterator<Edge> edges = this.edges(direction);
long triangles = 0L;
long triads = 0L;
long totalEdges = 0L;
long totalVertices = 0L;
Id vertex = null;
Set<Id> adjVertices = newOrderedSet();
while (edges.hasNext()) {
HugeEdge edge = (HugeEdge) edges.next();
this.updateProgress(++totalEdges);
Id source = edge.ownerVertex().id();
Id target = edge.otherVertex().id();
if (vertex == source) {
// Ignore and skip the target vertex if exceed degree
if (adjVertices.size() < degree || degree == NO_LIMIT) {
adjVertices.add(target);
}
continue;
}
if (vertex != null) {
assert vertex != source;
/*
* Find graph mode like this:
* A -> [B,C,D,E,F]
* B -> [D,F]
* E -> [B,C,F]
*/
triangles += this.intersect(degree, adjVertices);
triads += this.localTriads(adjVertices.size());
totalVertices++;
// Reset for the next source
adjVertices = newOrderedSet();
}
vertex = source;
adjVertices.add(target);
}
if (vertex != null) {
triangles += this.intersect(degree, adjVertices);
triads += this.localTriads(adjVertices.size());
totalVertices++;
}
String suffix = "_" + direction.string();
return ImmutableMap.of("edges" + suffix, totalEdges,
"vertices" + suffix, totalVertices,
KEY_TRIANGLES, triangles,
KEY_TRIADS, triads);
}
protected Map<String, Long> trianglesForBothDir(long degree) {
AtomicLong triangles = new AtomicLong(0L);
AtomicLong triads = new AtomicLong(0L);
AtomicLong totalEdges = new AtomicLong(0L);
AtomicLong totalVertices = new AtomicLong(0L);
this.traverse(null, null, v -> {
Id source = (Id) v.id();
MutableLong edgesCount = new MutableLong(0L);
Set<Id> adjVertices = this.adjacentVertices(source, degree,
edgesCount);
triangles.addAndGet(this.intersect(degree, adjVertices));
triads.addAndGet(this.localTriads(adjVertices.size()));
totalVertices.incrementAndGet();
totalEdges.addAndGet(edgesCount.longValue());
});
assert totalEdges.get() % 2L == 0L;
assert triangles.get() % 3L == 0L;
// totalEdges /= 2L
totalEdges.getAndAccumulate(2L, (l, w) -> l / w);
// triangles /= 3L
triangles.getAndAccumulate(3L, (l, w) -> l / w);
// triads -= triangles * 2L
triads.addAndGet(triangles.get() * -2L);
return ImmutableMap.of("edges", totalEdges.get(),
"vertices", totalVertices.get(),
KEY_TRIANGLES, triangles.get(),
KEY_TRIADS, triads.get());
}
private Set<Id> adjacentVertices(Id source, long degree,
MutableLong edgesCount) {
Iterator<Id> adjVertices = this.adjacentVertices(source,
Directions.BOTH,
(Id) null, degree);
Set<Id> set = newOrderedSet();
while (adjVertices.hasNext()) {
edgesCount.increment();
set.add(adjVertices.next());
}
return set;
}
protected long intersect(long degree, Set<Id> adjVertices) {<FILL_FUNCTION_BODY>}
protected long localTriads(int size) {
return size * (size - 1L) / 2L;
}
}
|
long count = 0L;
Directions dir = Directions.OUT;
Id empty = IdGenerator.ZERO;
Iterator<Id> vertices;
for (Id v : adjVertices) {
vertices = this.adjacentVertices(v, dir, (Id) null, degree);
Id lastVertex = empty;
while (vertices.hasNext()) {
Id vertex = vertices.next();
if (lastVertex.equals(vertex)) {
// Skip duplicated target vertex (through sortkeys)
continue;
}
lastVertex = vertex;
/*
* FIXME: deduplicate two edges with opposite directions
* between two specified adjacent vertices
*/
if (adjVertices.contains(vertex)) {
count++;
}
}
}
return count;
| 1,408
| 208
| 1,616
|
<methods>public non-sealed void <init>() ,public java.lang.String category() <variables>private static final int MAX_TIMES
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/algorithm/comm/WeakConnectedComponent.java
|
Traverser
|
findMinComponent
|
class Traverser extends AlgoTraverser {
private final Map<Id, Id> vertexComponentMap = new HashMap<>();
public Traverser(UserJob<Object> job) {
super(job);
}
public Object connectedComponent(int maxTimes,
Directions direction,
long degree) {
this.initSchema();
this.initVertexComponentMap();
int times;
for (times = 0; times < maxTimes; times++) {
long changeCount = 0;
Id currentSourceVertexId = null;
// the edges are ordered by ownerVertex
Iterator<Edge> edges = this.edges(direction);
List<Id> adjacentVertices = new ArrayList<>();
while (edges.hasNext()) {
HugeEdge edge = (HugeEdge) edges.next();
Id sourceVertexId = edge.ownerVertex().id();
Id targetVertexId = edge.otherVertex().id();
if (currentSourceVertexId == null) {
currentSourceVertexId = sourceVertexId;
adjacentVertices.add(targetVertexId);
} else if (currentSourceVertexId.equals(sourceVertexId)) {
if (adjacentVertices.size() < degree) {
adjacentVertices.add(targetVertexId);
}
} else {
changeCount += this.findAndSetMinComponent(
currentSourceVertexId,
adjacentVertices);
adjacentVertices = new ArrayList<>();
currentSourceVertexId = sourceVertexId;
adjacentVertices.add(targetVertexId);
}
}
changeCount += this.findAndSetMinComponent(
currentSourceVertexId,
adjacentVertices);
LOG.debug("iterationTimes:{}, changeCount:{}",
times, changeCount);
if (changeCount == 0L) {
break;
}
}
int compCount = writeBackValue();
return ImmutableMap.of("components", compCount,
"iteration_times", times,
"times", maxTimes);
}
private void initSchema() {
String cl = C_LABEL;
SchemaManager schema = this.graph().schema();
schema.propertyKey(cl).asText().ifNotExist().create();
for (VertexLabel vl : schema.getVertexLabels()) {
schema.vertexLabel(vl.name()).properties(cl)
.nullableKeys(cl).append();
}
}
private void initVertexComponentMap() {
Iterator<Vertex> vertices = this.vertices();
while (vertices.hasNext()) {
Id id = ((HugeVertex) vertices.next()).id();
this.vertexComponentMap.put(id, id);
}
}
/**
* process for a vertex and its adjacentVertices
*
* @param sourceVertexId the source vertex
* @param adjacentVertices the adjacent vertices attached to source
* vertex
* @return the count of vertex that changed Component
*/
private long findAndSetMinComponent(Id sourceVertexId,
List<Id> adjacentVertices) {
if (!this.vertexComponentMap.containsKey(sourceVertexId)) {
return 0L;
}
Id min = this.findMinComponent(sourceVertexId, adjacentVertices);
return this.updateComponentIfNeeded(min,
sourceVertexId,
adjacentVertices);
}
private Id findMinComponent(Id sourceVertexId,
List<Id> adjacentVertices) {<FILL_FUNCTION_BODY>}
private long updateComponentIfNeeded(Id min,
Id sourceVertexId,
List<Id> adjacentVertices) {
long changedCount = 0;
Id comp = this.vertexComponentMap.get(sourceVertexId);
if (comp.compareTo(min) > 0) {
this.vertexComponentMap.put(sourceVertexId, min);
changedCount++;
}
for (Id vertex : adjacentVertices) {
comp = this.vertexComponentMap.get(vertex);
if (comp != null && comp.compareTo(min) > 0) {
this.vertexComponentMap.put(vertex, min);
changedCount++;
}
}
return changedCount;
}
/**
* @return the count of components
*/
private int writeBackValue() {
Map<Id, Integer> componentIndexMap = new HashMap<>();
int index = 0;
for (Map.Entry<Id, Id> entry : this.vertexComponentMap.entrySet()) {
Id comp = entry.getValue();
Integer componentIndex = componentIndexMap.get(comp);
if (componentIndex == null) {
componentIndex = index;
componentIndexMap.put(comp, componentIndex);
index++;
}
Vertex vertex = this.vertex(entry.getKey());
if (vertex != null) {
vertex.property(C_LABEL, String.valueOf(componentIndex));
this.commitIfNeeded();
}
}
this.graph().tx().commit();
return index;
}
}
|
Id min = this.vertexComponentMap.get(sourceVertexId);
for (Id vertex : adjacentVertices) {
Id comp = this.vertexComponentMap.get(vertex);
if (comp != null && comp.compareTo(min) < 0) {
min = comp;
}
}
return min;
| 1,277
| 84
| 1,361
|
<methods>public non-sealed void <init>() ,public java.lang.String category() <variables>private static final int MAX_TIMES
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/algorithm/path/RingsDetectAlgorithm.java
|
Traverser
|
rings
|
class Traverser extends AlgoTraverser {
public Traverser(UserJob<Object> job, int workers) {
super(job, ALGO_NAME, workers);
}
public Object rings(String sourceLabel, String sourceCLabel,
Directions dir, String label, int depth,
long degree, long eachLimit, long limit,
boolean countOnly) {<FILL_FUNCTION_BODY>}
}
|
JsonMap ringsJson = new JsonMap();
ringsJson.startObject();
if (countOnly) {
ringsJson.appendKey("rings_count");
} else {
ringsJson.appendKey("rings");
ringsJson.startList();
}
SubGraphTraverser traverser = new SubGraphTraverser(this.graph());
AtomicLong count = new AtomicLong(0L);
this.traverse(sourceLabel, sourceCLabel, v -> {
Id source = (Id) v.id();
PathSet rings = traverser.rings(source, dir, label, depth,
true, degree, MAX_CAPACITY,
eachLimit);
assert eachLimit == NO_LIMIT || rings.size() <= eachLimit;
for (Path ring : rings) {
if (eachLimit == NO_LIMIT && !ring.ownedBy(source)) {
// Only dedup rings when each_limit!=NO_LIMIT
continue;
}
if (count.incrementAndGet() > limit && limit != NO_LIMIT) {
throw new StopExecution("exceed limit %s", limit);
}
if (!countOnly) {
String ringJson = JsonUtil.toJson(ring.vertices());
synchronized (ringsJson) {
ringsJson.appendRaw(ringJson);
}
}
}
});
if (countOnly) {
long counted = count.get();
if (limit != NO_LIMIT && counted > limit) {
// The count increased by multi threads and exceed limit
counted = limit;
}
ringsJson.append(counted);
} else {
ringsJson.endList();
}
ringsJson.endObject();
return ringsJson.asJson();
| 110
| 451
| 561
|
<methods>public non-sealed void <init>() ,public void checkParameters(Map<java.lang.String,java.lang.Object>) <variables>public static final int BATCH,public static final java.lang.String CATEGORY_AGGR,public static final java.lang.String CATEGORY_CENT,public static final java.lang.String CATEGORY_COMM,public static final java.lang.String CATEGORY_PATH,public static final java.lang.String CATEGORY_RANK,public static final java.lang.String CATEGORY_SIMI,public static final java.lang.String C_LABEL,public static final double DEFAULT_ALPHA,public static final long DEFAULT_CAPACITY,public static final long DEFAULT_DEGREE,public static final long DEFAULT_EACH_LIMIT,public static final long DEFAULT_LIMIT,public static final double DEFAULT_PRECISION,public static final long DEFAULT_SAMPLE,public static final long DEFAULT_STABLE_TIMES,public static final long DEFAULT_TIMES,public static final java.lang.String EXPORT_PATH,public static final java.lang.String KEY_ALPHA,public static final java.lang.String KEY_CAPACITY,public static final java.lang.String KEY_CLEAR,public static final java.lang.String KEY_DEGREE,public static final java.lang.String KEY_DEPTH,public static final java.lang.String KEY_DIRECTION,public static final java.lang.String KEY_EACH_LIMIT,public static final java.lang.String KEY_EXPORT_COMM,public static final java.lang.String KEY_LABEL,public static final java.lang.String KEY_LIMIT,public static final java.lang.String KEY_PRECISION,public static final java.lang.String KEY_SAMPLE,public static final java.lang.String KEY_SHOW_COMM,public static final java.lang.String KEY_SHOW_MOD,public static final java.lang.String KEY_SKIP_ISOLATED,public static final java.lang.String KEY_SOURCE_CLABEL,public static final java.lang.String KEY_SOURCE_LABEL,public static final java.lang.String KEY_SOURCE_SAMPLE,public static final java.lang.String KEY_STABLE_TIMES,public static final java.lang.String KEY_TIMES,public static final java.lang.String KEY_TOP,public static final java.lang.String KEY_WORKERS,public static final long MAX_CAPACITY,public static final long MAX_QUERY_LIMIT,public static final long MAX_RESULT_SIZE,public static final java.lang.String R_RANK,public static final java.lang.String USER_DIR
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/algorithm/rank/PageRankAlgorithm.java
|
DoublePair
|
equals
|
class DoublePair implements Comparable<DoublePair> {
private double left;
private double right;
private DoublePair(double left, double right) {
this.left = left;
this.right = right;
}
public void addLeft(double value) {
this.left += value;
}
public void addRight(double value) {
this.right += value;
}
public double left() {
return this.left;
}
public void left(double value) {
this.left = value;
}
public double right() {
return this.right;
}
public void right(double value) {
this.right = value;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("left:").append(this.left)
.append(", right: ").append(this.right);
return sb.toString();
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Double.hashCode(this.left) ^ Double.hashCode(this.right);
}
// only left saves the rank value.
@Override
public int compareTo(DoublePair o) {
double result = this.left - o.left;
if (result > 0.0) {
return 1;
} else if (result < 0.0) {
return -1;
}
return 0;
}
}
|
if (!(obj instanceof DoublePair)) {
return false;
}
DoublePair other = (DoublePair) obj;
return this.left == other.left && this.right == other.right;
| 405
| 53
| 458
|
<methods>public non-sealed void <init>() ,public java.lang.String category() <variables>private static final int MAX_TIMES
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/algorithm/similarity/FusiformSimilarityAlgorithm.java
|
FusiformSimilarityAlgorithm
|
topSimilars
|
class FusiformSimilarityAlgorithm extends AbstractAlgorithm {
public static final String ALGO_NAME = "fusiform_similarity";
public static final String KEY_MIN_NEIGHBORS = "min_neighbors";
public static final String KEY_MIN_SIMILARS = "min_similars";
public static final String KEY_TOP_SIMILARS = "top_similars";
public static final String KEY_GROUP_PROPERTY = "group_property";
public static final String KEY_MIN_GROUPS = "min_groups";
public static final int DEFAULT_MIN_NEIGHBORS = 10;
public static final int DEFAULT_MIN_SIMILARS = 6;
public static final int DEFAULT_TOP_SIMILARS = 0;
public static final int DEFAULT_MIN_GROUPS = 0;
@Override
public String category() {
return CATEGORY_SIMI;
}
@Override
public String name() {
return ALGO_NAME;
}
@Override
public void checkParameters(Map<String, Object> parameters) {
minNeighbors(parameters);
alpha(parameters);
minSimilars(parameters);
topSimilars(parameters);
groupProperty(parameters);
minGroups(parameters);
degree(parameters);
limit(parameters);
sourceLabel(parameters);
sourceCLabel(parameters);
direction(parameters);
edgeLabel(parameters);
workers(parameters);
}
@Override
public Object call(UserJob<Object> job, Map<String, Object> parameters) {
int workers = workers(parameters);
try (Traverser traverser = new Traverser(job, workers)) {
return traverser.fusiformSimilars(sourceLabel(parameters),
sourceCLabel(parameters),
direction(parameters),
edgeLabel(parameters),
minNeighbors(parameters),
alpha(parameters),
minSimilars(parameters),
topSimilars(parameters),
groupProperty(parameters),
minGroups(parameters),
degree(parameters),
limit(parameters));
}
}
protected static int minNeighbors(Map<String, Object> parameters) {
if (!parameters.containsKey(KEY_MIN_NEIGHBORS)) {
return DEFAULT_MIN_NEIGHBORS;
}
int minNeighbors = ParameterUtil.parameterInt(parameters,
KEY_MIN_NEIGHBORS);
HugeTraverser.checkPositive(minNeighbors, KEY_MIN_NEIGHBORS);
return minNeighbors;
}
protected static int minSimilars(Map<String, Object> parameters) {
if (!parameters.containsKey(KEY_MIN_SIMILARS)) {
return DEFAULT_MIN_SIMILARS;
}
int minSimilars = ParameterUtil.parameterInt(parameters,
KEY_MIN_SIMILARS);
HugeTraverser.checkPositive(minSimilars, KEY_MIN_SIMILARS);
return minSimilars;
}
protected static int topSimilars(Map<String, Object> parameters) {<FILL_FUNCTION_BODY>}
protected static String groupProperty(Map<String, Object> parameters) {
if (!parameters.containsKey(KEY_GROUP_PROPERTY)) {
return null;
}
return ParameterUtil.parameterString(parameters, KEY_GROUP_PROPERTY);
}
protected static int minGroups(Map<String, Object> parameters) {
if (!parameters.containsKey(KEY_MIN_GROUPS)) {
return DEFAULT_MIN_GROUPS;
}
int minGroups = ParameterUtil.parameterInt(parameters, KEY_MIN_GROUPS);
HugeTraverser.checkPositive(minGroups, KEY_MIN_GROUPS);
return minGroups;
}
protected static long limit(Map<String, Object> parameters) {
if (!parameters.containsKey(KEY_LIMIT)) {
return DEFAULT_LIMIT;
}
long limit = ParameterUtil.parameterLong(parameters, KEY_LIMIT);
HugeTraverser.checkLimit(limit);
return limit;
}
private static class Traverser extends AlgoTraverser {
public Traverser(UserJob<Object> job, int workers) {
super(job, ALGO_NAME, workers);
}
public Object fusiformSimilars(String sourceLabel, String sourceCLabel,
Directions direction, String label,
int minNeighbors, double alpha,
int minSimilars, long topSimilars,
String groupProperty, int minGroups,
long degree, long limit) {
HugeGraph graph = this.graph();
FusiformSimilarityTraverser traverser =
new FusiformSimilarityTraverser(graph);
AtomicLong count = new AtomicLong(0L);
JsonMap similarsJson = new JsonMap();
similarsJson.startObject();
this.traverse(sourceLabel, sourceCLabel, v -> {
SimilarsMap similars = traverser.fusiformSimilarity(
IteratorUtils.of(v), direction,
label, minNeighbors, alpha,
minSimilars, (int) topSimilars,
groupProperty, minGroups, degree,
MAX_CAPACITY, NO_LIMIT, true);
if (similars.isEmpty()) {
return;
}
String result = JsonUtil.toJson(similars.toMap());
result = result.substring(1, result.length() - 1);
synchronized (similarsJson) {
if (count.incrementAndGet() > limit && limit != NO_LIMIT) {
throw new StopExecution("exceed limit %s", limit);
}
similarsJson.appendRaw(result);
}
});
similarsJson.endObject();
return similarsJson.asJson();
}
}
}
|
if (!parameters.containsKey(KEY_TOP_SIMILARS)) {
return DEFAULT_TOP_SIMILARS;
}
int minSimilars = ParameterUtil.parameterInt(parameters,
KEY_TOP_SIMILARS);
HugeTraverser.checkNonNegative(minSimilars, KEY_TOP_SIMILARS);
return minSimilars;
| 1,556
| 109
| 1,665
|
<methods>public non-sealed void <init>() ,public void checkParameters(Map<java.lang.String,java.lang.Object>) <variables>public static final int BATCH,public static final java.lang.String CATEGORY_AGGR,public static final java.lang.String CATEGORY_CENT,public static final java.lang.String CATEGORY_COMM,public static final java.lang.String CATEGORY_PATH,public static final java.lang.String CATEGORY_RANK,public static final java.lang.String CATEGORY_SIMI,public static final java.lang.String C_LABEL,public static final double DEFAULT_ALPHA,public static final long DEFAULT_CAPACITY,public static final long DEFAULT_DEGREE,public static final long DEFAULT_EACH_LIMIT,public static final long DEFAULT_LIMIT,public static final double DEFAULT_PRECISION,public static final long DEFAULT_SAMPLE,public static final long DEFAULT_STABLE_TIMES,public static final long DEFAULT_TIMES,public static final java.lang.String EXPORT_PATH,public static final java.lang.String KEY_ALPHA,public static final java.lang.String KEY_CAPACITY,public static final java.lang.String KEY_CLEAR,public static final java.lang.String KEY_DEGREE,public static final java.lang.String KEY_DEPTH,public static final java.lang.String KEY_DIRECTION,public static final java.lang.String KEY_EACH_LIMIT,public static final java.lang.String KEY_EXPORT_COMM,public static final java.lang.String KEY_LABEL,public static final java.lang.String KEY_LIMIT,public static final java.lang.String KEY_PRECISION,public static final java.lang.String KEY_SAMPLE,public static final java.lang.String KEY_SHOW_COMM,public static final java.lang.String KEY_SHOW_MOD,public static final java.lang.String KEY_SKIP_ISOLATED,public static final java.lang.String KEY_SOURCE_CLABEL,public static final java.lang.String KEY_SOURCE_LABEL,public static final java.lang.String KEY_SOURCE_SAMPLE,public static final java.lang.String KEY_STABLE_TIMES,public static final java.lang.String KEY_TIMES,public static final java.lang.String KEY_TOP,public static final java.lang.String KEY_WORKERS,public static final long MAX_CAPACITY,public static final long MAX_QUERY_LIMIT,public static final long MAX_RESULT_SIZE,public static final java.lang.String R_RANK,public static final java.lang.String USER_DIR
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/computer/LouvainComputer.java
|
LouvainComputer
|
stableTimes
|
class LouvainComputer extends AbstractComputer {
public static final String LOUVAIN = "louvain";
public static final String KEY_STABLE_TIMES = "stable_times";
public static final String KEY_PRECISION = "precision";
public static final String KEY_SHOW_MOD = "show_modularity";
public static final String KEY_SHOW_COMM = "show_community";
public static final String KEY_EXPORT_COMM = "export_community";
public static final String KEY_SKIP_ISOLATED = "skip_isolated";
public static final String KEY_CLEAR = "clear";
public static final long DEFAULT_STABLE_TIMES = 3L;
private static final int MAX_TIMES = 2048;
@Override
public String name() {
return LOUVAIN;
}
@Override
public String category() {
return CATEGORY_COMM;
}
@Override
public void checkParameters(Map<String, Object> parameters) {
times(parameters);
stableTimes(parameters);
precision(parameters);
degree(parameters);
showModularity(parameters);
showCommunity(parameters);
exportCommunity(parameters);
skipIsolated(parameters);
clearPass(parameters);
}
@Override
protected Map<String, Object> checkAndCollectParameters(
Map<String, Object> parameters) {
return ImmutableMap.of(TIMES, times(parameters),
PRECISION, precision(parameters),
DIRECTION, direction(parameters),
DEGREE, degree(parameters));
}
protected static int stableTimes(Map<String, Object> parameters) {<FILL_FUNCTION_BODY>}
protected static Long showModularity(Map<String, Object> parameters) {
if (!parameters.containsKey(KEY_SHOW_MOD)) {
return null;
}
long pass = ParameterUtil.parameterLong(parameters, KEY_SHOW_MOD);
HugeTraverser.checkNonNegative(pass, KEY_SHOW_MOD);
return pass;
}
protected static String showCommunity(Map<String, Object> parameters) {
if (!parameters.containsKey(KEY_SHOW_COMM)) {
return null;
}
return ParameterUtil.parameterString(parameters, KEY_SHOW_COMM);
}
protected static Long exportCommunity(Map<String, Object> parameters) {
if (!parameters.containsKey(KEY_EXPORT_COMM)) {
return null;
}
long pass = ParameterUtil.parameterLong(parameters, KEY_EXPORT_COMM);
HugeTraverser.checkNonNegative(pass, KEY_EXPORT_COMM);
return pass;
}
protected static boolean skipIsolated(Map<String, Object> parameters) {
if (!parameters.containsKey(KEY_SKIP_ISOLATED)) {
return true;
}
return ParameterUtil.parameterBoolean(parameters, KEY_SKIP_ISOLATED);
}
protected static Long clearPass(Map<String, Object> parameters) {
if (!parameters.containsKey(KEY_CLEAR)) {
return null;
}
long pass = ParameterUtil.parameterLong(parameters, KEY_CLEAR);
HugeTraverser.checkNonNegativeOrNoLimit(pass, KEY_CLEAR);
return pass;
}
}
|
if (!parameters.containsKey(KEY_STABLE_TIMES)) {
return (int) DEFAULT_STABLE_TIMES;
}
int times = ParameterUtil.parameterInt(parameters, KEY_STABLE_TIMES);
HugeTraverser.checkPositiveOrNoLimit(times, KEY_STABLE_TIMES);
E.checkArgument(times <= MAX_TIMES,
"The maximum number of stable iterations is %s, " +
"but got %s", MAX_TIMES, times);
return times;
| 870
| 140
| 1,010
|
<methods>public non-sealed void <init>() ,public java.lang.Object call(Job<java.lang.Object>, Map<java.lang.String,java.lang.Object>) ,public void checkParameters(Map<java.lang.String,java.lang.Object>) <variables>protected static final java.lang.String CATEGORY_COMM,protected static final java.lang.String CATEGORY_RANK,private static final java.lang.String COMMON,private static final java.lang.String COMPUTER_HOME,public static final long DEFAULT_DEGREE,public static final int DEFAULT_MAX_STEPS,public static final double DEFAULT_PRECISION,public static final int DEFAULT_TIMES,public static final java.lang.String DEGREE,public static final java.lang.String DIRECTION,private static final java.lang.String ENV,private static final java.lang.String EQUAL,private static final java.lang.String HADOOP_HOME,private static final Logger LOG,private static final java.lang.String MAIN_COMMAND,public static final java.lang.String MAX_STEPS,private static final java.lang.String MINUS_C,public static final java.lang.String PRECISION,private static final java.lang.String SPACE,public static final java.lang.String TIMES,private Map<java.lang.String,java.lang.Object> commonConfig,private YAMLConfiguration config
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/computer/LpaComputer.java
|
LpaComputer
|
property
|
class LpaComputer extends AbstractComputer {
public static final String LPA = "lpa";
public static final String PROPERTY = "property";
public static final String DEFAULT_PROPERTY = "id";
@Override
public String name() {
return LPA;
}
@Override
public String category() {
return CATEGORY_COMM;
}
@Override
public void checkParameters(Map<String, Object> parameters) {
times(parameters);
property(parameters);
precision(parameters);
direction(parameters);
degree(parameters);
}
@Override
protected Map<String, Object> checkAndCollectParameters(
Map<String, Object> parameters) {
return ImmutableMap.of(TIMES, times(parameters),
PROPERTY, property(parameters),
PRECISION, precision(parameters),
DIRECTION, direction(parameters),
DEGREE, degree(parameters));
}
private static String property(Map<String, Object> parameters) {<FILL_FUNCTION_BODY>}
}
|
if (!parameters.containsKey(PROPERTY)) {
return DEFAULT_PROPERTY;
}
String property = ParameterUtil.parameterString(parameters, PROPERTY);
E.checkArgument(property != null && !property.isEmpty(),
"The value of %s can not be null or empty", PROPERTY);
return property;
| 278
| 90
| 368
|
<methods>public non-sealed void <init>() ,public java.lang.Object call(Job<java.lang.Object>, Map<java.lang.String,java.lang.Object>) ,public void checkParameters(Map<java.lang.String,java.lang.Object>) <variables>protected static final java.lang.String CATEGORY_COMM,protected static final java.lang.String CATEGORY_RANK,private static final java.lang.String COMMON,private static final java.lang.String COMPUTER_HOME,public static final long DEFAULT_DEGREE,public static final int DEFAULT_MAX_STEPS,public static final double DEFAULT_PRECISION,public static final int DEFAULT_TIMES,public static final java.lang.String DEGREE,public static final java.lang.String DIRECTION,private static final java.lang.String ENV,private static final java.lang.String EQUAL,private static final java.lang.String HADOOP_HOME,private static final Logger LOG,private static final java.lang.String MAIN_COMMAND,public static final java.lang.String MAX_STEPS,private static final java.lang.String MINUS_C,public static final java.lang.String PRECISION,private static final java.lang.String SPACE,public static final java.lang.String TIMES,private Map<java.lang.String,java.lang.Object> commonConfig,private YAMLConfiguration config
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/computer/PageRankComputer.java
|
PageRankComputer
|
alpha
|
class PageRankComputer extends AbstractComputer {
public static final String PAGE_RANK = "page_rank";
public static final String ALPHA = "alpha";
public static final double DEFAULT_ALPHA = 0.15D;
@Override
public String name() {
return PAGE_RANK;
}
@Override
public String category() {
return CATEGORY_RANK;
}
@Override
public void checkParameters(Map<String, Object> parameters) {
maxSteps(parameters);
alpha(parameters);
precision(parameters);
}
@Override
protected Map<String, Object> checkAndCollectParameters(
Map<String, Object> parameters) {
return ImmutableMap.of(MAX_STEPS, maxSteps(parameters),
ALPHA, alpha(parameters),
PRECISION, precision(parameters));
}
private static double alpha(Map<String, Object> parameters) {<FILL_FUNCTION_BODY>}
}
|
if (!parameters.containsKey(ALPHA)) {
return DEFAULT_ALPHA;
}
double alpha = ParameterUtil.parameterDouble(parameters, ALPHA);
E.checkArgument(alpha > 0 && alpha < 1,
"The value of %s must be (0, 1), but got %s",
ALPHA, alpha);
return alpha;
| 266
| 96
| 362
|
<methods>public non-sealed void <init>() ,public java.lang.Object call(Job<java.lang.Object>, Map<java.lang.String,java.lang.Object>) ,public void checkParameters(Map<java.lang.String,java.lang.Object>) <variables>protected static final java.lang.String CATEGORY_COMM,protected static final java.lang.String CATEGORY_RANK,private static final java.lang.String COMMON,private static final java.lang.String COMPUTER_HOME,public static final long DEFAULT_DEGREE,public static final int DEFAULT_MAX_STEPS,public static final double DEFAULT_PRECISION,public static final int DEFAULT_TIMES,public static final java.lang.String DEGREE,public static final java.lang.String DIRECTION,private static final java.lang.String ENV,private static final java.lang.String EQUAL,private static final java.lang.String HADOOP_HOME,private static final Logger LOG,private static final java.lang.String MAIN_COMMAND,public static final java.lang.String MAX_STEPS,private static final java.lang.String MINUS_C,public static final java.lang.String PRECISION,private static final java.lang.String SPACE,public static final java.lang.String TIMES,private Map<java.lang.String,java.lang.Object> commonConfig,private YAMLConfiguration config
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/schema/EdgeLabelRemoveJob.java
|
EdgeLabelRemoveJob
|
removeEdgeLabel
|
class EdgeLabelRemoveJob extends SchemaJob {
@Override
public String type() {
return REMOVE_SCHEMA;
}
@Override
public Object execute() {
removeEdgeLabel(this.params(), this.schemaId());
return null;
}
private static void removeEdgeLabel(HugeGraphParams graph, Id id) {<FILL_FUNCTION_BODY>}
}
|
GraphTransaction graphTx = graph.graphTransaction();
SchemaTransaction schemaTx = graph.schemaTransaction();
EdgeLabel edgeLabel = schemaTx.getEdgeLabel(id);
// If the edge label does not exist, return directly
if (edgeLabel == null) {
return;
}
if (edgeLabel.status().deleting()) {
LOG.info("The edge label '{}' has been in {} status, " +
"please check if it's expected to delete it again",
edgeLabel, edgeLabel.status());
}
// Remove index related data(include schema) of this edge label
Set<Id> indexIds = ImmutableSet.copyOf(edgeLabel.indexLabels());
LockUtil.Locks locks = new LockUtil.Locks(graph.name());
try {
locks.lockWrites(LockUtil.EDGE_LABEL_DELETE, id);
schemaTx.updateSchemaStatus(edgeLabel, SchemaStatus.DELETING);
try {
for (Id indexId : indexIds) {
IndexLabelRemoveJob.removeIndexLabel(graph, indexId);
}
// Remove all edges which has matched label
// TODO: use event to replace direct call
graphTx.removeEdges(edgeLabel);
/*
* Should commit changes to backend store before release
* delete lock
*/
graph.graph().tx().commit();
// Remove edge label
removeSchema(schemaTx, edgeLabel);
} catch (Throwable e) {
schemaTx.updateSchemaStatus(edgeLabel, SchemaStatus.UNDELETED);
throw e;
}
} finally {
locks.unlock();
}
| 106
| 411
| 517
|
<methods>public non-sealed void <init>() ,public static java.lang.String formatTaskName(org.apache.hugegraph.type.HugeType, org.apache.hugegraph.backend.id.Id, java.lang.String) <variables>public static final java.lang.String CLEAR_OLAP,public static final java.lang.String CREATE_INDEX,public static final java.lang.String CREATE_OLAP,protected static final Logger LOG,public static final java.lang.String REBUILD_INDEX,public static final java.lang.String REMOVE_OLAP,public static final java.lang.String REMOVE_SCHEMA,private static final java.lang.String SPLITOR
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/schema/IndexLabelRebuildJob.java
|
IndexLabelRebuildJob
|
removeIndex
|
class IndexLabelRebuildJob extends SchemaJob {
@Override
public String type() {
return REBUILD_INDEX;
}
@Override
public Object execute() {
SchemaElement schema = this.schemaElement();
// If the schema does not exist, ignore it
if (schema != null) {
this.rebuildIndex(schema);
}
return null;
}
private void rebuildIndex(SchemaElement schema) {
switch (schema.type()) {
case INDEX_LABEL:
IndexLabel indexLabel = (IndexLabel) schema;
SchemaLabel label;
if (indexLabel.baseType() == HugeType.VERTEX_LABEL) {
label = this.graph().vertexLabel(indexLabel.baseValue());
} else {
assert indexLabel.baseType() == HugeType.EDGE_LABEL;
label = this.graph().edgeLabel(indexLabel.baseValue());
}
assert label != null;
this.rebuildIndex(label, ImmutableSet.of(indexLabel.id()));
break;
case VERTEX_LABEL:
case EDGE_LABEL:
label = (SchemaLabel) schema;
this.rebuildIndex(label, label.indexLabels());
break;
default:
assert schema.type() == HugeType.PROPERTY_KEY;
throw new AssertionError(String.format(
"The %s can't rebuild index", schema.type()));
}
}
private void rebuildIndex(SchemaLabel label, Collection<Id> indexLabelIds) {
SchemaTransaction schemaTx = this.params().schemaTransaction();
GraphTransaction graphTx = this.params().graphTransaction();
Consumer<?> indexUpdater = (elem) -> {
for (Id id : indexLabelIds) {
graphTx.updateIndex(id, (HugeElement) elem, false);
}
};
LockUtil.Locks locks = new LockUtil.Locks(schemaTx.graphName());
try {
locks.lockWrites(LockUtil.INDEX_LABEL_REBUILD, indexLabelIds);
Set<IndexLabel> ils = indexLabelIds.stream()
.map(this.graph()::indexLabel)
.collect(Collectors.toSet());
for (IndexLabel il : ils) {
if (il.status() == SchemaStatus.CREATING) {
continue;
}
schemaTx.updateSchemaStatus(il, SchemaStatus.REBUILDING);
}
this.removeIndex(indexLabelIds);
/*
* Note: Here must commit index transaction firstly.
* Because remove index convert to (id like <?>:personByCity):
* `delete from index table where label = ?`,
* But append index will convert to (id like Beijing:personByCity):
* `update index element_ids += xxx where field_value = ?
* and index_label_name = ?`,
* They have different id lead to it can't compare and optimize
*/
graphTx.commit();
try {
if (label.type() == HugeType.VERTEX_LABEL) {
@SuppressWarnings("unchecked")
Consumer<Vertex> consumer = (Consumer<Vertex>) indexUpdater;
graphTx.traverseVerticesByLabel((VertexLabel) label,
consumer, false);
} else {
assert label.type() == HugeType.EDGE_LABEL;
@SuppressWarnings("unchecked")
Consumer<Edge> consumer = (Consumer<Edge>) indexUpdater;
graphTx.traverseEdgesByLabel((EdgeLabel) label,
consumer, false);
}
graphTx.commit();
} catch (Throwable e) {
for (IndexLabel il : ils) {
schemaTx.updateSchemaStatus(il, SchemaStatus.INVALID);
}
throw e;
}
for (IndexLabel il : ils) {
schemaTx.updateSchemaStatus(il, SchemaStatus.CREATED);
}
} finally {
locks.unlock();
}
}
private void removeIndex(Collection<Id> indexLabelIds) {<FILL_FUNCTION_BODY>}
private SchemaElement schemaElement() {
HugeType type = this.schemaType();
Id id = this.schemaId();
switch (type) {
case VERTEX_LABEL:
return this.graph().vertexLabel(id);
case EDGE_LABEL:
return this.graph().edgeLabel(id);
case INDEX_LABEL:
return this.graph().indexLabel(id);
default:
throw new AssertionError(String.format(
"Invalid HugeType '%s' for rebuild", type));
}
}
}
|
SchemaTransaction schemaTx = this.params().schemaTransaction();
GraphTransaction graphTx = this.params().graphTransaction();
for (Id id : indexLabelIds) {
IndexLabel il = schemaTx.getIndexLabel(id);
if (il == null || il.status() == SchemaStatus.CREATING) {
/*
* TODO: How to deal with non-existent index name:
* continue or throw exception?
*/
continue;
}
LockUtil.Locks locks = new LockUtil.Locks(schemaTx.graphName());
try {
locks.lockWrites(LockUtil.INDEX_LABEL_DELETE, indexLabelIds);
graphTx.removeIndex(il);
} catch (Throwable e) {
schemaTx.updateSchemaStatus(il, SchemaStatus.INVALID);
throw e;
} finally {
locks.unlock();
}
}
| 1,231
| 229
| 1,460
|
<methods>public non-sealed void <init>() ,public static java.lang.String formatTaskName(org.apache.hugegraph.type.HugeType, org.apache.hugegraph.backend.id.Id, java.lang.String) <variables>public static final java.lang.String CLEAR_OLAP,public static final java.lang.String CREATE_INDEX,public static final java.lang.String CREATE_OLAP,protected static final Logger LOG,public static final java.lang.String REBUILD_INDEX,public static final java.lang.String REMOVE_OLAP,public static final java.lang.String REMOVE_SCHEMA,private static final java.lang.String SPLITOR
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/schema/IndexLabelRemoveJob.java
|
IndexLabelRemoveJob
|
removeIndexLabel
|
class IndexLabelRemoveJob extends SchemaJob {
@Override
public String type() {
return REMOVE_SCHEMA;
}
@Override
public Object execute() {
removeIndexLabel(this.params(), this.schemaId());
return null;
}
protected static void removeIndexLabel(HugeGraphParams graph, Id id) {<FILL_FUNCTION_BODY>}
}
|
GraphTransaction graphTx = graph.graphTransaction();
SchemaTransaction schemaTx = graph.schemaTransaction();
IndexLabel indexLabel = schemaTx.getIndexLabel(id);
// If the index label does not exist, return directly
if (indexLabel == null) {
return;
}
if (indexLabel.status().deleting()) {
LOG.info("The index label '{}' has been in {} status, " +
"please check if it's expected to delete it again",
indexLabel, indexLabel.status());
}
LockUtil.Locks locks = new LockUtil.Locks(graph.name());
try {
locks.lockWrites(LockUtil.INDEX_LABEL_DELETE, id);
// TODO add update lock
// Set index label to "deleting" status
schemaTx.updateSchemaStatus(indexLabel, SchemaStatus.DELETING);
try {
// Remove indexLabel from indexLabels of vertex/edge label
schemaTx.removeIndexLabelFromBaseLabel(indexLabel);
// Remove index data
// TODO: use event to replace direct call
graphTx.removeIndex(indexLabel);
/*
* Should commit changes to backend store before release
* delete lock
*/
graph.graph().tx().commit();
// Remove index label
removeSchema(schemaTx, indexLabel);
} catch (Throwable e) {
schemaTx.updateSchemaStatus(indexLabel, SchemaStatus.UNDELETED);
throw e;
}
} finally {
locks.unlock();
}
| 106
| 387
| 493
|
<methods>public non-sealed void <init>() ,public static java.lang.String formatTaskName(org.apache.hugegraph.type.HugeType, org.apache.hugegraph.backend.id.Id, java.lang.String) <variables>public static final java.lang.String CLEAR_OLAP,public static final java.lang.String CREATE_INDEX,public static final java.lang.String CREATE_OLAP,protected static final Logger LOG,public static final java.lang.String REBUILD_INDEX,public static final java.lang.String REMOVE_OLAP,public static final java.lang.String REMOVE_SCHEMA,private static final java.lang.String SPLITOR
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/schema/OlapPropertyKeyClearJob.java
|
OlapPropertyKeyClearJob
|
clearIndexLabel
|
class OlapPropertyKeyClearJob extends IndexLabelRemoveJob {
@Override
public String type() {
return CLEAR_OLAP;
}
@Override
public Object execute() {
Id olap = this.schemaId();
// Clear olap data table
this.params().graphTransaction().clearOlapPk(olap);
// Clear corresponding index data
clearIndexLabel(this.params(), olap);
return null;
}
protected static void clearIndexLabel(HugeGraphParams graph, Id id) {<FILL_FUNCTION_BODY>}
protected static Id findOlapIndexLabel(HugeGraphParams graph, Id olap) {
SchemaTransaction schemaTx = graph.schemaTransaction();
for (IndexLabel indexLabel : schemaTx.getIndexLabels()) {
if (indexLabel.indexFields().contains(olap)) {
return indexLabel.id();
}
}
return null;
}
}
|
Id olapIndexLabel = findOlapIndexLabel(graph, id);
if (olapIndexLabel == null) {
return;
}
GraphTransaction graphTx = graph.graphTransaction();
SchemaTransaction schemaTx = graph.schemaTransaction();
IndexLabel indexLabel = schemaTx.getIndexLabel(olapIndexLabel);
// If the index label does not exist, return directly
if (indexLabel == null) {
return;
}
LockUtil.Locks locks = new LockUtil.Locks(graph.name());
try {
locks.lockWrites(LockUtil.INDEX_LABEL_DELETE, olapIndexLabel);
// Set index label to "rebuilding" status
schemaTx.updateSchemaStatus(indexLabel, SchemaStatus.REBUILDING);
try {
// Remove index data
graphTx.removeIndex(indexLabel);
/*
* Should commit changes to backend store before release
* delete lock
*/
graph.graph().tx().commit();
schemaTx.updateSchemaStatus(indexLabel, SchemaStatus.CREATED);
} catch (Throwable e) {
schemaTx.updateSchemaStatus(indexLabel, SchemaStatus.INVALID);
throw e;
}
} finally {
locks.unlock();
}
| 244
| 319
| 563
|
<methods>public non-sealed void <init>() ,public java.lang.Object execute() ,public java.lang.String type() <variables>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/schema/OlapPropertyKeyCreateJob.java
|
OlapPropertyKeyCreateJob
|
execute
|
class OlapPropertyKeyCreateJob extends SchemaJob {
@Override
public String type() {
return CREATE_OLAP;
}
@Override
public Object execute() {<FILL_FUNCTION_BODY>}
}
|
SchemaTransaction schemaTx = this.params().schemaTransaction();
PropertyKey propertyKey = schemaTx.getPropertyKey(this.schemaId());
// Create olap index label schema
schemaTx.createIndexLabelForOlapPk(propertyKey);
// Create olap data table
this.params().graphTransaction().createOlapPk(propertyKey.id());
return null;
| 63
| 96
| 159
|
<methods>public non-sealed void <init>() ,public static java.lang.String formatTaskName(org.apache.hugegraph.type.HugeType, org.apache.hugegraph.backend.id.Id, java.lang.String) <variables>public static final java.lang.String CLEAR_OLAP,public static final java.lang.String CREATE_INDEX,public static final java.lang.String CREATE_OLAP,protected static final Logger LOG,public static final java.lang.String REBUILD_INDEX,public static final java.lang.String REMOVE_OLAP,public static final java.lang.String REMOVE_SCHEMA,private static final java.lang.String SPLITOR
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/schema/OlapPropertyKeyRemoveJob.java
|
OlapPropertyKeyRemoveJob
|
execute
|
class OlapPropertyKeyRemoveJob extends OlapPropertyKeyClearJob {
@Override
public String type() {
return REMOVE_OLAP;
}
@Override
public Object execute() {<FILL_FUNCTION_BODY>}
}
|
Id olap = this.schemaId();
// Remove olap data table
this.params().graphTransaction().removeOlapPk(olap);
// Remove corresponding index label and index data
Id indexLabel = findOlapIndexLabel(this.params(), olap);
if (indexLabel != null) {
removeIndexLabel(this.params(), indexLabel);
}
// Remove olap property key
SchemaTransaction schemaTx = this.params().schemaTransaction();
PropertyKey propertyKey = schemaTx.getPropertyKey(olap);
removeSchema(schemaTx, propertyKey);
return null;
| 67
| 155
| 222
|
<methods>public non-sealed void <init>() ,public java.lang.Object execute() ,public java.lang.String type() <variables>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/schema/SchemaJob.java
|
SchemaJob
|
updateSchema
|
class SchemaJob extends SysJob<Object> {
public static final String REMOVE_SCHEMA = "remove_schema";
public static final String REBUILD_INDEX = "rebuild_index";
public static final String CREATE_INDEX = "create_index";
public static final String CREATE_OLAP = "create_olap";
public static final String CLEAR_OLAP = "clear_olap";
public static final String REMOVE_OLAP = "remove_olap";
protected static final Logger LOG = Log.logger(SchemaJob.class);
private static final String SPLITOR = ":";
protected HugeType schemaType() {
String name = this.task().name();
String[] parts = name.split(SPLITOR, 3);
E.checkState(parts.length == 3 && parts[0] != null,
"Task name should be formatted to String " +
"'TYPE:ID:NAME', but got '%s'", name);
return HugeType.valueOf(parts[0]);
}
protected Id schemaId() {
String name = this.task().name();
String[] parts = name.split(SPLITOR, 3);
E.checkState(parts.length == 3 && parts[1] != null,
"Task name should be formatted to String " +
"'TYPE:ID:NAME', but got '%s'", name);
return IdGenerator.of(Long.valueOf(parts[1]));
}
protected String schemaName() {
String name = this.task().name();
String[] parts = name.split(SPLITOR, 3);
E.checkState(parts.length == 3 && parts[2] != null,
"Task name should be formatted to String " +
"'TYPE:ID:NAME', but got '%s'", name);
return parts[2];
}
public static String formatTaskName(HugeType type, Id id, String name) {
E.checkNotNull(type, "schema type");
E.checkNotNull(id, "schema id");
E.checkNotNull(name, "schema name");
return String.join(SPLITOR, type.toString(), id.asString(), name);
}
/**
* Use reflection to call SchemaTransaction.removeSchema(),
* which is protected
*
* @param tx The remove operation actual executer
* @param schema the schema to be removed
*/
protected static void removeSchema(SchemaTransaction tx,
SchemaElement schema) {
try {
Method method = SchemaTransaction.class
.getDeclaredMethod("removeSchema",
SchemaElement.class);
method.setAccessible(true);
method.invoke(tx, schema);
} catch (NoSuchMethodException | IllegalAccessException |
InvocationTargetException e) {
throw new AssertionError(
"Can't call SchemaTransaction.removeSchema()", e);
}
}
/**
* Use reflection to call SchemaTransaction.updateSchema(),
* which is protected
*
* @param tx The update operation actual execute
* @param schema the schema to be updated
*/
protected static void updateSchema(SchemaTransaction tx,
SchemaElement schema) {<FILL_FUNCTION_BODY>}
}
|
try {
Method method = SchemaTransaction.class
.getDeclaredMethod("updateSchema",
SchemaElement.class);
method.setAccessible(true);
method.invoke(tx, schema);
} catch (NoSuchMethodException | IllegalAccessException |
InvocationTargetException e) {
throw new AssertionError(
"Can't call SchemaTransaction.updateSchema()", e);
}
| 828
| 107
| 935
|
<methods>public non-sealed void <init>() ,public java.lang.Object call() throws java.lang.Exception<variables>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/schema/VertexLabelRemoveJob.java
|
VertexLabelRemoveJob
|
removeVertexLabel
|
class VertexLabelRemoveJob extends SchemaJob {
@Override
public String type() {
return REMOVE_SCHEMA;
}
@Override
public Object execute() {
removeVertexLabel(this.params(), this.schemaId());
return null;
}
private static void removeVertexLabel(HugeGraphParams graph, Id id) {<FILL_FUNCTION_BODY>}
}
|
GraphTransaction graphTx = graph.graphTransaction();
SchemaTransaction schemaTx = graph.schemaTransaction();
VertexLabel vertexLabel = schemaTx.getVertexLabel(id);
// If the vertex label does not exist, return directly
if (vertexLabel == null) {
return;
}
if (vertexLabel.status().deleting()) {
LOG.info("The vertex label '{}' has been in {} status, " +
"please check if it's expected to delete it again",
vertexLabel, vertexLabel.status());
}
// Check no edge label use the vertex label
List<EdgeLabel> edgeLabels = schemaTx.getEdgeLabels();
for (EdgeLabel edgeLabel : edgeLabels) {
if (edgeLabel.linkWithLabel(id)) {
throw new HugeException(
"Not allowed to remove vertex label '%s' " +
"because the edge label '%s' still link with it",
vertexLabel.name(), edgeLabel.name());
}
}
/*
* Copy index label ids because removeIndexLabel will mutate
* vertexLabel.indexLabels()
*/
Set<Id> indexLabelIds = ImmutableSet.copyOf(vertexLabel.indexLabels());
LockUtil.Locks locks = new LockUtil.Locks(graph.name());
try {
locks.lockWrites(LockUtil.VERTEX_LABEL_DELETE, id);
schemaTx.updateSchemaStatus(vertexLabel, SchemaStatus.DELETING);
try {
for (Id ilId : indexLabelIds) {
IndexLabelRemoveJob.removeIndexLabel(graph, ilId);
}
// TODO: use event to replace direct call
// Deleting a vertex will automatically deletes the held edge
graphTx.removeVertices(vertexLabel);
/*
* Should commit changes to backend store before release
* delete lock
*/
graph.graph().tx().commit();
// Remove vertex label
removeSchema(schemaTx, vertexLabel);
} catch (Throwable e) {
schemaTx.updateSchemaStatus(vertexLabel,
SchemaStatus.UNDELETED);
throw e;
}
} finally {
locks.unlock();
}
| 107
| 553
| 660
|
<methods>public non-sealed void <init>() ,public static java.lang.String formatTaskName(org.apache.hugegraph.type.HugeType, org.apache.hugegraph.backend.id.Id, java.lang.String) <variables>public static final java.lang.String CLEAR_OLAP,public static final java.lang.String CREATE_INDEX,public static final java.lang.String CREATE_OLAP,protected static final Logger LOG,public static final java.lang.String REBUILD_INDEX,public static final java.lang.String REMOVE_OLAP,public static final java.lang.String REMOVE_SCHEMA,private static final java.lang.String SPLITOR
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/system/DeleteExpiredElementJob.java
|
DeleteExpiredElementJob
|
execute
|
class DeleteExpiredElementJob<V> extends DeleteExpiredJob<V> {
private static final String JOB_TYPE = "delete_expired_element";
private Set<HugeElement> elements;
public DeleteExpiredElementJob(Set<HugeElement> elements) {
E.checkArgument(elements != null && !elements.isEmpty(),
"The element can't be null or empty");
this.elements = elements;
}
@Override
public String type() {
return JOB_TYPE;
}
@Override
public V execute() throws Exception {<FILL_FUNCTION_BODY>}
}
|
LOG.debug("Delete expired elements: {}", this.elements);
HugeGraphParams graph = this.params();
GraphTransaction tx = graph.graphTransaction();
try {
for (HugeElement element : this.elements) {
element.remove();
}
tx.commit();
} catch (Exception e) {
tx.rollback();
LOG.warn("Failed to delete expired elements: {}", this.elements);
throw e;
} finally {
JOB_COUNTERS.jobCounter(graph.graph()).decrement();
}
return null;
| 162
| 151
| 313
|
<methods>public non-sealed void <init>() ,public static void asyncDeleteExpiredObject(org.apache.hugegraph.HugeGraph, V) ,public static EphemeralJob<V> newDeleteExpiredElementJob(org.apache.hugegraph.job.system.JobCounters.JobCounter, V) <variables>protected static final org.apache.hugegraph.job.system.JobCounters JOB_COUNTERS,protected static final Logger LOG,private static final int MAX_JOBS
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/system/DeleteExpiredIndexJob.java
|
DeleteExpiredIndexJob
|
execute
|
class DeleteExpiredIndexJob<V> extends DeleteExpiredJob<V> {
private static final String JOB_TYPE = "delete_expired_index";
private final Set<HugeIndex> indexes;
public DeleteExpiredIndexJob(Set<HugeIndex> indexes) {
E.checkArgument(indexes != null && !indexes.isEmpty(),
"The indexes can't be null or empty");
this.indexes = indexes;
}
@Override
public String type() {
return JOB_TYPE;
}
@Override
public V execute() throws Exception {<FILL_FUNCTION_BODY>}
/*
* Delete expired element(if exist) of the index,
* otherwise just delete expired index only
*/
private void deleteExpiredIndex(HugeGraphParams graph, HugeIndex index) {
GraphTransaction tx = graph.graphTransaction();
HugeType type = index.indexLabel().queryType().isVertex() ?
HugeType.VERTEX : HugeType.EDGE;
IdQuery query = new IdQuery(type);
query.query(index.elementId());
query.showExpired(true);
Iterator<?> elements = type.isVertex() ?
tx.queryVertices(query) :
tx.queryEdges(query);
if (elements.hasNext()) {
HugeElement element = (HugeElement) elements.next();
if (element.expiredTime() == index.expiredTime()) {
element.remove();
} else {
tx.removeIndex(index);
}
} else {
tx.removeIndex(index);
}
}
}
|
LOG.debug("Delete expired indexes: {}", this.indexes);
HugeGraphParams graph = this.params();
GraphTransaction tx = graph.graphTransaction();
try {
for (HugeIndex index : this.indexes) {
this.deleteExpiredIndex(graph, index);
}
tx.commit();
} catch (Throwable e) {
tx.rollback();
LOG.warn("Failed to delete expired indexes: {}", this.indexes);
throw e;
} finally {
JOB_COUNTERS.jobCounter(graph.graph()).decrement();
}
return null;
| 422
| 162
| 584
|
<methods>public non-sealed void <init>() ,public static void asyncDeleteExpiredObject(org.apache.hugegraph.HugeGraph, V) ,public static EphemeralJob<V> newDeleteExpiredElementJob(org.apache.hugegraph.job.system.JobCounters.JobCounter, V) <variables>protected static final org.apache.hugegraph.job.system.JobCounters JOB_COUNTERS,protected static final Logger LOG,private static final int MAX_JOBS
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/system/DeleteExpiredJob.java
|
DeleteExpiredJob
|
asyncDeleteExpiredObject
|
class DeleteExpiredJob<T> extends EphemeralJob<T> {
protected static final Logger LOG = Log.logger(DeleteExpiredJob.class);
private static final int MAX_JOBS = 1000;
protected static final JobCounters JOB_COUNTERS = new JobCounters();
public static <V> void asyncDeleteExpiredObject(HugeGraph graph, V object) {<FILL_FUNCTION_BODY>}
public static <V> EphemeralJob<V> newDeleteExpiredElementJob(
JobCounter jobCounter, V object) {
if (object instanceof HugeElement) {
return new DeleteExpiredElementJob<>(jobCounter.elements());
} else {
assert object instanceof HugeIndex;
return new DeleteExpiredIndexJob<>(jobCounter.indexes());
}
}
}
|
E.checkArgumentNotNull(object, "The object can't be null");
JobCounters.JobCounter jobCounter = JOB_COUNTERS.jobCounter(graph);
if (!jobCounter.addAndTriggerDelete(object)) {
return;
}
if (jobCounter.jobs() >= MAX_JOBS) {
LOG.debug("Pending delete expired objects jobs size {} has " +
"reached the limit {}, abandon {}",
jobCounter.jobs(), MAX_JOBS, object);
return;
}
jobCounter.increment();
EphemeralJob<V> job = newDeleteExpiredElementJob(jobCounter, object);
jobCounter.clear(object);
HugeTask<?> task;
try {
task = EphemeralJobBuilder.<V>of(graph)
.name("delete_expired_object")
.job(job)
.schedule();
} catch (Throwable e) {
jobCounter.decrement();
if (e.getMessage().contains("Pending tasks size") &&
e.getMessage().contains("has exceeded the max limit")) {
// Reach tasks limit, just ignore it
return;
}
throw e;
}
/*
* If TASK_SYNC_DELETION is true, wait async thread done before
* continue. This is used when running tests.
*/
if (graph.option(CoreOptions.TASK_SYNC_DELETION)) {
task.syncWait();
}
| 214
| 383
| 597
|
<methods>public non-sealed void <init>() ,public T call() throws java.lang.Exception,public abstract T execute() throws java.lang.Exception,public abstract java.lang.String type() <variables>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/job/system/JobCounters.java
|
JobCounter
|
addElementAndTriggerDelete
|
class JobCounter {
private final AtomicInteger jobs;
private Set<HugeElement> elements;
private Set<HugeIndex> indexes;
private final int batchSize;
public JobCounter(int batchSize) {
this.jobs = new AtomicInteger(0);
this.elements = ConcurrentHashMap.newKeySet();
this.indexes = ConcurrentHashMap.newKeySet();
this.batchSize = batchSize;
}
public int jobs() {
return this.jobs.get();
}
public void decrement() {
this.jobs.decrementAndGet();
}
public void increment() {
this.jobs.incrementAndGet();
}
public Set<HugeElement> elements() {
return this.elements;
}
public Set<HugeIndex> indexes() {
return this.indexes;
}
public void clear(Object object) {
if (object instanceof HugeElement) {
this.elements = ConcurrentHashMap.newKeySet();
} else {
assert object instanceof HugeIndex;
this.indexes = ConcurrentHashMap.newKeySet();
}
}
public boolean addAndTriggerDelete(Object object) {
return object instanceof HugeElement ?
addElementAndTriggerDelete((HugeElement) object) :
addIndexAndTriggerDelete((HugeIndex) object);
}
/**
* Try to add element in collection waiting to be deleted
*
* @param element
* @return true if we should create a new delete job, false otherwise
*/
public boolean addElementAndTriggerDelete(HugeElement element) {<FILL_FUNCTION_BODY>}
/**
* Try to add edge in collection waiting to be deleted
*
* @param index
* @return true if we should create a new delete job, false otherwise
*/
public boolean addIndexAndTriggerDelete(HugeIndex index) {
if (this.indexes.size() >= this.batchSize) {
return true;
}
this.indexes.add(index);
return this.indexes.size() >= this.batchSize;
}
}
|
if (this.elements.size() >= this.batchSize) {
return true;
}
this.elements.add(element);
return this.elements.size() >= this.batchSize;
| 559
| 53
| 612
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/masterelection/ClusterRole.java
|
ClusterRole
|
equals
|
class ClusterRole {
private final String node;
private long clock;
private final int epoch;
private final String url;
public ClusterRole(String node, String url, int epoch) {
this(node, url, epoch, 1);
}
public ClusterRole(String node, String url, int epoch, long clock) {
this.node = node;
this.url = url;
this.epoch = epoch;
this.clock = clock;
}
public void increaseClock() {
this.clock++;
}
public boolean isMaster(String node) {
return Objects.equals(this.node, node);
}
public int epoch() {
return this.epoch;
}
public long clock() {
return this.clock;
}
public void clock(long clock) {
this.clock = clock;
}
public String node() {
return this.node;
}
public String url() {
return this.url;
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(node, clock, epoch);
}
@Override
public String toString() {
return "RoleStateData{" +
"node='" + node + '\'' +
", clock=" + clock +
", epoch=" + epoch +
'}';
}
}
|
if (this == obj) {
return true;
}
if (!(obj instanceof ClusterRole)) {
return false;
}
ClusterRole clusterRole = (ClusterRole) obj;
return clock == clusterRole.clock &&
epoch == clusterRole.epoch &&
Objects.equals(node, clusterRole.node);
| 388
| 88
| 476
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/masterelection/GlobalMasterInfo.java
|
GlobalMasterInfo
|
masterInfo
|
class GlobalMasterInfo {
private final static NodeInfo NO_MASTER = new NodeInfo(false, "");
private volatile boolean supportElection;
private volatile NodeInfo masterNodeInfo;
private volatile Id nodeId;
private volatile NodeRole nodeRole;
public GlobalMasterInfo() {
this(NO_MASTER);
}
public GlobalMasterInfo(NodeInfo masterInfo) {
this.supportElection = false;
this.masterNodeInfo = masterInfo;
this.nodeId = null;
this.nodeRole = null;
}
public void supportElection(boolean featureSupport) {
this.supportElection = featureSupport;
}
public boolean supportElection() {
return this.supportElection;
}
public void resetMasterInfo() {
this.masterNodeInfo = NO_MASTER;
}
public void masterInfo(boolean isMaster, String nodeUrl) {<FILL_FUNCTION_BODY>}
public NodeInfo masterInfo() {
return this.masterNodeInfo;
}
public Id nodeId() {
return this.nodeId;
}
public NodeRole nodeRole() {
return this.nodeRole;
}
public void initNodeId(Id id) {
this.nodeId = id;
}
public void initNodeRole(NodeRole role) {
E.checkArgument(role != null, "The server role can't be null");
E.checkArgument(this.nodeRole == null,
"The server role can't be init twice");
this.nodeRole = role;
}
public void changeNodeRole(NodeRole role) {
E.checkArgument(role != null, "The server role can't be null");
this.nodeRole = role;
}
public static GlobalMasterInfo master(String nodeId) {
NodeInfo masterInfo = new NodeInfo(true, nodeId);
GlobalMasterInfo nodeInfo = new GlobalMasterInfo(masterInfo);
nodeInfo.nodeId = IdGenerator.of(nodeId);
nodeInfo.nodeRole = NodeRole.MASTER;
return nodeInfo;
}
public static class NodeInfo {
private final boolean isMaster;
private final String nodeUrl;
public NodeInfo(boolean isMaster, String url) {
this.isMaster = isMaster;
this.nodeUrl = url;
}
public boolean isMaster() {
return this.isMaster;
}
public String nodeUrl() {
return this.nodeUrl;
}
}
}
|
// final can avoid instruction rearrangement, visibility can be ignored
this.masterNodeInfo = new NodeInfo(isMaster, nodeUrl);
| 653
| 37
| 690
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/masterelection/RoleElectionOptions.java
|
RoleElectionOptions
|
instance
|
class RoleElectionOptions extends OptionHolder {
private RoleElectionOptions() {
super();
}
private static volatile RoleElectionOptions instance;
public static synchronized RoleElectionOptions instance() {<FILL_FUNCTION_BODY>}
public static final ConfigOption<Integer> EXCEEDS_FAIL_COUNT =
new ConfigOption<>(
"server.role.fail_count",
"When the node failed count of update or query heartbeat " +
"is reaches this threshold, the node will become abdication state to guard" +
"safe property.",
rangeInt(0, Integer.MAX_VALUE),
5
);
public static final ConfigOption<String> NODE_EXTERNAL_URL =
new ConfigOption<>(
"server.role.node_external_url",
"The url of external accessibility.",
disallowEmpty(),
"http://127.0.0.1:8080"
);
public static final ConfigOption<Integer> RANDOM_TIMEOUT_MILLISECOND =
new ConfigOption<>(
"server.role.random_timeout",
"The random timeout in ms that be used when candidate node request " +
"to become master state to reduce competitive voting.",
rangeInt(0, Integer.MAX_VALUE),
1000
);
public static final ConfigOption<Integer> HEARTBEAT_INTERVAL_SECOND =
new ConfigOption<>(
"server.role.heartbeat_interval",
"The role state machine heartbeat interval second time.",
rangeInt(0, Integer.MAX_VALUE),
2
);
public static final ConfigOption<Integer> MASTER_DEAD_TIMES =
new ConfigOption<>(
"server.role.master_dead_times",
"When the worker node detects that the number of times " +
"the master node fails to update heartbeat reaches this threshold, " +
"the worker node will become to a candidate node.",
rangeInt(0, Integer.MAX_VALUE),
10
);
public static final ConfigOption<Integer> BASE_TIMEOUT_MILLISECOND =
new ConfigOption<>(
"server.role.base_timeout",
"The role state machine candidate state base timeout time.",
rangeInt(0, Integer.MAX_VALUE),
500
);
}
|
if (instance == null) {
instance = new RoleElectionOptions();
// Should initialize all static members first, then register.
instance.registerOptions();
}
return instance;
| 599
| 51
| 650
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/masterelection/StandardClusterRoleStore.java
|
StandardClusterRoleStore
|
updateIfNodePresent
|
class StandardClusterRoleStore implements ClusterRoleStore {
private static final Logger LOG = Log.logger(StandardClusterRoleStore.class);
private static final int RETRY_QUERY_TIMEOUT = 200;
private final HugeGraphParams graph;
private boolean firstTime;
public StandardClusterRoleStore(HugeGraphParams graph) {
this.graph = graph;
Schema schema = new Schema(graph);
schema.initSchemaIfNeeded();
this.firstTime = true;
}
@Override
public boolean updateIfNodePresent(ClusterRole clusterRole) {<FILL_FUNCTION_BODY>}
private BackendEntry constructEntry(ClusterRole clusterRole) {
List<Object> list = new ArrayList<>(8);
list.add(T.label);
list.add(P.ROLE_DATA);
list.add(P.NODE);
list.add(clusterRole.node());
list.add(P.URL);
list.add(clusterRole.url());
list.add(P.CLOCK);
list.add(clusterRole.clock());
list.add(P.EPOCH);
list.add(clusterRole.epoch());
list.add(P.TYPE);
list.add("default");
HugeVertex vertex = this.graph.systemTransaction()
.constructVertex(false, list.toArray());
return this.graph.serializer().writeVertex(vertex);
}
@Override
public Optional<ClusterRole> query() {
Optional<Vertex> vertex = this.queryVertex();
if (!vertex.isPresent() && !this.firstTime) {
// If query nothing, retry once
try {
Thread.sleep(RETRY_QUERY_TIMEOUT);
} catch (InterruptedException ignored) {
}
vertex = this.queryVertex();
}
this.firstTime = false;
return vertex.map(this::from);
}
private ClusterRole from(Vertex vertex) {
String node = (String) vertex.property(P.NODE).value();
String url = (String) vertex.property(P.URL).value();
Long clock = (Long) vertex.property(P.CLOCK).value();
Integer epoch = (Integer) vertex.property(P.EPOCH).value();
return new ClusterRole(node, url, epoch, clock);
}
private Optional<Vertex> queryVertex() {
GraphTransaction tx = this.graph.systemTransaction();
ConditionQuery query = new ConditionQuery(HugeType.VERTEX);
VertexLabel vl = this.graph.graph().vertexLabel(P.ROLE_DATA);
query.eq(HugeKeys.LABEL, vl.id());
query.query(Condition.eq(vl.primaryKeys().get(0), "default"));
query.showHidden(true);
Iterator<Vertex> vertexIterator = tx.queryVertices(query);
if (vertexIterator.hasNext()) {
return Optional.of(vertexIterator.next());
}
return Optional.empty();
}
public static final class P {
public static final String ROLE_DATA = Graph.Hidden.hide("role_data");
public static final String LABEL = T.label.getAccessor();
public static final String NODE = Graph.Hidden.hide("role_node");
public static final String CLOCK = Graph.Hidden.hide("role_clock");
public static final String EPOCH = Graph.Hidden.hide("role_epoch");
public static final String URL = Graph.Hidden.hide("role_url");
public static final String TYPE = Graph.Hidden.hide("role_type");
}
public static final class Schema extends SchemaDefine {
public Schema(HugeGraphParams graph) {
super(graph, P.ROLE_DATA);
}
@Override
public void initSchemaIfNeeded() {
if (this.existVertexLabel(this.label)) {
return;
}
String[] properties = this.initProperties();
VertexLabel label = this.schema()
.vertexLabel(this.label)
.enableLabelIndex(true)
.usePrimaryKeyId()
.primaryKeys(P.TYPE)
.properties(properties)
.build();
this.graph.schemaTransaction().addVertexLabel(label);
}
private String[] initProperties() {
List<String> props = new ArrayList<>();
props.add(createPropertyKey(P.NODE, DataType.TEXT));
props.add(createPropertyKey(P.URL, DataType.TEXT));
props.add(createPropertyKey(P.CLOCK, DataType.LONG));
props.add(createPropertyKey(P.EPOCH, DataType.INT));
props.add(createPropertyKey(P.TYPE, DataType.TEXT));
return super.initProperties(props);
}
}
}
|
// if epoch increase, update and return true
// if epoch equal, ignore different node, return false
Optional<Vertex> oldClusterRoleOpt = this.queryVertex();
if (oldClusterRoleOpt.isPresent()) {
ClusterRole oldClusterRole = this.from(oldClusterRoleOpt.get());
if (clusterRole.epoch() < oldClusterRole.epoch()) {
return false;
}
if (clusterRole.epoch() == oldClusterRole.epoch() &&
!Objects.equals(clusterRole.node(), oldClusterRole.node())) {
return false;
}
LOG.trace("Server {} epoch {} begin remove data old epoch {}, ",
clusterRole.node(), clusterRole.epoch(), oldClusterRole.epoch());
this.graph.systemTransaction().removeVertex((HugeVertex) oldClusterRoleOpt.get());
this.graph.systemTransaction().commitOrRollback();
LOG.trace("Server {} epoch {} success remove data old epoch {}, ",
clusterRole.node(), clusterRole.epoch(), oldClusterRole.epoch());
}
try {
GraphTransaction tx = this.graph.systemTransaction();
tx.doUpdateIfAbsent(this.constructEntry(clusterRole));
tx.commitOrRollback();
LOG.trace("Server {} epoch {} success update data",
clusterRole.node(), clusterRole.epoch());
} catch (Throwable ignore) {
LOG.trace("Server {} epoch {} fail update data",
clusterRole.node(), clusterRole.epoch());
return false;
}
return true;
| 1,255
| 388
| 1,643
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/masterelection/StandardRoleElectionStateMachine.java
|
WorkerState
|
merge
|
class WorkerState implements RoleState {
private ClusterRole clusterRole;
private int clock;
public WorkerState(ClusterRole clusterRole) {
this.clusterRole = clusterRole;
this.clock = 0;
}
@Override
public RoleState transform(StateMachineContext context) {
RoleState.heartBeatPark(context);
RoleState nextState = new UnknownState(this.clusterRole.epoch()).transform(context);
if (nextState instanceof WorkerState) {
this.merge((WorkerState) nextState);
if (this.clock > context.config().masterDeadTimes()) {
return new CandidateState(this.clusterRole.epoch() + 1);
} else {
return this;
}
} else {
return nextState;
}
}
@Override
public Callback callback(RoleListener callback) {
return callback::onAsRoleWorker;
}
public void merge(WorkerState state) {<FILL_FUNCTION_BODY>}
}
|
if (state.clusterRole.epoch() > this.clusterRole.epoch()) {
this.clock = 0;
this.clusterRole = state.clusterRole;
} else if (state.clusterRole.epoch() < this.clusterRole.epoch()) {
throw new IllegalStateException("Epoch must increase");
} else if (state.clusterRole.epoch() == this.clusterRole.epoch() &&
state.clusterRole.clock() < this.clusterRole.clock()) {
throw new IllegalStateException("Clock must increase");
} else if (state.clusterRole.epoch() == this.clusterRole.epoch() &&
state.clusterRole.clock() > this.clusterRole.clock()) {
this.clock = 0;
this.clusterRole = state.clusterRole;
} else {
this.clock++;
}
| 269
| 214
| 483
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/masterelection/StandardRoleListener.java
|
StandardRoleListener
|
unknown
|
class StandardRoleListener implements RoleListener {
private static final Logger LOG = Log.logger(StandardRoleListener.class);
private final TaskManager taskManager;
private final GlobalMasterInfo roleInfo;
private volatile boolean selfIsMaster;
public StandardRoleListener(TaskManager taskManager,
GlobalMasterInfo roleInfo) {
this.taskManager = taskManager;
this.taskManager.enableRoleElection();
this.roleInfo = roleInfo;
this.selfIsMaster = false;
}
@Override
public void onAsRoleMaster(StateMachineContext context) {
if (!selfIsMaster) {
this.taskManager.onAsRoleMaster();
LOG.info("Server {} change to master role", context.config().node());
}
this.updateMasterInfo(context);
this.selfIsMaster = true;
}
@Override
public void onAsRoleWorker(StateMachineContext context) {
if (this.selfIsMaster) {
this.taskManager.onAsRoleWorker();
LOG.info("Server {} change to worker role", context.config().node());
}
this.updateMasterInfo(context);
this.selfIsMaster = false;
}
@Override
public void onAsRoleCandidate(StateMachineContext context) {
// pass
}
@Override
public void onAsRoleAbdication(StateMachineContext context) {
if (this.selfIsMaster) {
this.taskManager.onAsRoleWorker();
LOG.info("Server {} change to worker role", context.config().node());
}
this.updateMasterInfo(context);
this.selfIsMaster = false;
}
@Override
public void error(StateMachineContext context, Throwable e) {
LOG.error("Server {} exception occurred", context.config().node(), e);
}
@Override
public void unknown(StateMachineContext context) {<FILL_FUNCTION_BODY>}
public void updateMasterInfo(StateMachineContext context) {
StateMachineContext.MasterServerInfo master = context.master();
if (master == null) {
this.roleInfo.resetMasterInfo();
return;
}
boolean isMaster = Objects.equals(context.node(), master.node());
this.roleInfo.masterInfo(isMaster, master.url());
}
}
|
if (this.selfIsMaster) {
this.taskManager.onAsRoleWorker();
LOG.info("Server {} change to worker role", context.config().node());
}
this.updateMasterInfo(context);
this.selfIsMaster = false;
| 595
| 70
| 665
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/schema/EdgeLabel.java
|
EdgeLabel
|
sourceLabel
|
class EdgeLabel extends SchemaLabel {
public static final EdgeLabel NONE = new EdgeLabel(null, NONE_ID, UNDEF);
private Id sourceLabel = NONE_ID;
private Id targetLabel = NONE_ID;
private Frequency frequency;
private List<Id> sortKeys;
public EdgeLabel(final HugeGraph graph, Id id, String name) {
super(graph, id, name);
this.frequency = Frequency.DEFAULT;
this.sortKeys = new ArrayList<>();
}
@Override
public HugeType type() {
return HugeType.EDGE_LABEL;
}
public Frequency frequency() {
return this.frequency;
}
public void frequency(Frequency frequency) {
this.frequency = frequency;
}
public boolean directed() {
// TODO: implement (do we need this method?)
return true;
}
public String sourceLabelName() {
return this.graph.vertexLabelOrNone(this.sourceLabel).name();
}
public Id sourceLabel() {
return this.sourceLabel;
}
public void sourceLabel(Id id) {<FILL_FUNCTION_BODY>}
public String targetLabelName() {
return this.graph.vertexLabelOrNone(this.targetLabel).name();
}
public Id targetLabel() {
return this.targetLabel;
}
public void targetLabel(Id id) {
E.checkArgument(this.targetLabel == NONE_ID,
"Not allowed to set target label multi times " +
"of edge label '%s'", this.name());
this.targetLabel = id;
}
public boolean linkWithLabel(Id id) {
return this.sourceLabel.equals(id) || this.targetLabel.equals(id);
}
public boolean linkWithVertexLabel(Id label, Directions dir) {
if (dir.equals(Directions.IN)) {
return this.targetLabel.equals(label);
} else if (dir.equals(Directions.OUT)) {
return this.sourceLabel.equals(label);
} else if (dir.equals(Directions.BOTH)) {
return this.targetLabel.equals(label) || this.sourceLabel.equals(label);
}
return false;
}
public boolean checkLinkEqual(Id sourceLabel, Id targetLabel) {
return this.sourceLabel.equals(sourceLabel) &&
this.targetLabel.equals(targetLabel);
}
public boolean existSortKeys() {
return !this.sortKeys.isEmpty();
}
public List<Id> sortKeys() {
return Collections.unmodifiableList(this.sortKeys);
}
public void sortKey(Id id) {
this.sortKeys.add(id);
}
public void sortKeys(Id... ids) {
this.sortKeys.addAll(Arrays.asList(ids));
}
public boolean hasSameContent(EdgeLabel other) {
return super.hasSameContent(other) &&
this.frequency == other.frequency &&
Objects.equal(this.sourceLabelName(), other.sourceLabelName()) &&
Objects.equal(this.targetLabelName(), other.targetLabelName()) &&
Objects.equal(this.graph.mapPkId2Name(this.sortKeys),
other.graph.mapPkId2Name(other.sortKeys));
}
public static EdgeLabel undefined(HugeGraph graph, Id id) {
return new EdgeLabel(graph, id, UNDEF);
}
public interface Builder extends SchemaBuilder<EdgeLabel> {
Id rebuildIndex();
Builder link(String sourceLabel, String targetLabel);
Builder sourceLabel(String label);
Builder targetLabel(String label);
Builder singleTime();
Builder multiTimes();
Builder sortKeys(String... keys);
Builder properties(String... properties);
Builder nullableKeys(String... keys);
Builder frequency(Frequency frequency);
Builder ttl(long ttl);
Builder ttlStartTime(String ttlStartTime);
Builder enableLabelIndex(boolean enable);
Builder userdata(String key, Object value);
Builder userdata(Map<String, Object> userdata);
}
}
|
E.checkArgument(this.sourceLabel == NONE_ID,
"Not allowed to set source label multi times " +
"of edge label '%s'", this.name());
this.sourceLabel = id;
| 1,096
| 56
| 1,152
|
<methods>public void <init>(org.apache.hugegraph.HugeGraph, org.apache.hugegraph.backend.id.Id, java.lang.String) ,public void addIndexLabel(org.apache.hugegraph.backend.id.Id) ,public transient void addIndexLabels(org.apache.hugegraph.backend.id.Id[]) ,public boolean enableLabelIndex() ,public void enableLabelIndex(boolean) ,public boolean existsIndexLabel() ,public static org.apache.hugegraph.backend.id.Id getEdgeLabelId(org.apache.hugegraph.HugeGraph, java.lang.Object) ,public static org.apache.hugegraph.backend.id.Id getLabelId(org.apache.hugegraph.HugeGraph, org.apache.hugegraph.type.HugeType, java.lang.Object) ,public static org.apache.hugegraph.backend.id.Id getVertexLabelId(org.apache.hugegraph.HugeGraph, java.lang.Object) ,public boolean hasSameContent(org.apache.hugegraph.schema.SchemaLabel) ,public Set<org.apache.hugegraph.backend.id.Id> indexLabels() ,public void nullableKey(org.apache.hugegraph.backend.id.Id) ,public Set<org.apache.hugegraph.backend.id.Id> nullableKeys() ,public transient void nullableKeys(org.apache.hugegraph.backend.id.Id[]) ,public void nullableKeys(Set<org.apache.hugegraph.backend.id.Id>) ,public Set<org.apache.hugegraph.backend.id.Id> properties() ,public void properties(Set<org.apache.hugegraph.backend.id.Id>) ,public transient org.apache.hugegraph.schema.SchemaLabel properties(org.apache.hugegraph.backend.id.Id[]) ,public void property(org.apache.hugegraph.backend.id.Id) ,public void removeIndexLabel(org.apache.hugegraph.backend.id.Id) ,public void ttl(long) ,public long ttl() ,public void ttlStartTime(org.apache.hugegraph.backend.id.Id) ,public org.apache.hugegraph.backend.id.Id ttlStartTime() ,public java.lang.String ttlStartTimeName() ,public boolean undefined() <variables>private boolean enableLabelIndex,private final non-sealed Set<org.apache.hugegraph.backend.id.Id> indexLabels,private final non-sealed Set<org.apache.hugegraph.backend.id.Id> nullableKeys,private final non-sealed Set<org.apache.hugegraph.backend.id.Id> properties,private long ttl,private org.apache.hugegraph.backend.id.Id ttlStartTime
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/schema/SchemaElement.java
|
SchemaElement
|
equals
|
class SchemaElement implements Nameable, Typeable,
Cloneable {
public static final int MAX_PRIMITIVE_SYS_ID = 32;
public static final int NEXT_PRIMITIVE_SYS_ID = 8;
// ABS of system schema id must be below MAX_PRIMITIVE_SYS_ID
protected static final int VL_IL_ID = -1;
protected static final int EL_IL_ID = -2;
protected static final int PKN_IL_ID = -3;
protected static final int VLN_IL_ID = -4;
protected static final int ELN_IL_ID = -5;
protected static final int ILN_IL_ID = -6;
protected static final int OLAP_VL_ID = -7;
public static final Id NONE_ID = IdGenerator.ZERO;
public static final String UNDEF = "~undefined";
protected final HugeGraph graph;
private final Id id;
private final String name;
private final Userdata userdata;
private SchemaStatus status;
public SchemaElement(final HugeGraph graph, Id id, String name) {
E.checkArgumentNotNull(id, "SchemaElement id can't be null");
E.checkArgumentNotNull(name, "SchemaElement name can't be null");
this.graph = graph;
this.id = id;
this.name = name;
this.userdata = new Userdata();
this.status = SchemaStatus.CREATED;
}
public HugeGraph graph() {
E.checkState(this.graph != null,
"Graph is null of schema '%s'", this.name);
return this.graph;
}
public Id id() {
return this.id;
}
public long longId() {
return this.id.asLong();
}
@Override
public String name() {
return this.name;
}
public Map<String, Object> userdata() {
return Collections.unmodifiableMap(this.userdata);
}
public void userdata(String key, Object value) {
E.checkArgumentNotNull(key, "userdata key");
E.checkArgumentNotNull(value, "userdata value");
this.userdata.put(key, value);
}
public void userdata(Userdata userdata) {
this.userdata.putAll(userdata);
}
public void removeUserdata(String key) {
E.checkArgumentNotNull(key, "The userdata key can't be null");
this.userdata.remove(key);
}
public void removeUserdata(Userdata userdata) {
for (String key : userdata.keySet()) {
this.userdata.remove(key);
}
}
public SchemaStatus status() {
return this.status;
}
public void status(SchemaStatus status) {
this.status = status;
}
public boolean system() {
return this.longId() < 0L;
}
public boolean primitive() {
long id = this.longId();
return -MAX_PRIMITIVE_SYS_ID <= id && id < 0L;
}
public boolean hidden() {
return Graph.Hidden.isHidden(this.name());
}
public SchemaElement copy() {
try {
return (SchemaElement) super.clone();
} catch (CloneNotSupportedException e) {
throw new HugeException("Failed to clone schema", e);
}
}
public boolean hasSameContent(SchemaElement other) {
return Objects.equal(this.name(), other.name()) &&
Objects.equal(this.userdata(), other.userdata());
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return this.type().hashCode() ^ this.id.hashCode();
}
@Override
public String toString() {
return String.format("%s(id=%s)", this.name, this.id);
}
public static int schemaId(Id id) {
long l = id.asLong();
// Currently we limit the schema id to within 4 bytes
E.checkArgument(Integer.MIN_VALUE <= l && l <= Integer.MAX_VALUE,
"Schema id is out of bound: %s", l);
return (int) l;
}
public static class TaskWithSchema {
private SchemaElement schemaElement;
private Id task;
public TaskWithSchema(SchemaElement schemaElement, Id task) {
E.checkNotNull(schemaElement, "schema element");
this.schemaElement = schemaElement;
this.task = task;
}
public void propertyKey(PropertyKey propertyKey) {
E.checkNotNull(propertyKey, "property key");
this.schemaElement = propertyKey;
}
public void indexLabel(IndexLabel indexLabel) {
E.checkNotNull(indexLabel, "index label");
this.schemaElement = indexLabel;
}
public PropertyKey propertyKey() {
E.checkState(this.schemaElement instanceof PropertyKey,
"Expect property key, but actual schema type is " +
"'%s'", this.schemaElement.getClass());
return (PropertyKey) this.schemaElement;
}
public IndexLabel indexLabel() {
E.checkState(this.schemaElement instanceof IndexLabel,
"Expect index label, but actual schema type is " +
"'%s'", this.schemaElement.getClass());
return (IndexLabel) this.schemaElement;
}
public SchemaElement schemaElement() {
return this.schemaElement;
}
public Id task() {
return this.task;
}
}
}
|
if (!(obj instanceof SchemaElement)) {
return false;
}
SchemaElement other = (SchemaElement) obj;
return this.type() == other.type() && this.id.equals(other.id());
| 1,491
| 60
| 1,551
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/schema/SchemaLabel.java
|
SchemaLabel
|
getLabelId
|
class SchemaLabel extends SchemaElement
implements Indexable, Propertiable {
private final Set<Id> properties;
private final Set<Id> nullableKeys;
private final Set<Id> indexLabels;
private boolean enableLabelIndex;
private long ttl;
private Id ttlStartTime;
public SchemaLabel(final HugeGraph graph, Id id, String name) {
super(graph, id, name);
this.properties = new HashSet<>();
this.nullableKeys = new HashSet<>();
this.indexLabels = new HashSet<>();
this.enableLabelIndex = true;
this.ttl = 0L;
this.ttlStartTime = NONE_ID;
}
@Override
public Set<Id> properties() {
return Collections.unmodifiableSet(this.properties);
}
public void properties(Set<Id> properties) {
this.properties.addAll(properties);
}
public SchemaLabel properties(Id... ids) {
this.properties.addAll(Arrays.asList(ids));
return this;
}
public void property(Id id) {
this.properties.add(id);
}
public Set<Id> nullableKeys() {
return Collections.unmodifiableSet(this.nullableKeys);
}
public void nullableKey(Id id) {
this.nullableKeys.add(id);
}
public void nullableKeys(Id... ids) {
this.nullableKeys.addAll(Arrays.asList(ids));
}
public void nullableKeys(Set<Id> nullableKeys) {
this.nullableKeys.addAll(nullableKeys);
}
@Override
public Set<Id> indexLabels() {
return Collections.unmodifiableSet(this.indexLabels);
}
public void addIndexLabel(Id id) {
this.indexLabels.add(id);
}
public void addIndexLabels(Id... ids) {
this.indexLabels.addAll(Arrays.asList(ids));
}
public boolean existsIndexLabel() {
return !this.indexLabels().isEmpty();
}
public void removeIndexLabel(Id id) {
this.indexLabels.remove(id);
}
public boolean enableLabelIndex() {
return this.enableLabelIndex;
}
public void enableLabelIndex(boolean enable) {
this.enableLabelIndex = enable;
}
public boolean undefined() {
return this.name() == UNDEF;
}
public void ttl(long ttl) {
assert ttl >= 0L;
this.ttl = ttl;
}
public long ttl() {
assert this.ttl >= 0L;
return this.ttl;
}
public void ttlStartTime(Id id) {
this.ttlStartTime = id;
}
public Id ttlStartTime() {
return this.ttlStartTime;
}
public String ttlStartTimeName() {
return NONE_ID.equals(this.ttlStartTime) ? null :
this.graph.propertyKey(this.ttlStartTime).name();
}
public boolean hasSameContent(SchemaLabel other) {
return super.hasSameContent(other) && this.ttl == other.ttl &&
this.enableLabelIndex == other.enableLabelIndex &&
Objects.equal(this.graph.mapPkId2Name(this.properties),
other.graph.mapPkId2Name(other.properties)) &&
Objects.equal(this.graph.mapPkId2Name(this.nullableKeys),
other.graph.mapPkId2Name(other.nullableKeys)) &&
Objects.equal(this.graph.mapIlId2Name(this.indexLabels),
other.graph.mapIlId2Name(other.indexLabels)) &&
Objects.equal(this.ttlStartTimeName(), other.ttlStartTimeName());
}
public static Id getLabelId(HugeGraph graph, HugeType type, Object label) {<FILL_FUNCTION_BODY>}
public static Id getVertexLabelId(HugeGraph graph, Object label) {
return SchemaLabel.getLabelId(graph, HugeType.VERTEX, label);
}
public static Id getEdgeLabelId(HugeGraph graph, Object label) {
return SchemaLabel.getLabelId(graph, HugeType.EDGE, label);
}
}
|
E.checkNotNull(graph, "graph");
E.checkNotNull(type, "type");
E.checkNotNull(label, "label");
if (label instanceof Number) {
return IdGenerator.of(((Number) label).longValue());
} else if (label instanceof String) {
if (type.isVertex()) {
return graph.vertexLabel((String) label).id();
} else if (type.isEdge()) {
return graph.edgeLabel((String) label).id();
} else {
throw new HugeException(
"Not support query from '%s' with label '%s'",
type, label);
}
} else {
throw new HugeException(
"The label type must be number or string, but got '%s'",
label.getClass());
}
| 1,170
| 204
| 1,374
|
<methods>public void <init>(org.apache.hugegraph.HugeGraph, org.apache.hugegraph.backend.id.Id, java.lang.String) ,public org.apache.hugegraph.schema.SchemaElement copy() ,public boolean equals(java.lang.Object) ,public org.apache.hugegraph.HugeGraph graph() ,public boolean hasSameContent(org.apache.hugegraph.schema.SchemaElement) ,public int hashCode() ,public boolean hidden() ,public org.apache.hugegraph.backend.id.Id id() ,public long longId() ,public java.lang.String name() ,public boolean primitive() ,public void removeUserdata(java.lang.String) ,public void removeUserdata(org.apache.hugegraph.schema.Userdata) ,public static int schemaId(org.apache.hugegraph.backend.id.Id) ,public org.apache.hugegraph.type.define.SchemaStatus status() ,public void status(org.apache.hugegraph.type.define.SchemaStatus) ,public boolean system() ,public java.lang.String toString() ,public Map<java.lang.String,java.lang.Object> userdata() ,public void userdata(java.lang.String, java.lang.Object) ,public void userdata(org.apache.hugegraph.schema.Userdata) <variables>protected static final int ELN_IL_ID,protected static final int EL_IL_ID,protected static final int ILN_IL_ID,public static final int MAX_PRIMITIVE_SYS_ID,public static final int NEXT_PRIMITIVE_SYS_ID,public static final org.apache.hugegraph.backend.id.Id NONE_ID,protected static final int OLAP_VL_ID,protected static final int PKN_IL_ID,public static final java.lang.String UNDEF,protected static final int VLN_IL_ID,protected static final int VL_IL_ID,protected final non-sealed org.apache.hugegraph.HugeGraph graph,private final non-sealed org.apache.hugegraph.backend.id.Id id,private final non-sealed java.lang.String name,private org.apache.hugegraph.type.define.SchemaStatus status,private final non-sealed org.apache.hugegraph.schema.Userdata userdata
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/schema/SchemaManager.java
|
SchemaManager
|
getEdgeLabel
|
class SchemaManager {
private final SchemaTransaction transaction;
private HugeGraph graph;
public SchemaManager(SchemaTransaction transaction, HugeGraph graph) {
E.checkNotNull(transaction, "transaction");
E.checkNotNull(graph, "graph");
this.transaction = transaction;
this.graph = graph;
}
public HugeGraph proxy(HugeGraph graph) {
E.checkNotNull(graph, "graph");
HugeGraph old = this.graph;
this.graph = graph;
return old;
}
public PropertyKey.Builder propertyKey(String name) {
return new PropertyKeyBuilder(this.transaction, this.graph, name);
}
public VertexLabel.Builder vertexLabel(String name) {
return new VertexLabelBuilder(this.transaction, this.graph, name);
}
public EdgeLabel.Builder edgeLabel(String name) {
return new EdgeLabelBuilder(this.transaction, this.graph, name);
}
public IndexLabel.Builder indexLabel(String name) {
return new IndexLabelBuilder(this.transaction, this.graph, name);
}
public PropertyKey getPropertyKey(String name) {
E.checkArgumentNotNull(name, "The name parameter can't be null");
PropertyKey propertyKey = this.transaction.getPropertyKey(name);
checkExists(HugeType.PROPERTY_KEY, propertyKey, name);
return propertyKey;
}
public VertexLabel getVertexLabel(String name) {
E.checkArgumentNotNull(name, "The name parameter can't be null");
VertexLabel vertexLabel = this.transaction.getVertexLabel(name);
checkExists(HugeType.VERTEX_LABEL, vertexLabel, name);
return vertexLabel;
}
public EdgeLabel getEdgeLabel(String name) {<FILL_FUNCTION_BODY>}
public IndexLabel getIndexLabel(String name) {
E.checkArgumentNotNull(name, "The name parameter can't be null");
IndexLabel indexLabel = this.transaction.getIndexLabel(name);
checkExists(HugeType.INDEX_LABEL, indexLabel, name);
return indexLabel;
}
public List<PropertyKey> getPropertyKeys() {
return this.graph.propertyKeys().stream()
.filter(pk -> !Graph.Hidden.isHidden(pk.name()))
.collect(Collectors.toList());
}
public List<VertexLabel> getVertexLabels() {
return this.graph.vertexLabels().stream()
.filter(vl -> !Graph.Hidden.isHidden(vl.name()))
.collect(Collectors.toList());
}
public List<EdgeLabel> getEdgeLabels() {
return this.graph.edgeLabels().stream()
.filter(el -> !Graph.Hidden.isHidden(el.name()))
.collect(Collectors.toList());
}
public List<IndexLabel> getIndexLabels() {
return this.graph.indexLabels().stream()
.filter(il -> !Graph.Hidden.isHidden(il.name()))
.collect(Collectors.toList());
}
public void copyFrom(SchemaManager schema) {
for (PropertyKey pk : schema.getPropertyKeys()) {
new PropertyKeyBuilder(this.transaction, this.graph, pk).create();
}
for (VertexLabel vl : schema.getVertexLabels()) {
new VertexLabelBuilder(this.transaction, this.graph, vl).create();
}
for (EdgeLabel el : schema.getEdgeLabels()) {
new EdgeLabelBuilder(this.transaction, this.graph, el).create();
}
for (IndexLabel il : schema.getIndexLabels()) {
new IndexLabelBuilder(this.transaction, this.graph, il).create();
}
}
private static void checkExists(HugeType type, Object object, String name) {
if (object == null) {
throw new NotFoundException("%s with name '%s' does not exist",
type.readableName(), name);
}
}
}
|
E.checkArgumentNotNull(name, "The name parameter can't be null");
EdgeLabel edgeLabel = this.transaction.getEdgeLabel(name);
checkExists(HugeType.EDGE_LABEL, edgeLabel, name);
return edgeLabel;
| 1,049
| 67
| 1,116
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/schema/Userdata.java
|
Userdata
|
check
|
class Userdata extends HashMap<String, Object> {
private static final long serialVersionUID = -1235451175617197049L;
public static final String CREATE_TIME = "~create_time";
public static final String DEFAULT_VALUE = "~default_value";
public Userdata() {
}
public Userdata(Map<String, Object> map) {
this.putAll(map);
}
public static void check(Userdata userdata, Action action) {<FILL_FUNCTION_BODY>}
}
|
if (userdata == null) {
return;
}
switch (action) {
case INSERT:
case APPEND:
for (Map.Entry<String, Object> e : userdata.entrySet()) {
if (e.getValue() == null) {
throw new NotAllowException(
"Not allowed to pass null userdata value " +
"when create or append schema");
}
}
break;
case ELIMINATE:
case DELETE:
// pass
break;
default:
throw new AssertionError(String.format(
"Unknown schema action '%s'", action));
}
| 150
| 165
| 315
|
<methods>public void <init>() ,public void <init>(int) ,public void <init>(Map<? extends java.lang.String,? extends java.lang.Object>) ,public void <init>(int, float) ,public void clear() ,public java.lang.Object clone() ,public java.lang.Object compute(java.lang.String, BiFunction<? super java.lang.String,? super java.lang.Object,? extends java.lang.Object>) ,public java.lang.Object computeIfAbsent(java.lang.String, Function<? super java.lang.String,? extends java.lang.Object>) ,public java.lang.Object computeIfPresent(java.lang.String, BiFunction<? super java.lang.String,? super java.lang.Object,? extends java.lang.Object>) ,public boolean containsKey(java.lang.Object) ,public boolean containsValue(java.lang.Object) ,public Set<Entry<java.lang.String,java.lang.Object>> entrySet() ,public void forEach(BiConsumer<? super java.lang.String,? super java.lang.Object>) ,public java.lang.Object get(java.lang.Object) ,public java.lang.Object getOrDefault(java.lang.Object, java.lang.Object) ,public boolean isEmpty() ,public Set<java.lang.String> keySet() ,public java.lang.Object merge(java.lang.String, java.lang.Object, BiFunction<? super java.lang.Object,? super java.lang.Object,? extends java.lang.Object>) ,public java.lang.Object put(java.lang.String, java.lang.Object) ,public void putAll(Map<? extends java.lang.String,? extends java.lang.Object>) ,public java.lang.Object putIfAbsent(java.lang.String, java.lang.Object) ,public java.lang.Object remove(java.lang.Object) ,public boolean remove(java.lang.Object, java.lang.Object) ,public java.lang.Object replace(java.lang.String, java.lang.Object) ,public boolean replace(java.lang.String, java.lang.Object, java.lang.Object) ,public void replaceAll(BiFunction<? super java.lang.String,? super java.lang.Object,? extends java.lang.Object>) ,public int size() ,public Collection<java.lang.Object> values() <variables>static final int DEFAULT_INITIAL_CAPACITY,static final float DEFAULT_LOAD_FACTOR,static final int MAXIMUM_CAPACITY,static final int MIN_TREEIFY_CAPACITY,static final int TREEIFY_THRESHOLD,static final int UNTREEIFY_THRESHOLD,transient Set<Entry<java.lang.String,java.lang.Object>> entrySet,final float loadFactor,transient int modCount,private static final long serialVersionUID,transient int size,transient Node<java.lang.String,java.lang.Object>[] table,int threshold
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/schema/VertexLabel.java
|
VertexLabel
|
hasSameContent
|
class VertexLabel extends SchemaLabel {
public static final VertexLabel NONE = new VertexLabel(null, NONE_ID, UNDEF);
// OLAP_VL_ID means all of vertex label ids
private static final Id OLAP_VL_ID = IdGenerator.of(SchemaLabel.OLAP_VL_ID);
// OLAP_VL_NAME means all of vertex label names
private static final String OLAP_VL_NAME = "*olap";
// OLAP_VL means all of vertex labels
public static final VertexLabel OLAP_VL = new VertexLabel(null, OLAP_VL_ID,
OLAP_VL_NAME);
private IdStrategy idStrategy;
private List<Id> primaryKeys;
public VertexLabel(final HugeGraph graph, Id id, String name) {
super(graph, id, name);
this.idStrategy = IdStrategy.DEFAULT;
this.primaryKeys = new ArrayList<>();
}
@Override
public HugeType type() {
return HugeType.VERTEX_LABEL;
}
public boolean olap() {
return VertexLabel.OLAP_VL.id().equals(this.id());
}
public IdStrategy idStrategy() {
return this.idStrategy;
}
public void idStrategy(IdStrategy idStrategy) {
this.idStrategy = idStrategy;
}
public List<Id> primaryKeys() {
return Collections.unmodifiableList(this.primaryKeys);
}
public void primaryKey(Id id) {
this.primaryKeys.add(id);
}
public void primaryKeys(Id... ids) {
this.primaryKeys.addAll(Arrays.asList(ids));
}
public boolean existsLinkLabel() {
return this.graph().existsLinkLabel(this.id());
}
public boolean hasSameContent(VertexLabel other) {<FILL_FUNCTION_BODY>}
public static VertexLabel undefined(HugeGraph graph) {
return new VertexLabel(graph, NONE_ID, UNDEF);
}
public static VertexLabel undefined(HugeGraph graph, Id id) {
return new VertexLabel(graph, id, UNDEF);
}
public interface Builder extends SchemaBuilder<VertexLabel> {
Id rebuildIndex();
Builder idStrategy(IdStrategy idStrategy);
Builder useAutomaticId();
Builder usePrimaryKeyId();
Builder useCustomizeStringId();
Builder useCustomizeNumberId();
Builder useCustomizeUuidId();
Builder properties(String... properties);
Builder primaryKeys(String... keys);
Builder nullableKeys(String... keys);
Builder ttl(long ttl);
Builder ttlStartTime(String ttlStartTime);
Builder enableLabelIndex(boolean enable);
Builder userdata(String key, Object value);
Builder userdata(Map<String, Object> userdata);
}
}
|
return super.hasSameContent(other) &&
this.idStrategy == other.idStrategy &&
Objects.equal(this.graph.mapPkId2Name(this.primaryKeys),
other.graph.mapPkId2Name(other.primaryKeys));
| 777
| 68
| 845
|
<methods>public void <init>(org.apache.hugegraph.HugeGraph, org.apache.hugegraph.backend.id.Id, java.lang.String) ,public void addIndexLabel(org.apache.hugegraph.backend.id.Id) ,public transient void addIndexLabels(org.apache.hugegraph.backend.id.Id[]) ,public boolean enableLabelIndex() ,public void enableLabelIndex(boolean) ,public boolean existsIndexLabel() ,public static org.apache.hugegraph.backend.id.Id getEdgeLabelId(org.apache.hugegraph.HugeGraph, java.lang.Object) ,public static org.apache.hugegraph.backend.id.Id getLabelId(org.apache.hugegraph.HugeGraph, org.apache.hugegraph.type.HugeType, java.lang.Object) ,public static org.apache.hugegraph.backend.id.Id getVertexLabelId(org.apache.hugegraph.HugeGraph, java.lang.Object) ,public boolean hasSameContent(org.apache.hugegraph.schema.SchemaLabel) ,public Set<org.apache.hugegraph.backend.id.Id> indexLabels() ,public void nullableKey(org.apache.hugegraph.backend.id.Id) ,public Set<org.apache.hugegraph.backend.id.Id> nullableKeys() ,public transient void nullableKeys(org.apache.hugegraph.backend.id.Id[]) ,public void nullableKeys(Set<org.apache.hugegraph.backend.id.Id>) ,public Set<org.apache.hugegraph.backend.id.Id> properties() ,public void properties(Set<org.apache.hugegraph.backend.id.Id>) ,public transient org.apache.hugegraph.schema.SchemaLabel properties(org.apache.hugegraph.backend.id.Id[]) ,public void property(org.apache.hugegraph.backend.id.Id) ,public void removeIndexLabel(org.apache.hugegraph.backend.id.Id) ,public void ttl(long) ,public long ttl() ,public void ttlStartTime(org.apache.hugegraph.backend.id.Id) ,public org.apache.hugegraph.backend.id.Id ttlStartTime() ,public java.lang.String ttlStartTimeName() ,public boolean undefined() <variables>private boolean enableLabelIndex,private final non-sealed Set<org.apache.hugegraph.backend.id.Id> indexLabels,private final non-sealed Set<org.apache.hugegraph.backend.id.Id> nullableKeys,private final non-sealed Set<org.apache.hugegraph.backend.id.Id> properties,private long ttl,private org.apache.hugegraph.backend.id.Id ttlStartTime
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/schema/builder/AbstractBuilder.java
|
AbstractBuilder
|
lockCheckAndCreateSchema
|
class AbstractBuilder {
private final SchemaTransaction transaction;
private final HugeGraph graph;
public AbstractBuilder(SchemaTransaction transaction, HugeGraph graph) {
E.checkNotNull(transaction, "transaction");
E.checkNotNull(graph, "graph");
this.transaction = transaction;
this.graph = graph;
}
protected HugeGraph graph() {
return this.graph;
}
protected Id validOrGenerateId(HugeType type, Id id, String name) {
return this.transaction.validOrGenerateId(type, id, name);
}
protected void checkSchemaName(String name) {
this.transaction.checkSchemaName(name);
}
protected Id rebuildIndex(IndexLabel indexLabel, Set<Id> dependencies) {
return this.transaction.rebuildIndex(indexLabel, dependencies);
}
protected <V> V lockCheckAndCreateSchema(HugeType type, String name,
Function<String, V> callback) {<FILL_FUNCTION_BODY>}
protected void updateSchemaStatus(SchemaElement element,
SchemaStatus status) {
this.transaction.updateSchemaStatus(element, status);
}
protected void checkSchemaIdIfRestoringMode(HugeType type, Id id) {
if (this.transaction.graphMode() == GraphMode.RESTORING) {
E.checkArgument(id != null,
"Must provide schema id if in RESTORING mode");
if (this.transaction.existsSchemaId(type, id)) {
throw new ExistedException(type.readableName() + " id", id);
}
}
}
protected PropertyKey propertyKeyOrNull(String name) {
return this.transaction.getPropertyKey(name);
}
protected VertexLabel vertexLabelOrNull(String name) {
return this.transaction.getVertexLabel(name);
}
protected EdgeLabel edgeLabelOrNull(String name) {
return this.transaction.getEdgeLabel(name);
}
protected IndexLabel indexLabelOrNull(String name) {
return this.transaction.getIndexLabel(name);
}
}
|
String graph = this.transaction.graphName();
LockUtil.Locks locks = new LockUtil.Locks(graph);
try {
locks.lockWrites(LockUtil.hugeType2Group(type),
IdGenerator.of(name));
return callback.apply(name);
} finally {
locks.unlock();
}
| 542
| 88
| 630
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/structure/HugeEdgeProperty.java
|
HugeEdgeProperty
|
equals
|
class HugeEdgeProperty<V> extends HugeProperty<V> {
public HugeEdgeProperty(HugeElement owner, PropertyKey key, V value) {
super(owner, key, value);
}
@Override
public HugeType type() {
return this.pkey.aggregateType().isNone() ?
HugeType.PROPERTY : HugeType.AGGR_PROPERTY_E;
}
@Override
public HugeEdge element() {
assert this.owner instanceof HugeEdge;
return (HugeEdge) this.owner;
}
@Override
public void remove() {
assert this.owner instanceof HugeEdge;
EdgeLabel edgeLabel = ((HugeEdge) this.owner).schemaLabel();
E.checkArgument(edgeLabel.nullableKeys().contains(
this.propertyKey().id()),
"Can't remove non-null edge property '%s'", this);
this.owner.graph().removeEdgeProperty(this);
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return ElementHelper.hashCode(this);
}
public HugeEdgeProperty<V> switchEdgeOwner() {
assert this.owner instanceof HugeEdge;
return new HugeEdgeProperty<>(((HugeEdge) this.owner).switchOwner(),
this.pkey, this.value);
}
}
|
if (!(obj instanceof Property)) {
return false;
}
return ElementHelper.areEqual(this, obj);
| 370
| 34
| 404
|
<methods>public void <init>(org.apache.hugegraph.structure.HugeElement, org.apache.hugegraph.schema.PropertyKey, V) ,public org.apache.hugegraph.structure.HugeElement element() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.Object id() ,public boolean isAggregateType() ,public boolean isPresent() ,public java.lang.String key() ,public java.lang.String name() ,public org.apache.hugegraph.schema.PropertyKey propertyKey() ,public java.lang.Object serialValue(boolean) ,public java.lang.String toString() ,public org.apache.hugegraph.type.HugeType type() ,public V value() throws java.util.NoSuchElementException<variables>protected final non-sealed org.apache.hugegraph.structure.HugeElement owner,protected final non-sealed org.apache.hugegraph.schema.PropertyKey pkey,protected final non-sealed V value
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/structure/HugeFeatures.java
|
HugeElementFeatures
|
willAllowId
|
class HugeElementFeatures implements ElementFeatures {
@Override
public boolean supportsAddProperty() {
return true;
}
@Override
public boolean supportsRemoveProperty() {
return true;
}
@Override
public boolean supportsStringIds() {
return true;
}
@Override
public boolean supportsNumericIds() {
return false;
}
@Override
public boolean supportsUuidIds() {
return false;
}
@Override
public boolean supportsAnyIds() {
return false;
}
@Override
public boolean supportsCustomIds() {
return true;
}
@Override
public boolean supportsUserSuppliedIds() {
return false;
}
@Override
public boolean willAllowId(Object id) {<FILL_FUNCTION_BODY>}
}
|
if (!this.supportsUserSuppliedIds()) {
return false;
} else {
return this.supportsAnyIds() ||
this.supportsCustomIds() && id instanceof Id ||
this.supportsStringIds() && id instanceof String ||
this.supportsNumericIds() && id instanceof Number ||
this.supportsUuidIds() && id instanceof UUID;
}
| 222
| 99
| 321
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/structure/HugeProperty.java
|
HugeProperty
|
equals
|
class HugeProperty<V> implements Property<V>, GraphType {
protected final HugeElement owner;
protected final PropertyKey pkey;
protected final V value;
public HugeProperty(HugeElement owner, PropertyKey pkey, V value) {
E.checkArgument(owner != null, "Property owner can't be null");
E.checkArgument(pkey != null, "Property key can't be null");
E.checkArgument(value != null, "Property value can't be null");
this.owner = owner;
this.pkey = pkey;
this.value = pkey.validValueOrThrow(value);
}
public PropertyKey propertyKey() {
return this.pkey;
}
public Object id() {
return SplicingIdGenerator.concat(this.owner.id().asString(), this.key());
}
@Override
public HugeType type() {
return HugeType.PROPERTY;
}
@Override
public String name() {
return this.pkey.name();
}
@Override
public String key() {
return this.pkey.name();
}
@Override
public V value() throws NoSuchElementException {
return this.value;
}
public Object serialValue(boolean encodeNumber) {
return this.pkey.serialValue(this.value, encodeNumber);
}
@Override
public boolean isPresent() {
return null != this.value;
}
public boolean isAggregateType() {
return !this.pkey.aggregateType().isNone();
}
@Override
public HugeElement element() {
return this.owner;
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return ElementHelper.hashCode(this);
}
@Override
public String toString() {
return StringFactory.propertyString(this);
}
}
|
if (!(obj instanceof HugeProperty)) {
return false;
}
HugeProperty<?> other = (HugeProperty<?>) obj;
return this.owner.equals(other.owner) && this.pkey.equals(other.pkey);
| 526
| 70
| 596
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/structure/HugeVertexProperty.java
|
HugeVertexProperty
|
equals
|
class HugeVertexProperty<V> extends HugeProperty<V>
implements VertexProperty<V> {
public HugeVertexProperty(HugeElement owner, PropertyKey key, V value) {
super(owner, key, value);
}
@Override
public HugeType type() {
return this.pkey.aggregateType().isNone() ?
HugeType.PROPERTY : HugeType.AGGR_PROPERTY_V;
}
@Override
public <U> Property<U> property(String key, U value) {
throw new NotSupportException("nested property");
}
@Override
public HugeVertex element() {
assert this.owner instanceof HugeVertex;
return (HugeVertex) this.owner;
}
@Override
public void remove() {
assert this.owner instanceof HugeVertex;
VertexLabel vertexLabel = ((HugeVertex) this.owner).schemaLabel();
E.checkArgument(vertexLabel.nullableKeys().contains(
this.propertyKey().id()),
"Can't remove non-null vertex property '%s'", this);
this.owner.graph().removeVertexProperty(this);
}
@Override
public <U> Iterator<Property<U>> properties(String... propertyKeys) {
throw new NotSupportException("nested property");
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return ElementHelper.hashCode((Element) this);
}
}
|
if (!(obj instanceof VertexProperty)) {
return false;
}
@SuppressWarnings("unchecked")
VertexProperty<V> other = (VertexProperty<V>) obj;
return this.id().equals(other.id());
| 399
| 67
| 466
|
<methods>public void <init>(org.apache.hugegraph.structure.HugeElement, org.apache.hugegraph.schema.PropertyKey, V) ,public org.apache.hugegraph.structure.HugeElement element() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.Object id() ,public boolean isAggregateType() ,public boolean isPresent() ,public java.lang.String key() ,public java.lang.String name() ,public org.apache.hugegraph.schema.PropertyKey propertyKey() ,public java.lang.Object serialValue(boolean) ,public java.lang.String toString() ,public org.apache.hugegraph.type.HugeType type() ,public V value() throws java.util.NoSuchElementException<variables>protected final non-sealed org.apache.hugegraph.structure.HugeElement owner,protected final non-sealed org.apache.hugegraph.schema.PropertyKey pkey,protected final non-sealed V value
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/task/EphemeralJobQueue.java
|
BatchEphemeralJob
|
execute
|
class BatchEphemeralJob extends EphemeralJob<Object> {
private static final long PAGE_SIZE = Query.COMMIT_BATCH;
private static final String BATCH_EPHEMERAL_JOB = "batch-ephemeral-job";
private static final long MAX_CONSUME_COUNT = 2 * PAGE_SIZE;
private WeakReference<EphemeralJobQueue> queueWeakReference;
public BatchEphemeralJob(EphemeralJobQueue queue) {
this.queueWeakReference = new WeakReference<>(queue);
}
@Override
public String type() {
return BATCH_EPHEMERAL_JOB;
}
@Override
public Object execute() throws Exception {<FILL_FUNCTION_BODY>}
private Object executeBatchJob(List<EphemeralJob<?>> jobs, Object prevResult) throws
Exception {
GraphTransaction graphTx = this.params().systemTransaction();
GraphTransaction systemTx = this.params().graphTransaction();
Object result = prevResult;
for (EphemeralJob<?> job : jobs) {
this.initJob(job);
Object obj = job.call();
if (job instanceof Reduce) {
result = ((Reduce) job).reduce(result, obj);
}
}
graphTx.commit();
systemTx.commit();
return result;
}
private void initJob(EphemeralJob<?> job) {
job.graph(this.graph());
job.params(this.params());
}
@Override
public Object call() throws Exception {
try {
return super.call();
} catch (Throwable e) {
LOG.warn("Failed to execute BatchEphemeralJob", e);
EphemeralJobQueue queue = this.queueWeakReference.get();
if (e instanceof InterruptedException) {
Thread.currentThread().interrupt();
if (queue != null) {
queue.clear();
queue.consumeComplete();
}
throw e;
}
if (queue != null) {
queue.consumeComplete();
if (!queue.isEmpty()) {
queue.reScheduleIfNeeded();
}
}
throw e;
}
}
}
|
boolean stop = false;
Object result = null;
int consumeCount = 0;
InterruptedException interruptedException = null;
EphemeralJobQueue queue;
List<EphemeralJob<?>> batchJobs = new ArrayList<>();
while (!stop) {
if (interruptedException == null && Thread.currentThread().isInterrupted()) {
interruptedException = new InterruptedException();
}
queue = this.queueWeakReference.get();
if (queue == null) {
stop = true;
continue;
}
if (queue.isEmpty() || consumeCount > MAX_CONSUME_COUNT ||
interruptedException != null) {
queue.consumeComplete();
stop = true;
if (!queue.isEmpty()) {
queue.reScheduleIfNeeded();
}
continue;
}
try {
while (!queue.isEmpty() && batchJobs.size() < PAGE_SIZE) {
EphemeralJob<?> job = queue.poll();
if (job == null) {
continue;
}
batchJobs.add(job);
}
if (batchJobs.isEmpty()) {
continue;
}
consumeCount += batchJobs.size();
result = this.executeBatchJob(batchJobs, result);
} catch (InterruptedException e) {
interruptedException = e;
} finally {
batchJobs.clear();
}
}
if (interruptedException != null) {
Thread.currentThread().interrupt();
throw interruptedException;
}
return result;
| 593
| 412
| 1,005
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/task/HugeServerInfo.java
|
P
|
unhide
|
class P {
public static final String SERVER = Graph.Hidden.hide("server");
public static final String ID = T.id.getAccessor();
public static final String LABEL = T.label.getAccessor();
public static final String NAME = "~server_name";
public static final String ROLE = "~server_role";
public static final String LOAD = "~server_load";
public static final String MAX_LOAD = "~server_max_load";
public static final String UPDATE_TIME = "~server_update_time";
public static String unhide(String key) {<FILL_FUNCTION_BODY>}
}
|
final String prefix = Graph.Hidden.hide("server_");
if (key.startsWith(prefix)) {
return key.substring(prefix.length());
}
return key;
| 167
| 52
| 219
|
<no_super_class>
|
apache_incubator-hugegraph
|
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/task/TaskCallable.java
|
TaskCallable
|
empty
|
class TaskCallable<V> implements Callable<V> {
private static final Logger LOG = Log.logger(TaskCallable.class);
private static final String ERROR_COMMIT = "Failed to commit changes: ";
private static final Set<String> ERROR_MESSAGES = ImmutableSet.of(
/*
* "The max length of bytes is" exception message occurs when
* task input size exceeds TASK_INPUT_SIZE_LIMIT or task result size
* exceeds TASK_RESULT_SIZE_LIMIT
*/
"The max length of bytes is",
/*
* "Batch too large" exception message occurs when using
* cassandra store and task input size is in
* [batch_size_fail_threshold_in_kb, TASK_INPUT_SIZE_LIMIT) or
* task result size is in
* [batch_size_fail_threshold_in_kb, TASK_RESULT_SIZE_LIMIT)
*/
"Batch too large"
);
private HugeTask<V> task = null;
private HugeGraph graph = null;
private volatile long lastSaveTime = System.currentTimeMillis();
private volatile long saveInterval = 1000 * 30;
public TaskCallable() {
// pass
}
protected void done() {
this.closeTx();
}
protected void cancelled() {
// Do nothing, subclasses may override this method
}
protected void closeTx() {
Transaction tx = this.graph().tx();
if (tx.isOpen()) {
tx.close();
}
}
public void setMinSaveInterval(long seconds) {
E.checkArgument(seconds > 0,
"Must set interval > 0, but got '%s'", seconds);
this.saveInterval = seconds * 1000L;
}
public void updateProgress(int progress) {
HugeTask<V> task = this.task();
task.progress(progress);
long elapse = System.currentTimeMillis() - this.lastSaveTime;
if (elapse > this.saveInterval) {
this.save();
this.lastSaveTime = System.currentTimeMillis();
}
}
public int progress() {
HugeTask<V> task = this.task();
return task.progress();
}
protected void save() {
HugeTask<V> task = this.task();
task.updateTime(new Date());
try {
this.graph().taskScheduler().save(task);
} catch (Throwable e) {
if (task.completed()) {
/*
* Failed to save task and the status is stable(can't be update)
* just log the task, and try again.
*/
LOG.error("Failed to save task with error \"{}\": {}",
e, task.asMap(false));
String message = e.getMessage();
if (message.contains(ERROR_COMMIT) && needSaveWithEx(message)) {
task.failToSave(e);
this.graph().taskScheduler().save(task);
return;
}
}
throw e;
}
}
protected void graph(HugeGraph graph) {
this.graph = graph;
}
public HugeGraph graph() {
E.checkState(this.graph != null,
"Can't call graph() before scheduling task");
return this.graph;
}
protected void task(HugeTask<V> task) {
this.task = task;
}
public HugeTask<V> task() {
E.checkState(this.task != null,
"Can't call task() before scheduling task");
return this.task;
}
@SuppressWarnings("unchecked")
public static <V> TaskCallable<V> fromClass(String className) {
try {
Class<?> clazz = Class.forName(className);
return (TaskCallable<V>) clazz.newInstance();
} catch (Exception e) {
throw new HugeException("Failed to load task: %s", e, className);
}
}
private static boolean needSaveWithEx(String message) {
for (String error : ERROR_MESSAGES) {
if (message.contains(error)) {
return true;
}
}
return false;
}
public static <V> TaskCallable<V> empty(Exception e) {<FILL_FUNCTION_BODY>}
public abstract static class SysTaskCallable<V> extends TaskCallable<V> {
private HugeGraphParams params = null;
protected void params(HugeGraphParams params) {
this.params = params;
}
protected HugeGraphParams params() {
E.checkState(this.params != null,
"Can't call scheduler() before scheduling task");
return this.params;
}
}
}
|
return new TaskCallable<V>() {
@Override
public V call() throws Exception {
throw e;
}
};
| 1,265
| 39
| 1,304
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.