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/traversal/algorithm/CollectionPathsTraverser.java
NearestTraverser
processOneForBackward
class NearestTraverser extends Traverser { public NearestTraverser(HugeTraverser traverser, TraverseStrategy strategy, Collection<Id> sources, Collection<Id> targets, EdgeStep step, int depth, long capacity, long limit, boolean concurrent) { super(traverser, strategy, sources, targets, step, depth, capacity, limit, concurrent); } @Override protected void processOneForForward(Id sourceV, Id targetV) { Node source = this.sources.get(sourceV).get(0); // If have loop, skip target if (source.contains(targetV)) { return; } // If cross point exists, path found, concat them if (this.targetsAll.containsKey(targetV)) { Node node = this.targetsAll.get(targetV).get(0); List<Id> path = source.joinPath(node); if (!path.isEmpty()) { this.paths.add(new Path(targetV, path)); if (this.reachLimit()) { return; } } } // Add node to next start-nodes this.addNodeToNewVertices(targetV, new Node(targetV, source)); } @Override protected void processOneForBackward(Id sourceV, Id targetV) {<FILL_FUNCTION_BODY>} @Override protected void reInitCurrentStepIfNeeded(EdgeStep step, boolean forward) { if (forward) { // Re-init targets this.sources = this.newVertices; // Record all passed vertices this.addNewVerticesToAll(this.sourcesAll); } else { // Re-init targets this.targets = this.newVertices; // Record all passed vertices this.addNewVerticesToAll(this.targetsAll); } } @Override public void addNodeToNewVertices(Id id, Node node) { this.newVertices.putIfAbsent(id, ImmutableList.of(node)); } @Override public void addNewVerticesToAll(Map<Id, List<Node>> targets) { for (Map.Entry<Id, List<Node>> entry : this.newVertices.entrySet()) { targets.putIfAbsent(entry.getKey(), entry.getValue()); } } @Override protected int accessedNodes() { return this.sourcesAll.size() + this.targetsAll.size(); } }
Node sourcee = this.targets.get(sourceV).get(0); // If have loop, skip target if (sourcee.contains(targetV)) { return; } // If cross point exists, path found, concat them if (this.sourcesAll.containsKey(targetV)) { Node node = this.sourcesAll.get(targetV).get(0); List<Id> path = sourcee.joinPath(node); if (!path.isEmpty()) { Path newPath = new Path(targetV, path); newPath.reverse(); this.paths.add(newPath); if (this.reachLimit()) { return; } } } // Add node to next start-nodes this.addNodeToNewVertices(targetV, new Node(targetV, sourcee));
657
217
874
<methods>public void <init>(org.apache.hugegraph.HugeGraph) ,public static void checkCapacity(long) ,public static void checkCapacity(long, long, java.lang.String) ,public static void checkDegree(long) ,public static void checkLimit(long) ,public static void checkNonNegative(long, java.lang.String) ,public static void checkNonNegativeOrNoLimit(long, java.lang.String) ,public static void checkPositive(long, java.lang.String) ,public static void checkPositiveOrNoLimit(long, java.lang.String) ,public static void checkSkipDegree(long, long, long) ,public static void checkTraverseMode(java.lang.String) ,public Iterator<Edge> createNestedIterator(org.apache.hugegraph.backend.id.Id, org.apache.hugegraph.traversal.algorithm.steps.Steps, int, Set<org.apache.hugegraph.backend.id.Id>, boolean) ,public Iterator<Edge> edgesOfVertex(org.apache.hugegraph.backend.id.Id, org.apache.hugegraph.traversal.algorithm.steps.Steps) ,public org.apache.hugegraph.traversal.algorithm.HugeTraverser.EdgesIterator edgesOfVertices(Iterator<org.apache.hugegraph.backend.id.Id>, org.apache.hugegraph.type.define.Directions, List<org.apache.hugegraph.backend.id.Id>, long) ,public org.apache.hugegraph.HugeGraph graph() ,public static boolean isTraverseModeDFS(java.lang.String) ,public static List<org.apache.hugegraph.structure.HugeEdge> pathEdges(Iterator<Edge>, org.apache.hugegraph.structure.HugeEdge) ,public static Iterator<Edge> skipSuperNodeIfNeeded(Iterator<Edge>, long, long) ,public static Map<K,V> topN(Map<K,V>, boolean, long) <variables>public static final java.lang.String DEFAULT_CAPACITY,public static final java.lang.String DEFAULT_ELEMENTS_LIMIT,public static final java.lang.String DEFAULT_LIMIT,public static final java.lang.String DEFAULT_MAX_DEGREE,public static final int DEFAULT_MAX_DEPTH,public static final java.lang.String DEFAULT_PAGE_LIMIT,public static final java.lang.String DEFAULT_PATHS_LIMIT,public static final java.lang.String DEFAULT_SAMPLE,public static final java.lang.String DEFAULT_SKIP_DEGREE,public static final java.lang.String DEFAULT_WEIGHT,protected static final Logger LOG,protected static final int MAX_VERTICES,public static final long NO_LIMIT,public static final java.lang.String TRAVERSE_MODE_BFS,public static final java.lang.String TRAVERSE_MODE_DFS,private static org.apache.hugegraph.util.collection.CollectionFactory collectionFactory,public java.util.concurrent.atomic.AtomicLong edgeIterCounter,private final non-sealed org.apache.hugegraph.HugeGraph graph,public java.util.concurrent.atomic.AtomicLong vertexIterCounter
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/algorithm/CountTraverser.java
CountTraverser
count
class CountTraverser extends HugeTraverser { private boolean containsTraversed = false; private long dedupSize = 1000000L; private final Set<Id> dedupSet = newIdSet(); private final MutableLong count = new MutableLong(0L); public CountTraverser(HugeGraph graph) { super(graph); } public long count(Id source, List<EdgeStep> steps, boolean containsTraversed, long dedupSize) {<FILL_FUNCTION_BODY>} private Iterator<Edge> edgesOfVertexWithCount(Id source, EdgeStep step) { if (this.dedup(source)) { return QueryResults.emptyIterator(); } Iterator<Edge> flatten = this.edgesOfVertex(source, step); return new FilterIterator<>(flatten, e -> { if (this.containsTraversed) { // Count intermediate vertices this.count.increment(); } return true; }); } private void checkDedupSize(long dedup) { checkNonNegativeOrNoLimit(dedup, "dedup size"); } private boolean dedup(Id vertex) { if (!this.needDedup()) { return false; } if (this.dedupSet.contains(vertex)) { // Skip vertex already traversed return true; } else if (!this.reachDedup()) { // Record vertex not traversed before if not reach dedup size this.dedupSet.add(vertex); } return false; } private boolean needDedup() { return this.dedupSize != 0L; } private boolean reachDedup() { return this.dedupSize != NO_LIMIT && this.dedupSet.size() >= this.dedupSize; } }
E.checkNotNull(source, "source vertex id"); this.checkVertexExist(source, "source vertex"); E.checkArgument(steps != null && !steps.isEmpty(), "The steps can't be empty"); checkDedupSize(dedupSize); this.containsTraversed = containsTraversed; this.dedupSize = dedupSize; if (this.containsTraversed) { this.count.increment(); } int stepNum = steps.size(); EdgeStep firstStep = steps.get(0); if (stepNum == 1) { // Just one step, query count and return long edgesCount = this.edgesCount(source, firstStep); this.count.add(edgesCount); return this.count.longValue(); } // Multiple steps, construct first step to iterator Iterator<Edge> edges = this.edgesOfVertexWithCount(source, firstStep); // Wrap steps to Iterator except last step for (int i = 1; i < stepNum - 1; i++) { EdgeStep currentStep = steps.get(i); edges = new FlatMapperIterator<>(edges, (edge) -> { Id target = ((HugeEdge) edge).id().otherVertexId(); return this.edgesOfVertexWithCount(target, currentStep); }); } try { // The last step, just query count EdgeStep lastStep = steps.get(stepNum - 1); while (edges.hasNext()) { Id target = ((HugeEdge) edges.next()).id().otherVertexId(); if (this.dedup(target)) { continue; } // Count last layer vertices(without dedup size) long edgesCount = this.edgesCount(target, lastStep); this.count.add(edgesCount); } return this.count.longValue(); } finally { CloseableIterator.closeIterator(edges); }
494
511
1,005
<methods>public void <init>(org.apache.hugegraph.HugeGraph) ,public static void checkCapacity(long) ,public static void checkCapacity(long, long, java.lang.String) ,public static void checkDegree(long) ,public static void checkLimit(long) ,public static void checkNonNegative(long, java.lang.String) ,public static void checkNonNegativeOrNoLimit(long, java.lang.String) ,public static void checkPositive(long, java.lang.String) ,public static void checkPositiveOrNoLimit(long, java.lang.String) ,public static void checkSkipDegree(long, long, long) ,public static void checkTraverseMode(java.lang.String) ,public Iterator<Edge> createNestedIterator(org.apache.hugegraph.backend.id.Id, org.apache.hugegraph.traversal.algorithm.steps.Steps, int, Set<org.apache.hugegraph.backend.id.Id>, boolean) ,public Iterator<Edge> edgesOfVertex(org.apache.hugegraph.backend.id.Id, org.apache.hugegraph.traversal.algorithm.steps.Steps) ,public org.apache.hugegraph.traversal.algorithm.HugeTraverser.EdgesIterator edgesOfVertices(Iterator<org.apache.hugegraph.backend.id.Id>, org.apache.hugegraph.type.define.Directions, List<org.apache.hugegraph.backend.id.Id>, long) ,public org.apache.hugegraph.HugeGraph graph() ,public static boolean isTraverseModeDFS(java.lang.String) ,public static List<org.apache.hugegraph.structure.HugeEdge> pathEdges(Iterator<Edge>, org.apache.hugegraph.structure.HugeEdge) ,public static Iterator<Edge> skipSuperNodeIfNeeded(Iterator<Edge>, long, long) ,public static Map<K,V> topN(Map<K,V>, boolean, long) <variables>public static final java.lang.String DEFAULT_CAPACITY,public static final java.lang.String DEFAULT_ELEMENTS_LIMIT,public static final java.lang.String DEFAULT_LIMIT,public static final java.lang.String DEFAULT_MAX_DEGREE,public static final int DEFAULT_MAX_DEPTH,public static final java.lang.String DEFAULT_PAGE_LIMIT,public static final java.lang.String DEFAULT_PATHS_LIMIT,public static final java.lang.String DEFAULT_SAMPLE,public static final java.lang.String DEFAULT_SKIP_DEGREE,public static final java.lang.String DEFAULT_WEIGHT,protected static final Logger LOG,protected static final int MAX_VERTICES,public static final long NO_LIMIT,public static final java.lang.String TRAVERSE_MODE_BFS,public static final java.lang.String TRAVERSE_MODE_DFS,private static org.apache.hugegraph.util.collection.CollectionFactory collectionFactory,public java.util.concurrent.atomic.AtomicLong edgeIterCounter,private final non-sealed org.apache.hugegraph.HugeGraph graph,public java.util.concurrent.atomic.AtomicLong vertexIterCounter
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/algorithm/CustomizePathsTraverser.java
WeightNode
weights
class WeightNode extends Node { private final double weight; public WeightNode(Id id, Node parent, double weight) { super(id, parent); this.weight = weight; } public List<Double> weights() {<FILL_FUNCTION_BODY>} }
List<Double> weights = newList(); WeightNode current = this; while (current.parent() != null) { weights.add(current.weight); current = (WeightNode) current.parent(); } Collections.reverse(weights); return weights;
77
76
153
<methods>public void <init>(org.apache.hugegraph.HugeGraph) ,public static void checkCapacity(long) ,public static void checkCapacity(long, long, java.lang.String) ,public static void checkDegree(long) ,public static void checkLimit(long) ,public static void checkNonNegative(long, java.lang.String) ,public static void checkNonNegativeOrNoLimit(long, java.lang.String) ,public static void checkPositive(long, java.lang.String) ,public static void checkPositiveOrNoLimit(long, java.lang.String) ,public static void checkSkipDegree(long, long, long) ,public static void checkTraverseMode(java.lang.String) ,public Iterator<Edge> createNestedIterator(org.apache.hugegraph.backend.id.Id, org.apache.hugegraph.traversal.algorithm.steps.Steps, int, Set<org.apache.hugegraph.backend.id.Id>, boolean) ,public Iterator<Edge> edgesOfVertex(org.apache.hugegraph.backend.id.Id, org.apache.hugegraph.traversal.algorithm.steps.Steps) ,public org.apache.hugegraph.traversal.algorithm.HugeTraverser.EdgesIterator edgesOfVertices(Iterator<org.apache.hugegraph.backend.id.Id>, org.apache.hugegraph.type.define.Directions, List<org.apache.hugegraph.backend.id.Id>, long) ,public org.apache.hugegraph.HugeGraph graph() ,public static boolean isTraverseModeDFS(java.lang.String) ,public static List<org.apache.hugegraph.structure.HugeEdge> pathEdges(Iterator<Edge>, org.apache.hugegraph.structure.HugeEdge) ,public static Iterator<Edge> skipSuperNodeIfNeeded(Iterator<Edge>, long, long) ,public static Map<K,V> topN(Map<K,V>, boolean, long) <variables>public static final java.lang.String DEFAULT_CAPACITY,public static final java.lang.String DEFAULT_ELEMENTS_LIMIT,public static final java.lang.String DEFAULT_LIMIT,public static final java.lang.String DEFAULT_MAX_DEGREE,public static final int DEFAULT_MAX_DEPTH,public static final java.lang.String DEFAULT_PAGE_LIMIT,public static final java.lang.String DEFAULT_PATHS_LIMIT,public static final java.lang.String DEFAULT_SAMPLE,public static final java.lang.String DEFAULT_SKIP_DEGREE,public static final java.lang.String DEFAULT_WEIGHT,protected static final Logger LOG,protected static final int MAX_VERTICES,public static final long NO_LIMIT,public static final java.lang.String TRAVERSE_MODE_BFS,public static final java.lang.String TRAVERSE_MODE_DFS,private static org.apache.hugegraph.util.collection.CollectionFactory collectionFactory,public java.util.concurrent.atomic.AtomicLong edgeIterCounter,private final non-sealed org.apache.hugegraph.HugeGraph graph,public java.util.concurrent.atomic.AtomicLong vertexIterCounter
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/algorithm/CustomizedCrosspointsTraverser.java
CustomizedCrosspointsTraverser
crosspointsPaths
class CustomizedCrosspointsTraverser extends HugeTraverser { private final EdgeRecord edgeResults; public CustomizedCrosspointsTraverser(HugeGraph graph) { super(graph); this.edgeResults = new EdgeRecord(false); } private static CrosspointsPaths intersectionPaths(List<HugeVertex> sources, List<Path> paths, long limit) { // Split paths by end vertices MultivaluedMap<Id, Id> endVertices = newMultivalueMap(); for (Path path : paths) { List<Id> vertices = path.vertices(); int length = vertices.size(); endVertices.add(vertices.get(0), vertices.get(length - 1)); } Set<Id> sourceIds = sources.stream().map(HugeVertex::id) .collect(Collectors.toSet()); Set<Id> ids = endVertices.keySet(); if (sourceIds.size() != ids.size() || !sourceIds.containsAll(ids)) { return CrosspointsPaths.EMPTY; } // Get intersection of end vertices Collection<Id> intersection = null; for (List<Id> ends : endVertices.values()) { if (intersection == null) { intersection = ends; } else { intersection = CollectionUtil.intersect(intersection, ends); } if (intersection == null || intersection.isEmpty()) { return CrosspointsPaths.EMPTY; } } assert intersection != null; // Limit intersection number to limit crosspoints vertices in result int size = intersection.size(); if (limit != NO_LIMIT && size > limit) { intersection = newList(intersection).subList(0, size - 1); } // Filter intersection paths List<Path> results = newList(); for (Path path : paths) { List<Id> vertices = path.vertices(); int length = vertices.size(); if (intersection.contains(vertices.get(length - 1))) { results.add(path); } } return new CrosspointsPaths(newSet(intersection), results); } public EdgeRecord edgeResults() { return edgeResults; } public CrosspointsPaths crosspointsPaths(Iterator<Vertex> vertices, List<PathPattern> pathPatterns, long capacity, long limit) {<FILL_FUNCTION_BODY>} public static class PathPattern { private final List<Step> steps; public PathPattern() { this.steps = newList(); } public List<Step> steps() { return this.steps; } public int size() { return this.steps.size(); } public void add(Step step) { this.steps.add(step); } } public static class Step { private final EdgeStep edgeStep; public Step(HugeGraph g, Directions direction, List<String> labels, Map<String, Object> properties, long degree, long skipDegree) { this.edgeStep = new EdgeStep(g, direction, labels, properties, degree, skipDegree); } } public static class CrosspointsPaths { private static final CrosspointsPaths EMPTY = new CrosspointsPaths( ImmutableSet.of(), ImmutableList.of() ); private final Set<Id> crosspoints; private final List<Path> paths; public CrosspointsPaths(Set<Id> crosspoints, List<Path> paths) { this.crosspoints = crosspoints; this.paths = paths; } public Set<Id> crosspoints() { return this.crosspoints; } public List<Path> paths() { return this.paths; } } }
E.checkArgument(vertices.hasNext(), "The source vertices can't be empty"); E.checkArgument(!pathPatterns.isEmpty(), "The steps pattern can't be empty"); checkCapacity(capacity); checkLimit(limit); MultivaluedMap<Id, Node> initialSources = newMultivalueMap(); List<HugeVertex> verticesList = newList(); while (vertices.hasNext()) { HugeVertex vertex = (HugeVertex) vertices.next(); verticesList.add(vertex); Node node = new Node(vertex.id(), null); initialSources.add(vertex.id(), node); } List<Path> paths = newList(); long edgeCount = 0L; long vertexCount = 0L; for (PathPattern pathPattern : pathPatterns) { MultivaluedMap<Id, Node> sources = initialSources; int stepNum = pathPattern.size(); long access = 0; MultivaluedMap<Id, Node> newVertices = null; for (Step step : pathPattern.steps()) { stepNum--; newVertices = newMultivalueMap(); Iterator<Edge> edges; // Traversal vertices of previous level for (Map.Entry<Id, List<Node>> entry : sources.entrySet()) { List<Node> adjacency = newList(); edges = this.edgesOfVertex(entry.getKey(), step.edgeStep); vertexCount += 1; while (edges.hasNext()) { HugeEdge edge = (HugeEdge) edges.next(); edgeCount += 1; Id target = edge.id().otherVertexId(); this.edgeResults.addEdge(entry.getKey(), target, edge); for (Node n : entry.getValue()) { // If have loop, skip target if (n.contains(target)) { continue; } Node newNode = new Node(target, n); adjacency.add(newNode); checkCapacity(capacity, ++access, "customized crosspoints"); } } // Add current node's adjacent nodes for (Node node : adjacency) { newVertices.add(node.id(), node); } } // Re-init sources sources = newVertices; } assert stepNum == 0; assert newVertices != null; for (List<Node> nodes : newVertices.values()) { for (Node n : nodes) { paths.add(new Path(n.path())); } } } this.vertexIterCounter.addAndGet(vertexCount); this.edgeIterCounter.addAndGet(edgeCount); return intersectionPaths(verticesList, paths, limit);
1,059
715
1,774
<methods>public void <init>(org.apache.hugegraph.HugeGraph) ,public static void checkCapacity(long) ,public static void checkCapacity(long, long, java.lang.String) ,public static void checkDegree(long) ,public static void checkLimit(long) ,public static void checkNonNegative(long, java.lang.String) ,public static void checkNonNegativeOrNoLimit(long, java.lang.String) ,public static void checkPositive(long, java.lang.String) ,public static void checkPositiveOrNoLimit(long, java.lang.String) ,public static void checkSkipDegree(long, long, long) ,public static void checkTraverseMode(java.lang.String) ,public Iterator<Edge> createNestedIterator(org.apache.hugegraph.backend.id.Id, org.apache.hugegraph.traversal.algorithm.steps.Steps, int, Set<org.apache.hugegraph.backend.id.Id>, boolean) ,public Iterator<Edge> edgesOfVertex(org.apache.hugegraph.backend.id.Id, org.apache.hugegraph.traversal.algorithm.steps.Steps) ,public org.apache.hugegraph.traversal.algorithm.HugeTraverser.EdgesIterator edgesOfVertices(Iterator<org.apache.hugegraph.backend.id.Id>, org.apache.hugegraph.type.define.Directions, List<org.apache.hugegraph.backend.id.Id>, long) ,public org.apache.hugegraph.HugeGraph graph() ,public static boolean isTraverseModeDFS(java.lang.String) ,public static List<org.apache.hugegraph.structure.HugeEdge> pathEdges(Iterator<Edge>, org.apache.hugegraph.structure.HugeEdge) ,public static Iterator<Edge> skipSuperNodeIfNeeded(Iterator<Edge>, long, long) ,public static Map<K,V> topN(Map<K,V>, boolean, long) <variables>public static final java.lang.String DEFAULT_CAPACITY,public static final java.lang.String DEFAULT_ELEMENTS_LIMIT,public static final java.lang.String DEFAULT_LIMIT,public static final java.lang.String DEFAULT_MAX_DEGREE,public static final int DEFAULT_MAX_DEPTH,public static final java.lang.String DEFAULT_PAGE_LIMIT,public static final java.lang.String DEFAULT_PATHS_LIMIT,public static final java.lang.String DEFAULT_SAMPLE,public static final java.lang.String DEFAULT_SKIP_DEGREE,public static final java.lang.String DEFAULT_WEIGHT,protected static final Logger LOG,protected static final int MAX_VERTICES,public static final long NO_LIMIT,public static final java.lang.String TRAVERSE_MODE_BFS,public static final java.lang.String TRAVERSE_MODE_DFS,private static org.apache.hugegraph.util.collection.CollectionFactory collectionFactory,public java.util.concurrent.atomic.AtomicLong edgeIterCounter,private final non-sealed org.apache.hugegraph.HugeGraph graph,public java.util.concurrent.atomic.AtomicLong vertexIterCounter
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/algorithm/EdgeExistenceTraverser.java
EdgeExistenceTraverser
queryEdgeExistence
class EdgeExistenceTraverser extends HugeTraverser { public EdgeExistenceTraverser(HugeGraph graph) { super(graph); } public Iterator<Edge> queryEdgeExistence(Id sourceId, Id targetId, String label, String sortValues, long limit) {<FILL_FUNCTION_BODY>} private Iterator<Edge> queryByNeighbors(Id sourceId, Id targetId, long limit) { return new FilterIterator<>(edgesOfVertex(sourceId, Directions.OUT, (Id) null, limit), edge -> targetId.equals(edge.inVertex().id())); } }
// If no label provided, fallback to a slow query by filtering if (label == null || label.isEmpty()) { return queryByNeighbors(sourceId, targetId, limit); } EdgeLabel edgeLabel = graph().edgeLabel(label); ConditionQuery conditionQuery = new ConditionQuery(HugeType.EDGE); conditionQuery.eq(HugeKeys.OWNER_VERTEX, sourceId); conditionQuery.eq(HugeKeys.OTHER_VERTEX, targetId); conditionQuery.eq(HugeKeys.LABEL, edgeLabel.id()); conditionQuery.eq(HugeKeys.DIRECTION, Directions.OUT); conditionQuery.limit(limit); if (edgeLabel.existSortKeys() && !sortValues.isEmpty()) { conditionQuery.eq(HugeKeys.SORT_VALUES, sortValues); } else { conditionQuery.eq(HugeKeys.SORT_VALUES, ""); } return graph().edges(conditionQuery);
167
256
423
<methods>public void <init>(org.apache.hugegraph.HugeGraph) ,public static void checkCapacity(long) ,public static void checkCapacity(long, long, java.lang.String) ,public static void checkDegree(long) ,public static void checkLimit(long) ,public static void checkNonNegative(long, java.lang.String) ,public static void checkNonNegativeOrNoLimit(long, java.lang.String) ,public static void checkPositive(long, java.lang.String) ,public static void checkPositiveOrNoLimit(long, java.lang.String) ,public static void checkSkipDegree(long, long, long) ,public static void checkTraverseMode(java.lang.String) ,public Iterator<Edge> createNestedIterator(org.apache.hugegraph.backend.id.Id, org.apache.hugegraph.traversal.algorithm.steps.Steps, int, Set<org.apache.hugegraph.backend.id.Id>, boolean) ,public Iterator<Edge> edgesOfVertex(org.apache.hugegraph.backend.id.Id, org.apache.hugegraph.traversal.algorithm.steps.Steps) ,public org.apache.hugegraph.traversal.algorithm.HugeTraverser.EdgesIterator edgesOfVertices(Iterator<org.apache.hugegraph.backend.id.Id>, org.apache.hugegraph.type.define.Directions, List<org.apache.hugegraph.backend.id.Id>, long) ,public org.apache.hugegraph.HugeGraph graph() ,public static boolean isTraverseModeDFS(java.lang.String) ,public static List<org.apache.hugegraph.structure.HugeEdge> pathEdges(Iterator<Edge>, org.apache.hugegraph.structure.HugeEdge) ,public static Iterator<Edge> skipSuperNodeIfNeeded(Iterator<Edge>, long, long) ,public static Map<K,V> topN(Map<K,V>, boolean, long) <variables>public static final java.lang.String DEFAULT_CAPACITY,public static final java.lang.String DEFAULT_ELEMENTS_LIMIT,public static final java.lang.String DEFAULT_LIMIT,public static final java.lang.String DEFAULT_MAX_DEGREE,public static final int DEFAULT_MAX_DEPTH,public static final java.lang.String DEFAULT_PAGE_LIMIT,public static final java.lang.String DEFAULT_PATHS_LIMIT,public static final java.lang.String DEFAULT_SAMPLE,public static final java.lang.String DEFAULT_SKIP_DEGREE,public static final java.lang.String DEFAULT_WEIGHT,protected static final Logger LOG,protected static final int MAX_VERTICES,public static final long NO_LIMIT,public static final java.lang.String TRAVERSE_MODE_BFS,public static final java.lang.String TRAVERSE_MODE_DFS,private static org.apache.hugegraph.util.collection.CollectionFactory collectionFactory,public java.util.concurrent.atomic.AtomicLong edgeIterCounter,private final non-sealed org.apache.hugegraph.HugeGraph graph,public java.util.concurrent.atomic.AtomicLong vertexIterCounter
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/algorithm/JaccardSimilarTraverser.java
JaccardSimilarTraverser
jaccardSimilarsSingle
class JaccardSimilarTraverser extends OltpTraverser { public JaccardSimilarTraverser(HugeGraph graph) { super(graph); } private static void reachCapacity(long count, long capacity) { if (capacity != NO_LIMIT && count > capacity) { throw new HugeException("Reach capacity '%s'", capacity); } } public double jaccardSimilarity(Id vertex, Id other, Directions dir, String label, long degree) { E.checkNotNull(vertex, "vertex id"); E.checkNotNull(other, "the other vertex id"); this.checkVertexExist(vertex, "vertex"); this.checkVertexExist(other, "other vertex"); E.checkNotNull(dir, "direction"); checkDegree(degree); Id labelId = this.getEdgeLabelIdOrNull(label); Set<Id> sourceNeighbors = IteratorUtils.set(this.adjacentVertices( vertex, dir, labelId, degree)); Set<Id> targetNeighbors = IteratorUtils.set(this.adjacentVertices( other, dir, labelId, degree)); this.vertexIterCounter.addAndGet(2L); this.edgeIterCounter.addAndGet(sourceNeighbors.size()); this.edgeIterCounter.addAndGet(targetNeighbors.size()); return jaccardSimilarity(sourceNeighbors, targetNeighbors); } public double jaccardSimilarity(Set<Id> set1, Set<Id> set2) { int interNum = CollectionUtil.intersect(set1, set2).size(); int unionNum = CollectionUtil.union(set1, set2).size(); if (unionNum == 0) { return 0.0D; } return (double) interNum / unionNum; } public Map<Id, Double> jaccardSimilars(Id source, EdgeStep step, int top, long capacity) { E.checkNotNull(source, "source vertex id"); this.checkVertexExist(source, "source vertex"); checkCapacity(capacity); Map<Id, Double> results; int maxDepth = 3; if (maxDepth >= this.concurrentDepth()) { results = this.jaccardSimilarsConcurrent(source, step, capacity); } else { results = this.jaccardSimilarsSingle(source, step, capacity); } if (top > 0) { results = HugeTraverser.topN(results, true, top); } return results; } public Map<Id, Double> jaccardSimilarsConcurrent(Id source, EdgeStep step, long capacity) { AtomicLong count = new AtomicLong(0L); Set<Id> accessed = ConcurrentHashMap.newKeySet(); accessed.add(source); reachCapacity(count.incrementAndGet(), capacity); // Query neighbors Set<Id> layer1s = this.adjacentVertices(source, step); this.vertexIterCounter.addAndGet(1L); this.edgeIterCounter.addAndGet(layer1s.size()); reachCapacity(count.get() + layer1s.size(), capacity); count.addAndGet(layer1s.size()); if (layer1s.isEmpty()) { return ImmutableMap.of(); } Map<Id, Double> results = new ConcurrentHashMap<>(); Set<Id> layer2All = ConcurrentHashMap.newKeySet(); this.traverseIds(layer1s.iterator(), id -> { // Skip if accessed already if (accessed.contains(id)) { return; } Set<Id> layer2s = this.adjacentVertices(id, step); this.vertexIterCounter.addAndGet(1L); this.edgeIterCounter.addAndGet(layer2s.size()); if (layer2s.isEmpty()) { results.put(id, 0.0D); } layer2All.addAll(layer2s); reachCapacity(count.get() + layer2All.size(), capacity); double jaccardSimilarity = this.jaccardSimilarity(layer1s, layer2s); results.put(id, jaccardSimilarity); accessed.add(id); }); count.addAndGet(layer2All.size()); this.traverseIds(layer2All.iterator(), id -> { // Skip if accessed already if (accessed.contains(id)) { return; } Set<Id> layer3s = this.adjacentVertices(id, step); this.vertexIterCounter.addAndGet(1L); this.edgeIterCounter.addAndGet(layer3s.size()); reachCapacity(count.get() + layer3s.size(), capacity); if (layer3s.isEmpty()) { results.put(id, 0.0D); } double jaccardSimilarity = this.jaccardSimilarity(layer1s, layer3s); results.put(id, jaccardSimilarity); accessed.add(id); }); return results; } public Map<Id, Double> jaccardSimilarsSingle(Id source, EdgeStep step, long capacity) {<FILL_FUNCTION_BODY>} }
long count = 0L; Set<Id> accessed = newIdSet(); accessed.add(source); reachCapacity(++count, capacity); // Query neighbors Set<Id> layer1s = this.adjacentVertices(source, step); this.vertexIterCounter.addAndGet(1L); this.edgeIterCounter.addAndGet(layer1s.size()); reachCapacity(count + layer1s.size(), capacity); count += layer1s.size(); if (layer1s.isEmpty()) { return ImmutableMap.of(); } Map<Id, Double> results = newMap(); Set<Id> layer2s; Set<Id> layer2All = newIdSet(); double jaccardSimilarity; for (Id neighbor : layer1s) { // Skip if accessed already if (accessed.contains(neighbor)) { continue; } layer2s = this.adjacentVertices(neighbor, step); this.vertexIterCounter.addAndGet(1L); this.edgeIterCounter.addAndGet(layer2s.size()); if (layer2s.isEmpty()) { results.put(neighbor, 0.0D); continue; } layer2All.addAll(layer2s); reachCapacity(count + layer2All.size(), capacity); jaccardSimilarity = this.jaccardSimilarity(layer1s, layer2s); results.put(neighbor, jaccardSimilarity); accessed.add(neighbor); } count += layer2All.size(); Set<Id> layer3s; for (Id neighbor : layer2All) { // Skip if accessed already if (accessed.contains(neighbor)) { continue; } layer3s = this.adjacentVertices(neighbor, step); this.vertexIterCounter.addAndGet(1L); this.edgeIterCounter.addAndGet(layer3s.size()); reachCapacity(count + layer3s.size(), capacity); if (layer3s.isEmpty()) { results.put(neighbor, 0.0D); continue; } jaccardSimilarity = this.jaccardSimilarity(layer1s, layer3s); results.put(neighbor, jaccardSimilarity); accessed.add(neighbor); } return results;
1,406
628
2,034
<methods>public void close() ,public static void destroy() <variables>private static final java.lang.String EXECUTOR_NAME,private static org.apache.hugegraph.util.Consumers.ExecutorPool executors
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/algorithm/KneighborTraverser.java
KneighborTraverser
customizedKneighbor
class KneighborTraverser extends OltpTraverser { public KneighborTraverser(HugeGraph graph) { super(graph); } public Set<Id> kneighbor(Id sourceV, Directions dir, String label, int depth, long degree, long limit) { E.checkNotNull(sourceV, "source vertex id"); this.checkVertexExist(sourceV, "source vertex"); E.checkNotNull(dir, "direction"); checkPositive(depth, "k-neighbor max_depth"); checkDegree(degree); checkLimit(limit); Id labelId = this.getEdgeLabelIdOrNull(label); KneighborRecords records = new KneighborRecords(true, sourceV, true); Consumer<EdgeId> consumer = edgeId -> { if (this.reachLimit(limit, records.size())) { return; } records.addPath(edgeId.ownerVertexId(), edgeId.otherVertexId()); }; while (depth-- > 0) { records.startOneLayer(true); traverseIdsByBfs(records.keys(), dir, labelId, degree, NO_LIMIT, consumer); records.finishOneLayer(); if (reachLimit(limit, records.size())) { break; } } this.vertexIterCounter.addAndGet(records.size()); return records.idsBySet(limit); } public KneighborRecords customizedKneighbor(Id source, Steps steps, int maxDepth, long limit) {<FILL_FUNCTION_BODY>} private boolean reachLimit(long limit, int size) { return limit != NO_LIMIT && size >= limit; } }
E.checkNotNull(source, "source vertex id"); this.checkVertexExist(source, "source vertex"); checkPositive(maxDepth, "k-neighbor max_depth"); checkLimit(limit); KneighborRecords records = new KneighborRecords(true, source, true); Consumer<Edge> consumer = edge -> { if (this.reachLimit(limit, records.size())) { return; } EdgeId edgeId = ((HugeEdge) edge).id(); records.addPath(edgeId.ownerVertexId(), edgeId.otherVertexId()); records.edgeResults().addEdge(edgeId.ownerVertexId(), edgeId.otherVertexId(), edge); }; while (maxDepth-- > 0) { records.startOneLayer(true); traverseIdsByBfs(records.keys(), steps, NO_LIMIT, consumer); records.finishOneLayer(); if (this.reachLimit(limit, records.size())) { break; } } this.vertexIterCounter.addAndGet(records.size()); return records;
454
290
744
<methods>public void close() ,public static void destroy() <variables>private static final java.lang.String EXECUTOR_NAME,private static org.apache.hugegraph.util.Consumers.ExecutorPool executors
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/algorithm/KoutTraverser.java
KoutTraverser
customizedKout
class KoutTraverser extends OltpTraverser { public KoutTraverser(HugeGraph graph) { super(graph); } public Set<Id> kout(Id sourceV, Directions dir, String label, int depth, boolean nearest, long degree, long capacity, long limit) { E.checkNotNull(sourceV, "source vertex id"); this.checkVertexExist(sourceV, "source vertex"); E.checkNotNull(dir, "direction"); checkPositive(depth, "k-out max_depth"); checkDegree(degree); checkCapacity(capacity); checkLimit(limit); if (capacity != NO_LIMIT) { // Capacity must > limit because sourceV is counted in capacity E.checkArgument(capacity >= limit && limit != NO_LIMIT, "Capacity can't be less than limit, " + "but got capacity '%s' and limit '%s'", capacity, limit); } Id labelId = this.getEdgeLabelIdOrNull(label); Set<Id> sources = newIdSet(); Set<Id> neighbors = newIdSet(); Set<Id> visited = nearest ? newIdSet() : null; neighbors.add(sourceV); ConcurrentVerticesConsumer consumer; long remaining = capacity == NO_LIMIT ? NO_LIMIT : capacity - 1; while (depth-- > 0) { // Just get limit nodes in last layer if limit < remaining capacity if (depth == 0 && limit != NO_LIMIT && (limit < remaining || remaining == NO_LIMIT)) { remaining = limit; } if (visited != null) { visited.addAll(neighbors); } // swap sources and neighbors Set<Id> tmp = neighbors; neighbors = sources; sources = tmp; // start consumer = new ConcurrentVerticesConsumer(sourceV, visited, remaining, neighbors); this.vertexIterCounter.addAndGet(sources.size()); this.edgeIterCounter.addAndGet(neighbors.size()); traverseIdsByBfs(sources.iterator(), dir, labelId, degree, capacity, consumer); sources.clear(); if (capacity != NO_LIMIT) { // Update 'remaining' value to record remaining capacity remaining -= neighbors.size(); if (remaining <= 0 && depth > 0) { throw new HugeException( "Reach capacity '%s' while remaining depth '%s'", capacity, depth); } } } return neighbors; } public KoutRecords customizedKout(Id source, Steps steps, int maxDepth, boolean nearest, long capacity, long limit) {<FILL_FUNCTION_BODY>} public KoutRecords dfsKout(Id source, Steps steps, int maxDepth, boolean nearest, long capacity, long limit) { E.checkNotNull(source, "source vertex id"); this.checkVertexExist(source, "source vertex"); checkPositive(maxDepth, "k-out max_depth"); checkCapacity(capacity); checkLimit(limit); Set<Id> all = newIdSet(); all.add(source); KoutRecords records = new KoutRecords(false, source, nearest, maxDepth); Iterator<Edge> iterator = this.createNestedIterator(source, steps, maxDepth, all, nearest); while (iterator.hasNext()) { HugeEdge edge = (HugeEdge) iterator.next(); this.edgeIterCounter.addAndGet(1L); Id target = edge.id().otherVertexId(); if (!nearest || !all.contains(target)) { records.addFullPath(HugeTraverser.pathEdges(iterator, edge)); } if (limit != NO_LIMIT && records.size() >= limit || capacity != NO_LIMIT && all.size() > capacity) { break; } } return records; } private void checkCapacity(long capacity, long accessed, long depth) { if (capacity == NO_LIMIT) { return; } if (accessed >= capacity && depth > 0) { throw new HugeException( "Reach capacity '%s' while remaining depth '%s'", capacity, depth); } } private boolean reachLimit(long limit, long depth, int size) { return limit != NO_LIMIT && depth <= 0 && size >= limit; } }
E.checkNotNull(source, "source vertex id"); this.checkVertexExist(source, "source vertex"); checkPositive(maxDepth, "k-out max_depth"); checkCapacity(capacity); checkLimit(limit); long[] depth = new long[1]; depth[0] = maxDepth; KoutRecords records = new KoutRecords(true, source, nearest, 0); Consumer<Edge> consumer = edge -> { if (this.reachLimit(limit, depth[0], records.size())) { return; } EdgeId edgeId = ((HugeEdge) edge).id(); records.addPath(edgeId.ownerVertexId(), edgeId.otherVertexId()); records.edgeResults().addEdge(edgeId.ownerVertexId(), edgeId.otherVertexId(), edge); }; while (depth[0]-- > 0) { List<Id> sources = records.ids(Query.NO_LIMIT); records.startOneLayer(true); traverseIdsByBfs(sources.iterator(), steps, capacity, consumer); this.vertexIterCounter.addAndGet(sources.size()); records.finishOneLayer(); checkCapacity(capacity, records.accessed(), depth[0]); } return records;
1,178
330
1,508
<methods>public void close() ,public static void destroy() <variables>private static final java.lang.String EXECUTOR_NAME,private static org.apache.hugegraph.util.Consumers.ExecutorPool executors
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/algorithm/PathTraverser.java
PathTraverser
forward
class PathTraverser { protected final HugeTraverser traverser; protected final long capacity; protected final long limit; protected int stepCount; protected int totalSteps; // TODO: delete or implement abstract method protected Map<Id, List<HugeTraverser.Node>> sources; protected Map<Id, List<HugeTraverser.Node>> sourcesAll; protected Map<Id, List<HugeTraverser.Node>> targets; protected Map<Id, List<HugeTraverser.Node>> targetsAll; protected Map<Id, List<HugeTraverser.Node>> newVertices; protected Set<HugeTraverser.Path> paths; protected TraverseStrategy traverseStrategy; protected EdgeRecord edgeResults; public PathTraverser(HugeTraverser traverser, TraverseStrategy strategy, Collection<Id> sources, Collection<Id> targets, long capacity, long limit, boolean concurrent) { this.traverser = traverser; this.traverseStrategy = strategy; this.capacity = capacity; this.limit = limit; this.stepCount = 0; this.sources = this.newMultiValueMap(); this.sourcesAll = this.newMultiValueMap(); this.targets = this.newMultiValueMap(); this.targetsAll = this.newMultiValueMap(); for (Id id : sources) { this.addNode(this.sources, id, new HugeTraverser.Node(id)); } for (Id id : targets) { this.addNode(this.targets, id, new HugeTraverser.Node(id)); } this.sourcesAll.putAll(this.sources); this.targetsAll.putAll(this.targets); this.paths = this.newPathSet(); this.edgeResults = new EdgeRecord(concurrent); } public void forward() {<FILL_FUNCTION_BODY>} public void backward() { EdgeStep currentStep = this.nextStep(false); if (currentStep == null) { return; } this.beforeTraverse(false); currentStep.swithDirection(); // Traversal vertices of previous level this.traverseOneLayer(this.targets, currentStep, this::backward); currentStep.swithDirection(); this.afterTraverse(currentStep, false); } public abstract EdgeStep nextStep(boolean forward); public void beforeTraverse(boolean forward) { this.clearNewVertices(); } public void traverseOneLayer(Map<Id, List<HugeTraverser.Node>> vertices, EdgeStep step, BiConsumer<Id, EdgeStep> consumer) { this.traverseStrategy.traverseOneLayer(vertices, step, consumer); } public void afterTraverse(EdgeStep step, boolean forward) { this.reInitCurrentStepIfNeeded(step, forward); this.stepCount++; } private void forward(Id v, EdgeStep step) { this.traverseOne(v, step, true); } private void backward(Id v, EdgeStep step) { this.traverseOne(v, step, false); } private void traverseOne(Id v, EdgeStep step, boolean forward) { if (this.reachLimit()) { return; } Iterator<Edge> edges = this.traverser.edgesOfVertex(v, step); while (edges.hasNext()) { HugeEdge edge = (HugeEdge) edges.next(); Id target = edge.id().otherVertexId(); this.traverser.edgeIterCounter.addAndGet(1L); this.edgeResults.addEdge(v, target, edge); this.processOne(v, target, forward); } this.traverser.vertexIterCounter.addAndGet(1L); } private void processOne(Id source, Id target, boolean forward) { if (forward) { this.processOneForForward(source, target); } else { this.processOneForBackward(source, target); } } protected abstract void processOneForForward(Id source, Id target); protected abstract void processOneForBackward(Id source, Id target); protected abstract void reInitCurrentStepIfNeeded(EdgeStep step, boolean forward); public void clearNewVertices() { this.newVertices = this.newMultiValueMap(); } public void addNodeToNewVertices(Id id, HugeTraverser.Node node) { this.addNode(this.newVertices, id, node); } public Map<Id, List<HugeTraverser.Node>> newMultiValueMap() { return this.traverseStrategy.newMultiValueMap(); } public Set<HugeTraverser.Path> newPathSet() { return this.traverseStrategy.newPathSet(); } public void addNode(Map<Id, List<HugeTraverser.Node>> vertices, Id id, HugeTraverser.Node node) { this.traverseStrategy.addNode(vertices, id, node); } public void addNewVerticesToAll(Map<Id, List<HugeTraverser.Node>> targets) { this.traverseStrategy.addNewVerticesToAll(this.newVertices, targets); } public Set<HugeTraverser.Path> paths() { return this.paths; } public int pathCount() { return this.paths.size(); } protected boolean finished() { return this.stepCount >= this.totalSteps || this.reachLimit(); } protected boolean reachLimit() { HugeTraverser.checkCapacity(this.capacity, this.accessedNodes(), "template paths"); return this.limit != NO_LIMIT && this.pathCount() >= this.limit; } protected int accessedNodes() { int size = 0; for (List<HugeTraverser.Node> value : this.sourcesAll.values()) { size += value.size(); } for (List<HugeTraverser.Node> value : this.targetsAll.values()) { size += value.size(); } return size; } }
EdgeStep currentStep = this.nextStep(true); if (currentStep == null) { return; } this.beforeTraverse(true); // Traversal vertices of previous level this.traverseOneLayer(this.sources, currentStep, this::forward); this.afterTraverse(currentStep, true);
1,645
90
1,735
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/algorithm/PathsTraverser.java
Traverser
forward
class Traverser { private final PathsRecords record; private final Id label; private final long degree; private final long capacity; private final long limit; private final PathSet paths; private long vertexCounter; private long edgeCounter; public Traverser(Id sourceV, Id targetV, Id label, long degree, long capacity, long limit) { this.record = new PathsRecords(false, sourceV, targetV); this.label = label; this.degree = degree; this.capacity = capacity; this.limit = limit; this.vertexCounter = 0L; this.edgeCounter = 0L; this.paths = new PathSet(); } /** * Search forward from source */ @Watched public void forward(Id targetV, Directions direction) {<FILL_FUNCTION_BODY>} /** * Search backward from target */ @Watched public void backward(Id sourceV, Directions direction) { Iterator<Edge> edges; this.record.startOneLayer(false); while (this.record.hasNextKey()) { Id vid = this.record.nextKey(); if (vid.equals(sourceV)) { continue; } edges = edgesOfVertex(vid, direction, this.label, this.degree); this.vertexCounter += 1L; while (edges.hasNext()) { HugeEdge edge = (HugeEdge) edges.next(); Id target = edge.id().otherVertexId(); this.edgeCounter += 1L; PathSet results = this.record.findPath(target, null, true, false); for (Path path : results) { this.paths.add(path); if (this.reachLimit()) { return; } } } } this.record.finishOneLayer(); } public PathSet paths() { return this.paths; } private boolean reachLimit() { checkCapacity(this.capacity, this.record.accessed(), "paths"); return this.limit != NO_LIMIT && this.paths.size() >= this.limit; } public long accessed() { return this.record.accessed(); } }
Iterator<Edge> edges; this.record.startOneLayer(true); while (this.record.hasNextKey()) { Id vid = this.record.nextKey(); if (vid.equals(targetV)) { continue; } edges = edgesOfVertex(vid, direction, this.label, this.degree); this.vertexCounter += 1L; while (edges.hasNext()) { HugeEdge edge = (HugeEdge) edges.next(); Id target = edge.id().otherVertexId(); this.edgeCounter += 1L; PathSet results = this.record.findPath(target, null, true, false); for (Path path : results) { this.paths.add(path); if (this.reachLimit()) { return; } } } } this.record.finishOneLayer();
605
233
838
<methods>public void <init>(org.apache.hugegraph.HugeGraph) ,public static void checkCapacity(long) ,public static void checkCapacity(long, long, java.lang.String) ,public static void checkDegree(long) ,public static void checkLimit(long) ,public static void checkNonNegative(long, java.lang.String) ,public static void checkNonNegativeOrNoLimit(long, java.lang.String) ,public static void checkPositive(long, java.lang.String) ,public static void checkPositiveOrNoLimit(long, java.lang.String) ,public static void checkSkipDegree(long, long, long) ,public static void checkTraverseMode(java.lang.String) ,public Iterator<Edge> createNestedIterator(org.apache.hugegraph.backend.id.Id, org.apache.hugegraph.traversal.algorithm.steps.Steps, int, Set<org.apache.hugegraph.backend.id.Id>, boolean) ,public Iterator<Edge> edgesOfVertex(org.apache.hugegraph.backend.id.Id, org.apache.hugegraph.traversal.algorithm.steps.Steps) ,public org.apache.hugegraph.traversal.algorithm.HugeTraverser.EdgesIterator edgesOfVertices(Iterator<org.apache.hugegraph.backend.id.Id>, org.apache.hugegraph.type.define.Directions, List<org.apache.hugegraph.backend.id.Id>, long) ,public org.apache.hugegraph.HugeGraph graph() ,public static boolean isTraverseModeDFS(java.lang.String) ,public static List<org.apache.hugegraph.structure.HugeEdge> pathEdges(Iterator<Edge>, org.apache.hugegraph.structure.HugeEdge) ,public static Iterator<Edge> skipSuperNodeIfNeeded(Iterator<Edge>, long, long) ,public static Map<K,V> topN(Map<K,V>, boolean, long) <variables>public static final java.lang.String DEFAULT_CAPACITY,public static final java.lang.String DEFAULT_ELEMENTS_LIMIT,public static final java.lang.String DEFAULT_LIMIT,public static final java.lang.String DEFAULT_MAX_DEGREE,public static final int DEFAULT_MAX_DEPTH,public static final java.lang.String DEFAULT_PAGE_LIMIT,public static final java.lang.String DEFAULT_PATHS_LIMIT,public static final java.lang.String DEFAULT_SAMPLE,public static final java.lang.String DEFAULT_SKIP_DEGREE,public static final java.lang.String DEFAULT_WEIGHT,protected static final Logger LOG,protected static final int MAX_VERTICES,public static final long NO_LIMIT,public static final java.lang.String TRAVERSE_MODE_BFS,public static final java.lang.String TRAVERSE_MODE_DFS,private static org.apache.hugegraph.util.collection.CollectionFactory collectionFactory,public java.util.concurrent.atomic.AtomicLong edgeIterCounter,private final non-sealed org.apache.hugegraph.HugeGraph graph,public java.util.concurrent.atomic.AtomicLong vertexIterCounter
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/algorithm/PersonalRankTraverser.java
PersonalRankTraverser
calcNewRanks
class PersonalRankTraverser extends HugeTraverser { private final double alpha; private final long degree; private final int maxDepth; public PersonalRankTraverser(HugeGraph graph, double alpha, long degree, int maxDepth) { super(graph); this.alpha = alpha; this.degree = degree; this.maxDepth = maxDepth; } public Map<Id, Double> personalRank(Id source, String label, WithLabel withLabel) { E.checkNotNull(source, "source vertex id"); this.checkVertexExist(source, "source vertex"); E.checkArgumentNotNull(label, "The edge label can't be null"); Map<Id, Double> ranks = newMap(); ranks.put(source, 1.0); Id labelId = this.getEdgeLabelIdOrNull(label); Directions dir = this.getStartDirection(source, label); Set<Id> outSeeds = newIdSet(); Set<Id> inSeeds = newIdSet(); if (dir == Directions.OUT) { outSeeds.add(source); } else { inSeeds.add(source); } Set<Id> rootAdjacencies = newIdSet(); for (long i = 0; i < this.maxDepth; i++) { Map<Id, Double> newRanks = this.calcNewRanks(outSeeds, inSeeds, labelId, ranks); ranks = this.compensateRoot(source, newRanks); if (i == 0) { rootAdjacencies.addAll(ranks.keySet()); } } // Remove directly connected neighbors removeAll(ranks, rootAdjacencies); // Remove unnecessary label if (withLabel == WithLabel.SAME_LABEL) { removeAll(ranks, dir == Directions.OUT ? inSeeds : outSeeds); } else if (withLabel == WithLabel.OTHER_LABEL) { removeAll(ranks, dir == Directions.OUT ? outSeeds : inSeeds); } return ranks; } private Map<Id, Double> calcNewRanks(Set<Id> outSeeds, Set<Id> inSeeds, Id label, Map<Id, Double> ranks) {<FILL_FUNCTION_BODY>} private Map<Id, Double> compensateRoot(Id root, Map<Id, Double> newRanks) { double rank = newRanks.getOrDefault(root, 0.0); rank += (1 - this.alpha); newRanks.put(root, rank); return newRanks; } private Directions getStartDirection(Id source, String label) { // NOTE: The outer layer needs to ensure that the vertex Id is valid HugeVertex vertex = (HugeVertex) graph().vertices(source).next(); VertexLabel vertexLabel = vertex.schemaLabel(); EdgeLabel edgeLabel = this.graph().edgeLabel(label); Id sourceLabel = edgeLabel.sourceLabel(); Id targetLabel = edgeLabel.targetLabel(); E.checkArgument(edgeLabel.linkWithLabel(vertexLabel.id()), "The vertex '%s' doesn't link with edge label '%s'", source, label); E.checkArgument(!sourceLabel.equals(targetLabel), "The edge label for personal rank must " + "link different vertex labels"); if (sourceLabel.equals(vertexLabel.id())) { return Directions.OUT; } else { assert targetLabel.equals(vertexLabel.id()); return Directions.IN; } } private static void removeAll(Map<Id, Double> map, Set<Id> keys) { for (Id key : keys) { map.remove(key); } } public enum WithLabel { SAME_LABEL, OTHER_LABEL, BOTH_LABEL } }
Map<Id, Double> newRanks = newMap(); BiFunction<Set<Id>, Directions, Set<Id>> neighborIncrRanks; neighborIncrRanks = (seeds, dir) -> { Set<Id> tmpSeeds = newIdSet(); for (Id seed : seeds) { Double oldRank = ranks.get(seed); E.checkState(oldRank != null, "Expect rank of seed exists"); Iterator<Id> iter = this.adjacentVertices(seed, dir, label, this.degree); List<Id> neighbors = IteratorUtils.list(iter); long degree = neighbors.size(); if (degree == 0L) { newRanks.put(seed, oldRank); continue; } double incrRank = oldRank * this.alpha / degree; // Collect all neighbors increment for (Id neighbor : neighbors) { tmpSeeds.add(neighbor); // Assign an initial value when firstly update neighbor rank double rank = newRanks.getOrDefault(neighbor, 0.0); newRanks.put(neighbor, rank + incrRank); } } return tmpSeeds; }; Set<Id> tmpInSeeds = neighborIncrRanks.apply(outSeeds, Directions.OUT); Set<Id> tmpOutSeeds = neighborIncrRanks.apply(inSeeds, Directions.IN); outSeeds.addAll(tmpOutSeeds); inSeeds.addAll(tmpInSeeds); return newRanks;
1,030
416
1,446
<methods>public void <init>(org.apache.hugegraph.HugeGraph) ,public static void checkCapacity(long) ,public static void checkCapacity(long, long, java.lang.String) ,public static void checkDegree(long) ,public static void checkLimit(long) ,public static void checkNonNegative(long, java.lang.String) ,public static void checkNonNegativeOrNoLimit(long, java.lang.String) ,public static void checkPositive(long, java.lang.String) ,public static void checkPositiveOrNoLimit(long, java.lang.String) ,public static void checkSkipDegree(long, long, long) ,public static void checkTraverseMode(java.lang.String) ,public Iterator<Edge> createNestedIterator(org.apache.hugegraph.backend.id.Id, org.apache.hugegraph.traversal.algorithm.steps.Steps, int, Set<org.apache.hugegraph.backend.id.Id>, boolean) ,public Iterator<Edge> edgesOfVertex(org.apache.hugegraph.backend.id.Id, org.apache.hugegraph.traversal.algorithm.steps.Steps) ,public org.apache.hugegraph.traversal.algorithm.HugeTraverser.EdgesIterator edgesOfVertices(Iterator<org.apache.hugegraph.backend.id.Id>, org.apache.hugegraph.type.define.Directions, List<org.apache.hugegraph.backend.id.Id>, long) ,public org.apache.hugegraph.HugeGraph graph() ,public static boolean isTraverseModeDFS(java.lang.String) ,public static List<org.apache.hugegraph.structure.HugeEdge> pathEdges(Iterator<Edge>, org.apache.hugegraph.structure.HugeEdge) ,public static Iterator<Edge> skipSuperNodeIfNeeded(Iterator<Edge>, long, long) ,public static Map<K,V> topN(Map<K,V>, boolean, long) <variables>public static final java.lang.String DEFAULT_CAPACITY,public static final java.lang.String DEFAULT_ELEMENTS_LIMIT,public static final java.lang.String DEFAULT_LIMIT,public static final java.lang.String DEFAULT_MAX_DEGREE,public static final int DEFAULT_MAX_DEPTH,public static final java.lang.String DEFAULT_PAGE_LIMIT,public static final java.lang.String DEFAULT_PATHS_LIMIT,public static final java.lang.String DEFAULT_SAMPLE,public static final java.lang.String DEFAULT_SKIP_DEGREE,public static final java.lang.String DEFAULT_WEIGHT,protected static final Logger LOG,protected static final int MAX_VERTICES,public static final long NO_LIMIT,public static final java.lang.String TRAVERSE_MODE_BFS,public static final java.lang.String TRAVERSE_MODE_DFS,private static org.apache.hugegraph.util.collection.CollectionFactory collectionFactory,public java.util.concurrent.atomic.AtomicLong edgeIterCounter,private final non-sealed org.apache.hugegraph.HugeGraph graph,public java.util.concurrent.atomic.AtomicLong vertexIterCounter
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/algorithm/PredictionTraverser.java
PredictionTraverser
adamicAdar
class PredictionTraverser extends OltpTraverser { public PredictionTraverser(HugeGraph graph) { super(graph); } public double adamicAdar(Id source, Id target, Directions dir, String label, long degree, int limit) {<FILL_FUNCTION_BODY>} public double resourceAllocation(Id source, Id target, Directions dir, String label, long degree, int limit) { Set<Id> neighbors = checkAndGetCommonNeighbors(source, target, dir, label, degree, limit); EdgeStep step = label == null ? new EdgeStep(graph(), dir) : new EdgeStep(graph(), dir, ImmutableList.of(label)); double sum = 0.0; for (Id vid : neighbors) { long currentDegree = this.edgesCount(vid, step); if (currentDegree > 0) { sum += 1.0 / currentDegree; } } return sum; } private Set<Id> checkAndGetCommonNeighbors(Id source, Id target, Directions dir, String label, long degree, int limit) { E.checkNotNull(source, "source id"); E.checkNotNull(target, "the target id"); this.checkVertexExist(source, "source"); this.checkVertexExist(target, "target"); E.checkNotNull(dir, "direction"); checkDegree(degree); SameNeighborTraverser traverser = new SameNeighborTraverser(graph()); return traverser.sameNeighbors(source, target, dir, label, degree, limit); } }
Set<Id> neighbors = checkAndGetCommonNeighbors(source, target, dir, label, degree, limit); EdgeStep step = label == null ? new EdgeStep(graph(), dir) : new EdgeStep(graph(), dir, ImmutableList.of(label)); double sum = 0.0; for (Id vid : neighbors) { long currentDegree = this.edgesCount(vid, step); if (currentDegree > 0) { sum += 1.0 / Math.log(currentDegree); } } return sum;
438
151
589
<methods>public void close() ,public static void destroy() <variables>private static final java.lang.String EXECUTOR_NAME,private static org.apache.hugegraph.util.Consumers.ExecutorPool executors
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/algorithm/SameNeighborTraverser.java
SameNeighborTraverser
sameNeighbors
class SameNeighborTraverser extends HugeTraverser { public SameNeighborTraverser(HugeGraph graph) { super(graph); } public Set<Id> sameNeighbors(Id vertex, Id other, Directions direction, String label, long degree, int limit) { E.checkNotNull(vertex, "vertex id"); E.checkNotNull(other, "the other vertex id"); this.checkVertexExist(vertex, "vertex"); this.checkVertexExist(other, "other vertex"); E.checkNotNull(direction, "direction"); checkDegree(degree); checkLimit(limit); Id labelId = this.getEdgeLabelIdOrNull(label); Set<Id> sourceNeighbors = IteratorUtils.set(this.adjacentVertices( vertex, direction, labelId, degree)); Set<Id> targetNeighbors = IteratorUtils.set(this.adjacentVertices( other, direction, labelId, degree)); Set<Id> sameNeighbors = (Set<Id>) CollectionUtil.intersect( sourceNeighbors, targetNeighbors); this.vertexIterCounter.addAndGet(2L); this.edgeIterCounter.addAndGet(sourceNeighbors.size()); this.edgeIterCounter.addAndGet(targetNeighbors.size()); if (limit != NO_LIMIT) { int end = Math.min(sameNeighbors.size(), limit); sameNeighbors = CollectionUtil.subSet(sameNeighbors, 0, end); } return sameNeighbors; } public Set<Id> sameNeighbors(List<Id> vertexIds, Directions direction, List<String> labels, long degree, int limit) {<FILL_FUNCTION_BODY>} }
E.checkNotNull(vertexIds, "vertex ids"); E.checkArgument(vertexIds.size() >= 2, "vertex_list size can't " + "be less than 2"); for (Id id : vertexIds) { this.checkVertexExist(id, "vertex"); } E.checkNotNull(direction, "direction"); checkDegree(degree); checkLimit(limit); List<Id> labelsId = new ArrayList<>(); if (labels != null) { for (String label : labels) { labelsId.add(this.getEdgeLabelIdOrNull(label)); } } Set<Id> sameNeighbors = new HashSet<>(); for (int i = 0; i < vertexIds.size(); i++) { Set<Id> vertexNeighbors = IteratorUtils.set(this.adjacentVertices( vertexIds.get(i), direction, labelsId, degree)); if (i == 0) { sameNeighbors = vertexNeighbors; } else { sameNeighbors = (Set<Id>) CollectionUtil.intersect( sameNeighbors, vertexNeighbors); } this.vertexIterCounter.addAndGet(1L); this.edgeIterCounter.addAndGet(vertexNeighbors.size()); } if (limit != NO_LIMIT) { int end = Math.min(sameNeighbors.size(), limit); sameNeighbors = CollectionUtil.subSet(sameNeighbors, 0, end); } return sameNeighbors;
478
419
897
<methods>public void <init>(org.apache.hugegraph.HugeGraph) ,public static void checkCapacity(long) ,public static void checkCapacity(long, long, java.lang.String) ,public static void checkDegree(long) ,public static void checkLimit(long) ,public static void checkNonNegative(long, java.lang.String) ,public static void checkNonNegativeOrNoLimit(long, java.lang.String) ,public static void checkPositive(long, java.lang.String) ,public static void checkPositiveOrNoLimit(long, java.lang.String) ,public static void checkSkipDegree(long, long, long) ,public static void checkTraverseMode(java.lang.String) ,public Iterator<Edge> createNestedIterator(org.apache.hugegraph.backend.id.Id, org.apache.hugegraph.traversal.algorithm.steps.Steps, int, Set<org.apache.hugegraph.backend.id.Id>, boolean) ,public Iterator<Edge> edgesOfVertex(org.apache.hugegraph.backend.id.Id, org.apache.hugegraph.traversal.algorithm.steps.Steps) ,public org.apache.hugegraph.traversal.algorithm.HugeTraverser.EdgesIterator edgesOfVertices(Iterator<org.apache.hugegraph.backend.id.Id>, org.apache.hugegraph.type.define.Directions, List<org.apache.hugegraph.backend.id.Id>, long) ,public org.apache.hugegraph.HugeGraph graph() ,public static boolean isTraverseModeDFS(java.lang.String) ,public static List<org.apache.hugegraph.structure.HugeEdge> pathEdges(Iterator<Edge>, org.apache.hugegraph.structure.HugeEdge) ,public static Iterator<Edge> skipSuperNodeIfNeeded(Iterator<Edge>, long, long) ,public static Map<K,V> topN(Map<K,V>, boolean, long) <variables>public static final java.lang.String DEFAULT_CAPACITY,public static final java.lang.String DEFAULT_ELEMENTS_LIMIT,public static final java.lang.String DEFAULT_LIMIT,public static final java.lang.String DEFAULT_MAX_DEGREE,public static final int DEFAULT_MAX_DEPTH,public static final java.lang.String DEFAULT_PAGE_LIMIT,public static final java.lang.String DEFAULT_PATHS_LIMIT,public static final java.lang.String DEFAULT_SAMPLE,public static final java.lang.String DEFAULT_SKIP_DEGREE,public static final java.lang.String DEFAULT_WEIGHT,protected static final Logger LOG,protected static final int MAX_VERTICES,public static final long NO_LIMIT,public static final java.lang.String TRAVERSE_MODE_BFS,public static final java.lang.String TRAVERSE_MODE_DFS,private static org.apache.hugegraph.util.collection.CollectionFactory collectionFactory,public java.util.concurrent.atomic.AtomicLong edgeIterCounter,private final non-sealed org.apache.hugegraph.HugeGraph graph,public java.util.concurrent.atomic.AtomicLong vertexIterCounter
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/algorithm/TemplatePathsTraverser.java
Traverser
afterTraverse
class Traverser extends PathTraverser { protected final List<RepeatEdgeStep> steps; protected boolean withRing; protected int sourceIndex; protected int targetIndex; protected boolean sourceFinishOneStep; protected boolean targetFinishOneStep; public Traverser(HugeTraverser traverser, TraverseStrategy strategy, Collection<Id> sources, Collection<Id> targets, List<RepeatEdgeStep> steps, boolean withRing, long capacity, long limit, boolean concurrent) { super(traverser, strategy, sources, targets, capacity, limit, concurrent); this.steps = steps; this.withRing = withRing; for (RepeatEdgeStep step : steps) { this.totalSteps += step.maxTimes(); } this.sourceIndex = 0; this.targetIndex = this.steps.size() - 1; this.sourceFinishOneStep = false; this.targetFinishOneStep = false; } @Override public RepeatEdgeStep nextStep(boolean forward) { return forward ? this.forwardStep() : this.backwardStep(); } @Override public void beforeTraverse(boolean forward) { this.clearNewVertices(); this.reInitAllIfNeeded(forward); } @Override public void afterTraverse(EdgeStep step, boolean forward) {<FILL_FUNCTION_BODY>} @Override protected void processOneForForward(Id sourceV, Id targetV) { for (Node source : this.sources.get(sourceV)) { // If have loop, skip target if (!this.withRing && source.contains(targetV)) { continue; } // If cross point exists, path found, concat them if (this.lastSuperStep() && this.targetsAll.containsKey(targetV)) { for (Node target : this.targetsAll.get(targetV)) { List<Id> path = joinPath(source, target, this.withRing); if (!path.isEmpty()) { this.paths.add(new Path(targetV, path)); if (this.reachLimit()) { return; } } } } // Add node to next start-nodes this.addNodeToNewVertices(targetV, new Node(targetV, source)); } } @Override protected void processOneForBackward(Id sourceV, Id targetV) { for (Node source : this.targets.get(sourceV)) { // If have loop, skip target if (!this.withRing && source.contains(targetV)) { continue; } // If cross point exists, path found, concat them if (this.lastSuperStep() && this.sourcesAll.containsKey(targetV)) { for (Node target : this.sourcesAll.get(targetV)) { List<Id> path = joinPath(source, target, this.withRing); if (!path.isEmpty()) { Path newPath = new Path(targetV, path); newPath.reverse(); this.paths.add(newPath); if (this.reachLimit()) { return; } } } } // Add node to next start-nodes this.addNodeToNewVertices(targetV, new Node(targetV, source)); } } private void reInitAllIfNeeded(boolean forward) { if (forward) { /* * Re-init source all if last forward finished one super step * and current step is not last super step */ if (this.sourceFinishOneStep && !this.lastSuperStep()) { this.sourcesAll = this.newMultiValueMap(); this.sourceFinishOneStep = false; } } else { /* * Re-init target all if last forward finished one super step * and current step is not last super step */ if (this.targetFinishOneStep && !this.lastSuperStep()) { this.targetsAll = this.newMultiValueMap(); this.targetFinishOneStep = false; } } } @Override protected void reInitCurrentStepIfNeeded(EdgeStep step, boolean forward) { RepeatEdgeStep currentStep = (RepeatEdgeStep) step; currentStep.decreaseTimes(); if (forward) { // Re-init sources if (currentStep.remainTimes() > 0) { this.sources = this.newVertices; } else { this.sources = this.sourcesAll; this.sourceFinishOneStep = true; } } else { // Re-init targets if (currentStep.remainTimes() > 0) { this.targets = this.newVertices; } else { this.targets = this.targetsAll; this.targetFinishOneStep = true; } } } public RepeatEdgeStep forwardStep() { RepeatEdgeStep currentStep = null; // Find next step to backward for (int i = 0; i < this.steps.size(); i++) { RepeatEdgeStep step = this.steps.get(i); if (step.remainTimes() > 0) { currentStep = step; this.sourceIndex = i; break; } } return currentStep; } public RepeatEdgeStep backwardStep() { RepeatEdgeStep currentStep = null; // Find next step to backward for (int i = this.steps.size() - 1; i >= 0; i--) { RepeatEdgeStep step = this.steps.get(i); if (step.remainTimes() > 0) { currentStep = step; this.targetIndex = i; break; } } return currentStep; } public boolean lastSuperStep() { return this.targetIndex == this.sourceIndex || this.targetIndex == this.sourceIndex + 1; } }
Map<Id, List<Node>> all = forward ? this.sourcesAll : this.targetsAll; this.addNewVerticesToAll(all); this.reInitCurrentStepIfNeeded(step, forward); this.stepCount++;
1,567
68
1,635
<methods>public void <init>(org.apache.hugegraph.HugeGraph) ,public static void checkCapacity(long) ,public static void checkCapacity(long, long, java.lang.String) ,public static void checkDegree(long) ,public static void checkLimit(long) ,public static void checkNonNegative(long, java.lang.String) ,public static void checkNonNegativeOrNoLimit(long, java.lang.String) ,public static void checkPositive(long, java.lang.String) ,public static void checkPositiveOrNoLimit(long, java.lang.String) ,public static void checkSkipDegree(long, long, long) ,public static void checkTraverseMode(java.lang.String) ,public Iterator<Edge> createNestedIterator(org.apache.hugegraph.backend.id.Id, org.apache.hugegraph.traversal.algorithm.steps.Steps, int, Set<org.apache.hugegraph.backend.id.Id>, boolean) ,public Iterator<Edge> edgesOfVertex(org.apache.hugegraph.backend.id.Id, org.apache.hugegraph.traversal.algorithm.steps.Steps) ,public org.apache.hugegraph.traversal.algorithm.HugeTraverser.EdgesIterator edgesOfVertices(Iterator<org.apache.hugegraph.backend.id.Id>, org.apache.hugegraph.type.define.Directions, List<org.apache.hugegraph.backend.id.Id>, long) ,public org.apache.hugegraph.HugeGraph graph() ,public static boolean isTraverseModeDFS(java.lang.String) ,public static List<org.apache.hugegraph.structure.HugeEdge> pathEdges(Iterator<Edge>, org.apache.hugegraph.structure.HugeEdge) ,public static Iterator<Edge> skipSuperNodeIfNeeded(Iterator<Edge>, long, long) ,public static Map<K,V> topN(Map<K,V>, boolean, long) <variables>public static final java.lang.String DEFAULT_CAPACITY,public static final java.lang.String DEFAULT_ELEMENTS_LIMIT,public static final java.lang.String DEFAULT_LIMIT,public static final java.lang.String DEFAULT_MAX_DEGREE,public static final int DEFAULT_MAX_DEPTH,public static final java.lang.String DEFAULT_PAGE_LIMIT,public static final java.lang.String DEFAULT_PATHS_LIMIT,public static final java.lang.String DEFAULT_SAMPLE,public static final java.lang.String DEFAULT_SKIP_DEGREE,public static final java.lang.String DEFAULT_WEIGHT,protected static final Logger LOG,protected static final int MAX_VERTICES,public static final long NO_LIMIT,public static final java.lang.String TRAVERSE_MODE_BFS,public static final java.lang.String TRAVERSE_MODE_DFS,private static org.apache.hugegraph.util.collection.CollectionFactory collectionFactory,public java.util.concurrent.atomic.AtomicLong edgeIterCounter,private final non-sealed org.apache.hugegraph.HugeGraph graph,public java.util.concurrent.atomic.AtomicLong vertexIterCounter
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/algorithm/iterator/NestedIterator.java
NestedIterator
pathEdges
class NestedIterator extends WrappedIterator<Edge> { private final int MAX_CACHED_COUNT = 1000; /** * Set<Id> visited: visited vertex-ids of all parent-tree * used to exclude visited vertex */ private final boolean nearest; private final Set<Id> visited; private final int MAX_VISITED_COUNT = 100000; // cache for edges, initial capacity to avoid memory fragment private final List<HugeEdge> cache; private final Map<Long, Integer> parentEdgePointerMap; private final Iterator<Edge> parentIterator; private final HugeTraverser traverser; private final Steps steps; private final ObjectIntMapping<Id> idMapping; private HugeEdge currentEdge; private int cachePointer; private Iterator<Edge> currentIterator; public NestedIterator(HugeTraverser traverser, Iterator<Edge> parentIterator, Steps steps, Set<Id> visited, boolean nearest) { this.traverser = traverser; this.parentIterator = parentIterator; this.steps = steps; this.visited = visited; this.nearest = nearest; this.cache = new ArrayList<>(MAX_CACHED_COUNT); this.parentEdgePointerMap = new HashMap<>(); this.cachePointer = 0; this.currentEdge = null; this.currentIterator = null; this.idMapping = ObjectIntMappingFactory.newObjectIntMapping(false); } private static Long makeVertexPairIndex(int source, int target) { return ((long) source & 0xFFFFFFFFL) | (((long) target << 32) & 0xFFFFFFFF00000000L); } @Override public boolean hasNext() { if (this.currentIterator == null || !this.currentIterator.hasNext()) { return fetch(); } return true; } @Override public Edge next() { return this.currentIterator.next(); } @Override protected Iterator<?> originIterator() { return this.parentIterator; } @Override protected boolean fetch() { while (this.currentIterator == null || !this.currentIterator.hasNext()) { if (this.currentIterator != null) { this.currentIterator = null; } if (this.cache.size() == this.cachePointer && !this.fillCache()) { return false; } this.currentEdge = this.cache.get(this.cachePointer); this.cachePointer++; this.currentIterator = traverser.edgesOfVertex(this.currentEdge.id().otherVertexId(), steps); this.traverser.vertexIterCounter.addAndGet(1L); } return true; } private boolean fillCache() { // fill cache from parent while (this.parentIterator.hasNext() && this.cache.size() < MAX_CACHED_COUNT) { HugeEdge edge = (HugeEdge) this.parentIterator.next(); Id vertexId = edge.id().otherVertexId(); this.traverser.edgeIterCounter.addAndGet(1L); if (!this.nearest || !this.visited.contains(vertexId)) { // update parent edge cache pointer int parentEdgePointer = -1; if (this.parentIterator instanceof NestedIterator) { parentEdgePointer = ((NestedIterator) this.parentIterator).currentEdgePointer(); } this.parentEdgePointerMap.put(makeEdgeIndex(edge), parentEdgePointer); this.cache.add(edge); if (this.visited.size() < MAX_VISITED_COUNT) { this.visited.add(vertexId); } } } return this.cache.size() > this.cachePointer; } public List<HugeEdge> pathEdges() { List<HugeEdge> edges = new ArrayList<>(); HugeEdge currentEdge = this.currentEdge; if (this.parentIterator instanceof NestedIterator) { NestedIterator parent = (NestedIterator) this.parentIterator; int parentEdgePointer = this.parentEdgePointerMap.get(makeEdgeIndex(currentEdge)); edges.addAll(parent.pathEdges(parentEdgePointer)); } edges.add(currentEdge); return edges; } private List<HugeEdge> pathEdges(int edgePointer) {<FILL_FUNCTION_BODY>} public int currentEdgePointer() { return this.cachePointer - 1; } private Long makeEdgeIndex(HugeEdge edge) { int sourceV = this.code(edge.id().ownerVertexId()); int targetV = this.code(edge.id().otherVertexId()); return makeVertexPairIndex(sourceV, targetV); } private int code(Id id) { if (id.number()) { long l = id.asLong(); if (0 <= l && l <= Integer.MAX_VALUE) { return (int) l; } } int code = this.idMapping.object2Code(id); assert code > 0; return -code; } }
List<HugeEdge> edges = new ArrayList<>(); HugeEdge edge = this.cache.get(edgePointer); if (this.parentIterator instanceof NestedIterator) { NestedIterator parent = (NestedIterator) this.parentIterator; int parentEdgePointer = this.parentEdgePointerMap.get(makeEdgeIndex(edge)); edges.addAll(parent.pathEdges(parentEdgePointer)); } edges.add(edge); return edges;
1,362
119
1,481
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/algorithm/records/AbstractRecords.java
AbstractRecords
code
class AbstractRecords implements Records { private final ObjectIntMapping<Id> idMapping; private final RecordType type; private final boolean concurrent; private Record currentRecord; private Record parentRecord; public AbstractRecords(RecordType type, boolean concurrent) { this.type = type; this.concurrent = concurrent; this.parentRecord = null; this.idMapping = ObjectIntMappingFactory.newObjectIntMapping(this.concurrent); } @Watched protected final int code(Id id) {<FILL_FUNCTION_BODY>} @Watched protected final Id id(int code) { if (code >= 0) { return IdGenerator.of(code); } return this.idMapping.code2Object(-code); } protected final Record newRecord() { return RecordFactory.newRecord(this.type, this.concurrent); } protected final Record currentRecord() { return this.currentRecord; } protected void currentRecord(Record currentRecord, Record parentRecord) { this.parentRecord = parentRecord; this.currentRecord = currentRecord; } protected Record parentRecord() { return this.parentRecord; } }
if (id.number()) { long l = id.asLong(); if (0 <= l && l <= Integer.MAX_VALUE) { return (int) l; } } int code = this.idMapping.object2Code(id); assert code > 0; return -code;
322
82
404
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/algorithm/records/DoubleWayMultiPathsRecords.java
DoubleWayMultiPathsRecords
linkPathLayer
class DoubleWayMultiPathsRecords extends AbstractRecords { private final Stack<Record> sourceRecords; private final Stack<Record> targetRecords; private IntIterator parentRecordKeys; private int currentKey; private boolean movingForward; private long accessed; public DoubleWayMultiPathsRecords(RecordType type, boolean concurrent, Id sourceV, Id targetV) { super(type, concurrent); int sourceCode = this.code(sourceV); int targetCode = this.code(targetV); Record firstSourceRecord = this.newRecord(); Record firstTargetRecord = this.newRecord(); firstSourceRecord.addPath(sourceCode, 0); firstTargetRecord.addPath(targetCode, 0); this.sourceRecords = new Stack<>(); this.targetRecords = new Stack<>(); this.sourceRecords.push(firstSourceRecord); this.targetRecords.push(firstTargetRecord); this.accessed = 2L; } @Override public void startOneLayer(boolean forward) { this.movingForward = forward; Record parentRecord = this.movingForward ? this.sourceRecords.peek() : this.targetRecords.peek(); this.currentRecord(this.newRecord(), parentRecord); this.parentRecordKeys = parentRecord.keys(); } @Override public void finishOneLayer() { Record record = this.currentRecord(); if (this.movingForward) { this.sourceRecords.push(record); } else { this.targetRecords.push(record); } this.accessed += record.size(); } @Watched @Override public boolean hasNextKey() { return this.parentRecordKeys.hasNext(); } @Watched @Override public Id nextKey() { this.currentKey = this.parentRecordKeys.next(); return this.id(this.currentKey); } public boolean parentsContain(int id) { Record parentRecord = this.parentRecord(); if (parentRecord == null) { return false; } IntIterator parents = parentRecord.get(this.currentKey); while (parents.hasNext()) { int parent = parents.next(); if (parent == id) { // Find backtrace path, stop return true; } } return false; } @Override public long accessed() { return this.accessed; } public boolean sourcesLessThanTargets() { return this.sourceRecords.peek().size() <= this.targetRecords.peek().size(); } @Watched protected final PathSet linkPath(int source, int target, boolean ring) { PathSet paths = new PathSet(); PathSet sources = this.linkSourcePath(source); PathSet targets = this.linkTargetPath(target); for (Path tpath : targets) { tpath.reverse(); for (Path spath : sources) { if (!ring) { // Avoid loop in path if (CollectionUtils.containsAny(spath.vertices(), tpath.vertices())) { continue; } } List<Id> ids = new ArrayList<>(spath.vertices()); ids.addAll(tpath.vertices()); Id crosspoint = this.id(this.movingForward ? target : source); paths.add(new Path(crosspoint, ids)); } } return paths; } private PathSet linkSourcePath(int source) { return this.linkPathLayer(this.sourceRecords, source, this.sourceRecords.size() - 1); } private PathSet linkTargetPath(int target) { return this.linkPathLayer(this.targetRecords, target, this.targetRecords.size() - 1); } private PathSet linkPathLayer(Stack<Record> all, int id, int layerIndex) {<FILL_FUNCTION_BODY>} @Watched protected final void addPath(int current, int parent) { this.currentRecord().addPath(current, parent); } protected final boolean sourceContains(int node) { return this.sourceRecords.peek().containsKey(node); } protected final boolean targetContains(int node) { return this.targetRecords.peek().containsKey(node); } protected final Stack<Record> sourceRecords() { return this.sourceRecords; } protected final Stack<Record> targetRecords() { return this.targetRecords; } protected final boolean movingForward() { return this.movingForward; } protected final int current() { return this.currentKey; } }
PathSet results = new PathSet(); if (layerIndex == 0) { Id sid = this.id(id); results.add(new Path(Lists.newArrayList(sid))); return results; } Id current = this.id(id); Record layer = all.elementAt(layerIndex); IntIterator iterator = layer.get(id); while (iterator.hasNext()) { int parent = iterator.next(); PathSet paths = this.linkPathLayer(all, parent, layerIndex - 1); paths.append(current); results.addAll(paths); } return results;
1,269
166
1,435
<methods>public void <init>(org.apache.hugegraph.traversal.algorithm.records.record.RecordType, boolean) <variables>private final non-sealed boolean concurrent,private org.apache.hugegraph.traversal.algorithm.records.record.Record currentRecord,private final non-sealed ObjectIntMapping<org.apache.hugegraph.backend.id.Id> idMapping,private org.apache.hugegraph.traversal.algorithm.records.record.Record parentRecord,private final non-sealed org.apache.hugegraph.traversal.algorithm.records.record.RecordType type
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/algorithm/records/KneighborRecords.java
KneighborRecords
paths
class KneighborRecords extends SingleWayMultiPathsRecords { public KneighborRecords(boolean concurrent, Id source, boolean nearest) { super(RecordType.INT, concurrent, source, nearest); } @Override public int size() { return (int) this.accessed(); } @Override public List<Id> ids(long limit) { List<Id> ids = CollectionFactory.newList(CollectionType.EC); this.getRecords(limit, ids); return ids; } public Set<Id> idsBySet(long limit) { Set<Id> ids = CollectionFactory.newSet(CollectionType.EC); this.getRecords(limit, ids); return ids; } private void getRecords(long limit, Collection<Id> ids) { Stack<Record> records = this.records(); // Not include record(i=0) to ignore source vertex for (int i = 1; i < records.size(); i++) { IntIterator iterator = records.get(i).keys(); while ((limit == NO_LIMIT || limit > 0L) && iterator.hasNext()) { ids.add(this.id(iterator.next())); limit--; } } } @Override public PathSet paths(long limit) {<FILL_FUNCTION_BODY>} }
PathSet paths = new PathSet(); Stack<Record> records = this.records(); for (int i = 1; i < records.size(); i++) { IntIterator iterator = records.get(i).keys(); while ((limit == NO_LIMIT || limit > 0L) && iterator.hasNext()) { paths.add(this.linkPath(i, iterator.next())); limit--; } } return paths;
370
118
488
<methods>public void <init>(org.apache.hugegraph.traversal.algorithm.records.record.RecordType, boolean, org.apache.hugegraph.backend.id.Id, boolean) ,public long accessed() ,public void addPath(org.apache.hugegraph.backend.id.Id, org.apache.hugegraph.backend.id.Id) ,public void addPathToRecord(int, int, org.apache.hugegraph.traversal.algorithm.records.record.Record) ,public org.apache.hugegraph.traversal.algorithm.HugeTraverser.EdgeRecord edgeResults() ,public org.apache.hugegraph.traversal.algorithm.HugeTraverser.PathSet findPath(org.apache.hugegraph.backend.id.Id, Function<org.apache.hugegraph.backend.id.Id,java.lang.Boolean>, boolean, boolean) ,public void finishOneLayer() ,public boolean hasNextKey() ,public abstract List<org.apache.hugegraph.backend.id.Id> ids(long) ,public Iterator<org.apache.hugegraph.backend.id.Id> keys() ,public org.apache.hugegraph.backend.id.Id nextKey() ,public abstract org.apache.hugegraph.traversal.algorithm.HugeTraverser.PathSet paths(long) ,public abstract int size() ,public void startOneLayer(boolean) <variables>private final non-sealed org.apache.hugegraph.util.collection.IntSet accessedVertices,private final non-sealed org.apache.hugegraph.traversal.algorithm.HugeTraverser.EdgeRecord edgeResults,private final non-sealed boolean nearest,private org.apache.hugegraph.util.collection.IntIterator parentRecordKeys,private final non-sealed Stack<org.apache.hugegraph.traversal.algorithm.records.record.Record> records,protected final non-sealed int sourceCode
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/algorithm/records/KoutRecords.java
KoutRecords
ids
class KoutRecords extends SingleWayMultiPathsRecords { // Non-zero depth is used for deepFirst traverse mode. // In such case, startOneLayer/finishOneLayer should not be called, // instead, we should use addFullPath private final int depth; public KoutRecords(boolean concurrent, Id source, boolean nearest, int depth) { super(RecordType.INT, concurrent, source, nearest); // add depth(num) records to record each layer this.depth = depth; for (int i = 0; i < depth; i++) { this.records().push(this.newRecord()); } assert (this.records().size() == (depth + 1)); // init top layer's parentRecord this.currentRecord(this.records().peek(), null); } @Override public int size() { return this.currentRecord().size(); } @Override public List<Id> ids(long limit) {<FILL_FUNCTION_BODY>} @Override public PathSet paths(long limit) { PathSet paths = new PathSet(); Stack<Record> records = this.records(); IntIterator iterator = records.peek().keys(); while ((limit == NO_LIMIT || limit-- > 0L) && iterator.hasNext()) { paths.add(this.linkPath(records.size() - 1, iterator.next())); } return paths; } public void addFullPath(List<HugeEdge> edges) { assert (depth == edges.size()); int sourceCode = this.code(edges.get(0).id().ownerVertexId()); int targetCode; for (int i = 0; i < edges.size(); i++) { HugeEdge edge = edges.get(i); Id sourceV = edge.id().ownerVertexId(); Id targetV = edge.id().otherVertexId(); assert (this.code(sourceV) == sourceCode); this.edgeResults().addEdge(sourceV, targetV, edge); targetCode = this.code(targetV); Record record = this.records().elementAt(i + 1); if (this.sourceCode == targetCode) { break; } this.addPathToRecord(sourceCode, targetCode, record); sourceCode = targetCode; } } }
List<Id> ids = CollectionFactory.newList(CollectionType.EC); IntIterator iterator = this.records().peek().keys(); while ((limit == NO_LIMIT || limit-- > 0L) && iterator.hasNext()) { ids.add(this.id(iterator.next())); } return ids;
621
89
710
<methods>public void <init>(org.apache.hugegraph.traversal.algorithm.records.record.RecordType, boolean, org.apache.hugegraph.backend.id.Id, boolean) ,public long accessed() ,public void addPath(org.apache.hugegraph.backend.id.Id, org.apache.hugegraph.backend.id.Id) ,public void addPathToRecord(int, int, org.apache.hugegraph.traversal.algorithm.records.record.Record) ,public org.apache.hugegraph.traversal.algorithm.HugeTraverser.EdgeRecord edgeResults() ,public org.apache.hugegraph.traversal.algorithm.HugeTraverser.PathSet findPath(org.apache.hugegraph.backend.id.Id, Function<org.apache.hugegraph.backend.id.Id,java.lang.Boolean>, boolean, boolean) ,public void finishOneLayer() ,public boolean hasNextKey() ,public abstract List<org.apache.hugegraph.backend.id.Id> ids(long) ,public Iterator<org.apache.hugegraph.backend.id.Id> keys() ,public org.apache.hugegraph.backend.id.Id nextKey() ,public abstract org.apache.hugegraph.traversal.algorithm.HugeTraverser.PathSet paths(long) ,public abstract int size() ,public void startOneLayer(boolean) <variables>private final non-sealed org.apache.hugegraph.util.collection.IntSet accessedVertices,private final non-sealed org.apache.hugegraph.traversal.algorithm.HugeTraverser.EdgeRecord edgeResults,private final non-sealed boolean nearest,private org.apache.hugegraph.util.collection.IntIterator parentRecordKeys,private final non-sealed Stack<org.apache.hugegraph.traversal.algorithm.records.record.Record> records,protected final non-sealed int sourceCode
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/algorithm/records/PathsRecords.java
PathsRecords
findPath
class PathsRecords extends DoubleWayMultiPathsRecords { public PathsRecords(boolean concurrent, Id sourceV, Id targetV) { super(RecordType.ARRAY, concurrent, sourceV, targetV); } @Watched @Override public PathSet findPath(Id target, Function<Id, Boolean> filter, boolean all, boolean ring) {<FILL_FUNCTION_BODY>} }
assert all; int targetCode = this.code(target); int parentCode = this.current(); PathSet paths = PathSet.EMPTY; // Traverse backtrace is not allowed, stop now if (this.parentsContain(targetCode)) { return paths; } // Add to current layer this.addPath(targetCode, parentCode); // If cross point exists, path found, concat them if (this.movingForward() && this.targetContains(targetCode)) { paths = this.linkPath(parentCode, targetCode, ring); } if (!this.movingForward() && this.sourceContains(targetCode)) { paths = this.linkPath(targetCode, parentCode, ring); } return paths;
113
201
314
<methods>public void <init>(org.apache.hugegraph.traversal.algorithm.records.record.RecordType, boolean, org.apache.hugegraph.backend.id.Id, org.apache.hugegraph.backend.id.Id) ,public long accessed() ,public void finishOneLayer() ,public boolean hasNextKey() ,public org.apache.hugegraph.backend.id.Id nextKey() ,public boolean parentsContain(int) ,public boolean sourcesLessThanTargets() ,public void startOneLayer(boolean) <variables>private long accessed,private int currentKey,private boolean movingForward,private org.apache.hugegraph.util.collection.IntIterator parentRecordKeys,private final non-sealed Stack<org.apache.hugegraph.traversal.algorithm.records.record.Record> sourceRecords,private final non-sealed Stack<org.apache.hugegraph.traversal.algorithm.records.record.Record> targetRecords
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/algorithm/records/SingleWayMultiPathsRecords.java
SingleWayMultiPathsRecords
findPath
class SingleWayMultiPathsRecords extends AbstractRecords { protected final int sourceCode; private final Stack<Record> records; private final boolean nearest; private final IntSet accessedVertices; private final EdgeRecord edgeResults; private IntIterator parentRecordKeys; public SingleWayMultiPathsRecords(RecordType type, boolean concurrent, Id source, boolean nearest) { super(type, concurrent); this.nearest = nearest; this.sourceCode = this.code(source); Record firstRecord = this.newRecord(); firstRecord.addPath(this.sourceCode, 0); this.records = new Stack<>(); this.records.push(firstRecord); this.edgeResults = new EdgeRecord(concurrent); this.accessedVertices = CollectionFactory.newIntSet(); } @Override public void startOneLayer(boolean forward) { Record parentRecord = this.records.peek(); this.currentRecord(this.newRecord(), parentRecord); this.parentRecordKeys = parentRecord.keys(); } @Override public void finishOneLayer() { this.records.push(this.currentRecord()); } @Override public boolean hasNextKey() { return this.parentRecordKeys.hasNext(); } @Override public Id nextKey() { return this.id(this.parentRecordKeys.next()); } @Override public PathSet findPath(Id target, Function<Id, Boolean> filter, boolean all, boolean ring) {<FILL_FUNCTION_BODY>} @Override public long accessed() { return this.accessedVertices.size(); } public Iterator<Id> keys() { return new IntIterator.MapperInt2ObjectIterator<>(this.parentRecordKeys, this::id); } @Watched public void addPath(Id source, Id target) { this.addPathToRecord(this.code(source), this.code(target), this.currentRecord()); } public void addPathToRecord(int sourceCode, int targetCode, Record record) { if (this.nearest && this.accessedVertices.contains(targetCode) || !this.nearest && record.containsKey(targetCode) || targetCode == this.sourceCode) { return; } record.addPath(targetCode, sourceCode); this.accessedVertices.add(targetCode); } protected final Path linkPath(int target) { List<Id> ids = CollectionFactory.newList(CollectionType.EC); // Find the layer where the target is located int foundLayer = -1; for (int i = 0; i < this.records.size(); i++) { IntMap layer = this.layer(i); if (!layer.containsKey(target)) { continue; } foundLayer = i; // Collect self node ids.add(this.id(target)); break; } // If a layer found, then concat parents if (foundLayer > 0) { for (int i = foundLayer; i > 0; i--) { IntMap layer = this.layer(i); // Uptrack parents target = layer.get(target); ids.add(this.id(target)); } } return new Path(ids); } protected final Path linkPath(int layerIndex, int target) { List<Id> ids = CollectionFactory.newList(CollectionType.EC); IntMap layer = this.layer(layerIndex); if (!layer.containsKey(target)) { throw new HugeException("Failed to get path for %s", this.id(target)); } // Collect self node ids.add(this.id(target)); // Concat parents for (int i = layerIndex; i > 0; i--) { layer = this.layer(i); // Uptrack parents target = layer.get(target); ids.add(this.id(target)); } Collections.reverse(ids); return new Path(ids); } protected final IntMap layer(int layerIndex) { Record record = this.records.elementAt(layerIndex); return ((Int2IntRecord) record).layer(); } protected final Stack<Record> records() { return this.records; } public EdgeRecord edgeResults() { return edgeResults; } public abstract int size(); public abstract List<Id> ids(long limit); public abstract PathSet paths(long limit); }
PathSet paths = new PathSet(); for (int i = 1; i < this.records.size(); i++) { IntIterator iterator = this.records.get(i).keys(); while (iterator.hasNext()) { paths.add(this.linkPath(i, iterator.next())); } } return paths;
1,199
92
1,291
<methods>public void <init>(org.apache.hugegraph.traversal.algorithm.records.record.RecordType, boolean) <variables>private final non-sealed boolean concurrent,private org.apache.hugegraph.traversal.algorithm.records.record.Record currentRecord,private final non-sealed ObjectIntMapping<org.apache.hugegraph.backend.id.Id> idMapping,private org.apache.hugegraph.traversal.algorithm.records.record.Record parentRecord,private final non-sealed org.apache.hugegraph.traversal.algorithm.records.record.RecordType type
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/algorithm/records/record/Int2IntRecord.java
Int2IntRecord
get
class Int2IntRecord implements Record { private final IntMap layer; public Int2IntRecord() { this.layer = CollectionFactory.newIntMap(); } @Override public IntIterator keys() { return this.layer.keys(); } @Override public boolean containsKey(int node) { return this.layer.containsKey(node); } @Override public IntIterator get(int node) {<FILL_FUNCTION_BODY>} @Override public void addPath(int node, int parent) { this.layer.put(node, parent); } @Override public int size() { return this.layer.size(); } @Override public boolean concurrent() { return this.layer.concurrent(); } public IntMap layer() { return this.layer; } @Override public String toString() { return this.layer.toString(); } }
int value = this.layer.get(node); if (value == IntMap.NULL_VALUE) { return IntIterator.EMPTY; } return IntIterator.wrap(value);
258
53
311
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/algorithm/records/record/Int2SetRecord.java
Int2SetRecord
addPath
class Int2SetRecord implements Record { private final IntObjectHashMap<IntHashSet> layer; public Int2SetRecord() { this.layer = new IntObjectHashMap<>(); } @Override public IntIterator keys() { return IntIterator.wrap(this.layer.keySet().intIterator()); } @Override public boolean containsKey(int node) { return this.layer.containsKey(node); } @Override public IntIterator get(int node) { return IntIterator.wrap(this.layer.get(node).intIterator()); } @Override public void addPath(int node, int parent) {<FILL_FUNCTION_BODY>} @Override public int size() { return this.layer.size(); } @Override public boolean concurrent() { return false; } @Override public String toString() { return this.layer.toString(); } }
IntHashSet values = this.layer.get(node); if (values != null) { values.add(parent); } else { // TODO: use one sorted-array instead to store all values this.layer.put(node, IntHashSet.newSetWith(parent)); }
257
79
336
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/algorithm/records/record/RecordFactory.java
RecordFactory
newRecord
class RecordFactory { public static Record newRecord(RecordType type) { return newRecord(type, false); } public static Record newRecord(RecordType type, boolean concurrent) {<FILL_FUNCTION_BODY>} }
Record record; switch (type) { case INT: record = new Int2IntRecord(); break; case SET: record = new Int2SetRecord(); break; case ARRAY: record = new Int2ArrayRecord(); break; default: throw new AssertionError("Unsupported record type: " + type); } if (concurrent && !record.concurrent()) { record = new SyncRecord(record); } return record;
64
132
196
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/algorithm/records/record/SyncRecord.java
SyncRecord
keys
class SyncRecord implements Record { private final Object lock; private final Record record; public SyncRecord(Record record) { this(record, null); } public SyncRecord(Record record, Object newLock) { if (record == null) { throw new IllegalArgumentException( "Cannot create a SyncRecord on a null record"); } else { this.record = record; this.lock = newLock == null ? this : newLock; } } @Override public IntIterator keys() {<FILL_FUNCTION_BODY>} @Override public boolean containsKey(int key) { synchronized (this.lock) { return this.record.containsKey(key); } } @Override public IntIterator get(int key) { synchronized (this.lock) { return this.record.get(key); } } @Override public void addPath(int node, int parent) { synchronized (this.lock) { this.record.addPath(node, parent); } } @Override public int size() { synchronized (this.lock) { return this.record.size(); } } @Override public boolean concurrent() { return true; } }
/* * Another threads call addPath() will change IntIterator inner array, * but in kout/kneighbor scenario it's ok because keys() and addPath() * won't be called simultaneously on same Record. */ synchronized (this.lock) { return this.record.keys(); }
347
83
430
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/algorithm/steps/Steps.java
Steps
handleStepEntity
class Steps { protected final Map<Id, StepEntity> edgeSteps; protected final Map<Id, StepEntity> vertexSteps; protected final Directions direction; protected final long degree; protected final long skipDegree; public Steps(HugeGraph graph, Directions direction, Map<String, Map<String, Object>> vSteps, Map<String, Map<String, Object>> eSteps, long degree, long skipDegree) { E.checkArgument(degree == NO_LIMIT || degree > 0L, "The max degree must be > 0 or == -1, but got: %s", degree); HugeTraverser.checkSkipDegree(skipDegree, degree, NO_LIMIT); this.direction = direction; // parse vertex steps this.vertexSteps = new HashMap<>(); if (vSteps != null && !vSteps.isEmpty()) { initVertexFilter(graph, vSteps); } // parse edge steps this.edgeSteps = new HashMap<>(); if (eSteps != null && !eSteps.isEmpty()) { initEdgeFilter(graph, eSteps); } this.degree = degree; this.skipDegree = skipDegree; } private void initVertexFilter(HugeGraph graph, Map<String, Map<String, Object>> vSteps) { for (Map.Entry<String, Map<String, Object>> entry : vSteps.entrySet()) { if (checkEntryEmpty(entry)) { continue; } E.checkArgument(entry.getKey() != null && !entry.getKey().isEmpty(), "The vertex step label could not be null"); VertexLabel vertexLabel = graph.vertexLabel(entry.getKey()); StepEntity stepEntity = handleStepEntity(graph, entry, vertexLabel.id()); this.vertexSteps.put(vertexLabel.id(), stepEntity); } } private void initEdgeFilter(HugeGraph graph, Map<String, Map<String, Object>> eSteps) { for (Map.Entry<String, Map<String, Object>> entry : eSteps.entrySet()) { if (checkEntryEmpty(entry)) { continue; } E.checkArgument(entry.getKey() != null && !entry.getKey().isEmpty(), "The edge step label could not be null"); EdgeLabel edgeLabel = graph.edgeLabel(entry.getKey()); StepEntity stepEntity = handleStepEntity(graph, entry, edgeLabel.id()); this.edgeSteps.put(edgeLabel.id(), stepEntity); } } private StepEntity handleStepEntity(HugeGraph graph, Map.Entry<String, Map<String, Object>> entry, Id id) {<FILL_FUNCTION_BODY>} private boolean checkEntryEmpty(Map.Entry<String, Map<String, Object>> entry) { return (entry.getKey() == null || entry.getKey().isEmpty()) && (entry.getValue() == null || entry.getValue().isEmpty()); } public long degree() { return this.degree; } public Map<Id, StepEntity> edgeSteps() { return this.edgeSteps; } public Map<Id, StepEntity> vertexSteps() { return this.vertexSteps; } public long skipDegree() { return this.skipDegree; } public Directions direction() { return this.direction; } public long limit() { return this.skipDegree > 0L ? this.skipDegree : this.degree; } public List<Id> edgeLabels() { return new ArrayList<>(this.edgeSteps.keySet()); } public boolean isEdgeEmpty() { return this.edgeSteps.isEmpty(); } public boolean isVertexEmpty() { return this.vertexSteps.isEmpty(); } @Override public String toString() { return "Steps{" + "edgeSteps=" + this.edgeSteps + ", vertexSteps=" + this.vertexSteps + ", direction=" + this.direction + ", degree=" + this.degree + ", skipDegree=" + this.skipDegree + '}'; } public static class StepEntity { protected final Id id; protected final String label; protected final Map<Id, Object> properties; public StepEntity(Id id, String label, Map<Id, Object> properties) { this.id = id; this.label = label; this.properties = properties; } public Id id() { return this.id; } public String label() { return this.label; } public Map<Id, Object> properties() { return this.properties; } @Override public String toString() { return String.format("StepEntity{id=%s,label=%s," + "properties=%s}", this.id, this.label, this.properties); } } }
Map<Id, Object> properties = null; if (entry.getValue() != null) { properties = TraversalUtil.transProperties(graph, entry.getValue()); } return new StepEntity(id, entry.getKey(), properties);
1,329
65
1,394
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/algorithm/strategy/ConcurrentTraverseStrategy.java
ConcurrentTraverseStrategy
addNewVerticesToAll
class ConcurrentTraverseStrategy extends OltpTraverser implements TraverseStrategy { public ConcurrentTraverseStrategy(HugeGraph graph) { super(graph); } @Override public Map<Id, List<Node>> newMultiValueMap() { return new OltpTraverser.ConcurrentMultiValuedMap<>(); } @Override public void traverseOneLayer(Map<Id, List<Node>> vertices, EdgeStep step, BiConsumer<Id, EdgeStep> biConsumer) { traverseIds(vertices.keySet().iterator(), (id) -> { biConsumer.accept(id, step); }); } @Override public Set<Path> newPathSet() { return ConcurrentHashMap.newKeySet(); } @Override public void addNode(Map<Id, List<Node>> vertices, Id id, Node node) { ((ConcurrentMultiValuedMap<Id, Node>) vertices).add(id, node); } @Override public void addNewVerticesToAll(Map<Id, List<Node>> newVertices, Map<Id, List<Node>> targets) {<FILL_FUNCTION_BODY>} }
ConcurrentMultiValuedMap<Id, Node> vertices = (ConcurrentMultiValuedMap<Id, Node>) targets; for (Map.Entry<Id, List<Node>> entry : newVertices.entrySet()) { vertices.addAll(entry.getKey(), entry.getValue()); }
313
78
391
<methods>public void close() ,public static void destroy() <variables>private static final java.lang.String EXECUTOR_NAME,private static org.apache.hugegraph.util.Consumers.ExecutorPool executors
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/algorithm/strategy/SingleTraverseStrategy.java
SingleTraverseStrategy
addNewVerticesToAll
class SingleTraverseStrategy extends OltpTraverser implements TraverseStrategy { public SingleTraverseStrategy(HugeGraph graph) { super(graph); } @Override public void traverseOneLayer(Map<Id, List<Node>> vertices, EdgeStep step, BiConsumer<Id, EdgeStep> biConsumer) { for (Id id : vertices.keySet()) { biConsumer.accept(id, step); } } @Override public Map<Id, List<Node>> newMultiValueMap() { return newMultivalueMap(); } @Override public Set<Path> newPathSet() { return new HugeTraverser.PathSet(); } @Override public void addNode(Map<Id, List<Node>> vertices, Id id, Node node) { ((MultivaluedMap<Id, Node>) vertices).add(id, node); } @Override public void addNewVerticesToAll(Map<Id, List<Node>> newVertices, Map<Id, List<Node>> targets) {<FILL_FUNCTION_BODY>} }
MultivaluedMap<Id, Node> vertices = (MultivaluedMap<Id, Node>) targets; for (Map.Entry<Id, List<Node>> entry : newVertices.entrySet()) { vertices.addAll(entry.getKey(), entry.getValue()); }
293
74
367
<methods>public void close() ,public static void destroy() <variables>private static final java.lang.String EXECUTOR_NAME,private static org.apache.hugegraph.util.Consumers.ExecutorPool executors
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/optimize/ConditionP.java
ConditionP
eq
class ConditionP extends P<Object> { private static final long serialVersionUID = 9094970577400072902L; private ConditionP(final BiPredicate<Object, Object> predicate, Object value) { super(predicate, value); } public static ConditionP textContains(Object value) { return new ConditionP(Condition.RelationType.TEXT_CONTAINS, value); } public static ConditionP contains(Object value) { return new ConditionP(Condition.RelationType.CONTAINS, value); } public static ConditionP containsK(Object value) { return new ConditionP(Condition.RelationType.CONTAINS_KEY, value); } public static ConditionP containsV(Object value) { return new ConditionP(Condition.RelationType.CONTAINS_VALUE, value); } public static ConditionP eq(Object value) {<FILL_FUNCTION_BODY>} }
// EQ that can compare two array return new ConditionP(Condition.RelationType.EQ, value);
254
30
284
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/optimize/HugeCountStep.java
HugeCountStep
processNextStart
class HugeCountStep<S extends Element> extends AbstractStep<S, Long> { private static final long serialVersionUID = -679873894532085972L; private final HugeGraphStep<?, S> originGraphStep; private boolean done = false; public HugeCountStep(final Traversal.Admin<?, ?> traversal, final HugeGraphStep<?, S> originGraphStep) { super(traversal); E.checkNotNull(originGraphStep, "originGraphStep"); this.originGraphStep = originGraphStep; } @Override public boolean equals(Object obj) { if (!(obj instanceof HugeCountStep)) { return false; } if (!super.equals(obj)) { return false; } HugeCountStep other = (HugeCountStep) obj; return Objects.equals(this.originGraphStep, other.originGraphStep) && this.done == other.done; } @Override public int hashCode() { return Objects.hash(super.hashCode(), this.originGraphStep, this.done); } @Override protected Admin<Long> processNextStart() throws NoSuchElementException {<FILL_FUNCTION_BODY>} }
if (this.done) { throw FastNoSuchElementException.instance(); } this.done = true; @SuppressWarnings({"unchecked", "rawtypes"}) Step<Long, Long> step = (Step) this; return this.getTraversal().getTraverserGenerator() .generate(this.originGraphStep.count(), step, 1L);
340
102
442
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/optimize/HugeCountStepStrategy.java
HugeCountStepStrategy
apply
class HugeCountStepStrategy extends AbstractTraversalStrategy<ProviderOptimizationStrategy> implements ProviderOptimizationStrategy { private static final long serialVersionUID = -3910433925919057771L; private static final HugeCountStepStrategy INSTANCE; static { INSTANCE = new HugeCountStepStrategy(); } private HugeCountStepStrategy() { // pass } @Override @SuppressWarnings({"rawtypes", "unchecked"}) public void apply(Traversal.Admin<?, ?> traversal) {<FILL_FUNCTION_BODY>} @Override public Set<Class<? extends ProviderOptimizationStrategy>> applyPrior() { return Collections.singleton(HugeGraphStepStrategy.class); } @Override public Set<Class<? extends ProviderOptimizationStrategy>> applyPost() { return Collections.singleton(HugeVertexStepStrategy.class); } public static HugeCountStepStrategy instance() { return INSTANCE; } }
TraversalUtil.convAllHasSteps(traversal); // Extract CountGlobalStep List<CountGlobalStep> steps = TraversalHelper.getStepsOfClass( CountGlobalStep.class, traversal); if (steps.isEmpty()) { return; } // Find HugeGraphStep before count() CountGlobalStep<?> originStep = steps.get(0); List<Step<?, ?>> originSteps = new ArrayList<>(); HugeGraphStep<?, ? extends Element> graphStep = null; Step<?, ?> step = originStep; do { if (!(step instanceof CountGlobalStep || step instanceof GraphStep || step instanceof IdentityStep || step instanceof NoOpBarrierStep || step instanceof CollectingBarrierStep) || (step instanceof TraversalParent && TraversalHelper.anyStepRecursively(s -> { return s instanceof SideEffectStep || s instanceof AggregateGlobalStep || s instanceof AggregateLocalStep; }, (TraversalParent) step))) { return; } originSteps.add(step); if (step instanceof HugeGraphStep) { graphStep = (HugeGraphStep<?, ? extends Element>) step; break; } step = step.getPreviousStep(); } while (step != null); if (graphStep == null) { return; } // Replace with HugeCountStep graphStep.queryInfo().aggregate(Aggregate.AggregateFunc.COUNT, null); HugeCountStep<?> countStep = new HugeCountStep<>(traversal, graphStep); for (Step<?, ?> origin : originSteps) { TraversalHelper.copyLabels(origin, countStep, false); traversal.removeStep(origin); } traversal.addStep(0, countStep);
289
487
776
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/optimize/HugeGraphStep.java
HugeGraphStep
makeQuery
class HugeGraphStep<S, E extends Element> extends GraphStep<S, E> implements QueryHolder { private static final long serialVersionUID = -679873894532085972L; private static final Logger LOG = Log.logger(HugeGraphStep.class); private final List<HasContainer> hasContainers = new ArrayList<>(); // Store limit/order-by private final Query queryInfo = new Query(HugeType.UNKNOWN); private Iterator<E> lastTimeResults = QueryResults.emptyIterator(); public HugeGraphStep(final GraphStep<S, E> originGraphStep) { super(originGraphStep.getTraversal(), originGraphStep.getReturnClass(), originGraphStep.isStartStep(), originGraphStep.getIds()); originGraphStep.getLabels().forEach(this::addLabel); boolean queryVertex = this.returnsVertex(); boolean queryEdge = this.returnsEdge(); assert queryVertex || queryEdge; this.setIteratorSupplier(() -> { Iterator<E> results = queryVertex ? this.vertices() : this.edges(); this.lastTimeResults = results; return results; }); } protected long count() { if (this.ids == null) { return 0L; } if (this.returnsVertex()) { return this.verticesCount(); } else { assert this.returnsEdge(); return this.edgesCount(); } } private long verticesCount() { if (!this.hasIds()) { HugeGraph graph = TraversalUtil.getGraph(this); Query query = this.makeQuery(graph, HugeType.VERTEX); return graph.queryNumber(query).longValue(); } return IteratorUtils.count(this.vertices()); } private long edgesCount() { if (!this.hasIds()) { HugeGraph graph = TraversalUtil.getGraph(this); Query query = this.makeQuery(graph, HugeType.EDGE); return graph.queryNumber(query).longValue(); } return IteratorUtils.count(this.edges()); } private Iterator<E> vertices() { LOG.debug("HugeGraphStep.vertices(): {}", this); HugeGraph graph = TraversalUtil.getGraph(this); // g.V().hasId(EMPTY_LIST) will set ids to null if (this.ids == null) { return QueryResults.emptyIterator(); } if (this.hasIds()) { return TraversalUtil.filterResult(this.hasContainers, graph.vertices(this.ids)); } Query query = this.makeQuery(graph, HugeType.VERTEX); @SuppressWarnings("unchecked") Iterator<E> result = (Iterator<E>) graph.vertices(query); return result; } private Iterator<E> edges() { LOG.debug("HugeGraphStep.edges(): {}", this); HugeGraph graph = TraversalUtil.getGraph(this); // g.E().hasId(EMPTY_LIST) will set ids to null if (this.ids == null) { return QueryResults.emptyIterator(); } if (this.hasIds()) { return TraversalUtil.filterResult(this.hasContainers, graph.edges(this.ids)); } Query query = this.makeQuery(graph, HugeType.EDGE); @SuppressWarnings("unchecked") Iterator<E> result = (Iterator<E>) graph.edges(query); return result; } private boolean hasIds() { return this.ids != null && this.ids.length > 0; } private Query makeQuery(HugeGraph graph, HugeType type) {<FILL_FUNCTION_BODY>} @Override public String toString() { if (this.hasContainers.isEmpty()) { return super.toString(); } return this.ids.length == 0 ? StringFactory.stepString(this, this.returnClass.getSimpleName(), this.hasContainers) : StringFactory.stepString(this, this.returnClass.getSimpleName(), Arrays.toString(this.ids), this.hasContainers); } @Override public List<HasContainer> getHasContainers() { return Collections.unmodifiableList(this.hasContainers); } @Override public void addHasContainer(final HasContainer has) { if (SYSPROP_PAGE.equals(has.getKey())) { this.setPage((String) has.getValue()); return; } this.hasContainers.add(has); } @Override public Query queryInfo() { return this.queryInfo; } @Override public Iterator<?> lastTimeResults() { return this.lastTimeResults; } @Override public boolean equals(Object obj) { if (!(obj instanceof HugeGraphStep)) { return false; } if (!super.equals(obj)) { return false; } HugeGraphStep other = (HugeGraphStep) obj; return this.hasContainers.equals(other.hasContainers) && this.queryInfo.equals(other.queryInfo) && this.lastTimeResults.equals(other.lastTimeResults); } @Override public int hashCode() { return super.hashCode() ^ this.queryInfo.hashCode() ^ this.hasContainers.hashCode(); } }
Query query; if (this.hasContainers.isEmpty()) { // Query all query = new Query(type); } else { ConditionQuery q = new ConditionQuery(type); query = TraversalUtil.fillConditionQuery(q, this.hasContainers, graph); } query = this.injectQueryInfo(query); return query;
1,503
99
1,602
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/optimize/HugeGraphStepStrategy.java
HugeGraphStepStrategy
apply
class HugeGraphStepStrategy extends AbstractTraversalStrategy<ProviderOptimizationStrategy> implements ProviderOptimizationStrategy { private static final long serialVersionUID = -2952498905649139719L; private static final HugeGraphStepStrategy INSTANCE; static { INSTANCE = new HugeGraphStepStrategy(); } private HugeGraphStepStrategy() { // pass } @Override @SuppressWarnings({"rawtypes", "unchecked"}) public void apply(Traversal.Admin<?, ?> traversal) {<FILL_FUNCTION_BODY>} @Override public Set<Class<? extends ProviderOptimizationStrategy>> applyPost() { return Collections.singleton(HugeCountStepStrategy.class); } public static HugeGraphStepStrategy instance() { return INSTANCE; } }
TraversalUtil.convAllHasSteps(traversal); // Extract conditions in GraphStep List<GraphStep> steps = TraversalHelper.getStepsOfClass( GraphStep.class, traversal); for (GraphStep originStep : steps) { TraversalUtil.trySetGraph(originStep, TraversalUtil.tryGetGraph(steps.get(0))); HugeGraphStep<?, ?> newStep = new HugeGraphStep<>(originStep); TraversalHelper.replaceStep(originStep, newStep, traversal); TraversalUtil.extractHasContainer(newStep, traversal); // TODO: support order-by optimize // TraversalUtil.extractOrder(newStep, traversal); TraversalUtil.extractRange(newStep, traversal, false); TraversalUtil.extractCount(newStep, traversal); }
244
241
485
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/optimize/HugePrimaryKeyStrategy.java
HugePrimaryKeyStrategy
apply
class HugePrimaryKeyStrategy extends AbstractTraversalStrategy<TraversalStrategy.ProviderOptimizationStrategy> implements ProviderOptimizationStrategy { private static final long serialVersionUID = 6307847098226016416L; private static final HugePrimaryKeyStrategy INSTANCE = new HugePrimaryKeyStrategy(); public static HugePrimaryKeyStrategy instance() { return INSTANCE; } @Override public void apply(Traversal.Admin<?, ?> traversal) {<FILL_FUNCTION_BODY>} }
List<Step> removeSteps = new LinkedList<>(); Mutating curAddStep = null; List<Step> stepList = traversal.getSteps(); for (int i = 0, s = stepList.size(); i < s; i++) { Step step = stepList.get(i); if (i == 0 && step instanceof AddVertexStartStep) { curAddStep = (Mutating) step; continue; } else if (curAddStep == null && (step) instanceof AddVertexStep) { curAddStep = (Mutating) step; continue; } if (curAddStep == null) { continue; } if (!(step instanceof AddPropertyStep)) { curAddStep = null; continue; } AddPropertyStep propertyStep = (AddPropertyStep) step; if (propertyStep.getCardinality() == Cardinality.single || propertyStep.getCardinality() == null) { Object[] kvs = new Object[2]; List<Object> kvList = new LinkedList<>(); propertyStep.getParameters().getRaw().forEach((k, v) -> { if (T.key.equals(k)) { kvs[0] = v.get(0); } else if (T.value.equals(k)) { kvs[1] = v.get(0); } else { kvList.add(k.toString()); kvList.add(v.get(0)); } }); curAddStep.configure(kvs); if (!kvList.isEmpty()) { curAddStep.configure(kvList.toArray(new Object[0])); } removeSteps.add(step); } else { curAddStep = null; } } for (Step index : removeSteps) { traversal.removeStep(index); }
152
501
653
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/optimize/HugeScriptTraversal.java
HugeScriptTraversal
applyStrategies
class HugeScriptTraversal<S, E> extends DefaultTraversal<S, E> { private static final long serialVersionUID = 4617322697747299673L; private final String script; private final String language; private final Map<String, Object> bindings; private final Map<String, String> aliases; private Object result; public HugeScriptTraversal(TraversalSource traversalSource, String language, String script, Map<String, Object> bindings, Map<String, String> aliases) { this.graph = traversalSource.getGraph(); this.language = language; this.script = script; this.bindings = bindings; this.aliases = aliases; this.result = null; } public Object result() { return this.result; } public String script() { return this.script; } @Override public void applyStrategies() throws IllegalStateException {<FILL_FUNCTION_BODY>} }
ScriptEngine engine = SingleGremlinScriptEngineManager.get(this.language); Bindings bindings = engine.createBindings(); bindings.putAll(this.bindings); @SuppressWarnings("rawtypes") TraversalStrategy[] strategies = this.getStrategies().toList() .toArray(new TraversalStrategy[0]); GraphTraversalSource g = this.graph.traversal(); if (strategies.length > 0) { g = g.withStrategies(strategies); } bindings.put("g", g); bindings.put("graph", this.graph); for (Map.Entry<String, String> entry : this.aliases.entrySet()) { Object value = bindings.get(entry.getValue()); if (value == null) { throw new IllegalArgumentException(String.format("Invalid alias '%s':'%s'", entry.getKey(), entry.getValue())); } bindings.put(entry.getKey(), value); } try { Object result = engine.eval(this.script, bindings); if (result instanceof Admin) { @SuppressWarnings({"unchecked"}) Admin<S, E> traversal = (Admin<S, E>) result; traversal.getSideEffects().mergeInto(this.sideEffects); traversal.getSteps().forEach(this::addStep); this.strategies = traversal.getStrategies(); } else { this.result = result; } super.applyStrategies(); } catch (ScriptException e) { throw new HugeException(e.getMessage(), e); }
281
445
726
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/optimize/HugeVertexStep.java
HugeVertexStep
flatMap
class HugeVertexStep<E extends Element> extends VertexStep<E> implements QueryHolder { private static final long serialVersionUID = -7850636388424382454L; private static final Logger LOG = Log.logger(HugeVertexStep.class); private final List<HasContainer> hasContainers = new ArrayList<>(); // Store limit/order-by private final Query queryInfo = new Query(null); private Iterator<E> iterator = QueryResults.emptyIterator(); public HugeVertexStep(final VertexStep<E> originVertexStep) { super(originVertexStep.getTraversal(), originVertexStep.getReturnClass(), originVertexStep.getDirection(), originVertexStep.getEdgeLabels()); originVertexStep.getLabels().forEach(this::addLabel); } @SuppressWarnings("unchecked") @Override protected Iterator<E> flatMap(final Traverser.Admin<Vertex> traverser) {<FILL_FUNCTION_BODY>} private Iterator<Vertex> vertices(Traverser.Admin<Vertex> traverser) { Iterator<Edge> edges = this.edges(traverser); Iterator<Vertex> vertices = this.queryAdjacentVertices(edges); if (LOG.isDebugEnabled()) { Vertex vertex = traverser.get(); LOG.debug("HugeVertexStep.vertices(): is there adjacent " + "vertices of {}: {}, has={}", vertex.id(), vertices.hasNext(), this.hasContainers); } return vertices; } private Iterator<Edge> edges(Traverser.Admin<Vertex> traverser) { Query query = this.constructEdgesQuery(traverser); return this.queryEdges(query); } protected Iterator<Vertex> queryAdjacentVertices(Iterator<Edge> edges) { HugeGraph graph = TraversalUtil.getGraph(this); Iterator<Vertex> vertices = graph.adjacentVertices(edges); if (!this.withVertexCondition()) { return vertices; } // TODO: query by vertex index to optimize return TraversalUtil.filterResult(this.hasContainers, vertices); } protected Iterator<Edge> queryEdges(Query query) { HugeGraph graph = TraversalUtil.getGraph(this); // Do query Iterator<Edge> edges = graph.edges(query); if (!this.withEdgeCondition()) { return edges; } // Do filter by edge conditions return TraversalUtil.filterResult(this.hasContainers, edges); } protected ConditionQuery constructEdgesQuery( Traverser.Admin<Vertex> traverser) { HugeGraph graph = TraversalUtil.getGraph(this); // Query for edge with conditions(else conditions for vertex) boolean withEdgeCond = this.withEdgeCondition(); boolean withVertexCond = this.withVertexCondition(); Id vertex = (Id) traverser.get().id(); Directions direction = Directions.convert(this.getDirection()); Id[] edgeLabels = graph.mapElName2Id(this.getEdgeLabels()); LOG.debug("HugeVertexStep.edges(): vertex={}, direction={}, " + "edgeLabels={}, has={}", vertex, direction, edgeLabels, this.hasContainers); ConditionQuery query = GraphTransaction.constructEdgesQuery( vertex, direction, edgeLabels); // Query by sort-keys if (withEdgeCond && edgeLabels.length == 1) { TraversalUtil.fillConditionQuery(query, this.hasContainers, graph); if (!GraphTransaction.matchPartialEdgeSortKeys(query, graph)) { // Can't query by sysprop and by index (HugeGraph-749) query.resetUserpropConditions(); } else if (GraphTransaction.matchFullEdgeSortKeys(query, graph)) { // All sysprop conditions are in sort-keys withEdgeCond = false; } else { // Partial sysprop conditions are in sort-keys assert !query.userpropKeys().isEmpty(); } } // Query by has(id) if (query.idsSize() > 0) { // Ignore conditions if query by edge id in has-containers // FIXME: should check that the edge id matches the `vertex` query.resetConditions(); LOG.warn("It's not recommended to query by has(id)"); } /* * Unset limit when needed to filter property after store query * like query: outE().has(k,v).limit(n) * NOTE: outE().limit(m).has(k,v).limit(n) will also be unset limit, * Can't unset limit if query by paging due to page position will be * exceeded when reaching the limit in tinkerpop layer */ if (withEdgeCond || withVertexCond) { org.apache.hugegraph.util.E.checkArgument(!this.queryInfo().paging(), "Can't query by paging " + "and filtering"); this.queryInfo().limit(Query.NO_LIMIT); } query = this.injectQueryInfo(query); return query; } protected boolean withVertexCondition() { return this.returnsVertex() && !this.hasContainers.isEmpty(); } protected boolean withEdgeCondition() { return this.returnsEdge() && !this.hasContainers.isEmpty(); } @Override public String toString() { if (this.hasContainers.isEmpty()) { return super.toString(); } return StringFactory.stepString( this, getDirection(), Arrays.asList(getEdgeLabels()), getReturnClass().getSimpleName(), this.hasContainers); } @Override public List<HasContainer> getHasContainers() { return Collections.unmodifiableList(this.hasContainers); } @Override public void addHasContainer(final HasContainer has) { if (SYSPROP_PAGE.equals(has.getKey())) { this.setPage((String) has.getValue()); return; } this.hasContainers.add(has); } @Override public Query queryInfo() { return this.queryInfo; } @Override public Iterator<?> lastTimeResults() { return this.iterator; } @Override public boolean equals(Object obj) { if (!(obj instanceof HugeVertexStep)) { return false; } if (!super.equals(obj)) { return false; } HugeVertexStep other = (HugeVertexStep) obj; return this.hasContainers.equals(other.hasContainers) && this.queryInfo.equals(other.queryInfo) && this.iterator.equals(other.iterator); } @Override public int hashCode() { return super.hashCode() ^ this.queryInfo.hashCode() ^ this.hasContainers.hashCode(); } }
boolean queryVertex = this.returnsVertex(); boolean queryEdge = this.returnsEdge(); assert queryVertex || queryEdge; if (queryVertex) { this.iterator = (Iterator<E>) this.vertices(traverser); } else { assert queryEdge; this.iterator = (Iterator<E>) this.edges(traverser); } return this.iterator;
1,884
105
1,989
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/optimize/HugeVertexStepByBatch.java
HugeVertexStepByBatch
lastTimeResults
class HugeVertexStepByBatch<E extends Element> extends HugeVertexStep<E> { private static final long serialVersionUID = -3609787815053052222L; private BatchMapperIterator<Traverser.Admin<Vertex>, E> batchIterator; private Traverser.Admin<Vertex> head; private Iterator<E> iterator; public HugeVertexStepByBatch(final VertexStep<E> originalVertexStep) { super(originalVertexStep); this.batchIterator = null; this.head = null; this.iterator = null; } @Override protected Traverser.Admin<E> processNextStart() { /* Override super.processNextStart() */ if (this.batchIterator == null) { int batchSize = (int) Query.QUERY_BATCH; this.batchIterator = new BatchMapperIterator<>( batchSize, this.starts, this::flatMap); } if (this.batchIterator.hasNext()) { assert this.head != null; E item = this.batchIterator.next(); // TODO: find the parent node accurately instead the head return this.head.split(item, this); } throw FastNoSuchElementException.instance(); } @Override public void reset() { super.reset(); this.closeIterator(); this.batchIterator = null; this.head = null; } @Override public Iterator<?> lastTimeResults() {<FILL_FUNCTION_BODY>} @Override protected void closeIterator() { CloseableIterator.closeIterator(this.batchIterator); } @SuppressWarnings("unchecked") private Iterator<E> flatMap(List<Traverser.Admin<Vertex>> traversers) { if (this.head == null && !traversers.isEmpty()) { this.head = traversers.get(0); } boolean queryVertex = this.returnsVertex(); boolean queryEdge = this.returnsEdge(); assert queryVertex || queryEdge; if (queryVertex) { this.iterator = (Iterator<E>) this.vertices(traversers); } else { assert queryEdge; this.iterator = (Iterator<E>) this.edges(traversers); } return this.iterator; } private Iterator<Vertex> vertices( List<Traverser.Admin<Vertex>> traversers) { assert !traversers.isEmpty(); Iterator<Edge> edges = this.edges(traversers); return this.queryAdjacentVertices(edges); } private Iterator<Edge> edges(List<Traverser.Admin<Vertex>> traversers) { assert !traversers.isEmpty(); BatchConditionQuery batchQuery = new BatchConditionQuery( HugeType.EDGE, traversers.size()); for (Traverser.Admin<Vertex> traverser : traversers) { ConditionQuery query = this.constructEdgesQuery(traverser); /* * Merge each query into batch query through IN condition * NOTE: duplicated results may be removed by backend store */ batchQuery.mergeToIN(query, HugeKeys.OWNER_VERTEX); } this.injectQueryInfo(batchQuery); return this.queryEdges(batchQuery); } }
/* * NOTE: fetch page from this iterator, can only get page info of * the lowest level, may lost info of upper levels. */ return this.iterator;
891
49
940
<methods>public void <init>(VertexStep<E>) ,public void addHasContainer(HasContainer) ,public boolean equals(java.lang.Object) ,public List<HasContainer> getHasContainers() ,public int hashCode() ,public Iterator<?> lastTimeResults() ,public org.apache.hugegraph.backend.query.Query queryInfo() ,public java.lang.String toString() <variables>private static final Logger LOG,private final List<HasContainer> hasContainers,private Iterator<E> iterator,private final org.apache.hugegraph.backend.query.Query queryInfo,private static final long serialVersionUID
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/traversal/optimize/HugeVertexStepStrategy.java
HugeVertexStepStrategy
containsTree
class HugeVertexStepStrategy extends AbstractTraversalStrategy<ProviderOptimizationStrategy> implements ProviderOptimizationStrategy { private static final long serialVersionUID = 491355700217483162L; private static final HugeVertexStepStrategy INSTANCE; static { INSTANCE = new HugeVertexStepStrategy(); } private HugeVertexStepStrategy() { // pass } @Override @SuppressWarnings({"rawtypes", "unchecked"}) public void apply(final Traversal.Admin<?, ?> traversal) { TraversalUtil.convAllHasSteps(traversal); List<VertexStep> steps = TraversalHelper.getStepsOfClass( VertexStep.class, traversal); boolean batchOptimize = false; if (!steps.isEmpty()) { boolean withPath = HugeVertexStepStrategy.containsPath(traversal); boolean withTree = HugeVertexStepStrategy.containsTree(traversal); /* * The graph of traversal may be null when `__` step is followed * by `count().is(0)` step, like the following gremlin: * `g.V(id).repeat(in()).until(or(inE().count().is(0), loops().is(2)))` * TODO: remove this `graph!=null` check after fixed the bug #1699 */ boolean supportIn = false; HugeGraph graph = TraversalUtil.tryGetGraph(steps.get(0)); if (graph != null) { supportIn = graph.backendStoreFeatures() .supportsQueryWithInCondition(); } batchOptimize = !withTree && !withPath && supportIn; } for (VertexStep originStep : steps) { HugeVertexStep<?> newStep = batchOptimize ? new HugeVertexStepByBatch<>(originStep) : new HugeVertexStep<>(originStep); TraversalHelper.replaceStep(originStep, newStep, traversal); TraversalUtil.extractHasContainer(newStep, traversal); // TODO: support order-by optimize // TraversalUtil.extractOrder(newStep, traversal); TraversalUtil.extractRange(newStep, traversal, true); TraversalUtil.extractCount(newStep, traversal); } } /** * Does a Traversal contain any Path step * * @param traversal * @return the traversal or its parents contain at least one Path step */ protected static boolean containsPath(Traversal.Admin<?, ?> traversal) { boolean hasPath = !TraversalHelper.getStepsOfClass( PathStep.class, traversal).isEmpty(); if (hasPath) { return true; } else if (traversal instanceof EmptyTraversal) { return false; } TraversalParent parent = traversal.getParent(); return containsPath(parent.asStep().getTraversal()); } /** * Does a Traversal contain any Tree step * * @param traversal * @return the traversal or its parents contain at least one Tree step */ protected static boolean containsTree(Traversal.Admin<?, ?> traversal) {<FILL_FUNCTION_BODY>} public static HugeVertexStepStrategy instance() { return INSTANCE; } }
boolean hasTree = !TraversalHelper.getStepsOfClass( TreeStep.class, traversal).isEmpty(); if (hasTree) { return true; } else if (traversal instanceof EmptyTraversal) { return false; } TraversalParent parent = traversal.getParent(); return containsTree(parent.asStep().getTraversal());
912
104
1,016
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/util/Blob.java
Blob
equals
class Blob implements Comparable<Blob> { public static final Blob EMPTY = new Blob(new byte[0]); private final byte[] bytes; private Blob(byte[] bytes) { E.checkNotNull(bytes, "bytes"); this.bytes = bytes; } public byte[] bytes() { return this.bytes; } public static Blob wrap(byte[] bytes) { return new Blob(bytes); } @Override public int hashCode() { return Arrays.hashCode(this.bytes); } @Override public boolean equals(Object obj) {<FILL_FUNCTION_BODY>} @Override public String toString() { String hex = Bytes.toHex(this.bytes); StringBuilder sb = new StringBuilder(6 + hex.length()); sb.append("Blob{").append(hex).append("}"); return sb.toString(); } @Override public int compareTo(Blob other) { E.checkNotNull(other, "other blob"); return Bytes.compare(this.bytes, other.bytes); } }
if (!(obj instanceof Blob)) { return false; } Blob other = (Blob) obj; return Arrays.equals(this.bytes, other.bytes);
304
50
354
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/util/CompressUtil.java
CompressUtil
decompressTar
class CompressUtil { public static void compressTar(String inputDir, String outputFile, Checksum checksum) throws IOException { LZ4Factory factory = LZ4Factory.fastestInstance(); LZ4Compressor compressor = factory.fastCompressor(); int blockSize = RaftContext.BLOCK_SIZE; try (FileOutputStream fos = new FileOutputStream(outputFile); CheckedOutputStream cos = new CheckedOutputStream(fos, checksum); BufferedOutputStream bos = new BufferedOutputStream(cos); LZ4BlockOutputStream lz4os = new LZ4BlockOutputStream(bos, blockSize, compressor); TarArchiveOutputStream tos = new TarArchiveOutputStream(lz4os)) { Path source = Paths.get(inputDir); CompressUtil.tarDir(source, tos); tos.flush(); fos.getFD().sync(); } } private static void tarDir(Path source, TarArchiveOutputStream tos) throws IOException { Files.walkFileTree(source, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { String entryName = buildTarEntryName(source, dir); if (!entryName.isEmpty()) { TarArchiveEntry entry = new TarArchiveEntry(dir.toFile(), entryName); tos.putArchiveEntry(entry); tos.closeArchiveEntry(); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException { // Only copy files, no symbolic links if (attributes.isSymbolicLink()) { return FileVisitResult.CONTINUE; } String targetFile = buildTarEntryName(source, file); TarArchiveEntry entry = new TarArchiveEntry(file.toFile(), targetFile); tos.putArchiveEntry(entry); Files.copy(file, tos); tos.closeArchiveEntry(); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException e) { return FileVisitResult.TERMINATE; } }); } private static String buildTarEntryName(Path topLevel, Path current) { return topLevel.getFileName().resolve(topLevel.relativize(current)) .toString(); } public static void decompressTar(String sourceFile, String outputDir, Checksum checksum) throws IOException {<FILL_FUNCTION_BODY>} private static Path zipSlipProtect(ArchiveEntry entry, Path targetDir) throws IOException { Path targetDirResolved = targetDir.resolve(entry.getName()); /* * Make sure normalized file still has targetDir as its prefix, * else throws exception */ Path normalizePath = targetDirResolved.normalize(); if (!normalizePath.startsWith(targetDir.normalize())) { throw new IOException(String.format("Bad entry: %s", entry.getName())); } return normalizePath; } public static void compressZip(String inputDir, String outputFile, Checksum checksum) throws IOException { String rootDir = Paths.get(inputDir).toAbsolutePath().getParent().toString(); String sourceDir = Paths.get(inputDir).getFileName().toString(); compressZip(rootDir, sourceDir, outputFile, checksum); } public static void compressZip(String rootDir, String sourceDir, String outputFile, Checksum checksum) throws IOException { try (FileOutputStream fos = new FileOutputStream(outputFile); CheckedOutputStream cos = new CheckedOutputStream(fos, checksum); BufferedOutputStream bos = new BufferedOutputStream(cos); ZipOutputStream zos = new ZipOutputStream(bos)) { CompressUtil.zipDir(rootDir, sourceDir, zos); zos.flush(); fos.getFD().sync(); } } private static void zipDir(String rootDir, String sourceDir, ZipOutputStream zos) throws IOException { String dir = Paths.get(rootDir, sourceDir).toString(); File[] files = new File(dir).listFiles(); E.checkNotNull(files, "files"); for (File file : files) { String child = Paths.get(sourceDir, file.getName()).toString(); if (file.isDirectory()) { zipDir(rootDir, child, zos); } else { zos.putNextEntry(new ZipEntry(child)); try (FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis)) { IOUtils.copy(bis, zos); } } } } public static void decompressZip(String sourceFile, String outputDir, Checksum checksum) throws IOException { try (FileInputStream fis = new FileInputStream(sourceFile); CheckedInputStream cis = new CheckedInputStream(fis, checksum); BufferedInputStream bis = new BufferedInputStream(cis); ZipInputStream zis = new ZipInputStream(bis)) { ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { String fileName = entry.getName(); File entryFile = new File(Paths.get(outputDir, fileName) .toString()); FileUtils.forceMkdir(entryFile.getParentFile()); try (FileOutputStream fos = new FileOutputStream(entryFile); BufferedOutputStream bos = new BufferedOutputStream(fos)) { IOUtils.copy(zis, bos); bos.flush(); fos.getFD().sync(); } } /* * Continue to read all remaining bytes(extra metadata of ZipEntry) * directly from the checked stream, Otherwise, the checksum value * maybe unexpected. * See https://coderanch.com/t/279175/java/ZipInputStream */ IOUtils.copy(cis, NullOutputStream.NULL_OUTPUT_STREAM); } } }
Path source = Paths.get(sourceFile); Path target = Paths.get(outputDir); if (Files.notExists(source)) { throw new IOException(String.format( "The source file %s doesn't exists", source)); } LZ4Factory factory = LZ4Factory.fastestInstance(); LZ4FastDecompressor decompressor = factory.fastDecompressor(); try (InputStream fis = Files.newInputStream(source); CheckedInputStream cis = new CheckedInputStream(fis, checksum); BufferedInputStream bis = new BufferedInputStream(cis); LZ4BlockInputStream lz4is = new LZ4BlockInputStream(bis, decompressor); TarArchiveInputStream tis = new TarArchiveInputStream(lz4is)) { ArchiveEntry entry; while ((entry = tis.getNextEntry()) != null) { // Create a new path, zip slip validate Path newPath = zipSlipProtect(entry, target); if (entry.isDirectory()) { Files.createDirectories(newPath); } else { // check parent folder again Path parent = newPath.toAbsolutePath().getParent(); if (parent != null) { if (Files.notExists(parent)) { Files.createDirectories(parent); } } // Copy TarArchiveInputStream to Path newPath Files.copy(tis, newPath, StandardCopyOption.REPLACE_EXISTING); } } }
1,595
389
1,984
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/util/ConfigUtil.java
ConfigUtil
buildConfig
class ConfigUtil { private static final Logger LOG = Log.logger(ConfigUtil.class); private static final String NODE_GRAPHS = "graphs"; private static final String CONF_SUFFIX = ".properties"; private static final String CHARSET = "UTF-8"; public static void checkGremlinConfig(String conf) { Parameters params = new Parameters(); try { FileBasedConfigurationBuilder<FileBasedConfiguration> builder = new FileBasedConfigurationBuilder(YAMLConfiguration.class) .configure(params.fileBased().setFileName(conf)); YAMLConfiguration config = (YAMLConfiguration) builder.getConfiguration(); List<HierarchicalConfiguration<ImmutableNode>> nodes = config.childConfigurationsAt( NODE_GRAPHS); if (nodes == null || nodes.isEmpty()) { return; } E.checkArgument(nodes.size() == 1, "Not allowed to specify multiple '%s' " + "nodes in config file '%s'", NODE_GRAPHS, conf); ImmutableNode root = null; NodeHandler<ImmutableNode> nodeHandler = null; for (HierarchicalConfiguration<ImmutableNode> node : nodes) { NodeModel<ImmutableNode> nodeModel = node.getNodeModel(); E.checkArgument(nodeModel != null && (nodeHandler = nodeModel.getNodeHandler()) != null && (root = nodeHandler.getRootNode()) != null, "Node '%s' must contain root", node); } } catch (ConfigurationException e) { throw new HugeException("Failed to load yaml config file '%s'", conf); } } public static Map<String, String> scanGraphsDir(String graphsDirPath) { LOG.info("Scanning option 'graphs' directory '{}'", graphsDirPath); File graphsDir = new File(graphsDirPath); E.checkArgument(graphsDir.exists() && graphsDir.isDirectory(), "Please ensure the path '%s' of option 'graphs' " + "exist and it's a directory", graphsDir); File[] confFiles = graphsDir.listFiles((dir, name) -> { return name.endsWith(CONF_SUFFIX); }); E.checkNotNull(confFiles, "graph configuration files"); Map<String, String> graphConfs = InsertionOrderUtil.newMap(); for (File confFile : confFiles) { // NOTE: use file name as graph name String name = StringUtils.substringBefore(confFile.getName(), ConfigUtil.CONF_SUFFIX); HugeFactory.checkGraphName(name, confFile.getPath()); graphConfs.put(name, confFile.getPath()); } return graphConfs; } public static String writeToFile(String dir, String graphName, HugeConfig config) { File file = FileUtils.getFile(dir); E.checkArgument(file.exists(), "The directory '%s' must exist", dir); String fileName = file.getPath() + File.separator + graphName + CONF_SUFFIX; try { File newFile = FileUtils.getFile(fileName); config.save(newFile); LOG.info("Write HugeConfig to file: '{}'", fileName); } catch (ConfigurationException e) { throw new HugeException("Failed to write HugeConfig to file '%s'", e, fileName); } return fileName; } public static void deleteFile(File file) { if (file == null || !file.exists()) { return; } try { FileUtils.forceDelete(file); } catch (IOException e) { throw new HugeException("Failed to delete HugeConfig file '%s'", e, file); } } public static PropertiesConfiguration buildConfig(String configText) {<FILL_FUNCTION_BODY>} }
E.checkArgument(StringUtils.isNotEmpty(configText), "The config text can't be null or empty"); PropertiesConfiguration propConfig = new PropertiesConfiguration(); try { Reader in = new StringReader(configText); propConfig.read(in); } catch (Exception e) { throw new IllegalStateException("Failed to read config options", e); } return propConfig;
1,018
104
1,122
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/util/CopyUtil.java
CopyUtil
cloneObject
class CopyUtil { @SuppressWarnings("unchecked") public static <T> T cloneObject(T o, T clone) throws Exception {<FILL_FUNCTION_BODY>} private static Object cloneArray(Object value) { Class<?> valueType = value.getClass(); assert valueType.isArray() && valueType.getComponentType().isPrimitive(); int len = Array.getLength(value); Object array = Array.newInstance(valueType.getComponentType(), len); System.arraycopy(value, 0, array, 0, len); return array; } public static <T> T copy(T object) { return copy(object, null); } public static <T> T copy(T object, T clone) { try { return cloneObject(object, clone); } catch (Exception e) { throw new HugeException("Failed to clone object", e); } } public static <T> T deepCopy(T object) { @SuppressWarnings("unchecked") Class<T> cls = (Class<T>) object.getClass(); return JsonUtil.fromJson(JsonUtil.toJson(object), cls); } }
if (clone == null) { clone = (T) o.getClass().newInstance(); } for (Field field : o.getClass().getDeclaredFields()) { field.setAccessible(true); Object value = field.get(o); if (value == null || Modifier.isFinal(field.getModifiers())) { continue; } Class<?> declareType = field.getType(); Class<?> valueType = value.getClass(); if (ReflectionUtil.isSimpleType(declareType) || ReflectionUtil.isSimpleType(valueType)) { field.set(clone, value); } else if (declareType.isArray() && valueType.isArray() && valueType.getComponentType().isPrimitive()) { field.set(clone, cloneArray(value)); } else { if (value == o) { field.set(clone, clone); } else { field.set(clone, cloneObject(value, null)); } } } return clone;
320
271
591
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/util/FixedTimerWindowRateLimiter.java
FixedTimerWindowRateLimiter
tryAcquire
class FixedTimerWindowRateLimiter implements RateLimiter { private final Timer timer; private final LongAdder count; private final int limit; public FixedTimerWindowRateLimiter(int limitPerSecond) { this.timer = new Timer("RateAuditLog", true); this.count = new LongAdder(); this.limit = limitPerSecond; // Count will be reset if hit limit (run once per 1000ms) this.timer.schedule(new TimerTask() { @Override public void run() { if (count.intValue() >= limit) { count.reset(); } } }, 0L, RESET_PERIOD); } @Override public boolean tryAcquire() {<FILL_FUNCTION_BODY>} }
if (count.intValue() >= limit) { return false; } count.increment(); return true;
214
37
251
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/util/FixedWatchWindowRateLimiter.java
FixedWatchWindowRateLimiter
tryAcquire
class FixedWatchWindowRateLimiter implements RateLimiter { private final LongAdder count; private final Stopwatch watch; private final int limit; public FixedWatchWindowRateLimiter(int limitPerSecond) { this.limit = limitPerSecond; this.watch = Stopwatch.createStarted(); this.count = new LongAdder(); } @Override public boolean tryAcquire() {<FILL_FUNCTION_BODY>} }
if (count.intValue() < limit) { count.increment(); return true; } // Reset only if 1000ms elapsed if (watch.elapsed(TimeUnit.MILLISECONDS) >= RESET_PERIOD) { count.reset(); watch.reset(); count.increment(); return true; } return false;
123
106
229
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/util/GZipUtil.java
GZipUtil
decompress
class GZipUtil { private static final int BUF_SIZE = (int) (4 * Bytes.KB); public static String md5(String input) { return DigestUtils.md5Hex(input); } public static BytesBuffer compress(byte[] data) { int estimateSize = data.length >> 3; BytesBuffer output = BytesBuffer.allocate(estimateSize); Deflater deflater = new Deflater(); deflater.setInput(data); deflater.finish(); byte[] buffer = new byte[BUF_SIZE]; while (!deflater.finished()) { int count = deflater.deflate(buffer); output.write(buffer, 0, count); } output.forReadWritten(); return output; } public static BytesBuffer decompress(byte[] data) {<FILL_FUNCTION_BODY>} }
int estimateSize = data.length << 3; BytesBuffer output = BytesBuffer.allocate(estimateSize); Inflater inflater = new Inflater(); inflater.setInput(data); byte[] buffer = new byte[BUF_SIZE]; while (!inflater.finished()) { try { int count = inflater.inflate(buffer); output.write(buffer, 0, count); } catch (DataFormatException e) { throw new BackendException("Failed to decompress", e); } } output.forReadWritten(); return output;
236
159
395
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/util/JsonUtil.java
JsonUtil
fromJson
class JsonUtil { private static final ObjectMapper MAPPER = new ObjectMapper(); private static final ImmutableSet<String> SPECIAL_FLOATS; static { SimpleModule module = new SimpleModule(); SPECIAL_FLOATS = ImmutableSet.of("-Infinity", "Infinity", "NaN"); module.addSerializer(RawJson.class, new RawJsonSerializer()); HugeGraphSONModule.registerCommonSerializers(module); HugeGraphSONModule.registerIdSerializers(module); HugeGraphSONModule.registerSchemaSerializers(module); HugeGraphSONModule.registerGraphSerializers(module); MAPPER.registerModule(module); } public static void registerModule(Module module) { MAPPER.registerModule(module); } public static String toJson(Object object) { try { return MAPPER.writeValueAsString(object); } catch (JsonProcessingException e) { throw new HugeException("Can't write json: %s", e, e.getMessage()); } } public static <T> T fromJson(String json, Class<T> clazz) { E.checkState(json != null, "Json value can't be null for '%s'", clazz.getSimpleName()); try { return MAPPER.readValue(json, clazz); } catch (IOException e) { throw new HugeException("Can't read json: %s", e, e.getMessage()); } } public static <T> T fromJson(String json, TypeReference<?> typeRef) {<FILL_FUNCTION_BODY>} /** * Number collection will be parsed to Double Collection via fromJson, * this method used to cast element in collection to original number type * * @param object original number * @param clazz target type * @return target number */ public static Object castNumber(Object object, Class<?> clazz) { if (object instanceof Number) { Number number = (Number) object; if (clazz == Byte.class) { object = number.byteValue(); } else if (clazz == Integer.class) { object = number.intValue(); } else if (clazz == Long.class) { object = number.longValue(); } else if (clazz == Float.class) { object = number.floatValue(); } else if (clazz == Double.class) { assert object instanceof Double : object; } else { assert clazz == Date.class : clazz; } } return object; } public static <V> boolean isInfinityOrNaN(V value) { return value instanceof String && SPECIAL_FLOATS.contains(value); } public static Object asJson(Object value) { return new RawJson(toJson(value)); } public static Object asJson(String value) { return new RawJson(value); } private static class RawJson { private final String value; public RawJson(String value) { this.value = value; } public String value() { return this.value; } } private static class RawJsonSerializer extends StdSerializer<RawJson> { private static final long serialVersionUID = 3240301861031054251L; public RawJsonSerializer() { super(RawJson.class); } @Override public void serialize(RawJson json, JsonGenerator generator, SerializerProvider provider) throws IOException { generator.writeRawValue(json.value()); } } }
E.checkState(json != null, "Json value can't be null for '%s'", typeRef.getType()); try { ObjectReader reader = MAPPER.readerFor(typeRef); return reader.readValue(json); } catch (IOException e) { throw new HugeException("Can't read json: %s", e, e.getMessage()); }
962
103
1,065
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/util/KryoUtil.java
KryoUtil
toKryoWithType
class KryoUtil { private static final ThreadLocal<Kryo> KRYOS = new ThreadLocal<>(); public static Kryo kryo() { Kryo kryo = KRYOS.get(); if (kryo != null) { return kryo; } kryo = new Kryo(); registerSerializers(kryo); KRYOS.set(kryo); return kryo; } public static byte[] toKryo(Object value) { try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); Output output = new Output(bos, 256)) { kryo().writeObject(output, value); output.flush(); return bos.toByteArray(); } catch (IOException e) { throw new BackendException("Failed to serialize: %s", e, value); } } public static <T> T fromKryo(byte[] value, Class<T> clazz) { E.checkState(value != null, "Kryo value can't be null for '%s'", clazz.getSimpleName()); return kryo().readObject(new Input(value), clazz); } public static byte[] toKryoWithType(Object value) {<FILL_FUNCTION_BODY>} @SuppressWarnings("unchecked") public static <T> T fromKryoWithType(byte[] value) { E.checkState(value != null, "Kryo value can't be null for object"); return (T) kryo().readClassAndObject(new Input(value)); } private static void registerSerializers(Kryo kryo) { kryo.addDefaultSerializer(UUID.class, new Serializer<UUID>() { @Override public UUID read(Kryo kryo, Input input, Class<UUID> c) { return new UUID(input.readLong(), input.readLong()); } @Override public void write(Kryo kryo, Output output, UUID uuid) { output.writeLong(uuid.getMostSignificantBits()); output.writeLong(uuid.getLeastSignificantBits()); } }); } }
try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); Output output = new Output(bos, 256)) { kryo().writeClassAndObject(output, value); output.flush(); return bos.toByteArray(); } catch (IOException e) { throw new BackendException("Failed to serialize: %s", e, value); }
589
96
685
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/util/LZ4Util.java
LZ4Util
decompress
class LZ4Util { protected static final float DEFAULT_BUFFER_RATIO = 1.5f; public static BytesBuffer compress(byte[] bytes, int blockSize) { return compress(bytes, blockSize, DEFAULT_BUFFER_RATIO); } public static BytesBuffer compress(byte[] bytes, int blockSize, float bufferRatio) { float ratio = bufferRatio <= 0.0F ? DEFAULT_BUFFER_RATIO : bufferRatio; LZ4Factory factory = LZ4Factory.fastestInstance(); LZ4Compressor compressor = factory.fastCompressor(); int initBufferSize = Math.round(bytes.length / ratio); BytesBuffer buf = new BytesBuffer(initBufferSize); LZ4BlockOutputStream lz4Output = new LZ4BlockOutputStream(buf, blockSize, compressor); try { lz4Output.write(bytes); lz4Output.close(); } catch (IOException e) { throw new BackendException("Failed to compress", e); } // If we need to perform reading outside the method, remember to call forReadWritten() return buf; } public static BytesBuffer decompress(byte[] bytes, int blockSize) { return decompress(bytes, blockSize, DEFAULT_BUFFER_RATIO); } public static BytesBuffer decompress(byte[] bytes, int blockSize, float bufferRatio) {<FILL_FUNCTION_BODY>} }
float ratio = bufferRatio <= 0.0F ? DEFAULT_BUFFER_RATIO : bufferRatio; LZ4Factory factory = LZ4Factory.fastestInstance(); LZ4FastDecompressor decompressor = factory.fastDecompressor(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); int initBufferSize = Math.min(Math.round(bytes.length * ratio), BytesBuffer.MAX_BUFFER_CAPACITY); BytesBuffer buf = new BytesBuffer(initBufferSize); LZ4BlockInputStream lzInput = new LZ4BlockInputStream(bais, decompressor); int count; byte[] buffer = new byte[blockSize]; try { while ((count = lzInput.read(buffer)) != -1) { buf.write(buffer, 0, count); } lzInput.close(); } catch (IOException e) { throw new BackendException("Failed to decompress", e); } // If we need to perform reading outside the method, remember to call forReadWritten() return buf;
376
279
655
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/util/ParameterUtil.java
ParameterUtil
parameterString
class ParameterUtil { public static Object parameter(Map<String, Object> parameters, String key) { Object value = parameters.get(key); E.checkArgument(value != null, "Expect '%s' in parameters: %s", key, parameters); return value; } public static String parameterString(Map<String, Object> parameters, String key) {<FILL_FUNCTION_BODY>} public static int parameterInt(Map<String, Object> parameters, String key) { Object value = parameter(parameters, key); E.checkArgument(value instanceof Number, "Expect int value for parameter '%s': '%s'", key, value); return ((Number) value).intValue(); } public static long parameterLong(Map<String, Object> parameters, String key) { Object value = parameter(parameters, key); E.checkArgument(value instanceof Number, "Expect long value for parameter '%s': '%s'", key, value); return ((Number) value).longValue(); } public static double parameterDouble(Map<String, Object> parameters, String key) { Object value = parameter(parameters, key); E.checkArgument(value instanceof Number, "Expect double value for parameter '%s': '%s'", key, value); return ((Number) value).doubleValue(); } public static boolean parameterBoolean(Map<String, Object> parameters, String key) { Object value = parameter(parameters, key); E.checkArgument(value instanceof Boolean, "Expect boolean value for parameter '%s': '%s'", key, value); return ((Boolean) value); } }
Object value = parameter(parameters, key); E.checkArgument(value instanceof String, "Expect string value for parameter '%s': '%s'", key, value); return (String) value;
436
55
491
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/util/Reflection.java
Reflection
loadClass
class Reflection { private static final Logger LOG = Log.logger(Reflection.class); private static final Class<?> REFLECTION_CLAZZ; private static final Method REGISTER_FILEDS_TO_FILTER_METHOD; private static final Method REGISTER_METHODS_TO_FILTER_METHOD; public static final String JDK_INTERNAL_REFLECT_REFLECTION = "jdk.internal.reflect.Reflection"; public static final String SUN_REFLECT_REFLECTION = "sun.reflect.Reflection"; static { Method registerFieldsToFilterMethodTemp = null; Method registerMethodsToFilterMethodTemp = null; Class<?> reflectionClazzTemp = null; try { reflectionClazzTemp = Class.forName(JDK_INTERNAL_REFLECT_REFLECTION); } catch (ClassNotFoundException e) { try { reflectionClazzTemp = Class.forName(SUN_REFLECT_REFLECTION); } catch (ClassNotFoundException ex) { LOG.error("Can't find Reflection class", ex); } } REFLECTION_CLAZZ = reflectionClazzTemp; if (REFLECTION_CLAZZ != null) { try { registerFieldsToFilterMethodTemp = REFLECTION_CLAZZ.getMethod("registerFieldsToFilter", Class.class, String[].class); } catch (Throwable e) { LOG.error("Can't find registerFieldsToFilter method", e); } try { registerMethodsToFilterMethodTemp = REFLECTION_CLAZZ.getMethod("registerMethodsToFilter", Class.class, String[].class); } catch (NoSuchMethodException e) { LOG.error("Can't find registerMethodsToFilter method", e); } } REGISTER_FILEDS_TO_FILTER_METHOD = registerFieldsToFilterMethodTemp; REGISTER_METHODS_TO_FILTER_METHOD = registerMethodsToFilterMethodTemp; } public static void registerFieldsToFilter(Class<?> containingClass, String... fieldNames) { if (REGISTER_FILEDS_TO_FILTER_METHOD == null) { throw new NotSupportException("Reflection.registerFieldsToFilter()"); } try { REGISTER_FILEDS_TO_FILTER_METHOD.setAccessible(true); REGISTER_FILEDS_TO_FILTER_METHOD.invoke(REFLECTION_CLAZZ, containingClass, fieldNames); } catch (IllegalAccessException | InvocationTargetException e) { throw new HugeException("Failed to register class '%s' fields to filter: %s", containingClass, Arrays.toString(fieldNames)); } } public static void registerMethodsToFilter(Class<?> containingClass, String... methodNames) { if (REGISTER_METHODS_TO_FILTER_METHOD == null) { throw new NotSupportException("Reflection.registerMethodsToFilterMethod()"); } try { REGISTER_METHODS_TO_FILTER_METHOD.setAccessible(true); REGISTER_METHODS_TO_FILTER_METHOD.invoke(REFLECTION_CLAZZ, containingClass, methodNames); } catch (IllegalAccessException | InvocationTargetException e) { throw new HugeException("Failed to register class '%s' methods to filter: %s", containingClass, Arrays.toString(methodNames)); } } public static Class<?> loadClass(String clazz) {<FILL_FUNCTION_BODY>} }
try { return Class.forName(clazz); } catch (ClassNotFoundException e) { throw new HugeException(e.getMessage(), e); }
929
46
975
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/util/StringEncoding.java
StringEncoding
writeAsciiString
class StringEncoding { private static final MessageDigest DIGEST; private static final byte[] BYTES_EMPTY = new byte[0]; private static final String STRING_EMPTY = ""; private static final int BLOCK_SIZE = 4096; static { final String ALG = "SHA-256"; try { DIGEST = MessageDigest.getInstance(ALG); } catch (NoSuchAlgorithmException e) { throw new HugeException("Failed to load algorithm %s", e, ALG); } } private static final Base64.Encoder BASE64_ENCODER = Base64.getEncoder(); private static final Base64.Decoder BASE64_DECODER = Base64.getDecoder(); /** Similar to {@link StringSerializer} */ public static int writeAsciiString(byte[] array, int offset, String value) {<FILL_FUNCTION_BODY>} public static String readAsciiString(byte[] array, int offset) { StringBuilder sb = new StringBuilder(); int c; do { c = 0xFF & array[offset++]; if (c != 0x80) { sb.append((char) (c & 0x7F)); } } while ((c & 0x80) <= 0); return sb.toString(); } public static int getAsciiByteLength(String value) { E.checkArgument(CharMatcher.ascii().matchesAllOf(value), "'%s' must be ASCII string", value); return value.isEmpty() ? 1 : value.length(); } public static byte[] encode(String value) { return value.getBytes(StandardCharsets.UTF_8); } public static String decode(byte[] bytes) { if (bytes.length == 0) { return STRING_EMPTY; } return new String(bytes, StandardCharsets.UTF_8); } public static String decode(byte[] bytes, int offset, int length) { if (length == 0) { return STRING_EMPTY; } return new String(bytes, offset, length, StandardCharsets.UTF_8); } public static String encodeBase64(byte[] bytes) { return BASE64_ENCODER.encodeToString(bytes); } public static byte[] decodeBase64(String value) { if (value.isEmpty()) { return BYTES_EMPTY; } return BASE64_DECODER.decode(value); } public static byte[] compress(String value) { return compress(value, LZ4Util.DEFAULT_BUFFER_RATIO); } public static byte[] compress(String value, float bufferRatio) { BytesBuffer buf = LZ4Util.compress(encode(value), BLOCK_SIZE, bufferRatio); return buf.bytes(); } public static String decompress(byte[] value) { return decompress(value, LZ4Util.DEFAULT_BUFFER_RATIO); } public static String decompress(byte[] value, float bufferRatio) { BytesBuffer buf = LZ4Util.decompress(value, BLOCK_SIZE, bufferRatio); return decode(buf.array(), 0, buf.position()); } public static String hashPassword(String password) { return BCrypt.hashpw(password, BCrypt.gensalt(4)); } public static boolean checkPassword(String candidatePassword, String dbPassword) { return BCrypt.checkpw(candidatePassword, dbPassword); } public static String sha256(String string) { byte[] stringBytes = encode(string); DIGEST.reset(); return StringEncoding.encodeBase64(DIGEST.digest(stringBytes)); } public static String format(byte[] bytes) { return String.format("%s[0x%s]", decode(bytes), Bytes.toHex(bytes)); } public static UUID uuid(String value) { E.checkArgument(value != null, "The UUID can't be null"); try { if (value.contains("-") && value.length() == 36) { return UUID.fromString(value); } // UUID represented by hex string E.checkArgument(value.length() == 32, "Invalid UUID string: %s", value); String high = value.substring(0, 16); String low = value.substring(16); return new UUID(Long.parseUnsignedLong(high, 16), Long.parseUnsignedLong(low, 16)); } catch (NumberFormatException ignored) { throw new IllegalArgumentException("Invalid UUID string: " + value); } } }
E.checkArgument(CharMatcher.ascii().matchesAllOf(value), "'%s' must be ASCII string", value); int len = value.length(); if (len == 0) { array[offset++] = (byte) 0x80; return offset; } int i = 0; do { int c = value.charAt(i); assert c <= 127; byte b = (byte) c; if (++i == len) { // End marker b |= 0x80; } array[offset++] = b; } while (i < len); return offset;
1,259
178
1,437
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/util/collection/CollectionFactory.java
CollectionFactory
newMap
class CollectionFactory { private final CollectionType type; public CollectionFactory() { this.type = CollectionType.EC; } public CollectionFactory(CollectionType type) { this.type = type; } public <V> List<V> newList() { return newList(this.type); } public <V> List<V> newList(int initialCapacity) { return newList(this.type, initialCapacity); } public <V> List<V> newList(Collection<V> collection) { return newList(this.type, collection); } public static <V> List<V> newList(CollectionType type) { switch (type) { case EC: return new FastList<>(); case JCF: return new ArrayList<>(); case FU: return new ObjectArrayList<>(); default: throw new AssertionError( "Unsupported collection type: " + type); } } public static <V> List<V> newList(CollectionType type, int initialCapacity) { switch (type) { case EC: return new FastList<>(initialCapacity); case JCF: return new ArrayList<>(initialCapacity); case FU: return new ObjectArrayList<>(initialCapacity); default: throw new AssertionError( "Unsupported collection type: " + type); } } public static <V> List<V> newList(CollectionType type, Collection<V> collection) { switch (type) { case EC: return new FastList<>(collection); case JCF: return new ArrayList<>(collection); case FU: return new ObjectArrayList<>(collection); default: throw new AssertionError( "Unsupported collection type: " + type); } } public <V> Set<V> newSet() { return newSet(this.type); } public <V> Set<V> newSet(int initialCapacity) { return newSet(this.type, initialCapacity); } public <V> Set<V> newSet(Collection<V> collection) { return newSet(this.type, collection); } public static <V> Set<V> newSet(CollectionType type) { switch (type) { case EC: return new UnifiedSet<>(); case JCF: return new HashSet<>(); case FU: return new ObjectOpenHashSet<>(); default: throw new AssertionError( "Unsupported collection type: " + type); } } public static <V> Set<V> newSet(CollectionType type, int initialCapacity) { switch (type) { case EC: return new UnifiedSet<>(initialCapacity); case JCF: return new HashSet<>(initialCapacity); case FU: return new ObjectOpenHashSet<>(initialCapacity); default: throw new AssertionError( "Unsupported collection type: " + type); } } public static <V> Set<V> newSet(CollectionType type, Collection<V> collection) { switch (type) { case EC: return new UnifiedSet<>(collection); case JCF: return new HashSet<>(collection); case FU: return new ObjectOpenHashSet<>(collection); default: throw new AssertionError( "Unsupported collection type: " + type); } } public <K, V> Map<K, V> newMap() { return newMap(this.type); } public <K, V> Map<K, V> newMap(int initialCapacity) { return newMap(this.type, initialCapacity); } public <K, V> Map<K, V> newMap(Map<? extends K, ? extends V> map) { return newMap(this.type, map); } public static <K, V> Map<K, V> newMap(CollectionType type) { /* * EC is faster 10%-20% than JCF, and it's more stable & less * memory cost(size is bigger, EC is better). */ switch (type) { case EC: return new UnifiedMap<>(); case JCF: return new HashMap<>(); case FU: return new Object2ObjectOpenHashMap<>(); default: throw new AssertionError( "Unsupported collection type: " + type); } } public static <K, V> Map<K, V> newMap(CollectionType type, int initialCapacity) { switch (type) { case EC: return new UnifiedMap<>(initialCapacity); case JCF: return new HashMap<>(initialCapacity); case FU: return new Object2ObjectOpenHashMap<>(initialCapacity); default: throw new AssertionError( "Unsupported collection type: " + type); } } public static <K, V> Map<K, V> newMap(CollectionType type, Map<? extends K, ? extends V> map) {<FILL_FUNCTION_BODY>} public static <V> MutableIntObjectMap<V> newIntObjectMap() { return new IntObjectHashMap<>(); } public static <V> MutableIntObjectMap<V> newIntObjectMap( int initialCapacity) { return new IntObjectHashMap<>(initialCapacity); } public static <V> MutableIntObjectMap<V> newIntObjectMap( IntObjectMap<? extends V> map) { return new IntObjectHashMap<>(map); } @SuppressWarnings("unchecked") public static <V> MutableIntObjectMap<V> newIntObjectMap( Object... objects) { IntObjectHashMap<V> map = IntObjectHashMap.newMap(); E.checkArgument(objects.length % 2 == 0, "Must provide even arguments for " + "CollectionFactory.newIntObjectMap"); for (int i = 0; i < objects.length; i += 2) { int key = objects[i] instanceof Id ? (int) ((Id) objects[i]).asLong() : (int) objects[i]; map.put(key, (V) objects[i + 1]); } return map; } public IdSet newIdSet() { return newIdSet(this.type); } public static IdSet newIdSet(CollectionType type) { return new IdSet(type); } public static IntSet newIntSet() { /* * Resume to the old version like this: * return concurrent ? new IntHashSet().asSynchronized() : * new IntHashSet(); */ return new IntSet.IntSetBySegments(Integer.MAX_VALUE); } public static IntMap newIntMap() { /* * Resume to the old version like this: * return concurrent ? new IntIntHashMap().asSynchronized() : * new IntIntHashMap(); */ return new IntMap.IntMapBySegments(Integer.MAX_VALUE); } }
switch (type) { case EC: return new UnifiedMap<>(map); case JCF: return new HashMap<>(map); case FU: return new Object2ObjectOpenHashMap<>(map); default: throw new AssertionError( "Unsupported collection type: " + type); }
1,894
89
1,983
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/util/collection/IdSet.java
IdSet
remove
class IdSet extends AbstractSet<Id> { private final LongHashSet numberIds; private final Set<Id> nonNumberIds; public IdSet(CollectionType type) { this.numberIds = new LongHashSet(); this.nonNumberIds = CollectionFactory.newSet(type); } @Override public int size() { return this.numberIds.size() + this.nonNumberIds.size(); } @Override public boolean isEmpty() { return this.numberIds.isEmpty() && this.nonNumberIds.isEmpty(); } @Override public boolean contains(Object object) { if (!(object instanceof Id)) { return false; } Id id = (Id) object; if (id.type() == Id.IdType.LONG) { return this.numberIds.contains(id.asLong()); } else { return this.nonNumberIds.contains(id); } } @Override public Iterator<Id> iterator() { return new ExtendableIterator<>( this.nonNumberIds.iterator(), new EcLongIdIterator(this.numberIds.longIterator())); } @Override public boolean add(Id id) { if (id.type() == Id.IdType.LONG) { return this.numberIds.add(id.asLong()); } else { return this.nonNumberIds.add(id); } } public boolean remove(Id id) {<FILL_FUNCTION_BODY>} @Override public void clear() { this.numberIds.clear(); this.nonNumberIds.clear(); } private static class EcLongIdIterator implements Iterator<Id> { private final MutableLongIterator iterator; public EcLongIdIterator(MutableLongIterator iter) { this.iterator = iter; } @Override public boolean hasNext() { return this.iterator.hasNext(); } @Override public Id next() { return IdGenerator.of(this.iterator.next()); } @Override public void remove() { this.iterator.remove(); } } }
if (id.type() == Id.IdType.LONG) { return this.numberIds.remove(id.asLong()); } else { return this.nonNumberIds.remove(id); }
573
57
630
<methods>public boolean equals(java.lang.Object) ,public int hashCode() ,public boolean removeAll(Collection<?>) <variables>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/util/collection/Int2IntsMap.java
Int2IntsMap
add
class Int2IntsMap { private static final int INIT_KEY_CAPACITY = 16; private static final int CHUNK_SIZE = 10; private static final int EXPANSION_FACTOR = 2; private static final int OFFSET_NEXT_FREE = 0; private static final int OFFSET_SIZE = 1; private static final int OFFSET_FIRST_CHUNK_DATA = 2; /* * chunkMap chunkTable * * -------- --------------- * | 1 | 0 |--------->0 | 33 | nextFree (free entry pointer) * | 2 | 10 |-----+ 1 | 19 | size (values count of key) * | 3 | 40 |---+ | 2 | int data | * | . | . | | | 3 | int data | * | x | y | | | . | ... | point to nextFreeChunk * -------- | | 9 | 20 |-----------------+ * | | --------------- | * | +-->10 | 13 | nextFree | * | 11 | 1 | size | * | 12 | int data | | * | 13 | 0 | | * | . | ... | | * | 19 | 0 | | * | --------------- | * | 20 | int data |<----------------+ * | 21 | int data | * | 22 | int data | * | 23 | int data | * | . | ... | point to nextFreeChunk * | 29 | 30 |-----------------+ * | --------------- | * | 30 | int data |<----------------+ * | 31 | int data | * | 32 | int data | * | 33 | 0 | * | . | ... | * | 39 | 0 | * | --------------- * +---->40 | 48 | nextFree * 41 | 6 | size * 42 | int data | * 43 | int data | * . | ... | * 47 | int data | * 48 | 0 | * 49 | 0 | * --------------- * 50 | ... | * | ... | * | ... | * | ... | */ private final IntIntHashMap chunkMap; private int[] chunkTable; private int nextFreeChunk; public Int2IntsMap() { this.chunkMap = new IntIntHashMap(INIT_KEY_CAPACITY); this.chunkTable = new int[INIT_KEY_CAPACITY * CHUNK_SIZE]; this.nextFreeChunk = 0; } public void add(int key, int value) {<FILL_FUNCTION_BODY>} public boolean containsKey(int key) { return this.chunkMap.containsKey(key); } public int[] getValues(int key) { int firstChunk = this.chunkMap.getIfAbsent(key, -1); if (firstChunk == -1) { return org.apache.hugegraph.util.collection.IntIterator.EMPTY_INTS; } int size = this.chunkTable[firstChunk + OFFSET_SIZE]; int[] values = new int[size]; int position = firstChunk + OFFSET_FIRST_CHUNK_DATA; int i = 0; while (i < size) { if (!this.endOfChunk(position)) { values[i++] = this.chunkTable[position++]; } else { position = this.chunkTable[position]; } } return values; } public IntIterator keys() { return this.chunkMap.keySet().intIterator(); } public int size() { return this.chunkMap.size(); } @Override public String toString() { int capacity = (this.size() + 1) * 64; StringBuilder sb = new StringBuilder(capacity); sb.append("{"); for (IntIterator iter = this.keys(); iter.hasNext(); ) { if (sb.length() > 1) { sb.append(", "); } int key = iter.next(); sb.append(key).append(": ["); int[] values = this.getValues(key); for (int i = 0; i < values.length; i++) { if (i > 0) { sb.append(", "); } sb.append(values[i]); } sb.append("]"); } sb.append("}"); return sb.toString(); } private boolean endOfChunk(int position) { // The last entry of chunk is next chunk pointer return (position + 1) % CHUNK_SIZE == 0; } private void ensureCapacity() { if (this.nextFreeChunk >= this.chunkTable.length) { this.expand(); } } private void expand() { int currentSize = this.chunkTable.length; int[] newTable = new int[currentSize * EXPANSION_FACTOR]; System.arraycopy(this.chunkTable, 0, newTable, 0, currentSize); this.chunkTable = newTable; } }
if (this.chunkMap.containsKey(key)) { int firstChunk = this.chunkMap.get(key); /* * The nextFree represent the position where the next element * will be located. */ int nextFree = this.chunkTable[firstChunk + OFFSET_NEXT_FREE]; if (!this.endOfChunk(nextFree)) { this.chunkTable[nextFree] = value; this.chunkTable[firstChunk + OFFSET_NEXT_FREE]++; } else { /* * If the nextFree points to the end of last chunk, * allocate a new chunk and let the nextFree point to * the start of new allocated chunk. */ this.ensureCapacity(); int lastEntryOfChunk = nextFree; this.chunkTable[lastEntryOfChunk] = this.nextFreeChunk; nextFree = this.nextFreeChunk; this.chunkTable[nextFree] = value; this.chunkTable[firstChunk + OFFSET_NEXT_FREE] = nextFree + 1; // Update next block this.nextFreeChunk += CHUNK_SIZE; } this.chunkTable[firstChunk + OFFSET_SIZE]++; } else { // New key, allocate 1st chunk and init this.ensureCapacity(); // Allocate 1st chunk this.chunkMap.put(key, this.nextFreeChunk); // Init first chunk int firstChunk = this.nextFreeChunk; int nextFree = firstChunk + OFFSET_FIRST_CHUNK_DATA; this.chunkTable[firstChunk + OFFSET_NEXT_FREE] = nextFree + 1; this.chunkTable[firstChunk + OFFSET_SIZE] = 1; this.chunkTable[nextFree] = value; // Update next block this.nextFreeChunk += CHUNK_SIZE; }
1,491
517
2,008
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/util/collection/ObjectIntMappingFactory.java
SingleThreadObjectIntMapping
object2Code
class SingleThreadObjectIntMapping<V> implements ObjectIntMapping<V> { private static final int MAGIC = 1 << 16; private static final int MAX_OFFSET = 10; private final IntObjectHashMap<V> int2IdMap; public SingleThreadObjectIntMapping() { this.int2IdMap = new IntObjectHashMap<>(); } @Watched @SuppressWarnings("unchecked") @Override public int object2Code(Object object) {<FILL_FUNCTION_BODY>} @Watched @Override public V code2Object(int code) { assert code > 0; return this.int2IdMap.get(code); } @Override public void clear() { this.int2IdMap.clear(); } @Override public String toString() { return this.int2IdMap.toString(); } }
int code = object.hashCode(); // TODO: improve hash algorithm for (int i = 1; i > 0; i <<= 1) { for (int j = 0; j < MAX_OFFSET; j++) { if (code <= 0) { if (code == 0) { code = 1; } else { code = -code; } } assert code > 0; V existed = this.int2IdMap.get(code); if (existed == null) { this.int2IdMap.put(code, (V) object); return code; } if (existed.equals(object)) { return code; } code = code + i + j; /* * If i < MAGIC, try (i * 2) to reduce conflicts, otherwise * try (i + 1), (i + 2), ..., (i + 10) to try more times * before try (i * 2). */ if (i < MAGIC) { break; } } } throw new HugeException("Failed to get code for object: %s", object);
248
300
548
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/version/CoreVersion.java
CoreVersion
check
class CoreVersion { public static final String NAME = "hugegraph-core"; public static final String DEFAULT_VERSION = "1.3.0"; /** * The second parameter of Version.of() is for IDE running without JAR */ public static final Version VERSION = Version.of(CoreVersion.class, DEFAULT_VERSION); /** * Update it when the gremlin version changed, search "tinkerpop.version" in pom */ public static final String GREMLIN_VERSION = "3.5.1"; static { // Check versions of the dependency packages CoreVersion.check(); } public static void check() {<FILL_FUNCTION_BODY>} }
// Check the version of hugegraph-common VersionUtil.check(CommonVersion.VERSION, "1.0", "1.55", CommonVersion.NAME);
182
42
224
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-dist/src/main/java/org/apache/hugegraph/cmd/ConfDumper.java
ConfDumper
writeOption
class ConfDumper { public static final String EOL = System.getProperty("line.separator"); private static final Logger LOG = Log.logger(ConfDumper.class); public static void main(String[] args) throws ConfigurationException, IOException { E.checkArgument(args.length == 1, "ConfDumper need a config file."); String input = args[0]; File output = new File(input + ".default"); LOG.info("Input config: {}", input); LOG.info("Output config: {}", output.getPath()); RegisterUtil.registerBackends(); RegisterUtil.registerServer(); HugeConfig config = new HugeConfig(input); for (String name : new TreeSet<>(OptionSpace.keys())) { TypedOption<?, ?> option = OptionSpace.get(name); writeOption(output, option, config.get(option)); } } private static void writeOption(File output, TypedOption<?, ?> option, Object value) throws IOException {<FILL_FUNCTION_BODY>} }
StringBuilder sb = new StringBuilder(); sb.append("# ").append(option.desc()).append(EOL); sb.append(option.name()).append("=").append(value).append(EOL); sb.append(EOL); // Write to output file FileUtils.write(output, sb.toString(), true);
277
86
363
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-dist/src/main/java/org/apache/hugegraph/cmd/InitStore.java
InitStore
initGraph
class InitStore { private static final Logger LOG = Log.logger(InitStore.class); // 6~8 retries may be needed under high load for Cassandra backend private static final int RETRIES = 10; // Less than 5000 may cause mismatch exception with Cassandra backend private static final long RETRY_INTERVAL = 5000; private static final MultiValueMap EXCEPTIONS = new MultiValueMap(); static { EXCEPTIONS.put("OperationTimedOutException", "Timed out waiting for server response"); EXCEPTIONS.put("NoHostAvailableException", "All host(s) tried for query failed"); EXCEPTIONS.put("InvalidQueryException", "does not exist"); EXCEPTIONS.put("InvalidQueryException", "unconfigured table"); } public static void main(String[] args) throws Exception { E.checkArgument(args.length == 1, "HugeGraph init-store need to pass the config file " + "of RestServer, like: conf/rest-server.properties"); E.checkArgument(args[0].endsWith(".properties"), "Expect the parameter is properties config file."); String restConf = args[0]; RegisterUtil.registerBackends(); RegisterUtil.registerPlugins(); RegisterUtil.registerServer(); HugeConfig restServerConfig = new HugeConfig(restConf); String graphsDir = restServerConfig.get(ServerOptions.GRAPHS); Map<String, String> graph2ConfigPaths = ConfigUtil.scanGraphsDir(graphsDir); List<HugeGraph> graphs = new ArrayList<>(graph2ConfigPaths.size()); try { for (Map.Entry<String, String> entry : graph2ConfigPaths.entrySet()) { graphs.add(initGraph(entry.getValue())); } StandardAuthenticator.initAdminUserIfNeeded(restConf); } finally { for (HugeGraph graph : graphs) { graph.close(); } HugeFactory.shutdown(30L, true); } } private static HugeGraph initGraph(String configPath) throws Exception {<FILL_FUNCTION_BODY>} private static void initBackend(final HugeGraph graph) throws InterruptedException { int retries = RETRIES; retry: do { try { graph.initBackend(); } catch (Exception e) { String clz = e.getClass().getSimpleName(); String message = e.getMessage(); if (EXCEPTIONS.containsKey(clz) && retries > 0) { @SuppressWarnings("unchecked") Collection<String> keywords = EXCEPTIONS.getCollection(clz); for (String keyword : keywords) { if (message.contains(keyword)) { LOG.info("Init failed with exception '{} : {}', " + "retry {}...", clz, message, RETRIES - retries + 1); Thread.sleep(RETRY_INTERVAL); continue retry; } } } throw e; } break; } while (retries-- > 0); } }
LOG.info("Init graph with config file: {}", configPath); HugeConfig config = new HugeConfig(configPath); // Forced set RAFT_MODE to false when initializing backend config.setProperty(CoreOptions.RAFT_MODE.name(), "false"); HugeGraph graph = (HugeGraph) GraphFactory.open(config); try { BackendStoreInfo backendStoreInfo = graph.backendStoreInfo(); if (backendStoreInfo.exists()) { backendStoreInfo.checkVersion(); /* * Init the required information for creating the admin account * (when switch from non-auth mode to auth mode) */ graph.initSystemInfo(); LOG.info("Skip init-store due to the backend store of '{}' " + "had been initialized", graph.name()); } else { initBackend(graph); } } catch (Throwable e) { graph.close(); throw e; } return graph;
820
251
1,071
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-dist/src/main/java/org/apache/hugegraph/cmd/StoreDumper.java
StoreDumper
dump
class StoreDumper { private final HugeGraph graph; private static final Logger LOG = Log.logger(StoreDumper.class); public StoreDumper(String conf) { this.graph = HugeFactory.open(conf); } public void dump(HugeType table, long offset, long limit) {<FILL_FUNCTION_BODY>} private BackendStore backendStore(HugeType table) { String m = table.isSchema() ? "schemaTransaction" : "graphTransaction"; Object tx = Whitebox.invoke(this, "graph", m); return Whitebox.invoke(tx.getClass(), "store", tx); } public void close() throws Exception { this.graph.close(); } public static void main(String[] args) throws Exception { E.checkArgument(args.length >= 1, "StoreDumper need a config file."); String conf = args[0]; RegisterUtil.registerBackends(); HugeType table = HugeType.valueOf(arg(args, 1, "VERTEX").toUpperCase()); long offset = Long.parseLong(arg(args, 2, "0")); long limit = Long.parseLong(arg(args, 3, "20")); StoreDumper dumper = new StoreDumper(conf); dumper.dump(table, offset, limit); dumper.close(); // Stop daemon thread HugeFactory.shutdown(30L, true); } private static String arg(String[] args, int index, String deflt) { if (index < args.length) { return args[index]; } return deflt; } }
BackendStore store = this.backendStore(table); Query query = new Query(table); Iterator<BackendEntry> rs = store.query(query); for (long i = 0; i < offset && rs.hasNext(); i++) { rs.next(); } LOG.info("Dump table {} (offset {} limit {}):", table, offset, limit); for (long i = 0; i < limit && rs.hasNext(); i++) { BackendEntry entry = rs.next(); LOG.info("{}", entry); } CloseableIterator.closeIterator(rs);
436
166
602
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-dist/src/main/java/org/apache/hugegraph/dist/DistOptions.java
DistOptions
instance
class DistOptions extends OptionHolder { private DistOptions() { super(); } private static volatile DistOptions instance; public static synchronized DistOptions instance() {<FILL_FUNCTION_BODY>} public static final ConfigListOption<String> BACKENDS = new ConfigListOption<>( "backends", "The all data store type.", disallowEmpty(), "memory" ); }
if (instance == null) { instance = new DistOptions(); instance.registerOptions(); } return instance;
113
35
148
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-dist/src/main/java/org/apache/hugegraph/dist/HugeGraphServer.java
HugeGraphServer
main
class HugeGraphServer { private static final Logger LOG = Log.logger(HugeGraphServer.class); private final RestServer restServer; private final GremlinServer gremlinServer; public static void register() { RegisterUtil.registerBackends(); RegisterUtil.registerPlugins(); RegisterUtil.registerServer(); } public HugeGraphServer(String gremlinServerConf, String restServerConf) throws Exception { // Only switch on security manager after HugeGremlinServer started SecurityManager securityManager = System.getSecurityManager(); System.setSecurityManager(null); ConfigUtil.checkGremlinConfig(gremlinServerConf); HugeConfig restServerConfig = new HugeConfig(restServerConf); String graphsDir = restServerConfig.get(ServerOptions.GRAPHS); EventHub hub = new EventHub("gremlin=>hub<=rest"); try { // Start HugeRestServer this.restServer = HugeRestServer.start(restServerConf, hub); } catch (Throwable e) { LOG.error("HugeRestServer start error: ", e); throw e; } try { // Start GremlinServer this.gremlinServer = HugeGremlinServer.start(gremlinServerConf, graphsDir, hub); } catch (Throwable e) { LOG.error("HugeGremlinServer start error: ", e); try { this.restServer.shutdown().get(); } catch (Throwable t) { LOG.error("HugeRestServer stop error: ", t); } throw e; } finally { System.setSecurityManager(securityManager); } } public void stop() { try { this.gremlinServer.stop().get(); LOG.info("HugeGremlinServer stopped"); } catch (Throwable e) { LOG.error("HugeGremlinServer stop error: ", e); } try { this.restServer.shutdown().get(); LOG.info("HugeRestServer stopped"); } catch (Throwable e) { LOG.error("HugeRestServer stop error: ", e); } try { HugeFactory.shutdown(30L); LOG.info("HugeGraph stopped"); } catch (Throwable e) { LOG.error("Failed to stop HugeGraph: ", e); } } public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>} }
if (args.length != 2) { String msg = "Start HugeGraphServer need to pass 2 parameters, " + "they are the config files of GremlinServer and " + "RestServer, for example: conf/gremlin-server.yaml " + "conf/rest-server.properties"; LOG.error(msg); throw new HugeException(msg); } HugeGraphServer.register(); HugeGraphServer server; try { server = new HugeGraphServer(args[0], args[1]); } catch (Throwable e) { HugeFactory.shutdown(30L, true); throw e; } /* * Remove HugeFactory.shutdown and let HugeGraphServer.stop() do it. * NOTE: HugeFactory.shutdown hook may be invoked before server stop, * causes event-hub can't execute notification events for another * shutdown executor such as gremlin-stop-shutdown */ HugeFactory.removeShutdownHook(); CompletableFuture<?> serverStopped = new CompletableFuture<>(); Runtime.getRuntime().addShutdownHook(new Thread(() -> { LOG.info("HugeGraphServer stopping"); server.stop(); LOG.info("HugeGraphServer stopped"); LogManager.shutdown(); serverStopped.complete(null); }, "hugegraph-server-shutdown")); // Wait for server-shutdown and server-stopped serverStopped.get();
666
392
1,058
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-dist/src/main/java/org/apache/hugegraph/dist/HugeGremlinServer.java
HugeGremlinServer
start
class HugeGremlinServer { private static final Logger LOG = Log.logger(HugeGremlinServer.class); public static GremlinServer start(String conf, String graphsDir, EventHub hub) throws Exception {<FILL_FUNCTION_BODY>} }
// Start GremlinServer with inject traversal source LOG.info(GremlinServer.getHeader()); final Settings settings; try { settings = Settings.read(conf); } catch (Exception e) { LOG.error("Can't found the configuration file at '{}' or " + "being parsed properly. [{}]", conf, e.getMessage()); throw e; } // Scan graph confs and inject into gremlin server context E.checkState(settings.graphs != null, "The GremlinServer's settings.graphs is null"); settings.graphs.putAll(ConfigUtil.scanGraphsDir(graphsDir)); LOG.info("Configuring Gremlin Server from {}", conf); ContextGremlinServer server = new ContextGremlinServer(settings, hub); // Inject customized traversal source server.injectTraversalSource(); server.start().exceptionally(t -> { LOG.error("Gremlin Server was unable to start and will " + "shutdown now: {}", t.getMessage()); server.stop().join(); throw new HugeException("Failed to start Gremlin Server"); }).join(); return server;
75
319
394
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-dist/src/main/java/org/apache/hugegraph/dist/RegisterUtil.java
RegisterUtil
registerMysql
class RegisterUtil { private static final Logger LOG = Log.logger(RegisterUtil.class); static { OptionSpace.register("core", CoreOptions.instance()); OptionSpace.register("dist", DistOptions.instance()); OptionSpace.register("masterElection", RoleElectionOptions.instance()); } public static void registerBackends() { String confFile = "/backend.properties"; URL input = RegisterUtil.class.getResource(confFile); E.checkState(input != null, "Can't read file '%s' as stream", confFile); PropertiesConfiguration props; try { props = new Configurations().properties(input); } catch (ConfigurationException e) { throw new HugeException("Can't load config file: %s", e, confFile); } HugeConfig config = new HugeConfig(props); List<String> backends = config.get(DistOptions.BACKENDS); for (String backend : backends) { registerBackend(backend); } } private static void registerBackend(String backend) { switch (backend) { case "cassandra": registerCassandra(); break; case "scylladb": registerScyllaDB(); break; case "hbase": registerHBase(); break; case "rocksdb": registerRocksDB(); break; case "mysql": registerMysql(); break; case "palo": registerPalo(); break; case "postgresql": registerPostgresql(); break; default: throw new HugeException("Unsupported backend type '%s'", backend); } } public static void registerCassandra() { // Register config OptionSpace.register("cassandra", "org.apache.hugegraph.backend.store.cassandra.CassandraOptions"); // Register serializer SerializerFactory.register("cassandra", "org.apache.hugegraph.backend.store.cassandra" + ".CassandraSerializer"); // Register backend BackendProviderFactory.register("cassandra", "org.apache.hugegraph.backend.store.cassandra" + ".CassandraStoreProvider"); } public static void registerScyllaDB() { // Register config OptionSpace.register("scylladb", "org.apache.hugegraph.backend.store.cassandra.CassandraOptions"); // Register serializer SerializerFactory.register("scylladb", "org.apache.hugegraph.backend.store.cassandra" + ".CassandraSerializer"); // Register backend BackendProviderFactory.register("scylladb", "org.apache.hugegraph.backend.store.scylladb" + ".ScyllaDBStoreProvider"); } public static void registerHBase() { // Register config OptionSpace.register("hbase", "org.apache.hugegraph.backend.store.hbase.HbaseOptions"); // Register serializer SerializerFactory.register("hbase", "org.apache.hugegraph.backend.store.hbase.HbaseSerializer"); // Register backend BackendProviderFactory.register("hbase", "org.apache.hugegraph.backend.store.hbase" + ".HbaseStoreProvider"); } public static void registerRocksDB() { // Register config OptionSpace.register("rocksdb", "org.apache.hugegraph.backend.store.rocksdb.RocksDBOptions"); // Register backend BackendProviderFactory.register("rocksdb", "org.apache.hugegraph.backend.store.rocksdb" + ".RocksDBStoreProvider"); BackendProviderFactory.register("rocksdbsst", "org.apache.hugegraph.backend.store.rocksdbsst" + ".RocksDBSstStoreProvider"); } public static void registerMysql() {<FILL_FUNCTION_BODY>} public static void registerPalo() { // Register config OptionSpace.register("palo", "org.apache.hugegraph.backend.store.palo.PaloOptions"); // Register serializer SerializerFactory.register("palo", "org.apache.hugegraph.backend.store.palo.PaloSerializer"); // Register backend BackendProviderFactory.register("palo", "org.apache.hugegraph.backend.store.palo" + ".PaloStoreProvider"); } public static void registerPostgresql() { // Register config OptionSpace.register("postgresql", "org.apache.hugegraph.backend.store.postgresql.PostgresqlOptions"); // Register serializer SerializerFactory.register("postgresql", "org.apache.hugegraph.backend.store.postgresql" + ".PostgresqlSerializer"); // Register backend BackendProviderFactory.register("postgresql", "org.apache.hugegraph.backend.store.postgresql" + ".PostgresqlStoreProvider"); } public static void registerServer() { // Register ServerOptions (rest-server) OptionSpace.register("server", "org.apache.hugegraph.config.ServerOptions"); // Register RpcOptions (rpc-server) OptionSpace.register("rpc", "org.apache.hugegraph.config.RpcOptions"); // Register AuthOptions (auth-server) OptionSpace.register("auth", "org.apache.hugegraph.config.AuthOptions"); } /** * Scan the jars in plugins directory and load them */ public static void registerPlugins() { ServiceLoader<HugeGraphPlugin> plugins = ServiceLoader.load(HugeGraphPlugin.class); for (HugeGraphPlugin plugin : plugins) { LOG.info("Loading plugin {}({})", plugin.name(), plugin.getClass().getCanonicalName()); String minVersion = plugin.supportsMinVersion(); String maxVersion = plugin.supportsMaxVersion(); if (!VersionUtil.match(CoreVersion.VERSION, minVersion, maxVersion)) { LOG.warn("Skip loading plugin '{}' due to the version range " + "'[{}, {})' that it's supported doesn't cover " + "current core version '{}'", plugin.name(), minVersion, maxVersion, CoreVersion.VERSION.get()); continue; } try { plugin.register(); LOG.info("Loaded plugin '{}'", plugin.name()); } catch (Exception e) { throw new HugeException("Failed to load plugin '%s'", plugin.name(), e); } } } }
// Register config OptionSpace.register("mysql", "org.apache.hugegraph.backend.store.mysql.MysqlOptions"); // Register serializer SerializerFactory.register("mysql", "org.apache.hugegraph.backend.store.mysql.MysqlSerializer"); // Register backend BackendProviderFactory.register("mysql", "org.apache.hugegraph.backend.store.mysql" + ".MysqlStoreProvider");
1,758
123
1,881
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-example/src/main/java/org/apache/hugegraph/example/Example3.java
Example3
loadNeighborRankData
class Example3 { private static final Logger LOG = Log.logger(Example3.class); public static void main(String[] args) throws Exception { LOG.info("Example3 start!"); HugeGraph graph = ExampleUtil.loadGraph(); Example3.loadNeighborRankData(graph); Example3.loadPersonalRankData(graph); graph.close(); HugeFactory.shutdown(30L); } public static void loadNeighborRankData(final HugeGraph graph) {<FILL_FUNCTION_BODY>} public static void loadPersonalRankData(final HugeGraph graph) { SchemaManager schema = graph.schema(); schema.propertyKey("name").asText().ifNotExist().create(); schema.vertexLabel("person") .properties("name") .useCustomizeStringId() .ifNotExist() .create(); schema.vertexLabel("movie") .properties("name") .useCustomizeStringId() .ifNotExist() .create(); schema.edgeLabel("like") .sourceLabel("person") .targetLabel("movie") .ifNotExist() .create(); graph.tx().open(); Vertex aPerson = graph.addVertex(T.label, "person", T.id, "A", "name", "A"); Vertex bPerson = graph.addVertex(T.label, "person", T.id, "B", "name", "B"); Vertex cPerson = graph.addVertex(T.label, "person", T.id, "C", "name", "C"); Vertex a = graph.addVertex(T.label, "movie", T.id, "a", "name", "a"); Vertex b = graph.addVertex(T.label, "movie", T.id, "b", "name", "b"); Vertex c = graph.addVertex(T.label, "movie", T.id, "c", "name", "c"); Vertex d = graph.addVertex(T.label, "movie", T.id, "d", "name", "d"); aPerson.addEdge("like", a); aPerson.addEdge("like", c); bPerson.addEdge("like", a); bPerson.addEdge("like", b); bPerson.addEdge("like", c); bPerson.addEdge("like", d); cPerson.addEdge("like", c); cPerson.addEdge("like", d); graph.tx().commit(); } }
SchemaManager schema = graph.schema(); schema.propertyKey("name").asText().ifNotExist().create(); schema.vertexLabel("person") .properties("name") .useCustomizeStringId() .ifNotExist() .create(); schema.vertexLabel("movie") .properties("name") .useCustomizeStringId() .ifNotExist() .create(); schema.edgeLabel("follow") .sourceLabel("person") .targetLabel("person") .ifNotExist() .create(); schema.edgeLabel("like") .sourceLabel("person") .targetLabel("movie") .ifNotExist() .create(); schema.edgeLabel("directedBy") .sourceLabel("movie") .targetLabel("person") .ifNotExist() .create(); graph.tx().open(); Vertex o = graph.addVertex(T.label, "person", T.id, "O", "name", "O"); Vertex a = graph.addVertex(T.label, "person", T.id, "A", "name", "A"); Vertex b = graph.addVertex(T.label, "person", T.id, "B", "name", "B"); Vertex c = graph.addVertex(T.label, "person", T.id, "C", "name", "C"); Vertex d = graph.addVertex(T.label, "person", T.id, "D", "name", "D"); Vertex e = graph.addVertex(T.label, "movie", T.id, "E", "name", "E"); Vertex f = graph.addVertex(T.label, "movie", T.id, "F", "name", "F"); Vertex g = graph.addVertex(T.label, "movie", T.id, "G", "name", "G"); Vertex h = graph.addVertex(T.label, "movie", T.id, "H", "name", "H"); Vertex i = graph.addVertex(T.label, "movie", T.id, "I", "name", "I"); Vertex j = graph.addVertex(T.label, "movie", T.id, "J", "name", "J"); Vertex k = graph.addVertex(T.label, "person", T.id, "K", "name", "K"); Vertex l = graph.addVertex(T.label, "person", T.id, "L", "name", "L"); Vertex m = graph.addVertex(T.label, "person", T.id, "M", "name", "M"); o.addEdge("follow", a); o.addEdge("follow", b); o.addEdge("follow", c); d.addEdge("follow", o); a.addEdge("follow", b); a.addEdge("like", e); a.addEdge("like", f); b.addEdge("like", g); b.addEdge("like", h); c.addEdge("like", i); c.addEdge("like", j); e.addEdge("directedBy", k); f.addEdge("directedBy", b); f.addEdge("directedBy", l); g.addEdge("directedBy", m); graph.tx().commit();
669
875
1,544
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-example/src/main/java/org/apache/hugegraph/example/ExampleUtil.java
ExampleUtil
waitAllTaskDone
class ExampleUtil { private static final Logger LOG = Log.logger(ExampleUtil.class); private static boolean registered = false; public static void registerPlugins() { if (registered) { return; } registered = true; RegisterUtil.registerCassandra(); RegisterUtil.registerScyllaDB(); RegisterUtil.registerHBase(); RegisterUtil.registerRocksDB(); RegisterUtil.registerMysql(); RegisterUtil.registerPalo(); } public static HugeGraph loadGraph() { return loadGraph(true, false); } public static HugeGraph loadGraph(boolean needClear, boolean needProfile) { if (needProfile) { profile(); } registerPlugins(); String conf = "hugegraph.properties"; try { String path = ExampleUtil.class.getClassLoader() .getResource(conf).getPath(); File file = new File(path); if (file.exists() && file.isFile()) { conf = path; } } catch (Exception ignored) { LOG.warn("loadGraph warn {} ", ignored); } HugeGraph graph = HugeFactory.open(conf); if (needClear) { graph.clearBackend(); } graph.initBackend(); graph.serverStarted(GlobalMasterInfo.master("server1")); return graph; } public static void profile() { try { PerfUtil.instance().profilePackage("org.apache.hugegraph"); } catch (Throwable e) { throw new RuntimeException(e); } } public static void waitAllTaskDone(HugeGraph graph) {<FILL_FUNCTION_BODY>} }
TaskScheduler scheduler = graph.taskScheduler(); Iterator<HugeTask<Object>> tasks = scheduler.tasks(null, -1L, null); while (tasks.hasNext()) { try { scheduler.waitUntilTaskCompleted(tasks.next().id(), 20L); } catch (TimeoutException e) { throw new HugeException("Failed to wait task done", e); } }
458
114
572
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-example/src/main/java/org/apache/hugegraph/example/PerfExample1.java
PerfExample1
testInsert
class PerfExample1 extends PerfExampleBase { public static void main(String[] args) throws Exception { PerfExample1 tester = new PerfExample1(); tester.test(args); // Stop daemon thread HugeFactory.shutdown(30L); } @Override protected void initSchema(SchemaManager schema) { schema.propertyKey("name").asText().ifNotExist().create(); schema.propertyKey("age").asInt().ifNotExist().create(); schema.propertyKey("lang").asText().ifNotExist().create(); schema.propertyKey("date").asText().ifNotExist().create(); schema.propertyKey("price").asInt().ifNotExist().create(); schema.vertexLabel("person") .properties("name", "age") .primaryKeys("name") .ifNotExist() .create(); schema.vertexLabel("software") .properties("name", "lang", "price") .primaryKeys("name") .ifNotExist() .create(); schema.edgeLabel("knows") .sourceLabel("person").targetLabel("person") .properties("date") .nullableKeys("date") .ifNotExist() .create(); schema.edgeLabel("created") .sourceLabel("person").targetLabel("software") .properties("date") .nullableKeys("date") .ifNotExist() .create(); } @Override protected void testInsert(GraphManager graph, int times, int multiple) {<FILL_FUNCTION_BODY>} }
List<Object> personIds = new ArrayList<>(PERSON_NUM * multiple); List<Object> softwareIds = new ArrayList<>(SOFTWARE_NUM * multiple); for (int time = 0; time < times; time++) { LOG.debug("============== random person vertex ==============="); for (int i = 0; i < PERSON_NUM * multiple; i++) { Random random = new Random(); int age = random.nextInt(70); String name = "P" + random.nextInt(); Vertex vertex = graph.addVertex(T.label, "person", "name", name, "age", age); personIds.add(vertex.id()); LOG.debug("Add person: {}", vertex); } LOG.debug("============== random software vertex ============"); for (int i = 0; i < SOFTWARE_NUM * multiple; i++) { Random random = new Random(); int price = random.nextInt(10000) + 1; String name = "S" + random.nextInt(); Vertex vertex = graph.addVertex(T.label, "software", "name", name, "lang", "java", "price", price); softwareIds.add(vertex.id()); LOG.debug("Add software: {}", vertex); } LOG.debug("========== random knows & created edges =========="); for (int i = 0; i < EDGE_NUM / 2 * multiple; i++) { Random random = new Random(); // Add edge: person --knows-> person Object p1 = personIds.get(random.nextInt(PERSON_NUM)); Object p2 = personIds.get(random.nextInt(PERSON_NUM)); graph.getVertex(p1).addEdge("knows", graph.getVertex(p2)); // Add edge: person --created-> software Object p3 = personIds.get(random.nextInt(PERSON_NUM)); Object s1 = softwareIds.get(random.nextInt(SOFTWARE_NUM)); graph.getVertex(p3).addEdge("created", graph.getVertex(s1)); } try { graph.tx().commit(); } catch (BackendException e) { if (e.getCause() instanceof NoHostAvailableException) { LOG.warn("Failed to commit tx: {}", e.getMessage()); } else { throw e; } } this.vertices.addAll(personIds); this.vertices.addAll(softwareIds); personIds.clear(); softwareIds.clear(); }
417
668
1,085
<methods>public non-sealed void <init>() ,public int test(java.lang.String[]) throws java.lang.Exception,public void testInsertPerf(org.apache.hugegraph.example.PerfExampleBase.GraphManager, int, int, int) throws java.lang.Exception,public void testQueryEdgePerf(org.apache.hugegraph.example.PerfExampleBase.GraphManager, int, int, int) throws java.lang.Exception,public void testQueryVertexPerf(org.apache.hugegraph.example.PerfExampleBase.GraphManager, int, int, int) throws java.lang.Exception<variables>public static final int EDGE_NUM,protected static final Logger LOG,public static final int PERSON_NUM,public static final int SOFTWARE_NUM,protected boolean profile,protected Set<java.lang.Object> vertices
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-example/src/main/java/org/apache/hugegraph/example/PerfExample2.java
PerfExample2
testInsert
class PerfExample2 extends PerfExampleBase { public static void main(String[] args) throws Exception { PerfExample2 tester = new PerfExample2(); tester.test(args); // Stop daemon thread HugeFactory.shutdown(30L); } @Override protected void initSchema(SchemaManager schema) { schema.propertyKey("name").asText().ifNotExist().create(); schema.vertexLabel("person") .useAutomaticId() .ifNotExist() .create(); schema.vertexLabel("software") .useAutomaticId() .ifNotExist() .create(); schema.edgeLabel("knows") .sourceLabel("person") .targetLabel("person") .ifNotExist() .create(); schema.edgeLabel("created") .sourceLabel("person") .targetLabel("software") .ifNotExist() .create(); } @Override protected void testInsert(GraphManager graph, int times, int multiple) {<FILL_FUNCTION_BODY>} }
List<Object> personIds = new ArrayList<>(PERSON_NUM * multiple); List<Object> softwareIds = new ArrayList<>(SOFTWARE_NUM * multiple); for (int time = 0; time < times; time++) { LOG.debug("============== random person vertex ==============="); for (int i = 0; i < PERSON_NUM * multiple; i++) { Vertex vertex = graph.addVertex(T.label, "person"); personIds.add(vertex.id()); LOG.debug("Add person: {}", vertex); } LOG.debug("============== random software vertex ============"); for (int i = 0; i < SOFTWARE_NUM * multiple; i++) { Vertex vertex = graph.addVertex(T.label, "software"); softwareIds.add(vertex.id()); LOG.debug("Add software: {}", vertex); } LOG.debug("========== random knows & created edges =========="); for (int i = 0; i < EDGE_NUM / 2 * multiple; i++) { Random random = new Random(); // Add edge: person --knows-> person Object p1 = personIds.get(random.nextInt(PERSON_NUM)); Object p2 = personIds.get(random.nextInt(PERSON_NUM)); graph.getVertex(p1).addEdge("knows", graph.getVertex(p2)); // Add edge: person --created-> software Object p3 = personIds.get(random.nextInt(PERSON_NUM)); Object s1 = softwareIds.get(random.nextInt(SOFTWARE_NUM)); graph.getVertex(p3).addEdge("created", graph.getVertex(s1)); } try { graph.tx().commit(); } catch (BackendException e) { if (e.getCause() instanceof NoHostAvailableException) { LOG.warn("Failed to commit tx: {}", e.getMessage()); } else { throw e; } } this.vertices.addAll(personIds); this.vertices.addAll(softwareIds); personIds.clear(); softwareIds.clear(); }
292
560
852
<methods>public non-sealed void <init>() ,public int test(java.lang.String[]) throws java.lang.Exception,public void testInsertPerf(org.apache.hugegraph.example.PerfExampleBase.GraphManager, int, int, int) throws java.lang.Exception,public void testQueryEdgePerf(org.apache.hugegraph.example.PerfExampleBase.GraphManager, int, int, int) throws java.lang.Exception,public void testQueryVertexPerf(org.apache.hugegraph.example.PerfExampleBase.GraphManager, int, int, int) throws java.lang.Exception<variables>public static final int EDGE_NUM,protected static final Logger LOG,public static final int PERSON_NUM,public static final int SOFTWARE_NUM,protected boolean profile,protected Set<java.lang.Object> vertices
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-example/src/main/java/org/apache/hugegraph/example/PerfExample3.java
PerfExample3
testInsert
class PerfExample3 extends PerfExampleBase { private static final Logger LOG = Log.logger(PerfExample3.class); public static void main(String[] args) throws Exception { PerfExample3 tester = new PerfExample3(); tester.test(args); // Stop daemon thread HugeFactory.shutdown(30L); } @Override protected void initSchema(SchemaManager schema) { // Schema changes will be commit directly into the back-end LOG.info("=============== propertyKey ================"); schema.propertyKey("id").asInt().ifNotExist().create(); schema.propertyKey("name").asText().ifNotExist().create(); schema.propertyKey("age").asInt().valueSingle().ifNotExist().create(); schema.propertyKey("city").asText().ifNotExist().create(); LOG.info("=============== vertexLabel ================"); schema.vertexLabel("person") .properties("name", "age", "city") .primaryKeys("name") .ifNotExist().create(); LOG.info("=============== vertexLabel & index ================"); schema.indexLabel("personByCity") .onV("person").secondary().by("city") .ifNotExist().create(); schema.indexLabel("personByAge") .onV("person").range().by("age") .ifNotExist().create(); LOG.info("=============== edgeLabel ================"); schema.edgeLabel("knows") .sourceLabel("person").targetLabel("person") .ifNotExist().create(); } @Override protected void testInsert(GraphManager graph, int times, int multiple) {<FILL_FUNCTION_BODY>} protected void testAppend(GraphManager graph) { Vertex v1 = graph.addVertex(T.label, "person", "name", String.format("p-%08d", 1), "city", "Hongkong", "age", 18); Vertex v2 = graph.addVertex(T.label, "person", "name", String.format("p-%08d", 10000002), "city", "Hongkong", "age", 20); v1.addEdge("knows", v2); graph.tx().commit(); } }
final int TIMES = times * multiple; final int BATCH = 100; long total = 0; // Insert in order for (int i = 0; i < TIMES; i++) { for (int j = 0; j < BATCH; j++) { String name = String.format("p-%08d", total++); Vertex v = graph.addVertex(T.label, "person", "name", name, "city", "Hongkong", "age", 3); this.vertices.add(v.id()); } graph.tx().commit(); }
613
164
777
<methods>public non-sealed void <init>() ,public int test(java.lang.String[]) throws java.lang.Exception,public void testInsertPerf(org.apache.hugegraph.example.PerfExampleBase.GraphManager, int, int, int) throws java.lang.Exception,public void testQueryEdgePerf(org.apache.hugegraph.example.PerfExampleBase.GraphManager, int, int, int) throws java.lang.Exception,public void testQueryVertexPerf(org.apache.hugegraph.example.PerfExampleBase.GraphManager, int, int, int) throws java.lang.Exception<variables>public static final int EDGE_NUM,protected static final Logger LOG,public static final int PERSON_NUM,public static final int SOFTWARE_NUM,protected boolean profile,protected Set<java.lang.Object> vertices
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-example/src/main/java/org/apache/hugegraph/example/PerfExample4.java
PerfExample4
testQueryVertex
class PerfExample4 extends PerfExample3 { private static final Logger LOG = Log.logger(PerfExample3.class); /** * Main method * * @param args 3 arguments, 1st should be 1, meaning single thread, * product of 2nd and 3rd is total number of "person" vertices * @throws InterruptedException */ public static void main(String[] args) throws Exception { PerfExample4 tester = new PerfExample4(); tester.test(args); // Stop daemon thread HugeFactory.shutdown(30L); } @Override protected void testQueryVertex(GraphManager graph, int threads, int thread, int multiple) {<FILL_FUNCTION_BODY>} protected static long elapsed(long start) { long current = System.currentTimeMillis(); return current - start; } }
int total = threads * multiple * 100; for (int i = 1; i <= total; i *= 10) { LOG.info(">>>> limit {} <<<<", i); long current = System.currentTimeMillis(); List<Vertex> persons = graph.traversal().V() .hasLabel("person") .limit(i).toList(); assert persons.size() == i; LOG.info(">>>> query by label index, cost: {}ms", elapsed(current)); current = System.currentTimeMillis(); persons = graph.traversal().V() .has("city", "Hongkong") .limit(i) .toList(); assert persons.size() == i; LOG.info(">>>> query by secondary index, cost: {}ms", elapsed(current)); current = System.currentTimeMillis(); persons = graph.traversal().V() .has("age", 3) .limit(i) .toList(); assert persons.size() == i; LOG.info(">>>> query by range index, cost: {}ms", elapsed(current)); }
243
299
542
<methods>public non-sealed void <init>() ,public static void main(java.lang.String[]) throws java.lang.Exception<variables>private static final Logger LOG
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-example/src/main/java/org/apache/hugegraph/example/TaskExample.java
TaskExample
testTask
class TaskExample { private static final Logger LOG = Log.logger(TaskExample.class); public static void main(String[] args) throws Exception { LOG.info("TaskExample start!"); HugeGraph graph = ExampleUtil.loadGraph(); testTask(graph); graph.close(); // Stop daemon thread HugeFactory.shutdown(30L); } public static void testTask(HugeGraph graph) throws InterruptedException {<FILL_FUNCTION_BODY>} public static class TestTask extends TaskCallable<Integer> { public static final int UNIT = 100; // ms public volatile boolean run = true; @Override public Integer call() throws Exception { LOG.info(">>>> running task with parameter: {}", this.task().input()); for (int i = this.task().progress(); i <= 100 && this.run; i++) { LOG.info(">>>> progress {}", i); this.task().progress(i); this.graph().taskScheduler().save(this.task()); Thread.sleep(UNIT); } return 18; } } }
Id id = IdGenerator.of(8); String callable = "org.apache.hugegraph.example.TaskExample$TestTask"; HugeTask<?> task = new HugeTask<>(id, null, callable, "test-parameter"); task.type("type-1"); task.name("test-task"); TaskScheduler scheduler = graph.taskScheduler(); scheduler.schedule(task); scheduler.save(task); Iterator<HugeTask<Object>> iter; iter = scheduler.tasks(TaskStatus.RUNNING, -1, null); LOG.info(">>>> running task: {}", IteratorUtils.toList(iter)); Thread.sleep(TestTask.UNIT * 33); task.cancel(true); Thread.sleep(TestTask.UNIT * 1); scheduler.save(task); // Find task not finished(actually it should be RUNNING) iter = scheduler.tasks(TaskStatus.CANCELLED, -1, null); assert iter.hasNext(); task = iter.next(); LOG.info(">>>> task may be interrupted"); Thread.sleep(TestTask.UNIT * 10); LOG.info(">>>> restore task..."); Whitebox.setInternalState(task, "status", TaskStatus.RUNNING); scheduler.restoreTasks(); Thread.sleep(TestTask.UNIT * 80); scheduler.save(task); iter = scheduler.tasks(TaskStatus.SUCCESS, -1, null); assert iter.hasNext(); task = iter.next(); assert task.status() == TaskStatus.SUCCESS; assert task.retries() == 1;
302
447
749
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-example/src/main/java/org/apache/hugegraph/example/ThreadRangePerfTest.java
ThreadRangePerfTest
main
class ThreadRangePerfTest { private static final Logger LOG = Log.logger(ThreadRangePerfTest.class); public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>} }
if (args.length != 6) { LOG.info("Usage: minThread maxThread threadStep " + "times multiple profile"); return; } int minThread = Integer.parseInt(args[0]); int maxThread = Integer.parseInt(args[1]); int threadStep = Integer.parseInt(args[2]); int times = Integer.parseInt(args[3]); int multiple = Integer.parseInt(args[4]); boolean profile = Boolean.parseBoolean(args[5]); String[] newargs = new String[4]; for (int i = minThread; i <= maxThread; i += threadStep) { int threads = i; newargs[0] = String.valueOf(threads); newargs[1] = String.valueOf(times); newargs[2] = String.valueOf(multiple); newargs[3] = String.valueOf(profile); LOG.info("==================================="); LOG.info("threads: {}, times: {}, multiple: {}, profile: {}", threads, times, multiple, profile); new PerfExample1().test(newargs); } // Stop daemon thread HugeFactory.shutdown(30L);
59
313
372
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-hbase/src/main/java/org/apache/hugegraph/backend/store/hbase/HbaseFeatures.java
HbaseFeatures
supportsTransaction
class HbaseFeatures implements BackendFeatures { private boolean enablePartition; public HbaseFeatures(boolean enablePartition) { this.enablePartition = enablePartition; } @Override public boolean supportsScanToken() { return false; } @Override public boolean supportsScanKeyPrefix() { return !this.enablePartition; } @Override public boolean supportsScanKeyRange() { return !this.enablePartition; } @Override public boolean supportsQuerySchemaByName() { // TODO: Supports this feature through HBase secondary index return false; } @Override public boolean supportsQueryByLabel() { // TODO: Supports this feature through HBase secondary index return false; } @Override public boolean supportsQueryWithInCondition() { return false; } @Override public boolean supportsQueryWithRangeCondition() { return true; } @Override public boolean supportsQuerySortByInputIds() { return true; } @Override public boolean supportsQueryWithOrderBy() { return true; } @Override public boolean supportsQueryWithContains() { // TODO: Need to traversal all items return false; } @Override public boolean supportsQueryWithContainsKey() { // TODO: Need to traversal all items return false; } @Override public boolean supportsQueryByPage() { return true; } @Override public boolean supportsDeleteEdgeByLabel() { // TODO: Supports this feature through HBase secondary index return false; } @Override public boolean supportsUpdateVertexProperty() { // Vertex properties are stored in a cell(column value) return false; } @Override public boolean supportsMergeVertexProperty() { return false; } @Override public boolean supportsUpdateEdgeProperty() { // Edge properties are stored in a cell(column value) return false; } @Override public boolean supportsTransaction() {<FILL_FUNCTION_BODY>} @Override public boolean supportsNumberType() { return false; } @Override public boolean supportsAggregateProperty() { return false; } @Override public boolean supportsTtl() { return true; } @Override public boolean supportsOlapProperties() { return false; } }
// TODO: Supports tx through BufferedMutator and range-lock return false;
640
25
665
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-hbase/src/main/java/org/apache/hugegraph/backend/store/hbase/HbaseMetrics.java
HbaseMetrics
formatMetrics
class HbaseMetrics implements BackendMetrics { private final HbaseSessions hbase; public HbaseMetrics(HbaseSessions hbase) { E.checkArgumentNotNull(hbase, "HBase connection is not opened"); this.hbase = hbase; } @Override public Map<String, Object> metrics() { Map<String, Object> results = this.clusterInfo(); if (results.containsKey(EXCEPTION)) { return results; } try (Admin admin = this.hbase.hbase().getAdmin()) { ClusterMetrics clusterMetrics = admin.getClusterMetrics(); Map<ServerName, ServerMetrics> metrics = clusterMetrics.getLiveServerMetrics(); Map<String, Object> regionServers = InsertionOrderUtil.newMap(); for (Map.Entry<ServerName, ServerMetrics> e : metrics.entrySet()) { ServerName server = e.getKey(); ServerMetrics serverMetrics = e.getValue(); regionServers.put(server.getAddress().toString(), formatMetrics(serverMetrics)); } results.put(SERVERS, regionServers); } catch (Throwable e) { results.put(EXCEPTION, e.toString()); } return results; } public Map<String, Object> compact(List<String> tableNames) { Map<String, Object> results = this.clusterInfo(); if (results.containsKey(EXCEPTION)) { return results; } try { this.hbase.compactTables(tableNames); results.put(SERVERS, ImmutableMap.of(SERVER_CLUSTER, "OK")); } catch (Throwable e) { results.put(EXCEPTION, e.toString()); } return results; } private Map<String, Object> clusterInfo() { Map<String, Object> results = InsertionOrderUtil.newMap(); try (Admin admin = this.hbase.hbase().getAdmin()) { // Cluster info ClusterMetrics clusterMetrics = admin.getClusterMetrics(); results.put(CLUSTER_ID, clusterMetrics.getClusterId()); results.put("master_name", clusterMetrics.getMasterName().getAddress().toString()); results.put("average_load", clusterMetrics.getAverageLoad()); results.put("hbase_version", clusterMetrics.getHBaseVersion()); results.put("region_count", clusterMetrics.getRegionCount()); results.put("leaving_servers", serversAddress(clusterMetrics.getDeadServerNames())); // Region servers info Collection<ServerName> regionServers = admin.getRegionServers(); results.put(NODES, regionServers.size()); results.put("region_servers", serversAddress(regionServers)); } catch (Throwable e) { results.put(EXCEPTION, e.toString()); } return results; } private static Map<String, Object> formatMetrics( ServerMetrics serverMetrics) {<FILL_FUNCTION_BODY>} private static Map<String, Object> formatRegions( Collection<RegionMetrics> regions) { Map<String, Object> metrics = InsertionOrderUtil.newMap(); for (RegionMetrics region : regions) { metrics.put(region.getNameAsString(), formatRegion(region)); } return metrics; } private static Map<String, Object> formatRegion(RegionMetrics region) { Map<String, Object> metrics = InsertionOrderUtil.newMap(); Size fileSize = region.getStoreFileSize(); long fileSizeBytes = (long) fileSize.get(Size.Unit.BYTE); metrics.put(DISK_USAGE, fileSize.get(Size.Unit.GIGABYTE)); metrics.put(DISK_USAGE + READABLE, UnitUtil.bytesToReadableString(fileSizeBytes)); metrics.put(DISK_UNIT, "GB"); metrics.put("index_store_size", region.getStoreFileIndexSize().get(Size.Unit.MEGABYTE)); metrics.put("root_level_index_store_size", region.getStoreFileRootLevelIndexSize() .get(Size.Unit.MEGABYTE)); metrics.put("mem_store_size", region.getMemStoreSize().get(Size.Unit.MEGABYTE)); metrics.put("bloom_filter_size", region.getBloomFilterSize().get(Size.Unit.MEGABYTE)); metrics.put("size_unit", "MB"); metrics.put("store_count", region.getStoreCount()); metrics.put("store_file_count", region.getStoreFileCount()); metrics.put("request_count", region.getRequestCount()); metrics.put("write_request_count", region.getWriteRequestCount()); metrics.put("read_request_count", region.getReadRequestCount()); metrics.put("filtered_read_request_count", region.getFilteredReadRequestCount()); metrics.put("completed_sequence_id", region.getCompletedSequenceId()); metrics.put("data_locality", region.getDataLocality()); metrics.put("compacted_cell_count", region.getCompactedCellCount()); metrics.put("compacting_cell_count", region.getCompactingCellCount()); metrics.put("last_compaction_time", new Date(region.getLastMajorCompactionTimestamp())); return metrics; } private static List<String> serversAddress( Collection<ServerName> servers) { return servers.stream().map(server -> { return server.getAddress().toString(); }).collect(Collectors.toList()); } }
Map<String, Object> metrics = InsertionOrderUtil.newMap(); Size memMax = serverMetrics.getMaxHeapSize(); Size memUsed = serverMetrics.getUsedHeapSize(); long memUsedBytes = (long) memUsed.get(Size.Unit.BYTE); metrics.put(MEM_MAX, memMax.get(Size.Unit.MEGABYTE)); metrics.put(MEM_USED, memUsed.get(Size.Unit.MEGABYTE)); metrics.put(MEM_USED + READABLE, UnitUtil.bytesToReadableString(memUsedBytes)); metrics.put(MEM_UNIT, "MB"); Collection<RegionMetrics> regions = serverMetrics.getRegionMetrics() .values(); long fileSizeBytes = 0L; for (RegionMetrics region : regions) { Double tempValue = region.getStoreFileSize().get(Size.Unit.BYTE); fileSizeBytes += tempValue.longValue(); } metrics.put(DISK_USAGE, UnitUtil.bytesToGB(fileSizeBytes)); metrics.put(DISK_USAGE + READABLE, UnitUtil.bytesToReadableString(fileSizeBytes)); metrics.put(DISK_UNIT, "GB"); metrics.put("request_count", serverMetrics.getRequestCount()); metrics.put("request_count_per_second", serverMetrics.getRequestCountPerSecond()); metrics.put("coprocessor_names", serverMetrics.getCoprocessorNames()); metrics.put("regions", formatRegions(regions)); return metrics;
1,461
408
1,869
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-hbase/src/main/java/org/apache/hugegraph/backend/store/hbase/HbaseOptions.java
HbaseOptions
instance
class HbaseOptions extends OptionHolder { private HbaseOptions() { super(); } private static volatile HbaseOptions instance; public static synchronized HbaseOptions instance() {<FILL_FUNCTION_BODY>} public static final ConfigOption<String> HBASE_HOSTS = new ConfigOption<>( "hbase.hosts", "The hostnames or ip addresses of HBase zookeeper, separated with commas.", disallowEmpty(), "localhost" ); public static final ConfigOption<Integer> HBASE_PORT = new ConfigOption<>( "hbase.port", "The port address of HBase zookeeper.", rangeInt(1, 65535), 2181 ); public static final ConfigOption<String> HBASE_ZNODE_PARENT = new ConfigOption<>( "hbase.znode_parent", "The znode parent path of HBase zookeeper.", disallowEmpty(), "/hbase" ); public static final ConfigOption<Integer> HBASE_ZK_RETRY = new ConfigOption<>( "hbase.zk_retry", "The recovery retry times of HBase zookeeper.", rangeInt(0, 1000), 3 ); public static final ConfigOption<Integer> HBASE_THREADS_MAX = new ConfigOption<>( "hbase.threads_max", "The max threads num of hbase connections.", rangeInt(1, 1000), 64 ); public static final ConfigOption<Long> TRUNCATE_TIMEOUT = new ConfigOption<>( "hbase.truncate_timeout", "The timeout in seconds of waiting for store truncate.", positiveInt(), 30L ); public static final ConfigOption<Long> AGGR_TIMEOUT = new ConfigOption<>( "hbase.aggregation_timeout", "The timeout in seconds of waiting for aggregation.", positiveInt(), 12 * 60 * 60L ); public static final ConfigOption<Boolean> HBASE_KERBEROS_ENABLE = new ConfigOption<>( "hbase.kerberos_enable", "Is Kerberos authentication enabled for HBase.", disallowEmpty(), false ); public static final ConfigOption<String> HBASE_KRB5_CONF = new ConfigOption<>( "hbase.krb5_conf", "Kerberos configuration file, including KDC IP, default realm, etc.", null, "/etc/krb5.conf" ); public static final ConfigOption<String> HBASE_HBASE_SITE = new ConfigOption<>( "hbase.hbase_site", "The HBase's configuration file", null, "/etc/hbase/conf/hbase-site.xml" ); public static final ConfigOption<String> HBASE_KERBEROS_PRINCIPAL = new ConfigOption<>( "hbase.kerberos_principal", "The HBase's principal for kerberos authentication.", null, "" ); public static final ConfigOption<String> HBASE_KERBEROS_KEYTAB = new ConfigOption<>( "hbase.kerberos_keytab", "The HBase's key tab file for kerberos authentication.", null, "" ); public static final ConfigOption<Boolean> HBASE_ENABLE_PARTITION = new ConfigOption<>( "hbase.enable_partition", "Is pre-split partitions enabled for HBase.", disallowEmpty(), true ); public static final ConfigOption<Integer> HBASE_VERTEX_PARTITION = new ConfigOption<>( "hbase.vertex_partitions", "The number of partitions of the HBase vertex table", nonNegativeInt(), 10 ); public static final ConfigOption<Integer> HBASE_EDGE_PARTITION = new ConfigOption<>( "hbase.edge_partitions", "The number of partitions of the HBase edge table", nonNegativeInt(), 30 ); }
if (instance == null) { instance = new HbaseOptions(); instance.registerOptions(); } return instance;
1,103
36
1,139
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-hbase/src/main/java/org/apache/hugegraph/backend/store/hbase/HbaseSerializer.java
HbaseSerializer
getPartition
class HbaseSerializer extends BinarySerializer { private static final Logger LOG = Log.logger(HbaseSerializer.class); private final short vertexLogicPartitions; private final short edgeLogicPartitions; public HbaseSerializer(HugeConfig config) { super(false, true, config.get(HbaseOptions.HBASE_ENABLE_PARTITION)); this.vertexLogicPartitions = config.get(HbaseOptions.HBASE_VERTEX_PARTITION).shortValue(); this.edgeLogicPartitions = config.get(HbaseOptions.HBASE_EDGE_PARTITION).shortValue(); LOG.debug("vertexLogicPartitions: " + vertexLogicPartitions); } @Override protected short getPartition(HugeType type, Id id) {<FILL_FUNCTION_BODY>} }
int hashcode = Arrays.hashCode(id.asBytes()); short partition = 1; if (type.isEdge()) { partition = (short) (hashcode % this.edgeLogicPartitions); } else if (type.isVertex()) { partition = (short) (hashcode % this.vertexLogicPartitions); } return partition > 0 ? partition : (short) -partition;
209
105
314
<methods>public void <init>() ,public void <init>(HugeConfig) ,public void <init>(boolean, boolean, boolean) ,public static void increaseOne(byte[]) ,public org.apache.hugegraph.backend.store.BackendEntry parse(org.apache.hugegraph.backend.store.BackendEntry) ,public org.apache.hugegraph.structure.HugeEdge readEdge(org.apache.hugegraph.HugeGraph, org.apache.hugegraph.backend.store.BackendEntry) ,public org.apache.hugegraph.schema.EdgeLabel readEdgeLabel(org.apache.hugegraph.HugeGraph, org.apache.hugegraph.backend.store.BackendEntry) ,public org.apache.hugegraph.structure.HugeIndex readIndex(org.apache.hugegraph.HugeGraph, org.apache.hugegraph.backend.query.ConditionQuery, org.apache.hugegraph.backend.store.BackendEntry) ,public org.apache.hugegraph.schema.IndexLabel readIndexLabel(org.apache.hugegraph.HugeGraph, org.apache.hugegraph.backend.store.BackendEntry) ,public org.apache.hugegraph.schema.PropertyKey readPropertyKey(org.apache.hugegraph.HugeGraph, org.apache.hugegraph.backend.store.BackendEntry) ,public org.apache.hugegraph.structure.HugeVertex readVertex(org.apache.hugegraph.HugeGraph, org.apache.hugegraph.backend.store.BackendEntry) ,public org.apache.hugegraph.schema.VertexLabel readVertexLabel(org.apache.hugegraph.HugeGraph, org.apache.hugegraph.backend.store.BackendEntry) ,public org.apache.hugegraph.backend.store.BackendEntry writeEdge(org.apache.hugegraph.structure.HugeEdge) ,public org.apache.hugegraph.backend.store.BackendEntry writeEdgeLabel(org.apache.hugegraph.schema.EdgeLabel) ,public org.apache.hugegraph.backend.store.BackendEntry writeEdgeProperty(HugeEdgeProperty<?>) ,public org.apache.hugegraph.backend.store.BackendEntry writeId(org.apache.hugegraph.type.HugeType, org.apache.hugegraph.backend.id.Id) ,public org.apache.hugegraph.backend.store.BackendEntry writeIndex(org.apache.hugegraph.structure.HugeIndex) ,public org.apache.hugegraph.backend.store.BackendEntry writeIndexLabel(org.apache.hugegraph.schema.IndexLabel) ,public org.apache.hugegraph.backend.store.BackendEntry writeOlapVertex(org.apache.hugegraph.structure.HugeVertex) ,public org.apache.hugegraph.backend.store.BackendEntry writePropertyKey(org.apache.hugegraph.schema.PropertyKey) ,public org.apache.hugegraph.backend.store.BackendEntry writeVertex(org.apache.hugegraph.structure.HugeVertex) ,public org.apache.hugegraph.backend.store.BackendEntry writeVertexLabel(org.apache.hugegraph.schema.VertexLabel) ,public org.apache.hugegraph.backend.store.BackendEntry writeVertexProperty(HugeVertexProperty<?>) <variables>private final non-sealed boolean enablePartition,private final non-sealed boolean indexWithIdPrefix,private final non-sealed boolean keyWithIdPrefix
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-hbase/src/main/java/org/apache/hugegraph/backend/store/hbase/HbaseStoreProvider.java
HbaseStoreProvider
driverVersion
class HbaseStoreProvider extends AbstractBackendStoreProvider { protected String namespace() { return this.graph().toLowerCase(); } @Override protected BackendStore newSchemaStore(HugeConfig config, String store) { return new HbaseStore.HbaseSchemaStore(config, this, this.namespace(), store); } @Override protected BackendStore newGraphStore(HugeConfig config, String store) { return new HbaseStore.HbaseGraphStore(config, this, this.namespace(), store); } @Override protected BackendStore newSystemStore(HugeConfig config, String store) { return new HbaseStore.HbaseSystemStore(config, this, this.namespace(), store); } @Override public String type() { return "hbase"; } @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] #287: support pagination when doing index query * [1.4] #270 & #398: support shard-index and vertex + sortkey prefix, * also split range table to rangeInt, rangeFloat, * rangeLong and rangeDouble * [1.5] #633: support unique index * [1.6] #680: update index element-id to bin format * [1.7] #746: support userdata for indexlabel * [1.8] #820: store vertex properties in one column * [1.9] #894: encode label id in string index * [1.10] #295: support ttl for vertex and edge * [1.11] #1333: support read frequency for property key * [1.12] #1533: add meta table in system store */ return "1.12";
234
320
554
<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-hbase/src/main/java/org/apache/hugegraph/backend/store/hbase/HbaseTables.java
Edge
parseRowColumns
class Edge extends HbaseTable { public static final String TABLE_SUFFIX = HugeType.EDGE.string(); public Edge(String store, boolean out, boolean enablePartition) { super(joinTableName(store, table(out)), enablePartition); } private static String table(boolean out) { // Edge out/in table return (out ? 'o' : 'i') + TABLE_SUFFIX; } public static Edge out(String store, boolean enablePartition) { return new Edge(store, true, enablePartition); } public static Edge in(String store, boolean enablePartition) { return new Edge(store, false, enablePartition); } @Override public void insert(HbaseSessions.Session session, BackendEntry entry) { long ttl = entry.ttl(); if (ttl == 0L) { session.put(this.table(), CF, entry.id().asBytes(), entry.columns()); } else { session.put(this.table(), CF, entry.id().asBytes(), entry.columns(), ttl); } } @Override protected void parseRowColumns(Result row, BackendEntry entry, Query query, boolean enablePartition) throws IOException {<FILL_FUNCTION_BODY>} }
/* * Collapse owner-vertex id from edge id, NOTE: unneeded to * collapse if BinarySerializer.keyWithIdPrefix set to true */ byte[] key = row.getRow(); if (enablePartition) { key = Arrays.copyOfRange(key, entry.id().length() + 2, key.length); } else { key = Arrays.copyOfRange(key, entry.id().length(), key.length); } long total = query.total(); CellScanner cellScanner = row.cellScanner(); while (cellScanner.advance() && total-- > 0) { Cell cell = cellScanner.current(); assert CellUtil.cloneQualifier(cell).length == 0; entry.columns(BackendColumn.of(key, CellUtil.cloneValue(cell))); }
333
217
550
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-mysql/src/main/java/org/apache/hugegraph/backend/store/mysql/MysqlEntryIterator.java
MysqlEntryIterator
fetch
class MysqlEntryIterator extends BackendEntryIterator { private final ResultSetWrapper results; private final BiFunction<BackendEntry, BackendEntry, BackendEntry> merger; private BackendEntry next; private BackendEntry lastest; private boolean exceedLimit; public MysqlEntryIterator(ResultSetWrapper rs, Query query, BiFunction<BackendEntry, BackendEntry, BackendEntry> merger) { super(query); this.results = rs; this.merger = merger; this.next = null; this.lastest = null; this.exceedLimit = false; } @Override protected final boolean fetch() {<FILL_FUNCTION_BODY>} @Override protected PageState pageState() { byte[] position; // There is no latest or no next page if (this.lastest == null || !this.exceedLimit && this.fetched() <= this.query.limit() && this.next == null) { position = PageState.EMPTY_BYTES; } else { MysqlBackendEntry entry = (MysqlBackendEntry) this.lastest; position = new PagePosition(entry.columnsMap()).toBytes(); } return new PageState(position, 0, (int) this.count()); } @Override protected void skipOffset() { // pass } @Override protected final long sizeOf(BackendEntry entry) { MysqlBackendEntry e = (MysqlBackendEntry) entry; int subRowsSize = e.subRows().size(); return subRowsSize > 0 ? subRowsSize : 1L; } @Override protected final long skip(BackendEntry entry, long skip) { MysqlBackendEntry e = (MysqlBackendEntry) entry; E.checkState(e.subRows().size() > skip, "Invalid entry to skip"); for (long i = 0; i < skip; i++) { e.subRows().remove(0); } return e.subRows().size(); } @Override public void close() throws Exception { this.results.close(); } private MysqlBackendEntry row2Entry(ResultSet result) throws SQLException { HugeType type = this.query.resultType(); MysqlBackendEntry entry = new MysqlBackendEntry(type); ResultSetMetaData metaData = result.getMetaData(); for (int i = 1; i <= metaData.getColumnCount(); i++) { String name = metaData.getColumnLabel(i); HugeKeys key = MysqlTable.parseKey(name); Object value = result.getObject(i); if (value == null) { assert key == HugeKeys.EXPIRED_TIME; continue; } entry.column(key, value); } return entry; } private void removeLastRecord() { MysqlBackendEntry entry = (MysqlBackendEntry) this.current; int lastOne = entry.subRows().size() - 1; assert lastOne >= 0; entry.subRows().remove(lastOne); } public static class PagePosition { private final Map<HugeKeys, Object> columns; public PagePosition(Map<HugeKeys, Object> columns) { this.columns = columns; } public Map<HugeKeys, Object> columns() { return this.columns; } @Override public String toString() { return JsonUtil.toJson(this.columns); } public byte[] toBytes() { String json = JsonUtil.toJson(this.columns); return StringEncoding.encode(json); } public static PagePosition fromBytes(byte[] bytes) { String json = StringEncoding.decode(bytes); @SuppressWarnings("unchecked") Map<String, Object> columns = JsonUtil.fromJson(json, Map.class); Map<HugeKeys, Object> keyColumns = new LinkedHashMap<>(); for (Map.Entry<String, Object> entry : columns.entrySet()) { HugeKeys key = MysqlTable.parseKey(entry.getKey()); keyColumns.put(key, entry.getValue()); } return new PagePosition(keyColumns); } } }
assert this.current == null; if (this.next != null) { this.current = this.next; this.next = null; } try { while (this.results.next()) { MysqlBackendEntry entry = this.row2Entry(this.results.resultSet()); this.lastest = entry; BackendEntry merged = this.merger.apply(this.current, entry); if (this.current == null) { // The first time to read this.current = merged; } else if (merged == this.current) { // Does the next entry belongs to the current entry assert merged != null; } else { // New entry assert this.next == null; this.next = merged; break; } // When limit exceed, stop fetching if (this.reachLimit(this.fetched() - 1)) { this.exceedLimit = true; // Need remove last one because fetched limit + 1 records this.removeLastRecord(); this.results.close(); break; } } } catch (SQLException e) { throw new BackendException("Fetch next error", e); } return this.current != null;
1,131
327
1,458
<methods>public void <init>(org.apache.hugegraph.backend.query.Query) ,public static final void checkInterrupted() ,public boolean hasNext() ,public transient java.lang.Object metadata(java.lang.String, java.lang.Object[]) ,public org.apache.hugegraph.backend.store.BackendEntry next() <variables>public static final long INLINE_BATCH_SIZE,private static final Logger LOG,private long count,protected org.apache.hugegraph.backend.store.BackendEntry current,protected final non-sealed org.apache.hugegraph.backend.query.Query query
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-mysql/src/main/java/org/apache/hugegraph/backend/store/mysql/MysqlOptions.java
MysqlOptions
instance
class MysqlOptions extends OptionHolder { protected MysqlOptions() { super(); } private static volatile MysqlOptions instance; public static synchronized MysqlOptions instance() {<FILL_FUNCTION_BODY>} public static final ConfigOption<String> JDBC_DRIVER = new ConfigOption<>( "jdbc.driver", "The JDBC driver class to connect database.", disallowEmpty(), "com.mysql.jdbc.Driver" ); public static final ConfigOption<String> JDBC_URL = new ConfigOption<>( "jdbc.url", "The url of database in JDBC format.", disallowEmpty(), "jdbc:mysql://127.0.0.1:3306" ); public static final ConfigOption<String> JDBC_USERNAME = new ConfigOption<>( "jdbc.username", "The username to login database.", disallowEmpty(), "root" ); public static final ConfigOption<String> JDBC_PASSWORD = new ConfigOption<>( "jdbc.password", "The password corresponding to jdbc.username.", null, "******" ); public static final ConfigOption<Boolean> JDBC_FORCED_AUTO_RECONNECT = new ConfigOption<>( "jdbc.forced_auto_reconnect", "Whether to forced auto reconnect to the database even " + "if the connection fails at the first time. Note that " + "forced_auto_reconnect=true will disable fail-fast.", disallowEmpty(), false ); public static final ConfigOption<Integer> JDBC_RECONNECT_MAX_TIMES = new ConfigOption<>( "jdbc.reconnect_max_times", "The reconnect times when the database connection fails.", rangeInt(1, 10), 3 ); public static final ConfigOption<Integer> JDBC_RECONNECT_INTERVAL = new ConfigOption<>( "jdbc.reconnect_interval", "The interval(seconds) between reconnections when the " + "database connection fails.", rangeInt(1, 10), 3 ); public static final ConfigOption<String> JDBC_SSL_MODE = new ConfigOption<>( "jdbc.ssl_mode", "The SSL mode of connections with database.", disallowEmpty(), "false" ); public static final ConfigOption<String> JDBC_STORAGE_ENGINE = new ConfigOption<>( "jdbc.storage_engine", "The storage engine of backend store database, " + "like InnoDB/MyISAM/RocksDB for MySQL.", disallowEmpty(), "InnoDB" ); }
if (instance == null) { instance = new MysqlOptions(); instance.registerOptions(); } return instance;
734
37
771
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-mysql/src/main/java/org/apache/hugegraph/backend/store/mysql/MysqlSerializer.java
MysqlSerializer
parseProperties
class MysqlSerializer extends TableSerializer { public MysqlSerializer(HugeConfig config) { super(config); } @Override public MysqlBackendEntry newBackendEntry(HugeType type, Id id) { return new MysqlBackendEntry(type, id); } @Override protected TableBackendEntry newBackendEntry(TableBackendEntry.Row row) { return new MysqlBackendEntry(row); } @Override protected MysqlBackendEntry convertEntry(BackendEntry backendEntry) { if (!(backendEntry instanceof MysqlBackendEntry)) { throw new BackendException("Not supported by MysqlSerializer"); } return (MysqlBackendEntry) backendEntry; } @Override protected Set<Object> parseIndexElemIds(TableBackendEntry entry) { Set<Object> elemIds = InsertionOrderUtil.newSet(); elemIds.add(entry.column(HugeKeys.ELEMENT_IDS)); for (TableBackendEntry.Row row : entry.subRows()) { elemIds.add(row.column(HugeKeys.ELEMENT_IDS)); } return elemIds; } @Override protected Id toId(Number number) { return IdGenerator.of(number.longValue()); } @Override protected Id[] toIdArray(Object object) { assert object instanceof String; String value = (String) object; Number[] values = JsonUtil.fromJson(value, Number[].class); Id[] ids = new Id[values.length]; int i = 0; for (Number number : values) { ids[i++] = IdGenerator.of(number.longValue()); } return ids; } @Override protected Object toLongSet(Collection<Id> ids) { return this.toLongList(ids); } @Override protected Object toLongList(Collection<Id> ids) { long[] values = new long[ids.size()]; int i = 0; for (Id id : ids) { values[i++] = id.asLong(); } return JsonUtil.toJson(values); } @Override protected void formatProperty(HugeProperty<?> prop, TableBackendEntry.Row row) { throw new BackendException("Not support updating single property " + "by MySQL"); } @Override protected void formatProperties(HugeElement element, TableBackendEntry.Row row) { Map<Number, Object> properties = new HashMap<>(); // Add all properties of a Vertex for (HugeProperty<?> prop : element.getProperties()) { Number key = prop.propertyKey().id().asLong(); Object val = prop.value(); properties.put(key, val); } row.column(HugeKeys.PROPERTIES, JsonUtil.toJson(properties)); } @Override protected void parseProperties(HugeElement element, TableBackendEntry.Row row) {<FILL_FUNCTION_BODY>} @Override protected void writeUserdata(SchemaElement schema, TableBackendEntry entry) { assert entry instanceof MysqlBackendEntry; entry.column(HugeKeys.USER_DATA, JsonUtil.toJson(schema.userdata())); } @Override protected void readUserdata(SchemaElement schema, TableBackendEntry entry) { assert entry instanceof MysqlBackendEntry; // Parse all user data of a schema element String json = entry.column(HugeKeys.USER_DATA); @SuppressWarnings("unchecked") Map<String, Object> userdata = JsonUtil.fromJson(json, Map.class); for (Map.Entry<String, Object> e : userdata.entrySet()) { schema.userdata(e.getKey(), e.getValue()); } } @Override public BackendEntry writeOlapVertex(HugeVertex vertex) { throw new NotImplementedException("Unsupported writeOlapVertex()"); } }
String properties = row.column(HugeKeys.PROPERTIES); // Query edge will wrapped by a vertex, whose properties is empty if (properties.isEmpty()) { return; } @SuppressWarnings("unchecked") Map<String, Object> props = JsonUtil.fromJson(properties, Map.class); for (Map.Entry<String, Object> prop : props.entrySet()) { /* * The key is string instead of int, because the key in json * must be string */ Id pkeyId = this.toId(Long.valueOf(prop.getKey())); String colJson = JsonUtil.toJson(prop.getValue()); this.parseProperty(pkeyId, colJson, element); }
1,062
191
1,253
<methods>public void <init>(HugeConfig) ,public org.apache.hugegraph.backend.serializer.TableBackendEntry newBackendEntry(org.apache.hugegraph.type.HugeType, org.apache.hugegraph.backend.id.Id) ,public org.apache.hugegraph.structure.HugeEdge readEdge(org.apache.hugegraph.HugeGraph, org.apache.hugegraph.backend.store.BackendEntry) ,public org.apache.hugegraph.schema.EdgeLabel readEdgeLabel(org.apache.hugegraph.HugeGraph, org.apache.hugegraph.backend.store.BackendEntry) ,public org.apache.hugegraph.structure.HugeIndex readIndex(org.apache.hugegraph.HugeGraph, org.apache.hugegraph.backend.query.ConditionQuery, org.apache.hugegraph.backend.store.BackendEntry) ,public org.apache.hugegraph.schema.IndexLabel readIndexLabel(org.apache.hugegraph.HugeGraph, org.apache.hugegraph.backend.store.BackendEntry) ,public org.apache.hugegraph.schema.PropertyKey readPropertyKey(org.apache.hugegraph.HugeGraph, org.apache.hugegraph.backend.store.BackendEntry) ,public org.apache.hugegraph.structure.HugeVertex readVertex(org.apache.hugegraph.HugeGraph, org.apache.hugegraph.backend.store.BackendEntry) ,public org.apache.hugegraph.schema.VertexLabel readVertexLabel(org.apache.hugegraph.HugeGraph, org.apache.hugegraph.backend.store.BackendEntry) ,public org.apache.hugegraph.backend.store.BackendEntry writeEdge(org.apache.hugegraph.structure.HugeEdge) ,public org.apache.hugegraph.backend.store.BackendEntry writeEdgeLabel(org.apache.hugegraph.schema.EdgeLabel) ,public org.apache.hugegraph.backend.store.BackendEntry writeEdgeProperty(HugeEdgeProperty<?>) ,public org.apache.hugegraph.backend.store.BackendEntry writeId(org.apache.hugegraph.type.HugeType, org.apache.hugegraph.backend.id.Id) ,public org.apache.hugegraph.backend.store.BackendEntry writeIndex(org.apache.hugegraph.structure.HugeIndex) ,public org.apache.hugegraph.backend.store.BackendEntry writeIndexLabel(org.apache.hugegraph.schema.IndexLabel) ,public org.apache.hugegraph.backend.store.BackendEntry writePropertyKey(org.apache.hugegraph.schema.PropertyKey) ,public org.apache.hugegraph.backend.store.BackendEntry writeVertex(org.apache.hugegraph.structure.HugeVertex) ,public org.apache.hugegraph.backend.store.BackendEntry writeVertexLabel(org.apache.hugegraph.schema.VertexLabel) ,public org.apache.hugegraph.backend.store.BackendEntry writeVertexProperty(HugeVertexProperty<?>) <variables>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-mysql/src/main/java/org/apache/hugegraph/backend/store/mysql/MysqlStoreProvider.java
MysqlStoreProvider
driverVersion
class MysqlStoreProvider extends AbstractBackendStoreProvider { protected String database() { return this.graph().toLowerCase(); } @Override protected BackendStore newSchemaStore(HugeConfig config, String store) { return new MysqlSchemaStore(this, this.database(), store); } @Override protected BackendStore newGraphStore(HugeConfig config, String store) { return new MysqlGraphStore(this, this.database(), store); } @Override protected BackendStore newSystemStore(HugeConfig config, String store) { return new MysqlSystemStore(this, this.database(), store); } @Override public String type() { return "mysql"; } @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] #633: support unique index * [1.5] #661: reduce the storage of vertex/edge id * [1.6] #691: support aggregate property * [1.7] #746: support userdata for indexlabel * [1.8] #894: asStoredString() encoding is changed to signed B64 * instead of sortable B64 * [1.9] #295: support ttl for vertex and edge * [1.10] #1333: support read frequency for property key * [1.11] #1506: rename read frequency to write type * [1.11] #1533: add meta table in system store */ return "1.11";
219
336
555
<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-mysql/src/main/java/org/apache/hugegraph/backend/store/mysql/MysqlTables.java
Edge
delete
class Edge extends MysqlTableTemplate { public static final String TABLE_SUFFIX = HugeType.EDGE.string(); private final Directions direction; private final String delByLabelTemplate; public Edge(String store, Directions direction) { this(store, direction, TYPES_MAPPING); } public Edge(String store, Directions direction, Map<String, String> typesMapping) { super(joinTableName(store, table(direction))); this.direction = direction; this.delByLabelTemplate = String.format( "DELETE FROM %s WHERE %s = ?;", this.table(), formatKey(HugeKeys.LABEL)); this.define = new TableDefine(typesMapping); this.define.column(HugeKeys.OWNER_VERTEX, SMALL_TEXT); this.define.column(HugeKeys.DIRECTION, TINYINT); this.define.column(HugeKeys.LABEL, DATATYPE_SL); this.define.column(HugeKeys.SORT_VALUES, SMALL_TEXT); this.define.column(HugeKeys.OTHER_VERTEX, SMALL_TEXT); this.define.column(HugeKeys.PROPERTIES, LARGE_JSON); this.define.column(HugeKeys.EXPIRED_TIME, BIGINT); this.define.keys(HugeKeys.OWNER_VERTEX, HugeKeys.DIRECTION, HugeKeys.LABEL, HugeKeys.SORT_VALUES, HugeKeys.OTHER_VERTEX); } @Override public List<Object> idColumnValue(Id id) { EdgeId edgeId; if (id instanceof EdgeId) { edgeId = (EdgeId) id; } else { String[] idParts = EdgeId.split(id); if (idParts.length == 1) { // Delete edge by label return Arrays.asList(idParts); } id = IdUtil.readString(id.asString()); edgeId = EdgeId.parse(id.asString()); } E.checkState(edgeId.direction() == this.direction, "Can't query %s edges from %s edges table", edgeId.direction(), this.direction); List<Object> list = new ArrayList<>(5); list.add(IdUtil.writeStoredString(edgeId.ownerVertexId())); list.add(edgeId.directionCode()); list.add(edgeId.edgeLabelId().asLong()); list.add(edgeId.sortValues()); list.add(IdUtil.writeStoredString(edgeId.otherVertexId())); return list; } @Override public void delete(MysqlSessions.Session session, MysqlBackendEntry.Row entry) {<FILL_FUNCTION_BODY>} private void deleteEdgesByLabel(MysqlSessions.Session session, Id label) { PreparedStatement deleteStmt; try { // Create or get delete prepare statement deleteStmt = session.prepareStatement(this.delByLabelTemplate); // Delete edges deleteStmt.setObject(1, label.asLong()); } catch (SQLException e) { throw new BackendException("Failed to prepare statement '%s'", this.delByLabelTemplate); } session.add(deleteStmt); } @Override public BackendEntry mergeEntries(BackendEntry e1, BackendEntry e2) { // Merge edges into vertex // TODO: merge rows before calling row2Entry() MysqlBackendEntry current = (MysqlBackendEntry) e1; MysqlBackendEntry next = (MysqlBackendEntry) e2; E.checkState(current == null || current.type().isVertex(), "The current entry must be null or VERTEX"); E.checkState(next != null && next.type().isEdge(), "The next entry must be EDGE"); long maxSize = BackendEntryIterator.INLINE_BATCH_SIZE; if (current != null && current.subRows().size() < maxSize) { Id nextVertexId = IdGenerator.of( next.<String>column(HugeKeys.OWNER_VERTEX)); if (current.id().equals(nextVertexId)) { current.subRow(next.row()); return current; } } return this.wrapByVertex(next); } private MysqlBackendEntry wrapByVertex(MysqlBackendEntry edge) { assert edge.type().isEdge(); String ownerVertex = edge.column(HugeKeys.OWNER_VERTEX); E.checkState(ownerVertex != null, "Invalid backend entry"); Id vertexId = IdGenerator.of(ownerVertex); MysqlBackendEntry vertex = new MysqlBackendEntry(HugeType.VERTEX, vertexId); vertex.column(HugeKeys.ID, ownerVertex); vertex.column(HugeKeys.PROPERTIES, ""); vertex.subRow(edge.row()); return vertex; } public static String table(Directions direction) { assert direction == Directions.OUT || direction == Directions.IN; return direction.type().string() + TABLE_SUFFIX; } public static MysqlTable out(String store) { return new Edge(store, Directions.OUT); } public static MysqlTable in(String store) { return new Edge(store, Directions.IN); } }
// Let super class do delete if not deleting edge by label List<Object> idParts = this.idColumnValue(entry.id()); if (idParts.size() > 1 || !entry.columns().isEmpty()) { super.delete(session, entry); return; } // The only element is label this.deleteEdgesByLabel(session, entry.id());
1,452
100
1,552
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-mysql/src/main/java/org/apache/hugegraph/backend/store/mysql/MysqlUtil.java
MysqlUtil
escapeString
class MysqlUtil { public static String escapeAndWrapString(String value) { return escapeString(value, true); } public static String escapeString(String value) { return escapeString(value, false); } private static String escapeString(String value, boolean wrap) {<FILL_FUNCTION_BODY>} public static boolean isEscapeNeededForString(String sql, int length) { boolean needsEscape = false; for (int i = 0; i < length; ++i) { char c = sql.charAt(i); switch (c) { case '\u0000': needsEscape = true; break; case '\n': needsEscape = true; break; case '\r': needsEscape = true; break; case '\u001a': needsEscape = true; break; case '\'': needsEscape = true; break; case '\\': needsEscape = true; break; default: break; } if (needsEscape) { break; } } return needsEscape; } }
int length = value.length(); if (!isEscapeNeededForString(value, length)) { if (!wrap) { return value; } StringBuilder buf = new StringBuilder(length + 2); buf.append('\'').append(value).append('\''); return buf.toString(); } StringBuilder buffer = new StringBuilder((int) (length * 1.1d)); if (wrap) { buffer.append('\''); } for (int i = 0; i < length; ++i) { char c = value.charAt(i); switch (c) { case '\u0000': buffer.append('\\'); buffer.append('0'); break; case '\n': buffer.append('\\'); buffer.append('n'); break; case '\r': buffer.append('\\'); buffer.append('r'); break; case '\u001a': buffer.append('\\'); buffer.append('Z'); break; case '"': /* * Doesn't need to add '\', because we wrap string with "'" * Assume that we don't use Ansi Mode */ buffer.append('"'); break; case '\'': buffer.append('\\'); buffer.append('\''); break; case '\\': buffer.append('\\'); buffer.append('\\'); break; default: buffer.append(c); break; } } if (wrap) { buffer.append('\''); } return buffer.toString();
317
431
748
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-mysql/src/main/java/org/apache/hugegraph/backend/store/mysql/ResultSetWrapper.java
ResultSetWrapper
close
class ResultSetWrapper implements AutoCloseable { private final ResultSet resultSet; private final Statement statement; public ResultSetWrapper(ResultSet resultSet, Statement statement) { this.resultSet = resultSet; this.statement = statement; } public boolean next() throws SQLException { return !this.resultSet.isClosed() && this.resultSet.next(); } @Override public void close() {<FILL_FUNCTION_BODY>} public ResultSet resultSet() { return resultSet; } }
try { if (this.resultSet != null) { this.resultSet.close(); } } catch (SQLException e) { throw new BackendException("Failed to close ResultSet", e); } finally { try { if (this.statement != null) { this.statement.close(); } } catch (SQLException e) { throw new BackendException("Failed to close Statement", e); } }
147
122
269
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-palo/src/main/java/org/apache/hugegraph/backend/store/palo/PaloFeatures.java
PaloFeatures
supportsQueryByLabel
class PaloFeatures implements BackendFeatures { @Override public boolean supportsScanToken() { return false; } @Override public boolean supportsScanKeyPrefix() { return false; } @Override public boolean supportsScanKeyRange() { return false; } @Override public boolean supportsQuerySchemaByName() { return true; } @Override public boolean supportsQueryByLabel() {<FILL_FUNCTION_BODY>} @Override public boolean supportsQueryWithInCondition() { return false; } @Override public boolean supportsQueryWithRangeCondition() { return true; } @Override public boolean supportsQuerySortByInputIds() { return false; } @Override public boolean supportsQueryWithContains() { return false; } @Override public boolean supportsQueryWithContainsKey() { return false; } @Override public boolean supportsQueryWithOrderBy() { return true; } @Override public boolean supportsQueryByPage() { return true; } @Override public boolean supportsDeleteEdgeByLabel() { return true; } @Override public boolean supportsUpdateVertexProperty() { return false; } @Override public boolean supportsMergeVertexProperty() { return false; } @Override public boolean supportsUpdateEdgeProperty() { return false; } @Override public boolean supportsTransaction() { return false; } @Override public boolean supportsNumberType() { return true; } @Override public boolean supportsAggregateProperty() { return false; } @Override public boolean supportsTtl() { return false; } @Override public boolean supportsOlapProperties() { return false; } }
/* * Create a rollup table on vertices/edges can speed up query by label, * but it will store data in vertices/edges again. * See: https://github.com/baidu/palo/wiki/Data-Model%2C-Rollup-%26 * -Prefix-Index */ return false;
503
90
593
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-palo/src/main/java/org/apache/hugegraph/backend/store/palo/PaloFile.java
PaloFile
scan
class PaloFile extends File { private static final long serialVersionUID = -1918775445693598353L; public PaloFile(String dir, String subDir, String fileName) { this(Paths.get(dir, subDir, fileName).toString()); } public PaloFile(String path, int id, int part) { this(Paths.get(path, formatFileName(id, part)).toString()); } public PaloFile(String path) { super(path); } public String table() { return this.getParentFile().getName(); } public int sessionId() { String[] parts = this.getName().split("-"); E.checkState(parts.length == 2, "Invalid file name format '%s' for palo temp file, " + "the legal format is session{m}-part{n}", this.getName()); return Integer.parseInt(parts[0].substring("session".length())); } public int sessionPart() { String[] parts = this.getName().split("-"); E.checkState(parts.length == 2, "Invalid file name format '%s' for palo temp file, " + "the legal format is session{m}-part{n}", this.getName()); return Integer.parseInt(parts[1].substring("part".length())); } public int writeLines(Collection<String> lines) { try { FileUtils.writeLines(this, Charsets.UTF_8.name(), lines, true); } catch (IOException e) { throw new BackendException(e); } return lines.size(); } public String readAsString() { try { return FileUtils.readFileToString(this); } catch (IOException e) { throw new BackendException(e); } } public void forceDelete() { if (this.exists()) { try { FileUtils.forceDelete(this); } catch (IOException e) { throw new BackendException(e); } } } public static void clearDir(String tempDir) { File file = FileUtils.getFile(tempDir); if (!file.exists()) { return; } try { FileUtils.forceDelete(file); } catch (IOException e) { throw new BackendException(e); } } public static List<PaloFile> scan(String path, List<String> tableDirs) {<FILL_FUNCTION_BODY>} private static String formatFileName(int id, int part) { return String.format("session%s-part%s", id, part); } private static int[] parseFileName(String fileName) { String[] nameParts = fileName.split("-"); E.checkArgument(nameParts.length == 2, "Invalid file name format '%s' for palo temp file, " + "the legal format is session{m}-part{n}", fileName); int[] rs = new int[2]; rs[0] = Integer.parseInt(nameParts[0].substring("session".length())); rs[1] = Integer.parseInt(nameParts[1].substring("part".length())); return rs; } public static long limitSize(HugeConfig config) { long limitSize = config.get(PaloOptions.PALO_FILE_LIMIT_SIZE); return limitSize * 1024 * 1024; } public static Set<Integer> scanSessionIds(HugeConfig config, List<String> tableDirs) { Set<Integer> sessionIds = new HashSet<>(); String path = config.get(PaloOptions.PALO_TEMP_DIR); File pathDir = Paths.get(path).toFile(); if (!pathDir.exists()) { return sessionIds; } for (String table : tableDirs) { File tableDir = Paths.get(path, table).toFile(); if (!tableDir.exists()) { continue; } String[] fileNames = tableDir.list(); if (fileNames == null || fileNames.length == 0) { continue; } for (String fileName : fileNames) { int[] parts = PaloFile.parseFileName(fileName); int sessionId = parts[0]; sessionIds.add(sessionId); } } return sessionIds; } }
File directory = FileUtils.getFile(path); if (!directory.exists()) { return ImmutableList.of(); } File[] subDirs = directory.listFiles((dir, name) -> { return tableDirs.contains(name); }); if (subDirs == null || subDirs.length == 0) { return ImmutableList.of(); } List<PaloFile> paloFiles = new ArrayList<>(subDirs.length); for (File subDir : subDirs) { String[] fileNames = subDir.list(); if (fileNames == null) { continue; } for (String fileName : fileNames) { paloFiles.add(new PaloFile(path, subDir.getName(), fileName)); } } /* * Sort palo file by updated time in asc order, * let old files to be processed in priority */ paloFiles.sort((file1, file2) -> { return (int) (file1.lastModified() - file2.lastModified()); }); return paloFiles;
1,170
290
1,460
<methods>public void <init>(java.lang.String) ,public void <init>(java.net.URI) ,public void <init>(java.lang.String, java.lang.String) ,public void <init>(java.io.File, java.lang.String) ,public boolean canExecute() ,public boolean canRead() ,public boolean canWrite() ,public int compareTo(java.io.File) ,public boolean createNewFile() throws java.io.IOException,public static java.io.File createTempFile(java.lang.String, java.lang.String) throws java.io.IOException,public static java.io.File createTempFile(java.lang.String, java.lang.String, java.io.File) throws java.io.IOException,public boolean delete() ,public void deleteOnExit() ,public boolean equals(java.lang.Object) ,public boolean exists() ,public java.io.File getAbsoluteFile() ,public java.lang.String getAbsolutePath() ,public java.io.File getCanonicalFile() throws java.io.IOException,public java.lang.String getCanonicalPath() throws java.io.IOException,public long getFreeSpace() ,public java.lang.String getName() ,public java.lang.String getParent() ,public java.io.File getParentFile() ,public java.lang.String getPath() ,public long getTotalSpace() ,public long getUsableSpace() ,public int hashCode() ,public boolean isAbsolute() ,public boolean isDirectory() ,public boolean isFile() ,public boolean isHidden() ,public long lastModified() ,public long length() ,public java.lang.String[] list() ,public java.lang.String[] list(java.io.FilenameFilter) ,public java.io.File[] listFiles() ,public java.io.File[] listFiles(java.io.FilenameFilter) ,public java.io.File[] listFiles(java.io.FileFilter) ,public static java.io.File[] listRoots() ,public boolean mkdir() ,public boolean mkdirs() ,public boolean renameTo(java.io.File) ,public boolean setExecutable(boolean) ,public boolean setExecutable(boolean, boolean) ,public boolean setLastModified(long) ,public boolean setReadOnly() ,public boolean setReadable(boolean) ,public boolean setReadable(boolean, boolean) ,public boolean setWritable(boolean) ,public boolean setWritable(boolean, boolean) ,public java.nio.file.Path toPath() ,public java.lang.String toString() ,public java.net.URI toURI() ,public java.net.URL toURL() throws java.net.MalformedURLException<variables>static final boolean $assertionsDisabled,private static final long PATH_OFFSET,private static final long PREFIX_LENGTH_OFFSET,private static final jdk.internal.misc.Unsafe UNSAFE,private volatile transient java.nio.file.Path filePath,private static final java.io.FileSystem fs,private final java.lang.String path,public static final java.lang.String pathSeparator,public static final char pathSeparatorChar,private final transient int prefixLength,public static final java.lang.String separator,public static final char separatorChar,private static final long serialVersionUID,private transient java.io.File.PathStatus status
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-palo/src/main/java/org/apache/hugegraph/backend/store/palo/PaloHttpClient.java
PaloHttpClient
buildUrl
class PaloHttpClient { private final RestClient client; public PaloHttpClient(HugeConfig config, String database) { String url = this.buildUrl(config, database); String username = config.get(PaloOptions.PALO_USERNAME); String password = config.get(PaloOptions.PALO_PASSWORD); Integer timeout = config.get(PaloOptions.PALO_HTTP_TIMEOUT); this.client = new Client(url, username, password, timeout); } private String buildUrl(HugeConfig config, String database) {<FILL_FUNCTION_BODY>} public void bulkLoadAsync(String table, String body, String label) { // Format path String path = table + "/_load"; // Format headers RestHeaders headers = new RestHeaders(); headers.add("Expect", "100-continue"); // Format params Map<String, Object> params = ImmutableMap.of("label", label); // Send request this.client.put(path, body, headers, params); } private static class Client extends AbstractRestClient { private static final int SECOND = 1000; public Client(String url, String user, String password, int timeout) { super(url, user, password, timeout * SECOND); } @Override protected void checkStatus(Response response, int... statuses) { // pass } } }
String host = config.get(PaloOptions.PALO_HOST); Integer port = config.get(PaloOptions.PALO_HTTP_PORT); return String.format("http://%s:%s/api/%s/", host, port, database);
374
71
445
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-palo/src/main/java/org/apache/hugegraph/backend/store/palo/PaloOptions.java
PaloOptions
instance
class PaloOptions extends OptionHolder { private PaloOptions() { super(); } private static volatile PaloOptions instance; public static synchronized PaloOptions instance() {<FILL_FUNCTION_BODY>} public static final ConfigOption<String> PALO_HOST = new ConfigOption<>( "palo.host", "The host/ip of Palo cluster.", disallowEmpty(), "127.0.0.1" ); public static final ConfigOption<Integer> PALO_HTTP_PORT = new ConfigOption<>( "palo.http_port", "The http port of Palo cluster.", positiveInt(), 8030 ); public static final ConfigOption<Integer> PALO_HTTP_TIMEOUT = new ConfigOption<>( "palo.http_timeout", "Timeout(second) for connecting and reading Palo.", nonNegativeInt(), 20 ); public static final ConfigOption<String> PALO_USERNAME = new ConfigOption<>( "palo.username", "The username to login Palo.", disallowEmpty(), "root" ); public static final ConfigOption<String> PALO_PASSWORD = new ConfigOption<>( "palo.password", "The password corresponding to palo.username.", null, "" ); public static final ConfigOption<Integer> PALO_POLL_INTERVAL = new ConfigOption<>( "palo.poll_interval", "The execution period of the background thread that " + "check whether need to load file data into Palo.", rangeInt(5, Integer.MAX_VALUE), 5 ); public static final ConfigOption<String> PALO_TEMP_DIR = new ConfigOption<>( "palo.temp_dir", "The temporary directory to store table files.", null, "palo-data" ); public static final ConfigOption<Integer> PALO_FILE_LIMIT_SIZE = new ConfigOption<>( "palo.file_limit_size", "The maximum size(MB) of each file for loading into Palo.", rangeInt(10, 1000), 50 ); }
if (instance == null) { instance = new PaloOptions(); instance.registerOptions(); } return instance;
596
36
632
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-palo/src/main/java/org/apache/hugegraph/backend/store/palo/PaloSerializer.java
PaloSerializer
writeEnableLabelIndex
class PaloSerializer extends MysqlSerializer { public PaloSerializer(HugeConfig config) { super(config); } @Override protected void writeEnableLabelIndex(SchemaLabel schema, TableBackendEntry entry) {<FILL_FUNCTION_BODY>} @Override protected void readEnableLabelIndex(SchemaLabel schema, TableBackendEntry entry) { Number enable = entry.column(HugeKeys.ENABLE_LABEL_INDEX); schema.enableLabelIndex(enable.byteValue() != 0); } }
Byte enable = (byte) (schema.enableLabelIndex() ? 1 : 0); entry.column(HugeKeys.ENABLE_LABEL_INDEX, enable);
143
45
188
<methods>public void <init>(HugeConfig) ,public org.apache.hugegraph.backend.store.mysql.MysqlBackendEntry newBackendEntry(org.apache.hugegraph.type.HugeType, org.apache.hugegraph.backend.id.Id) ,public org.apache.hugegraph.backend.store.BackendEntry writeOlapVertex(org.apache.hugegraph.structure.HugeVertex) <variables>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-palo/src/main/java/org/apache/hugegraph/backend/store/palo/PaloSessions.java
PaloLoadTask
run
class PaloLoadTask extends TimerTask { private static final String DF = "yyyy-MM-dd-HH-mm-ss"; private final SafeDateFormat dateFormat = new SafeDateFormat(DF); /** * There exist two running palo load task corresponds to two stores, * `SchemaStore -> SchemaLoadTask` and `GraphStore -> GraphLoadTask`, * the load task just handle with it's own subdirectory files, * like: `property_keys, vertex_labels ...` for SchemaLoadTask, * and: `vertices, edges ...` for GraphLoadTask * these subdirectory called validSubDirs. */ private final List<String> tableDirs; /** * session1-part1.txt session2-part1.txt ... * vertices 128m 125m ... * edges 256m 250m ... * ... ... ... ... */ private List<PaloFile> lastPaloFiles; private final PaloHttpClient client; public PaloLoadTask(List<String> tableDirs) { this.tableDirs = tableDirs; this.lastPaloFiles = null; this.client = new PaloHttpClient(config(), database()); } /** * TODO: Need to be optimized */ public void join() { Integer interval = config().get(PaloOptions.PALO_POLL_INTERVAL); while (this.lastPaloFiles != null && !this.lastPaloFiles.isEmpty()) { try { TimeUnit.SECONDS.sleep(interval); } catch (InterruptedException e) { throw new BackendException(e); } } } @Override public void run() {<FILL_FUNCTION_BODY>} private void tryLoadBatch(List<PaloFile> files) { PaloFile file = this.peekFile(files); // Load the first file when stopped inserting data this.loadThenDelete(file); files.remove(file); } private PaloFile peekFile(List<PaloFile> files) { assert !files.isEmpty(); long limitSize = PaloFile.limitSize(config()); // Load the file which exceed limit size in priority for (PaloFile file : files) { long fileSize = file.length(); if (fileSize >= limitSize) { return file; } } // Load the oldest file(files are sorted by updated time) return files.get(0); } private void loadThenDelete(PaloFile file) { // Parse session id from file name int sessionId = file.sessionId(); LOG.info("Ready to load one batch from file: {}", file); // Get write lock because will delete file Lock lock = PaloSessions.this.locks.get(sessionId).writeLock(); lock.lock(); try { String table = file.table(); String data = file.readAsString(); String label = this.formatLabel(table); this.client.bulkLoadAsync(table, data, label); // Force delete file file.forceDelete(); } finally { lock.unlock(); } } private String formatLabel(String table) { return table + "-" + this.dateFormat.format(new Date()); } }
LOG.debug("The Load task:{} ready to run", PaloSessions.this); // Scan the directory to get all file size String path = config().get(PaloOptions.PALO_TEMP_DIR); List<PaloFile> paloFiles = PaloFile.scan(path, this.tableDirs); // Do nothing if there is no file at present if (paloFiles.isEmpty()) { return; } // Try to load one batch if last time and this time have some files if (this.lastPaloFiles != null) { this.tryLoadBatch(paloFiles); } // Update the last palo files this.lastPaloFiles = paloFiles;
877
183
1,060
<methods>public void <init>(HugeConfig, java.lang.String, java.lang.String) ,public HugeConfig config() ,public void createDatabase() ,public java.lang.String database() ,public void dropDatabase() ,public java.lang.String escapedDatabase() ,public boolean existsDatabase() ,public boolean existsTable(java.lang.String) ,public synchronized void open() throws java.lang.Exception,public void resetConnections() ,public org.apache.hugegraph.backend.store.mysql.MysqlSessions.Session session() <variables>private static final int DROP_DB_TIMEOUT,private static final java.lang.String JDBC_PREFIX,private static final Logger LOG,private HugeConfig config,private java.lang.String database,private volatile boolean opened
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-palo/src/main/java/org/apache/hugegraph/backend/store/palo/PaloStore.java
PaloStore
openSessionPool
class PaloStore extends MysqlStore { private static final Logger LOG = Log.logger(PaloStore.class); public PaloStore(BackendStoreProvider provider, String database, String name) { super(provider, database, name); } @Override protected PaloSessions openSessionPool(HugeConfig config) {<FILL_FUNCTION_BODY>} private List<String> tableNames() { return this.tables().stream().map(BackendTable::table) .collect(Collectors.toList()); } }
LOG.info("Open palo session pool for {}", this); return new PaloSessions(config, this.database(), this.store(), this.tableNames());
146
45
191
<methods>public void <init>(org.apache.hugegraph.backend.store.BackendStoreProvider, java.lang.String, java.lang.String) ,public void beginTx() ,public void clear(boolean) ,public void close() ,public void commitTx() ,public java.lang.String database() ,public org.apache.hugegraph.backend.store.BackendFeatures features() ,public void init() ,public boolean initialized() ,public void mutate(org.apache.hugegraph.backend.store.BackendMutation) ,public synchronized void open(HugeConfig) ,public boolean opened() ,public org.apache.hugegraph.backend.store.BackendStoreProvider provider() ,public Iterator<org.apache.hugegraph.backend.store.BackendEntry> query(org.apache.hugegraph.backend.query.Query) ,public java.lang.Number queryNumber(org.apache.hugegraph.backend.query.Query) ,public void rollbackTx() ,public java.lang.String store() ,public void truncate() <variables>private static final org.apache.hugegraph.backend.store.BackendFeatures FEATURES,private static final Logger LOG,private final non-sealed java.lang.String database,private final non-sealed org.apache.hugegraph.backend.store.BackendStoreProvider provider,private org.apache.hugegraph.backend.store.mysql.MysqlSessions sessions,private final non-sealed java.lang.String store,private final non-sealed Map<org.apache.hugegraph.type.HugeType,org.apache.hugegraph.backend.store.mysql.MysqlTable> tables
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-palo/src/main/java/org/apache/hugegraph/backend/store/palo/PaloStoreProvider.java
PaloStoreProvider
driverVersion
class PaloStoreProvider extends MysqlStoreProvider { private static final BackendFeatures FEATURES = new PaloFeatures(); @Override protected BackendStore newSchemaStore(HugeConfig config, String store) { return new PaloSchemaStore(this, this.database(), store); } @Override protected BackendStore newGraphStore(HugeConfig config, String store) { return new PaloGraphStore(this, this.database(), store); } @Override public String type() { return "palo"; } @Override public String driverVersion() {<FILL_FUNCTION_BODY>} public static class PaloSchemaStore extends PaloStore { private final LocalCounter counter; public PaloSchemaStore(BackendStoreProvider provider, String database, String store) { super(provider, database, store); this.counter = new LocalCounter(); registerTableManager(HugeType.VERTEX_LABEL, new PaloTables.VertexLabel()); registerTableManager(HugeType.EDGE_LABEL, new PaloTables.EdgeLabel()); registerTableManager(HugeType.PROPERTY_KEY, new PaloTables.PropertyKey()); registerTableManager(HugeType.INDEX_LABEL, new PaloTables.IndexLabel()); } @Override public BackendFeatures features() { return FEATURES; } @Override public Id nextId(HugeType type) { return this.counter.nextId(type); } @Override public void increaseCounter(HugeType type, long increment) { this.counter.increaseCounter(type, increment); } @Override public long getCounter(HugeType type) { return this.counter.getCounter(type); } @Override public boolean isSchemaStore() { return true; } } public static class PaloGraphStore extends PaloStore { public PaloGraphStore(BackendStoreProvider provider, String database, String store) { super(provider, database, store); registerTableManager(HugeType.VERTEX, new PaloTables.Vertex(store)); registerTableManager(HugeType.EDGE_OUT, new PaloTables.Edge(store, Directions.OUT)); registerTableManager(HugeType.EDGE_IN, new PaloTables.Edge(store, Directions.IN)); registerTableManager(HugeType.SECONDARY_INDEX, new PaloTables.SecondaryIndex(store)); registerTableManager(HugeType.RANGE_INT_INDEX, new PaloTables.RangeIntIndex(store)); registerTableManager(HugeType.RANGE_FLOAT_INDEX, new PaloTables.RangeFloatIndex(store)); registerTableManager(HugeType.RANGE_LONG_INDEX, new PaloTables.RangeLongIndex(store)); registerTableManager(HugeType.RANGE_DOUBLE_INDEX, new PaloTables.RangeDoubleIndex(store)); registerTableManager(HugeType.SEARCH_INDEX, new PaloTables.SearchIndex(store)); registerTableManager(HugeType.SHARD_INDEX, new PaloTables.ShardIndex(store)); registerTableManager(HugeType.UNIQUE_INDEX, new PaloTables.UniqueIndex(store)); } @Override public BackendFeatures features() { return FEATURES; } @Override public boolean isSchemaStore() { return false; } @Override public Id nextId(HugeType type) { throw new UnsupportedOperationException("PaloGraphStore.nextId()"); } @Override public void increaseCounter(HugeType type, long num) { throw new UnsupportedOperationException( "PaloGraphStore.increaseCounter()"); } @Override public long getCounter(HugeType type) { throw new UnsupportedOperationException( "PaloGraphStore.getCounter()"); } } }
/* * 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] #633: support unique index * [1.5] #661: reduce the storage of vertex/edge id * [1.6] #746: support userdata for indexlabel * [1.7] #894: asStoredString() encoding is changed to signed B64 * instead of sortable B64 * [1.8] #295: support ttl for vertex and edge * [1.9] #1333: support read frequency for property key * [1.10] #1506: rename read frequency to write type * [1.10] #1533: add meta table in system store */ return "1.10";
1,073
319
1,392
<methods>public non-sealed void <init>() ,public java.lang.String driverVersion() ,public java.lang.String type() <variables>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-palo/src/main/java/org/apache/hugegraph/backend/store/palo/PaloTable.java
PaloTable
insert
class PaloTable extends MysqlTable { private static final Logger LOG = Log.logger(PaloTable.class); public PaloTable(String table) { super(table); } @Override public void createTable(MysqlSessions.Session session, TableDefine tableDefine) { StringBuilder sql = new StringBuilder(); sql.append("CREATE TABLE IF NOT EXISTS "); sql.append(this.table()).append(" ("); // Add columns int i = 0; for (Map.Entry<HugeKeys, String> entry : tableDefine.columns().entrySet()) { sql.append(formatKey(entry.getKey())); sql.append(" "); sql.append(entry.getValue()); if (++i != tableDefine.columns().size()) { sql.append(", "); } } sql.append(")"); // Unique keys sql.append(" UNIQUE KEY("); i = 0; for (HugeKeys key : tableDefine.keys()) { sql.append(formatKey(key)); if (++i != tableDefine.keys().size()) { sql.append(", "); } } sql.append(")"); // Hash keys sql.append(" DISTRIBUTED BY HASH("); i = 0; for (HugeKeys key : tableDefine.keys()) { sql.append(formatKey(key)); if (++i != tableDefine.keys().size()) { sql.append(", "); } } sql.append(");"); // TODO: 'replication_num(default=3)’ can be a configuration LOG.debug("Create table: {}", sql); try { session.execute(sql.toString()); } catch (SQLException e) { throw new BackendException("Failed to create table with '%s'", e, sql); } } @Override protected void appendPartition(StringBuilder delete) { delete.append(" PARTITION ").append(this.table()); } @Override public void insert(MysqlSessions.Session session, MysqlBackendEntry.Row entry) {<FILL_FUNCTION_BODY>} }
assert session instanceof PaloSessions.Session; PaloSessions.Session paloSession = (PaloSessions.Session) session; Set<HugeKeys> columnNames = this.tableDefine().columnNames(); // Ensure column order match with table define List<Object> columnValues = new ArrayList<>(columnNames.size()); for (HugeKeys key : columnNames) { columnValues.add(entry.column(key)); } String insert = StringUtils.join(columnValues, "\t"); paloSession.add(this.table(), insert);
584
146
730
<methods>public void <init>(java.lang.String) ,public void append(org.apache.hugegraph.backend.store.mysql.MysqlSessions.Session, org.apache.hugegraph.backend.serializer.TableBackendEntry.Row) ,public void clear(org.apache.hugegraph.backend.store.mysql.MysqlSessions.Session) ,public void delete(org.apache.hugegraph.backend.store.mysql.MysqlSessions.Session, org.apache.hugegraph.backend.serializer.TableBackendEntry.Row) ,public void eliminate(org.apache.hugegraph.backend.store.mysql.MysqlSessions.Session, org.apache.hugegraph.backend.serializer.TableBackendEntry.Row) ,public static java.lang.String formatKey(org.apache.hugegraph.type.define.HugeKeys) ,public static List<java.lang.String> formatKeys(List<org.apache.hugegraph.type.define.HugeKeys>) ,public void init(org.apache.hugegraph.backend.store.mysql.MysqlSessions.Session) ,public void insert(org.apache.hugegraph.backend.store.mysql.MysqlSessions.Session, org.apache.hugegraph.backend.serializer.TableBackendEntry.Row) ,public static org.apache.hugegraph.type.define.HugeKeys parseKey(java.lang.String) ,public Iterator<org.apache.hugegraph.backend.store.BackendEntry> query(org.apache.hugegraph.backend.store.mysql.MysqlSessions.Session, org.apache.hugegraph.backend.query.Query) ,public boolean queryExist(org.apache.hugegraph.backend.store.mysql.MysqlSessions.Session, org.apache.hugegraph.backend.serializer.TableBackendEntry.Row) ,public java.lang.Number queryNumber(org.apache.hugegraph.backend.store.mysql.MysqlSessions.Session, org.apache.hugegraph.backend.query.Query) ,public abstract org.apache.hugegraph.backend.store.TableDefine tableDefine() ,public void truncate(org.apache.hugegraph.backend.store.mysql.MysqlSessions.Session) ,public void updateIfAbsent(org.apache.hugegraph.backend.store.mysql.MysqlSessions.Session, org.apache.hugegraph.backend.serializer.TableBackendEntry.Row) ,public void updateIfPresent(org.apache.hugegraph.backend.store.mysql.MysqlSessions.Session, org.apache.hugegraph.backend.serializer.TableBackendEntry.Row) <variables>private static final java.lang.String DECIMAL,private static final Logger LOG,private java.lang.String deleteTemplate,private java.lang.String insertTemplate,private java.lang.String insertTemplateTtl,private final non-sealed org.apache.hugegraph.backend.store.mysql.MysqlTable.MysqlShardSplitter shardSplitter,private java.lang.String updateIfAbsentTemplate,private java.lang.String updateIfPresentTemplate
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-palo/src/main/java/org/apache/hugegraph/backend/store/palo/PaloTables.java
Index
mergeEntries
class Index extends PaloTableTemplate { public Index(String table) { super(table); } @Override protected BackendEntry mergeEntries(BackendEntry e1, BackendEntry e2) {<FILL_FUNCTION_BODY>} protected abstract String entryId(MysqlBackendEntry entry); }
MysqlBackendEntry current = (MysqlBackendEntry) e1; MysqlBackendEntry next = (MysqlBackendEntry) e2; E.checkState(current == null || current.type().isIndex(), "The current entry must be null or INDEX"); E.checkState(next != null && next.type().isIndex(), "The next entry must be INDEX"); long maxSize = BackendEntryIterator.INLINE_BATCH_SIZE; if (current != null && current.subRows().size() < maxSize) { String currentId = this.entryId(current); String nextId = this.entryId(next); if (currentId.equals(nextId)) { current.subRow(next.row()); return current; } } return next;
88
212
300
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-postgresql/src/main/java/org/apache/hugegraph/backend/store/postgresql/PostgresqlOptions.java
PostgresqlOptions
instance
class PostgresqlOptions extends MysqlOptions { private PostgresqlOptions() { super(); } private static volatile PostgresqlOptions instance; public static synchronized PostgresqlOptions instance() {<FILL_FUNCTION_BODY>} public static final ConfigOption<String> POSTGRESQL_CONNECT_DATABASE = new ConfigOption<>( "jdbc.postgresql.connect_database", "The database used to connect when init store, " + "drop store or check store exist.", disallowEmpty(), "template1" ); }
if (instance == null) { instance = new PostgresqlOptions(); instance.registerOptions(); } return instance;
153
37
190
<methods>public static synchronized org.apache.hugegraph.backend.store.mysql.MysqlOptions instance() <variables>public static final ConfigOption<java.lang.String> JDBC_DRIVER,public static final ConfigOption<java.lang.Boolean> JDBC_FORCED_AUTO_RECONNECT,public static final ConfigOption<java.lang.String> JDBC_PASSWORD,public static final ConfigOption<java.lang.Integer> JDBC_RECONNECT_INTERVAL,public static final ConfigOption<java.lang.Integer> JDBC_RECONNECT_MAX_TIMES,public static final ConfigOption<java.lang.String> JDBC_SSL_MODE,public static final ConfigOption<java.lang.String> JDBC_STORAGE_ENGINE,public static final ConfigOption<java.lang.String> JDBC_URL,public static final ConfigOption<java.lang.String> JDBC_USERNAME,private static volatile org.apache.hugegraph.backend.store.mysql.MysqlOptions instance
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-postgresql/src/main/java/org/apache/hugegraph/backend/store/postgresql/PostgresqlSerializer.java
PostgresqlSerializer
writeIndex
class PostgresqlSerializer extends MysqlSerializer { public PostgresqlSerializer(HugeConfig config) { super(config); } @Override public BackendEntry writeIndex(HugeIndex index) {<FILL_FUNCTION_BODY>} }
TableBackendEntry entry = newBackendEntry(index); /* * When field-values is null and elementIds size is 0, it is * meaningful for deletion of index data in secondary/range index. */ if (index.fieldValues() == null && index.elementIds().isEmpty()) { entry.column(HugeKeys.INDEX_LABEL_ID, index.indexLabel().longId()); } else { Object value = index.fieldValues(); if ("\u0000".equals(value)) { value = Strings.EMPTY; } entry.column(HugeKeys.FIELD_VALUES, value); entry.column(HugeKeys.INDEX_LABEL_ID, index.indexLabel().longId()); entry.column(HugeKeys.ELEMENT_IDS, IdUtil.writeStoredString(index.elementId())); entry.column(HugeKeys.EXPIRED_TIME, index.expiredTime()); entry.subId(index.elementId()); } return entry;
70
265
335
<methods>public void <init>(HugeConfig) ,public org.apache.hugegraph.backend.store.mysql.MysqlBackendEntry newBackendEntry(org.apache.hugegraph.type.HugeType, org.apache.hugegraph.backend.id.Id) ,public org.apache.hugegraph.backend.store.BackendEntry writeOlapVertex(org.apache.hugegraph.structure.HugeVertex) <variables>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-postgresql/src/main/java/org/apache/hugegraph/backend/store/postgresql/PostgresqlSessions.java
PostgresqlSessions
createDatabase
class PostgresqlSessions extends MysqlSessions { private static final Logger LOG = Log.logger(PostgresqlSessions.class); private static final String COCKROACH_DB_CREATE = "CREATE DATABASE %s ENCODING='UTF-8'"; private static final String POSTGRESQL_DB_CREATE = COCKROACH_DB_CREATE + " TEMPLATE=template0 LC_COLLATE='C' " + "LC_CTYPE='C';"; public PostgresqlSessions(HugeConfig config, String database, String store) { super(config, database, store); } @Override public boolean existsDatabase() { String statement = String.format( "SELECT datname FROM pg_catalog.pg_database " + "WHERE datname = '%s';", this.escapedDatabase()); try (Connection conn = this.openWithoutDB(0)) { ResultSet result = conn.createStatement().executeQuery(statement); return result.next(); } catch (Exception e) { throw new BackendException("Failed to obtain database info", e); } } @Override public void createDatabase() {<FILL_FUNCTION_BODY>} @Override protected String buildCreateDatabase(String database) { return String.format(POSTGRESQL_DB_CREATE, database); } @Override protected String buildDropDatabase(String database) { return String.format( "REVOKE CONNECT ON DATABASE %s FROM public;" + "SELECT pg_terminate_backend(pg_stat_activity.pid) " + " FROM pg_stat_activity " + " WHERE pg_stat_activity.datname = %s;" + "DROP DATABASE IF EXISTS %s;", database, escapeAndWrapString(database), database); } @Override protected String buildExistsTable(String table) { return String.format( "SELECT * FROM information_schema.tables " + "WHERE table_schema = 'public' AND table_name = '%s' LIMIT 1;", MysqlUtil.escapeString(table)); } @Override protected URIBuilder newConnectionURIBuilder(String url) throws URISyntaxException { // Suppress error log when database does not exist return new URIBuilder(url).addParameter("loggerLevel", "OFF"); } @Override protected String connectDatabase() { return this.config().get(PostgresqlOptions.POSTGRESQL_CONNECT_DATABASE); } public static String escapeAndWrapString(String value) { StringBuilder builder = new StringBuilder(8 + value.length()); builder.append('\''); try { Utils.escapeLiteral(builder, value, false); } catch (SQLException e) { throw new BackendException("Failed to escape '%s'", e, value); } builder.append('\''); return builder.toString(); } }
// Create database with non-database-session LOG.debug("Create database: {}", this.database()); String sql = this.buildCreateDatabase(this.database()); try (Connection conn = this.openWithoutDB(0)) { try { conn.createStatement().execute(sql); } catch (PSQLException e) { // CockroachDB not support 'template' arg of CREATE DATABASE if (e.getMessage().contains("syntax error at or near " + "\"template\"")) { sql = String.format(COCKROACH_DB_CREATE, this.database()); conn.createStatement().execute(sql); } } } catch (SQLException e) { if (!e.getMessage().endsWith("already exists")) { throw new BackendException("Failed to create database '%s'", e, this.database()); } // Ignore exception if database already exists }
768
238
1,006
<methods>public void <init>(HugeConfig, java.lang.String, java.lang.String) ,public HugeConfig config() ,public void createDatabase() ,public java.lang.String database() ,public void dropDatabase() ,public java.lang.String escapedDatabase() ,public boolean existsDatabase() ,public boolean existsTable(java.lang.String) ,public synchronized void open() throws java.lang.Exception,public void resetConnections() ,public org.apache.hugegraph.backend.store.mysql.MysqlSessions.Session session() <variables>private static final int DROP_DB_TIMEOUT,private static final java.lang.String JDBC_PREFIX,private static final Logger LOG,private HugeConfig config,private java.lang.String database,private volatile boolean opened
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-postgresql/src/main/java/org/apache/hugegraph/backend/store/postgresql/PostgresqlStoreProvider.java
PostgresqlStoreProvider
driverVersion
class PostgresqlStoreProvider extends MysqlStoreProvider { private static final Logger LOG = Log.logger(PostgresqlStoreProvider.class); @Override protected BackendStore newSchemaStore(HugeConfig config, String store) { return new PostgresqlSchemaStore(this, this.database(), store); } @Override protected BackendStore newGraphStore(HugeConfig config, String store) { return new PostgresqlGraphStore(this, this.database(), store); } @Override protected BackendStore newSystemStore(HugeConfig config, String store) { return new PostgresqlSystemStore(this, this.database(), store); } @Override public String type() { return "postgresql"; } @Override public String driverVersion() {<FILL_FUNCTION_BODY>} public static class PostgresqlSchemaStore extends PostgresqlStore { private final PostgresqlTables.Counters counters; public PostgresqlSchemaStore(BackendStoreProvider provider, String database, String store) { super(provider, database, store); this.counters = new PostgresqlTables.Counters(); registerTableManager(HugeType.VERTEX_LABEL, new PostgresqlTables.VertexLabel()); registerTableManager(HugeType.EDGE_LABEL, new PostgresqlTables.EdgeLabel()); registerTableManager(HugeType.PROPERTY_KEY, new PostgresqlTables.PropertyKey()); registerTableManager(HugeType.INDEX_LABEL, new PostgresqlTables.IndexLabel()); } @Override protected Collection<MysqlTable> tables() { List<MysqlTable> tables = new ArrayList<>(super.tables()); tables.add(this.counters); return tables; } @Override public void increaseCounter(HugeType type, long increment) { this.checkOpened(); MysqlSessions.Session session = this.session(type); this.counters.increaseCounter(session, type, increment); } @Override public long getCounter(HugeType type) { this.checkOpened(); MysqlSessions.Session session = this.session(type); return this.counters.getCounter(session, type); } @Override public boolean isSchemaStore() { return true; } } public static class PostgresqlGraphStore extends PostgresqlStore { public PostgresqlGraphStore(BackendStoreProvider provider, String database, String store) { super(provider, database, store); registerTableManager(HugeType.VERTEX, new PostgresqlTables.Vertex(store)); registerTableManager(HugeType.EDGE_OUT, new PostgresqlTables.Edge(store, Directions.OUT)); registerTableManager(HugeType.EDGE_IN, new PostgresqlTables.Edge(store, Directions.IN)); registerTableManager(HugeType.SECONDARY_INDEX, new PostgresqlTables.SecondaryIndex(store)); registerTableManager(HugeType.RANGE_INT_INDEX, new PostgresqlTables.RangeIntIndex(store)); registerTableManager(HugeType.RANGE_FLOAT_INDEX, new PostgresqlTables.RangeFloatIndex(store)); registerTableManager(HugeType.RANGE_LONG_INDEX, new PostgresqlTables.RangeLongIndex(store)); registerTableManager(HugeType.RANGE_DOUBLE_INDEX, new PostgresqlTables.RangeDoubleIndex(store)); registerTableManager(HugeType.SEARCH_INDEX, new PostgresqlTables.SearchIndex(store)); registerTableManager(HugeType.SHARD_INDEX, new PostgresqlTables.ShardIndex(store)); registerTableManager(HugeType.UNIQUE_INDEX, new PostgresqlTables.UniqueIndex(store)); } @Override public boolean isSchemaStore() { return false; } @Override public Id nextId(HugeType type) { throw new UnsupportedOperationException( "PostgresqlGraphStore.nextId()"); } @Override public void increaseCounter(HugeType type, long increment) { throw new UnsupportedOperationException( "PostgresqlGraphStore.increaseCounter()"); } @Override public long getCounter(HugeType type) { throw new UnsupportedOperationException( "PostgresqlGraphStore.getCounter()"); } } public static class PostgresqlSystemStore extends PostgresqlGraphStore { private final PostgresqlTables.Meta meta; public PostgresqlSystemStore(BackendStoreProvider provider, String database, String store) { super(provider, database, store); this.meta = new PostgresqlTables.Meta(); } @Override public void init() { super.init(); this.checkOpened(); MysqlSessions.Session session = this.session(HugeType.META); String driverVersion = this.provider().driverVersion(); this.meta.writeVersion(session, driverVersion); LOG.info("Write down the backend version: {}", driverVersion); } @Override public String storedVersion() { super.init(); this.checkOpened(); MysqlSessions.Session session = this.session(HugeType.META); return this.meta.readVersion(session); } @Override protected Collection<MysqlTable> tables() { List<MysqlTable> tables = new ArrayList<>(super.tables()); tables.add(this.meta); return tables; } } }
/* * Versions history: * [1.0] #441: supports PostgreSQL and Cockroach backend * [1.1] #270 & #398: support shard-index and vertex + sortkey prefix, * also split range table to rangeInt, rangeFloat, * rangeLong and rangeDouble * [1.2] #633: support unique index * [1.3] #661: reduce the storage of vertex/edge id * [1.4] #691: support aggregate property * [1.5] #746: support userdata for indexlabel * [1.6] #894: asStoredString() encoding is changed to signed B64 * instead of sortable B64 * [1.7] #295: support ttl for vertex and edge * [1.8] #1333: support read frequency for property key * [1.9] #1506: rename read frequency to write type * [1.9] #1533: add meta table in system store */ return "1.9";
1,507
289
1,796
<methods>public non-sealed void <init>() ,public java.lang.String driverVersion() ,public java.lang.String type() <variables>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-postgresql/src/main/java/org/apache/hugegraph/backend/store/postgresql/PostgresqlTable.java
PostgresqlTable
buildUpdateForcedParams
class PostgresqlTable extends MysqlTable { private String orderByKeysTemplate = null; public PostgresqlTable(String table) { super(table); } @Override protected String buildDropTemplate() { return String.format("DROP TABLE IF EXISTS %s CASCADE;", this.table()); } @Override protected String buildTruncateTemplate() { return String.format("TRUNCATE TABLE %s CASCADE;", this.table()); } @Override protected String engine(Session session) { return Strings.EMPTY; } @Override protected String buildUpdateForcedTemplate(MysqlBackendEntry.Row entry) { return this.buildInsertKeys(entry, false); } @Override protected List<?> buildUpdateForcedParams(MysqlBackendEntry.Row entry) {<FILL_FUNCTION_BODY>} @Override protected String buildUpdateIfAbsentTemplate(Row entry) { return this.buildInsertKeys(entry, true); } @Override protected List<?> buildUpdateIfAbsentParams(MysqlBackendEntry.Row entry) { return this.buildColumnsParams(entry); } protected String buildInsertKeys(MysqlBackendEntry.Row entry, boolean ignoreConflicts) { StringBuilder insert = new StringBuilder(); insert.append("INSERT INTO ").append(this.table()).append(" ("); int i = 0; int size = entry.columns().size(); for (HugeKeys key : entry.columns().keySet()) { insert.append(formatKey(key)); if (++i != size) { insert.append(", "); } } insert.append(") VALUES ("); for (i = 0; i < size; i++) { insert.append("?"); if (i != size - 1) { insert.append(", "); } } insert.append(")"); i = 0; size = this.tableDefine().keys().size(); insert.append(" ON CONFLICT ("); for (HugeKeys key : this.tableDefine().keys()) { insert.append(formatKey(key)); if (++i != size) { insert.append(", "); } } insert.append(")"); if (ignoreConflicts) { insert.append(" DO NOTHING"); } else { i = 0; size = entry.columns().keySet().size(); insert.append(" DO UPDATE SET "); for (HugeKeys key : entry.columns().keySet()) { insert.append(formatKey(key)).append(" = ?"); if (++i != size) { insert.append(", "); } } } return insert.toString(); } @Override protected String orderByKeys() { // Set order-by to keep results order consistence for PostgreSQL result if (this.orderByKeysTemplate != null) { return this.orderByKeysTemplate; } int i = 0; int size = this.tableDefine().keys().size(); StringBuilder select = new StringBuilder(" ORDER BY "); for (HugeKeys hugeKey : this.tableDefine().keys()) { String key = formatKey(hugeKey); select.append(key).append(" "); select.append("ASC "); if (++i != size) { select.append(", "); } } this.orderByKeysTemplate = select.toString(); return this.orderByKeysTemplate; } @Override protected WhereBuilder newWhereBuilder(boolean startWithWhere) { return new PgWhereBuilder(startWithWhere); } private static class PgWhereBuilder extends WhereBuilder { public PgWhereBuilder(boolean startWithWhere) { super(startWithWhere); } @Override protected String escapeAndWrapString(String value) { if (value.equals("\u0000")) { /* PR-2439 return string of '' */ return "''"; } return PostgresqlSessions.escapeAndWrapString(value); } } }
List<Object> params = new ArrayList<>(); List<Object> allColumns = this.buildColumnsParams(entry); params.addAll(allColumns); params.addAll(allColumns); return params;
1,098
57
1,155
<methods>public void <init>(java.lang.String) ,public void append(org.apache.hugegraph.backend.store.mysql.MysqlSessions.Session, org.apache.hugegraph.backend.serializer.TableBackendEntry.Row) ,public void clear(org.apache.hugegraph.backend.store.mysql.MysqlSessions.Session) ,public void delete(org.apache.hugegraph.backend.store.mysql.MysqlSessions.Session, org.apache.hugegraph.backend.serializer.TableBackendEntry.Row) ,public void eliminate(org.apache.hugegraph.backend.store.mysql.MysqlSessions.Session, org.apache.hugegraph.backend.serializer.TableBackendEntry.Row) ,public static java.lang.String formatKey(org.apache.hugegraph.type.define.HugeKeys) ,public static List<java.lang.String> formatKeys(List<org.apache.hugegraph.type.define.HugeKeys>) ,public void init(org.apache.hugegraph.backend.store.mysql.MysqlSessions.Session) ,public void insert(org.apache.hugegraph.backend.store.mysql.MysqlSessions.Session, org.apache.hugegraph.backend.serializer.TableBackendEntry.Row) ,public static org.apache.hugegraph.type.define.HugeKeys parseKey(java.lang.String) ,public Iterator<org.apache.hugegraph.backend.store.BackendEntry> query(org.apache.hugegraph.backend.store.mysql.MysqlSessions.Session, org.apache.hugegraph.backend.query.Query) ,public boolean queryExist(org.apache.hugegraph.backend.store.mysql.MysqlSessions.Session, org.apache.hugegraph.backend.serializer.TableBackendEntry.Row) ,public java.lang.Number queryNumber(org.apache.hugegraph.backend.store.mysql.MysqlSessions.Session, org.apache.hugegraph.backend.query.Query) ,public abstract org.apache.hugegraph.backend.store.TableDefine tableDefine() ,public void truncate(org.apache.hugegraph.backend.store.mysql.MysqlSessions.Session) ,public void updateIfAbsent(org.apache.hugegraph.backend.store.mysql.MysqlSessions.Session, org.apache.hugegraph.backend.serializer.TableBackendEntry.Row) ,public void updateIfPresent(org.apache.hugegraph.backend.store.mysql.MysqlSessions.Session, org.apache.hugegraph.backend.serializer.TableBackendEntry.Row) <variables>private static final java.lang.String DECIMAL,private static final Logger LOG,private java.lang.String deleteTemplate,private java.lang.String insertTemplate,private java.lang.String insertTemplateTtl,private final non-sealed org.apache.hugegraph.backend.store.mysql.MysqlTable.MysqlShardSplitter shardSplitter,private java.lang.String updateIfAbsentTemplate,private java.lang.String updateIfPresentTemplate
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-postgresql/src/main/java/org/apache/hugegraph/backend/store/postgresql/PostgresqlTables.java
Counters
increaseCounter
class Counters extends PostgresqlTableTemplate { public Counters() { super(new MysqlTables.Counters(TYPES_MAPPING)); } public long getCounter(Session session, HugeType type) { MysqlTables.Counters table = (MysqlTables.Counters) this.template; return table.getCounter(session, type); } public void increaseCounter(Session session, HugeType type, long increment) {<FILL_FUNCTION_BODY>} }
String update = String.format( "INSERT INTO %s (%s, %s) VALUES ('%s', %s) " + "ON CONFLICT (%s) DO UPDATE SET ID = %s.ID + %s;", this.table(), formatKey(HugeKeys.SCHEMA_TYPE), formatKey(HugeKeys.ID), type.name(), increment, formatKey(HugeKeys.SCHEMA_TYPE), this.table(), increment); try { session.execute(update); } catch (SQLException e) { throw new BackendException( "Failed to update counters with type '%s'", e, type); }
139
172
311
<no_super_class>