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-api/src/main/java/org/apache/hugegraph/api/traversers/AdamicAdarAPI.java
AdamicAdarAPI
get
class AdamicAdarAPI extends API { @GET @Timed @Produces(APPLICATION_JSON_WITH_CHARSET) public String get(@Context GraphManager manager, @PathParam("graph") String graph, @QueryParam("vertex") String current, @QueryParam("other") String other, @QueryParam("direction") String direction, @QueryParam("label") String edgeLabel, @QueryParam("max_degree") @DefaultValue(DEFAULT_MAX_DEGREE) long maxDegree, @QueryParam("limit") @DefaultValue(DEFAULT_ELEMENTS_LIMIT) int limit) {<FILL_FUNCTION_BODY>} }
LOG.debug("Graph [{}] get adamic adar between '{}' and '{}' with " + "direction {}, edge label {}, max degree '{}' and limit '{}'", graph, current, other, direction, edgeLabel, maxDegree, limit); Id sourceId = VertexAPI.checkAndParseVertexId(current); Id targetId = VertexAPI.checkAndParseVertexId(other); E.checkArgument(!current.equals(other), "The source and target vertex id can't be same"); Directions dir = Directions.convert(EdgeAPI.parseDirection(direction)); HugeGraph g = graph(manager, graph); try (PredictionTraverser traverser = new PredictionTraverser(g)) { double score = traverser.adamicAdar(sourceId, targetId, dir, edgeLabel, maxDegree, limit); return JsonUtil.toJson(ImmutableMap.of("adamic_adar", score)); }
174
253
427
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/traversers/CountAPI.java
CountAPI
post
class CountAPI extends API { private static final Logger LOG = Log.logger(CountAPI.class); @POST @Timed @Produces(APPLICATION_JSON_WITH_CHARSET) public String post(@Context GraphManager manager, @PathParam("graph") String graph, CountRequest request) {<FILL_FUNCTION_BODY>} private static List<EdgeStep> steps(HugeGraph graph, CountRequest request) { int stepSize = request.steps.size(); List<EdgeStep> steps = new ArrayList<>(stepSize); for (Step step : request.steps) { steps.add(step.jsonToStep(graph)); } return steps; } private static class CountRequest { @JsonProperty("source") public Object source; @JsonProperty("steps") public List<Step> steps; @JsonProperty("contains_traversed") public boolean containsTraversed = false; @JsonProperty("dedup_size") public long dedupSize = 1000000L; @Override public String toString() { return String.format("CountRequest{source=%s,steps=%s," + "containsTraversed=%s,dedupSize=%s}", this.source, this.steps, this.containsTraversed, this.dedupSize); } } private static class Step { @JsonProperty("direction") public Directions direction = Directions.BOTH; @JsonProperty("labels") public List<String> labels; @JsonProperty("properties") public Map<String, Object> properties; @JsonAlias("degree") @JsonProperty("max_degree") public long maxDegree = Long.parseLong(DEFAULT_MAX_DEGREE); @JsonProperty("skip_degree") public long skipDegree = Long.parseLong(DEFAULT_SKIP_DEGREE); @Override public String toString() { return String.format("Step{direction=%s,labels=%s,properties=%s" + "maxDegree=%s,skipDegree=%s}", this.direction, this.labels, this.properties, this.maxDegree, this.skipDegree); } private EdgeStep jsonToStep(HugeGraph graph) { return new EdgeStep(graph, this.direction, this.labels, this.properties, this.maxDegree, this.skipDegree); } } }
LOG.debug("Graph [{}] get count from '{}' with request {}", graph, request); E.checkArgumentNotNull(request.source, "The source of request can't be null"); Id sourceId = HugeVertex.getIdValue(request.source); E.checkArgumentNotNull(request.steps != null && !request.steps.isEmpty(), "The steps of request can't be null or empty"); E.checkArgumentNotNull(request.dedupSize == NO_LIMIT || request.dedupSize >= 0L, "The dedup size of request " + "must >= 0 or == -1, but got: '%s'", request.dedupSize); HugeGraph g = graph(manager, graph); List<EdgeStep> steps = steps(g, request); CountTraverser traverser = new CountTraverser(g); long count = traverser.count(sourceId, steps, request.containsTraversed, request.dedupSize); return manager.serializer(g).writeMap(ImmutableMap.of("count", count));
652
280
932
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/traversers/CrosspointsAPI.java
CrosspointsAPI
get
class CrosspointsAPI extends API { private static final Logger LOG = Log.logger(CrosspointsAPI.class); @GET @Timed @Produces(APPLICATION_JSON_WITH_CHARSET) public String get(@Context GraphManager manager, @PathParam("graph") String graph, @QueryParam("source") String source, @QueryParam("target") String target, @QueryParam("direction") String direction, @QueryParam("label") String edgeLabel, @QueryParam("max_depth") int depth, @QueryParam("max_degree") @DefaultValue(DEFAULT_MAX_DEGREE) long maxDegree, @QueryParam("capacity") @DefaultValue(DEFAULT_CAPACITY) long capacity, @QueryParam("limit") @DefaultValue(DEFAULT_PATHS_LIMIT) int limit) {<FILL_FUNCTION_BODY>} }
LOG.debug("Graph [{}] get crosspoints with paths from '{}', to '{}' " + "with direction '{}', edge label '{}', max depth '{}', " + "max degree '{}', capacity '{}' and limit '{}'", graph, source, target, direction, edgeLabel, depth, maxDegree, capacity, limit); ApiMeasurer measure = new ApiMeasurer(); Id sourceId = VertexAPI.checkAndParseVertexId(source); Id targetId = VertexAPI.checkAndParseVertexId(target); Directions dir = Directions.convert(EdgeAPI.parseDirection(direction)); HugeGraph g = graph(manager, graph); PathsTraverser traverser = new PathsTraverser(g); HugeTraverser.PathSet paths = traverser.paths(sourceId, dir, targetId, dir, edgeLabel, depth, maxDegree, capacity, limit); measure.addIterCount(traverser.vertexIterCounter.get(), traverser.edgeIterCounter.get()); return manager.serializer(g, measure.measures()) .writePaths("crosspoints", paths, true);
234
314
548
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/traversers/CustomizedCrosspointsAPI.java
CustomizedCrosspointsAPI
pathPatterns
class CustomizedCrosspointsAPI extends API { private static final Logger LOG = Log.logger(CustomizedCrosspointsAPI.class); private static List<CustomizedCrosspointsTraverser.PathPattern> pathPatterns( HugeGraph graph, CrosspointsRequest request) {<FILL_FUNCTION_BODY>} @POST @Timed @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON_WITH_CHARSET) public String post(@Context GraphManager manager, @PathParam("graph") String graph, CrosspointsRequest request) { E.checkArgumentNotNull(request, "The crosspoints request body can't be null"); E.checkArgumentNotNull(request.sources, "The sources of crosspoints request " + "can't be null"); E.checkArgument(request.pathPatterns != null && !request.pathPatterns.isEmpty(), "The steps of crosspoints request can't be empty"); LOG.debug("Graph [{}] get customized crosspoints from source vertex " + "'{}', with path_pattern '{}', with path '{}', with_vertex " + "'{}', capacity '{}', limit '{}' and with_edge '{}'", graph, request.sources, request.pathPatterns, request.withPath, request.withVertex, request.capacity, request.limit, request.withEdge); ApiMeasurer measure = new ApiMeasurer(); HugeGraph g = graph(manager, graph); Iterator<Vertex> sources = request.sources.vertices(g); CustomizedCrosspointsTraverser traverser = new CustomizedCrosspointsTraverser(g); List<CustomizedCrosspointsTraverser.PathPattern> patterns = pathPatterns(g, request); CustomizedCrosspointsTraverser.CrosspointsPaths paths = traverser.crosspointsPaths(sources, patterns, request.capacity, request.limit); measure.addIterCount(traverser.vertexIterCounter.get(), traverser.edgeIterCounter.get()); Iterator<?> iterVertex; Set<Id> vertexIds = new HashSet<>(); if (request.withPath) { for (HugeTraverser.Path path : paths.paths()) { vertexIds.addAll(path.vertices()); } } else { vertexIds = paths.crosspoints(); } if (request.withVertex && !vertexIds.isEmpty()) { iterVertex = g.vertices(vertexIds.toArray()); measure.addIterCount(vertexIds.size(), 0L); } else { iterVertex = vertexIds.iterator(); } Iterator<?> iterEdge = Collections.emptyIterator(); if (request.withPath) { Set<Edge> edges = traverser.edgeResults().getEdges(paths.paths()); if (request.withEdge) { iterEdge = edges.iterator(); } else { iterEdge = HugeTraverser.EdgeRecord.getEdgeIds(edges).iterator(); } } return manager.serializer(g, measure.measures()) .writeCrosspoints(paths, iterVertex, iterEdge, request.withPath); } private static class CrosspointsRequest { @JsonProperty("sources") public Vertices sources; @JsonProperty("path_patterns") public List<PathPattern> pathPatterns; @JsonProperty("capacity") public long capacity = Long.parseLong(DEFAULT_CAPACITY); @JsonProperty("limit") public int limit = Integer.parseInt(DEFAULT_PATHS_LIMIT); @JsonProperty("with_path") public boolean withPath = false; @JsonProperty("with_vertex") public boolean withVertex = false; @JsonProperty("with_edge") public boolean withEdge = false; @Override public String toString() { return String.format("CrosspointsRequest{sourceVertex=%s," + "pathPatterns=%s,withPath=%s,withVertex=%s," + "capacity=%s,limit=%s,withEdge=%s}", this.sources, this.pathPatterns, this.withPath, this.withVertex, this.capacity, this.limit, this.withEdge); } } private static class PathPattern { @JsonProperty("steps") public List<Step> steps; @Override public String toString() { return String.format("PathPattern{steps=%s", this.steps); } } private static class Step { @JsonProperty("direction") public Directions direction; @JsonProperty("labels") public List<String> labels; @JsonProperty("properties") public Map<String, Object> properties; @JsonAlias("degree") @JsonProperty("max_degree") public long maxDegree = Long.parseLong(DEFAULT_MAX_DEGREE); @JsonProperty("skip_degree") public long skipDegree = 0L; @Override public String toString() { return String.format("Step{direction=%s,labels=%s,properties=%s," + "maxDegree=%s,skipDegree=%s}", this.direction, this.labels, this.properties, this.maxDegree, this.skipDegree); } private CustomizedCrosspointsTraverser.Step jsonToStep(HugeGraph g) { return new CustomizedCrosspointsTraverser.Step(g, this.direction, this.labels, this.properties, this.maxDegree, this.skipDegree); } } }
int stepSize = request.pathPatterns.size(); List<CustomizedCrosspointsTraverser.PathPattern> pathPatterns = new ArrayList<>(stepSize); for (PathPattern pattern : request.pathPatterns) { CustomizedCrosspointsTraverser.PathPattern pathPattern = new CustomizedCrosspointsTraverser.PathPattern(); for (Step step : pattern.steps) { pathPattern.add(step.jsonToStep(graph)); } pathPatterns.add(pathPattern); } return pathPatterns;
1,524
147
1,671
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/traversers/CustomizedPathsAPI.java
CustomizedPathsAPI
post
class CustomizedPathsAPI extends API { private static final Logger LOG = Log.logger(CustomizedPathsAPI.class); private static List<WeightedEdgeStep> step(HugeGraph graph, PathRequest request) { int stepSize = request.steps.size(); List<WeightedEdgeStep> steps = new ArrayList<>(stepSize); for (Step step : request.steps) { steps.add(step.jsonToStep(graph)); } return steps; } @POST @Timed @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON_WITH_CHARSET) public String post(@Context GraphManager manager, @PathParam("graph") String graph, PathRequest request) {<FILL_FUNCTION_BODY>} private enum SortBy { INCR, DECR, NONE } private static class PathRequest { @JsonProperty("sources") public Vertices sources; @JsonProperty("steps") public List<Step> steps; @JsonProperty("sort_by") public SortBy sortBy; @JsonProperty("capacity") public long capacity = Long.parseLong(DEFAULT_CAPACITY); @JsonProperty("limit") public int limit = Integer.parseInt(DEFAULT_PATHS_LIMIT); @JsonProperty("with_vertex") public boolean withVertex = false; @JsonProperty("with_edge") public boolean withEdge = false; @Override public String toString() { return String.format("PathRequest{sourceVertex=%s,steps=%s," + "sortBy=%s,capacity=%s,limit=%s," + "withVertex=%s,withEdge=%s}", this.sources, this.steps, this.sortBy, this.capacity, this.limit, this.withVertex, this.withEdge); } } private static class Step { @JsonProperty("direction") public Directions direction; @JsonProperty("labels") public List<String> labels; @JsonProperty("properties") public Map<String, Object> properties; @JsonAlias("degree") @JsonProperty("max_degree") public long maxDegree = Long.parseLong(DEFAULT_MAX_DEGREE); @JsonProperty("skip_degree") public long skipDegree = 0L; @JsonProperty("weight_by") public String weightBy; @JsonProperty("default_weight") public double defaultWeight = Double.parseDouble(DEFAULT_WEIGHT); @JsonProperty("sample") public long sample = Long.parseLong(DEFAULT_SAMPLE); @Override public String toString() { return String.format("Step{direction=%s,labels=%s,properties=%s," + "maxDegree=%s,skipDegree=%s," + "weightBy=%s,defaultWeight=%s,sample=%s}", this.direction, this.labels, this.properties, this.maxDegree, this.skipDegree, this.weightBy, this.defaultWeight, this.sample); } private WeightedEdgeStep jsonToStep(HugeGraph g) { return new WeightedEdgeStep(g, this.direction, this.labels, this.properties, this.maxDegree, this.skipDegree, this.weightBy, this.defaultWeight, this.sample); } } }
E.checkArgumentNotNull(request, "The path request body can't be null"); E.checkArgumentNotNull(request.sources, "The sources of path request can't be null"); E.checkArgument(request.steps != null && !request.steps.isEmpty(), "The steps of path request can't be empty"); if (request.sortBy == null) { request.sortBy = SortBy.NONE; } LOG.debug("Graph [{}] get customized paths from source vertex '{}', " + "with steps '{}', sort by '{}', capacity '{}', limit '{}', " + "with_vertex '{}' and with_edge '{}'", graph, request.sources, request.steps, request.sortBy, request.capacity, request.limit, request.withVertex, request.withEdge); ApiMeasurer measure = new ApiMeasurer(); HugeGraph g = graph(manager, graph); Iterator<Vertex> sources = request.sources.vertices(g); List<WeightedEdgeStep> steps = step(g, request); boolean sorted = request.sortBy != SortBy.NONE; CustomizePathsTraverser traverser = new CustomizePathsTraverser(g); List<HugeTraverser.Path> paths; paths = traverser.customizedPaths(sources, steps, sorted, request.capacity, request.limit); measure.addIterCount(traverser.vertexIterCounter.get(), traverser.edgeIterCounter.get()); if (sorted) { boolean incr = request.sortBy == SortBy.INCR; paths = CustomizePathsTraverser.topNPath(paths, incr, request.limit); } Iterator<?> iterVertex; Set<Id> vertexIds = new HashSet<>(); for (HugeTraverser.Path path : paths) { vertexIds.addAll(path.vertices()); } if (request.withVertex && !vertexIds.isEmpty()) { iterVertex = g.vertices(vertexIds.toArray()); measure.addIterCount(vertexIds.size(), 0L); } else { iterVertex = vertexIds.iterator(); } Iterator<?> iterEdge; Set<Edge> edges = traverser.edgeResults().getEdges(paths); if (request.withEdge && !edges.isEmpty()) { iterEdge = edges.iterator(); } else { iterEdge = HugeTraverser.EdgeRecord.getEdgeIds(edges).iterator(); } return manager.serializer(g, measure.measures()) .writePaths("paths", paths, false, iterVertex, iterEdge);
903
699
1,602
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/traversers/EdgeExistenceAPI.java
EdgeExistenceAPI
get
class EdgeExistenceAPI extends TraverserAPI { private static final Logger LOG = Log.logger(EdgeExistenceAPI.class); private static final String DEFAULT_EMPTY = ""; @GET @Timed @Produces(APPLICATION_JSON_WITH_CHARSET) @Operation(summary = "get edges from 'source' to 'target' vertex") public String get(@Context GraphManager manager, @PathParam("graph") String graph, @QueryParam("source") String source, @QueryParam("target") String target, @QueryParam("label") String edgeLabel, @QueryParam("sort_values") @DefaultValue(DEFAULT_EMPTY) String sortValues, @QueryParam("limit") @DefaultValue(DEFAULT_LIMIT) long limit) {<FILL_FUNCTION_BODY>} }
LOG.debug("Graph [{}] get edgeExistence with " + "source '{}', target '{}', edgeLabel '{}', sortValue '{}', limit '{}'", graph, source, target, edgeLabel, sortValues, limit); E.checkArgumentNotNull(source, "The source can't be null"); E.checkArgumentNotNull(target, "The target can't be null"); Id sourceId = VertexAPI.checkAndParseVertexId(source); Id targetId = VertexAPI.checkAndParseVertexId(target); HugeGraph hugegraph = graph(manager, graph); EdgeExistenceTraverser traverser = new EdgeExistenceTraverser(hugegraph); Iterator<Edge> edges = traverser.queryEdgeExistence(sourceId, targetId, edgeLabel, sortValues, limit); return manager.serializer(hugegraph).writeEdges(edges, false);
212
233
445
<methods>public non-sealed void <init>() <variables>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/traversers/EdgesAPI.java
EdgesAPI
shards
class EdgesAPI extends API { private static final Logger LOG = Log.logger(EdgesAPI.class); @GET @Timed @Compress @Produces(APPLICATION_JSON_WITH_CHARSET) public String list(@Context GraphManager manager, @PathParam("graph") String graph, @QueryParam("ids") List<String> stringIds) { LOG.debug("Graph [{}] get edges by ids: {}", graph, stringIds); E.checkArgument(stringIds != null && !stringIds.isEmpty(), "The ids parameter can't be null or empty"); Object[] ids = new Id[stringIds.size()]; for (int i = 0; i < ids.length; i++) { ids[i] = HugeEdge.getIdValue(stringIds.get(i), false); } HugeGraph g = graph(manager, graph); Iterator<Edge> edges = g.edges(ids); return manager.serializer(g).writeEdges(edges, false); } @GET @Timed @Path("shards") @Compress @Produces(APPLICATION_JSON_WITH_CHARSET) public String shards(@Context GraphManager manager, @PathParam("graph") String graph, @QueryParam("split_size") long splitSize) {<FILL_FUNCTION_BODY>} @GET @Timed @Path("scan") @Compress @Produces(APPLICATION_JSON_WITH_CHARSET) public String scan(@Context GraphManager manager, @PathParam("graph") String graph, @QueryParam("start") String start, @QueryParam("end") String end, @QueryParam("page") String page, @QueryParam("page_limit") @DefaultValue(DEFAULT_PAGE_LIMIT) long pageLimit) { LOG.debug("Graph [{}] query edges by shard(start: {}, end: {}, " + "page: {}) ", graph, start, end, page); HugeGraph g = graph(manager, graph); ConditionQuery query = new ConditionQuery(HugeType.EDGE_OUT); query.scan(start, end); query.page(page); if (query.paging()) { query.limit(pageLimit); } Iterator<Edge> edges = g.edges(query); return manager.serializer(g).writeEdges(edges, query.paging()); } }
LOG.debug("Graph [{}] get vertex shards with split size '{}'", graph, splitSize); HugeGraph g = graph(manager, graph); List<Shard> shards = g.metadata(HugeType.EDGE_OUT, "splits", splitSize); return manager.serializer(g).writeList("shards", shards);
644
94
738
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/traversers/FusiformSimilarityAPI.java
FusiformSimilarityAPI
post
class FusiformSimilarityAPI extends API { private static final Logger LOG = Log.logger(FusiformSimilarityAPI.class); @POST @Timed @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON_WITH_CHARSET) public String post(@Context GraphManager manager, @PathParam("graph") String graph, FusiformSimilarityRequest request) {<FILL_FUNCTION_BODY>} private static class FusiformSimilarityRequest { @JsonProperty("sources") public Vertices sources; @JsonProperty("label") public String label; @JsonProperty("direction") public Directions direction; @JsonProperty("min_neighbors") public int minNeighbors; @JsonProperty("alpha") public double alpha; @JsonProperty("min_similars") public int minSimilars = 1; @JsonProperty("top") public int top; @JsonProperty("group_property") public String groupProperty; @JsonProperty("min_groups") public int minGroups; @JsonProperty("max_degree") public long maxDegree = Long.parseLong(DEFAULT_MAX_DEGREE); @JsonProperty("capacity") public long capacity = Long.parseLong(DEFAULT_CAPACITY); @JsonProperty("limit") public int limit = Integer.parseInt(DEFAULT_PATHS_LIMIT); @JsonProperty("with_intermediary") public boolean withIntermediary = false; @JsonProperty("with_vertex") public boolean withVertex = false; @Override public String toString() { return String.format("FusiformSimilarityRequest{sources=%s," + "label=%s,direction=%s,minNeighbors=%s," + "alpha=%s,minSimilars=%s,top=%s," + "groupProperty=%s,minGroups=%s," + "maxDegree=%s,capacity=%s,limit=%s," + "withIntermediary=%s,withVertex=%s}", this.sources, this.label, this.direction, this.minNeighbors, this.alpha, this.minSimilars, this.top, this.groupProperty, this.minGroups, this.maxDegree, this.capacity, this.limit, this.withIntermediary, this.withVertex); } } }
E.checkArgumentNotNull(request, "The fusiform similarity " + "request body can't be null"); E.checkArgumentNotNull(request.sources, "The sources of fusiform similarity " + "request can't be null"); if (request.direction == null) { request.direction = Directions.BOTH; } E.checkArgument(request.minNeighbors > 0, "The min neighbor count must be > 0, but got: %s", request.minNeighbors); E.checkArgument(request.maxDegree > 0L || request.maxDegree == NO_LIMIT, "The max degree of request must be > 0 or == -1, " + "but got: %s", request.maxDegree); E.checkArgument(request.alpha > 0 && request.alpha <= 1.0, "The alpha of request must be in range (0, 1], " + "but got '%s'", request.alpha); E.checkArgument(request.minSimilars >= 1, "The min similar count of request must be >= 1, " + "but got: %s", request.minSimilars); E.checkArgument(request.top >= 0, "The top must be >= 0, but got: %s", request.top); LOG.debug("Graph [{}] get fusiform similars from '{}' with " + "direction '{}', edge label '{}', min neighbor count '{}', " + "alpha '{}', min similar count '{}', group property '{}' " + "and min group count '{}'", graph, request.sources, request.direction, request.label, request.minNeighbors, request.alpha, request.minSimilars, request.groupProperty, request.minGroups); ApiMeasurer measure = new ApiMeasurer(); HugeGraph g = graph(manager, graph); Iterator<Vertex> sources = request.sources.vertices(g); E.checkArgument(sources != null && sources.hasNext(), "The source vertices can't be empty"); FusiformSimilarityTraverser traverser = new FusiformSimilarityTraverser(g); SimilarsMap result = traverser.fusiformSimilarity( sources, request.direction, request.label, request.minNeighbors, request.alpha, request.minSimilars, request.top, request.groupProperty, request.minGroups, request.maxDegree, request.capacity, request.limit, request.withIntermediary); CloseableIterator.closeIterator(sources); measure.addIterCount(traverser.vertexIterCounter.get(), traverser.edgeIterCounter.get()); Iterator<?> iterVertex; Set<Id> vertexIds = result.vertices(); if (request.withVertex && !vertexIds.isEmpty()) { iterVertex = g.vertices(vertexIds.toArray()); measure.addIterCount(vertexIds.size(), 0); } else { iterVertex = vertexIds.iterator(); } return manager.serializer(g, measure.measures()) .writeSimilars(result, iterVertex);
639
822
1,461
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/traversers/JaccardSimilarityAPI.java
JaccardSimilarityAPI
post
class JaccardSimilarityAPI extends TraverserAPI { private static final Logger LOG = Log.logger(JaccardSimilarityAPI.class); @GET @Timed @Produces(APPLICATION_JSON_WITH_CHARSET) public String get(@Context GraphManager manager, @PathParam("graph") String graph, @QueryParam("vertex") String vertex, @QueryParam("other") String other, @QueryParam("direction") String direction, @QueryParam("label") String edgeLabel, @QueryParam("max_degree") @DefaultValue(DEFAULT_MAX_DEGREE) long maxDegree) { LOG.debug("Graph [{}] get jaccard similarity between '{}' and '{}' " + "with direction {}, edge label {} and max degree '{}'", graph, vertex, other, direction, edgeLabel, maxDegree); ApiMeasurer measure = new ApiMeasurer(); Id sourceId = VertexAPI.checkAndParseVertexId(vertex); Id targetId = VertexAPI.checkAndParseVertexId(other); Directions dir = Directions.convert(EdgeAPI.parseDirection(direction)); HugeGraph g = graph(manager, graph); double similarity; try (JaccardSimilarTraverser traverser = new JaccardSimilarTraverser(g)) { similarity = traverser.jaccardSimilarity(sourceId, targetId, dir, edgeLabel, maxDegree); measure.addIterCount(traverser.vertexIterCounter.get(), traverser.edgeIterCounter.get()); } return manager.serializer(g, measure.measures()) .writeMap(ImmutableMap.of("jaccard_similarity", similarity)); } @POST @Timed @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON_WITH_CHARSET) public String post(@Context GraphManager manager, @PathParam("graph") String graph, Request request) {<FILL_FUNCTION_BODY>} private static class Request { @JsonProperty("vertex") public Object vertex; @JsonProperty("step") public TraverserAPI.Step step; @JsonProperty("top") public int top = Integer.parseInt(DEFAULT_LIMIT); @JsonProperty("capacity") public long capacity = Long.parseLong(DEFAULT_CAPACITY); @Override public String toString() { return String.format("Request{vertex=%s,step=%s,top=%s," + "capacity=%s}", this.vertex, this.step, this.top, this.capacity); } } }
E.checkArgumentNotNull(request, "The request body can't be null"); E.checkArgumentNotNull(request.vertex, "The source vertex of request can't be null"); E.checkArgument(request.step != null, "The steps of request can't be null"); E.checkArgument(request.top >= 0, "The top must be >= 0, but got: %s", request.top); LOG.debug("Graph [{}] get jaccard similars from source vertex '{}', " + "with step '{}', top '{}' and capacity '{}'", graph, request.vertex, request.step, request.top, request.capacity); ApiMeasurer measure = new ApiMeasurer(); HugeGraph g = graph(manager, graph); Id sourceId = HugeVertex.getIdValue(request.vertex); EdgeStep step = step(g, request.step); Map<Id, Double> results; try (JaccardSimilarTraverser traverser = new JaccardSimilarTraverser(g)) { results = traverser.jaccardSimilars(sourceId, step, request.top, request.capacity); measure.addIterCount(traverser.vertexIterCounter.get(), traverser.edgeIterCounter.get()); } return manager.serializer(g, measure.measures()) .writeMap(ImmutableMap.of("jaccard_similarity", results));
693
376
1,069
<methods>public non-sealed void <init>() <variables>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/traversers/KneighborAPI.java
KneighborAPI
post
class KneighborAPI extends TraverserAPI { private static final Logger LOG = Log.logger(KneighborAPI.class); @GET @Timed @Produces(APPLICATION_JSON_WITH_CHARSET) public String get(@Context GraphManager manager, @PathParam("graph") String graph, @QueryParam("source") String sourceV, @QueryParam("direction") String direction, @QueryParam("label") String edgeLabel, @QueryParam("max_depth") int depth, @QueryParam("count_only") @DefaultValue("false") boolean countOnly, @QueryParam("max_degree") @DefaultValue(DEFAULT_MAX_DEGREE) long maxDegree, @QueryParam("limit") @DefaultValue(DEFAULT_ELEMENTS_LIMIT) int limit) { LOG.debug("Graph [{}] get k-neighbor from '{}' with " + "direction '{}', edge label '{}', max depth '{}', " + "max degree '{}' and limit '{}'", graph, sourceV, direction, edgeLabel, depth, maxDegree, limit); ApiMeasurer measure = new ApiMeasurer(); Id source = VertexAPI.checkAndParseVertexId(sourceV); Directions dir = Directions.convert(EdgeAPI.parseDirection(direction)); HugeGraph g = graph(manager, graph); Set<Id> ids; try (KneighborTraverser traverser = new KneighborTraverser(g)) { ids = traverser.kneighbor(source, dir, edgeLabel, depth, maxDegree, limit); measure.addIterCount(traverser.vertexIterCounter.get(), traverser.edgeIterCounter.get()); } if (countOnly) { return manager.serializer(g, measure.measures()) .writeMap(ImmutableMap.of("vertices_size", ids.size())); } return manager.serializer(g, measure.measures()).writeList("vertices", ids); } @POST @Timed @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON_WITH_CHARSET) public String post(@Context GraphManager manager, @PathParam("graph") String graph, Request request) {<FILL_FUNCTION_BODY>} private static class Request { @JsonProperty("source") public Object source; @JsonProperty("steps") public TraverserAPI.VESteps steps; @JsonProperty("max_depth") public int maxDepth; @JsonProperty("limit") public int limit = Integer.parseInt(DEFAULT_ELEMENTS_LIMIT); @JsonProperty("count_only") public boolean countOnly = false; @JsonProperty("with_vertex") public boolean withVertex = false; @JsonProperty("with_path") public boolean withPath = false; @JsonProperty("with_edge") public boolean withEdge = false; @Override public String toString() { return String.format("PathRequest{source=%s,steps=%s,maxDepth=%s" + "limit=%s,countOnly=%s,withVertex=%s," + "withPath=%s,withEdge=%s}", this.source, this.steps, this.maxDepth, this.limit, this.countOnly, this.withVertex, this.withPath, this.withEdge); } } }
E.checkArgumentNotNull(request, "The request body can't be null"); E.checkArgumentNotNull(request.source, "The source of request can't be null"); E.checkArgument(request.steps != null, "The steps of request can't be null"); if (request.countOnly) { E.checkArgument(!request.withVertex && !request.withPath && !request.withEdge, "Can't return vertex, edge or path when count only"); } LOG.debug("Graph [{}] get customized kneighbor from source vertex " + "'{}', with steps '{}', limit '{}', count_only '{}', " + "with_vertex '{}', with_path '{}' and with_edge '{}'", graph, request.source, request.steps, request.limit, request.countOnly, request.withVertex, request.withPath, request.withEdge); ApiMeasurer measure = new ApiMeasurer(); HugeGraph g = graph(manager, graph); Id sourceId = HugeVertex.getIdValue(request.source); Steps steps = steps(g, request.steps); KneighborRecords results; try (KneighborTraverser traverser = new KneighborTraverser(g)) { results = traverser.customizedKneighbor(sourceId, steps, request.maxDepth, request.limit); measure.addIterCount(traverser.vertexIterCounter.get(), traverser.edgeIterCounter.get()); } long size = results.size(); if (request.limit != NO_LIMIT && size > request.limit) { size = request.limit; } List<Id> neighbors = request.countOnly ? ImmutableList.of() : results.ids(request.limit); HugeTraverser.PathSet paths = new HugeTraverser.PathSet(); if (request.withPath) { paths.addAll(results.paths(request.limit)); } if (request.countOnly) { return manager.serializer(g, measure.measures()) .writeNodesWithPath("kneighbor", neighbors, size, paths, QueryResults.emptyIterator(), QueryResults.emptyIterator()); } Iterator<?> iterVertex; Set<Id> vertexIds = new HashSet<>(neighbors); if (request.withPath) { for (HugeTraverser.Path p : paths) { vertexIds.addAll(p.vertices()); } } if (request.withVertex && !vertexIds.isEmpty()) { iterVertex = g.vertices(vertexIds.toArray()); measure.addIterCount(vertexIds.size(), 0L); } else { iterVertex = vertexIds.iterator(); } Iterator<?> iterEdge = Collections.emptyIterator(); if (request.withPath) { Set<Edge> edges = results.edgeResults().getEdges(paths); if (request.withEdge) { iterEdge = edges.iterator(); } else { iterEdge = HugeTraverser.EdgeRecord.getEdgeIds(edges).iterator(); } } return manager.serializer(g, measure.measures()) .writeNodesWithPath("kneighbor", neighbors, size, paths, iterVertex, iterEdge);
900
867
1,767
<methods>public non-sealed void <init>() <variables>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/traversers/NeighborRankAPI.java
NeighborRankAPI
neighborRank
class NeighborRankAPI extends API { private static final Logger LOG = Log.logger(NeighborRankAPI.class); @POST @Timed @Produces(APPLICATION_JSON_WITH_CHARSET) public String neighborRank(@Context GraphManager manager, @PathParam("graph") String graph, RankRequest request) {<FILL_FUNCTION_BODY>} private static List<NeighborRankTraverser.Step> steps(HugeGraph graph, RankRequest req) { List<NeighborRankTraverser.Step> steps = new ArrayList<>(); for (Step step : req.steps) { steps.add(step.jsonToStep(graph)); } return steps; } private static class RankRequest { @JsonProperty("source") private Object source; @JsonProperty("steps") private List<Step> steps; @JsonProperty("alpha") private double alpha; @JsonProperty("capacity") public long capacity = Long.parseLong(DEFAULT_CAPACITY); @Override public String toString() { return String.format("RankRequest{source=%s,steps=%s,alpha=%s," + "capacity=%s}", this.source, this.steps, this.alpha, this.capacity); } } private static class Step { @JsonProperty("direction") public Directions direction; @JsonProperty("labels") public List<String> labels; @JsonAlias("degree") @JsonProperty("max_degree") public long maxDegree = Long.parseLong(DEFAULT_MAX_DEGREE); @JsonProperty("skip_degree") public long skipDegree = 0L; @JsonProperty("top") public int top = Integer.parseInt(DEFAULT_PATHS_LIMIT); public static final int DEFAULT_CAPACITY_PER_LAYER = 100000; @Override public String toString() { return String.format("Step{direction=%s,labels=%s,maxDegree=%s," + "top=%s}", this.direction, this.labels, this.maxDegree, this.top); } private NeighborRankTraverser.Step jsonToStep(HugeGraph g) { return new NeighborRankTraverser.Step(g, this.direction, this.labels, this.maxDegree, this.skipDegree, this.top, DEFAULT_CAPACITY_PER_LAYER); } } }
E.checkArgumentNotNull(request, "The rank request body can't be null"); E.checkArgumentNotNull(request.source, "The source of rank request can't be null"); E.checkArgument(request.steps != null && !request.steps.isEmpty(), "The steps of rank request can't be empty"); E.checkArgument(request.steps.size() <= DEFAULT_MAX_DEPTH, "The steps length of rank request can't exceed %s", DEFAULT_MAX_DEPTH); E.checkArgument(request.alpha > 0 && request.alpha <= 1.0, "The alpha of rank request must be in range (0, 1], " + "but got '%s'", request.alpha); LOG.debug("Graph [{}] get neighbor rank from '{}' with steps '{}', " + "alpha '{}' and capacity '{}'", graph, request.source, request.steps, request.alpha, request.capacity); Id sourceId = HugeVertex.getIdValue(request.source); HugeGraph g = graph(manager, graph); List<NeighborRankTraverser.Step> steps = steps(g, request); NeighborRankTraverser traverser; traverser = new NeighborRankTraverser(g, request.alpha, request.capacity); List<Map<Id, Double>> ranks = traverser.neighborRank(sourceId, steps); return manager.serializer(g).writeList("ranks", ranks);
682
389
1,071
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/traversers/PathsAPI.java
PathsAPI
post
class PathsAPI extends TraverserAPI { private static final Logger LOG = Log.logger(PathsAPI.class); @GET @Timed @Produces(APPLICATION_JSON_WITH_CHARSET) public String get(@Context GraphManager manager, @PathParam("graph") String graph, @QueryParam("source") String source, @QueryParam("target") String target, @QueryParam("direction") String direction, @QueryParam("label") String edgeLabel, @QueryParam("max_depth") int depth, @QueryParam("max_degree") @DefaultValue(DEFAULT_MAX_DEGREE) long maxDegree, @QueryParam("capacity") @DefaultValue(DEFAULT_CAPACITY) long capacity, @QueryParam("limit") @DefaultValue(DEFAULT_PATHS_LIMIT) int limit) { LOG.debug("Graph [{}] get paths from '{}', to '{}' with " + "direction {}, edge label {}, max depth '{}', " + "max degree '{}', capacity '{}' and limit '{}'", graph, source, target, direction, edgeLabel, depth, maxDegree, capacity, limit); ApiMeasurer measure = new ApiMeasurer(); Id sourceId = VertexAPI.checkAndParseVertexId(source); Id targetId = VertexAPI.checkAndParseVertexId(target); Directions dir = Directions.convert(EdgeAPI.parseDirection(direction)); HugeGraph g = graph(manager, graph); PathsTraverser traverser = new PathsTraverser(g); HugeTraverser.PathSet paths = traverser.paths(sourceId, dir, targetId, dir.opposite(), edgeLabel, depth, maxDegree, capacity, limit); measure.addIterCount(traverser.vertexIterCounter.get(), traverser.edgeIterCounter.get()); return manager.serializer(g, measure.measures()) .writePaths("paths", paths, false); } @POST @Timed @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON_WITH_CHARSET) public String post(@Context GraphManager manager, @PathParam("graph") String graph, Request request) {<FILL_FUNCTION_BODY>} private static class Request { @JsonProperty("sources") public Vertices sources; @JsonProperty("targets") public Vertices targets; @JsonProperty("step") public TraverserAPI.Step step; @JsonProperty("max_depth") public int depth; @JsonProperty("nearest") public boolean nearest = false; @JsonProperty("capacity") public long capacity = Long.parseLong(DEFAULT_CAPACITY); @JsonProperty("limit") public int limit = Integer.parseInt(DEFAULT_PATHS_LIMIT); @JsonProperty("with_vertex") public boolean withVertex = false; @JsonProperty("with_edge") public boolean withEdge = false; @Override public String toString() { return String.format("PathRequest{sources=%s,targets=%s,step=%s," + "maxDepth=%s,nearest=%s,capacity=%s," + "limit=%s,withVertex=%s,withEdge=%s}", this.sources, this.targets, this.step, this.depth, this.nearest, this.capacity, this.limit, this.withVertex, this.withEdge); } } }
E.checkArgumentNotNull(request, "The request body can't be null"); E.checkArgumentNotNull(request.sources, "The sources of request can't be null"); E.checkArgumentNotNull(request.targets, "The targets of request can't be null"); E.checkArgumentNotNull(request.step, "The step of request can't be null"); E.checkArgument(request.depth > 0 && request.depth <= DEFAULT_MAX_DEPTH, "The depth of request must be in (0, %s], " + "but got: %s", DEFAULT_MAX_DEPTH, request.depth); LOG.debug("Graph [{}] get paths from source vertices '{}', target " + "vertices '{}', with step '{}', max depth '{}', " + "capacity '{}', limit '{}', with_vertex '{}' and with_edge '{}'", graph, request.sources, request.targets, request.step, request.depth, request.capacity, request.limit, request.withVertex, request.withEdge); ApiMeasurer measure = new ApiMeasurer(); HugeGraph g = graph(manager, graph); Iterator<Vertex> sources = request.sources.vertices(g); Iterator<Vertex> targets = request.targets.vertices(g); EdgeStep step = step(g, request.step); CollectionPathsTraverser traverser = new CollectionPathsTraverser(g); CollectionPathsTraverser.WrappedPathCollection wrappedPathCollection = traverser.paths(sources, targets, step, request.depth, request.nearest, request.capacity, request.limit); Collection<HugeTraverser.Path> paths = wrappedPathCollection.paths(); measure.addIterCount(traverser.vertexIterCounter.get(), traverser.edgeIterCounter.get()); Iterator<?> iterVertex; Set<Id> vertexIds = new HashSet<>(); for (HugeTraverser.Path path : paths) { vertexIds.addAll(path.vertices()); } if (request.withVertex && !vertexIds.isEmpty()) { iterVertex = g.vertices(vertexIds.toArray()); measure.addIterCount(vertexIds.size(), 0L); } else { iterVertex = vertexIds.iterator(); } Iterator<?> iterEdge; Set<Edge> edges = wrappedPathCollection.edges(); if (request.withEdge && !edges.isEmpty()) { iterEdge = edges.iterator(); } else { iterEdge = HugeTraverser.EdgeRecord.getEdgeIds(edges).iterator(); } return manager.serializer(g, measure.measures()) .writePaths("paths", paths, false, iterVertex, iterEdge);
924
729
1,653
<methods>public non-sealed void <init>() <variables>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/traversers/PersonalRankAPI.java
PersonalRankAPI
personalRank
class PersonalRankAPI extends API { private static final Logger LOG = Log.logger(PersonalRankAPI.class); private static final double DEFAULT_DIFF = 0.0001; private static final double DEFAULT_ALPHA = 0.85; private static final int DEFAULT_DEPTH = 5; @POST @Timed @Produces(APPLICATION_JSON_WITH_CHARSET) public String personalRank(@Context GraphManager manager, @PathParam("graph") String graph, RankRequest request) {<FILL_FUNCTION_BODY>} private static class RankRequest { @JsonProperty("source") private Object source; @JsonProperty("label") private String label; @JsonProperty("alpha") private double alpha = DEFAULT_ALPHA; // TODO: used for future enhancement @JsonProperty("max_diff") private double maxDiff = DEFAULT_DIFF; @JsonProperty("max_degree") private long maxDegree = Long.parseLong(DEFAULT_MAX_DEGREE); @JsonProperty("limit") private int limit = Integer.parseInt(DEFAULT_LIMIT); @JsonProperty("max_depth") private int maxDepth = DEFAULT_DEPTH; @JsonProperty("with_label") private PersonalRankTraverser.WithLabel withLabel = PersonalRankTraverser.WithLabel.BOTH_LABEL; @JsonProperty("sorted") private boolean sorted = true; @Override public String toString() { return String.format("RankRequest{source=%s,label=%s,alpha=%s," + "maxDiff=%s,maxDegree=%s,limit=%s," + "maxDepth=%s,withLabel=%s,sorted=%s}", this.source, this.label, this.alpha, this.maxDiff, this.maxDegree, this.limit, this.maxDepth, this.withLabel, this.sorted); } } }
E.checkArgumentNotNull(request, "The rank request body can't be null"); E.checkArgument(request.source != null, "The source vertex id of rank request can't be null"); E.checkArgument(request.label != null, "The edge label of rank request can't be null"); E.checkArgument(request.alpha > 0 && request.alpha <= 1.0, "The alpha of rank request must be in range (0, 1], " + "but got '%s'", request.alpha); E.checkArgument(request.maxDiff > 0 && request.maxDiff <= 1.0, "The max diff of rank request must be in range " + "(0, 1], but got '%s'", request.maxDiff); E.checkArgument(request.maxDegree > 0L || request.maxDegree == NO_LIMIT, "The max degree of rank request must be > 0 " + "or == -1, but got: %s", request.maxDegree); E.checkArgument(request.limit > 0L || request.limit == NO_LIMIT, "The limit of rank request must be > 0 or == -1, " + "but got: %s", request.limit); E.checkArgument(request.maxDepth > 1L && request.maxDepth <= DEFAULT_MAX_DEPTH, "The max depth of rank request must be " + "in range (1, %s], but got '%s'", DEFAULT_MAX_DEPTH, request.maxDepth); LOG.debug("Graph [{}] get personal rank from '{}' with " + "edge label '{}', alpha '{}', maxDegree '{}', " + "max depth '{}' and sorted '{}'", graph, request.source, request.label, request.alpha, request.maxDegree, request.maxDepth, request.sorted); Id sourceId = HugeVertex.getIdValue(request.source); HugeGraph g = graph(manager, graph); PersonalRankTraverser traverser; traverser = new PersonalRankTraverser(g, request.alpha, request.maxDegree, request.maxDepth); Map<Id, Double> ranks = traverser.personalRank(sourceId, request.label, request.withLabel); ranks = HugeTraverser.topN(ranks, request.sorted, request.limit); return manager.serializer(g).writeMap(ranks);
522
634
1,156
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/traversers/RaysAPI.java
RaysAPI
get
class RaysAPI extends API { private static final Logger LOG = Log.logger(RaysAPI.class); @GET @Timed @Produces(APPLICATION_JSON_WITH_CHARSET) public String get(@Context GraphManager manager, @PathParam("graph") String graph, @QueryParam("source") String sourceV, @QueryParam("direction") String direction, @QueryParam("label") String edgeLabel, @QueryParam("max_depth") int depth, @QueryParam("max_degree") @DefaultValue(DEFAULT_MAX_DEGREE) long maxDegree, @QueryParam("capacity") @DefaultValue(DEFAULT_CAPACITY) long capacity, @QueryParam("limit") @DefaultValue(DEFAULT_PATHS_LIMIT) int limit, @QueryParam("with_vertex") @DefaultValue("false") boolean withVertex, @QueryParam("with_edge") @DefaultValue("false") boolean withEdge) {<FILL_FUNCTION_BODY>} }
LOG.debug("Graph [{}] get rays paths from '{}' with " + "direction '{}', edge label '{}', max depth '{}', " + "max degree '{}', capacity '{}' and limit '{}'", graph, sourceV, direction, edgeLabel, depth, maxDegree, capacity, limit); ApiMeasurer measure = new ApiMeasurer(); Id source = VertexAPI.checkAndParseVertexId(sourceV); Directions dir = Directions.convert(EdgeAPI.parseDirection(direction)); HugeGraph g = graph(manager, graph); SubGraphTraverser traverser = new SubGraphTraverser(g); HugeTraverser.PathSet paths = traverser.rays(source, dir, edgeLabel, depth, maxDegree, capacity, limit); measure.addIterCount(traverser.vertexIterCounter.get(), traverser.edgeIterCounter.get()); Iterator<?> iterVertex; Set<Id> vertexIds = new HashSet<>(); for (HugeTraverser.Path path : paths) { vertexIds.addAll(path.vertices()); } if (withVertex && !vertexIds.isEmpty()) { iterVertex = g.vertices(vertexIds.toArray()); measure.addIterCount(vertexIds.size(), 0L); } else { iterVertex = vertexIds.iterator(); } Iterator<?> iterEdge; Set<Edge> edges = paths.getEdges(); if (withEdge && !edges.isEmpty()) { iterEdge = edges.iterator(); } else { iterEdge = HugeTraverser.EdgeRecord.getEdgeIds(edges).iterator(); } return manager.serializer(g, measure.measures()) .writePaths("rays", paths, false, iterVertex, iterEdge);
262
484
746
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/traversers/ResourceAllocationAPI.java
ResourceAllocationAPI
create
class ResourceAllocationAPI extends API { @GET @Timed @Produces(APPLICATION_JSON_WITH_CHARSET) public String create(@Context GraphManager manager, @PathParam("graph") String graph, @QueryParam("vertex") String current, @QueryParam("other") String other, @QueryParam("direction") String direction, @QueryParam("label") String edgeLabel, @QueryParam("max_degree") @DefaultValue(DEFAULT_MAX_DEGREE) long maxDegree, @QueryParam("limit") @DefaultValue(DEFAULT_ELEMENTS_LIMIT) int limit) {<FILL_FUNCTION_BODY>} }
LOG.debug("Graph [{}] get resource allocation between '{}' and '{}' " + "with direction {}, edge label {}, max degree '{}' and " + "limit '{}'", graph, current, other, direction, edgeLabel, maxDegree, limit); Id sourceId = VertexAPI.checkAndParseVertexId(current); Id targetId = VertexAPI.checkAndParseVertexId(other); E.checkArgument(!current.equals(other), "The source and target vertex id can't be same"); Directions dir = Directions.convert(EdgeAPI.parseDirection(direction)); HugeGraph g = graph(manager, graph); try (PredictionTraverser traverser = new PredictionTraverser(g)) { double score = traverser.resourceAllocation(sourceId, targetId, dir, edgeLabel, maxDegree, limit); return JsonUtil.toJson(ImmutableMap.of("resource_allocation", score)); }
173
256
429
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/traversers/RingsAPI.java
RingsAPI
get
class RingsAPI extends API { private static final Logger LOG = Log.logger(RingsAPI.class); @GET @Timed @Produces(APPLICATION_JSON_WITH_CHARSET) public String get(@Context GraphManager manager, @PathParam("graph") String graph, @QueryParam("source") String sourceV, @QueryParam("direction") String direction, @QueryParam("label") String edgeLabel, @QueryParam("max_depth") int depth, @QueryParam("source_in_ring") @DefaultValue("true") boolean sourceInRing, @QueryParam("max_degree") @DefaultValue(DEFAULT_MAX_DEGREE) long maxDegree, @QueryParam("capacity") @DefaultValue(DEFAULT_CAPACITY) long capacity, @QueryParam("limit") @DefaultValue(DEFAULT_PATHS_LIMIT) int limit, @QueryParam("with_vertex") @DefaultValue("false") boolean withVertex, @QueryParam("with_edge") @DefaultValue("false") boolean withEdge) {<FILL_FUNCTION_BODY>} }
LOG.debug("Graph [{}] get rings paths reachable from '{}' with " + "direction '{}', edge label '{}', max depth '{}', " + "source in ring '{}', max degree '{}', capacity '{}', " + "limit '{}', with_vertex '{}' and with_edge '{}'", graph, sourceV, direction, edgeLabel, depth, sourceInRing, maxDegree, capacity, limit, withVertex, withEdge); ApiMeasurer measure = new ApiMeasurer(); Id source = VertexAPI.checkAndParseVertexId(sourceV); Directions dir = Directions.convert(EdgeAPI.parseDirection(direction)); HugeGraph g = graph(manager, graph); SubGraphTraverser traverser = new SubGraphTraverser(g); HugeTraverser.PathSet paths = traverser.rings(source, dir, edgeLabel, depth, sourceInRing, maxDegree, capacity, limit); measure.addIterCount(traverser.vertexIterCounter.get(), traverser.edgeIterCounter.get()); Iterator<?> iterVertex; Set<Id> vertexIds = new HashSet<>(); for (HugeTraverser.Path path : paths) { vertexIds.addAll(path.vertices()); } if (withVertex && !vertexIds.isEmpty()) { iterVertex = g.vertices(vertexIds.toArray()); measure.addIterCount(vertexIds.size(), 0L); } else { iterVertex = vertexIds.iterator(); } Iterator<?> iterEdge; Set<Edge> edges = paths.getEdges(); if (withEdge && !edges.isEmpty()) { iterEdge = edges.iterator(); } else { iterEdge = HugeTraverser.EdgeRecord.getEdgeIds(edges).iterator(); } return manager.serializer(g, measure.measures()) .writePaths("rings", paths, false, iterVertex, iterEdge);
288
528
816
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/traversers/SameNeighborsAPI.java
SameNeighborsAPI
sameNeighbors
class SameNeighborsAPI extends API { private static final Logger LOG = Log.logger(SameNeighborsAPI.class); @GET @Timed @Produces(APPLICATION_JSON_WITH_CHARSET) public String get(@Context GraphManager manager, @PathParam("graph") String graph, @QueryParam("vertex") String vertex, @QueryParam("other") String other, @QueryParam("direction") String direction, @QueryParam("label") String edgeLabel, @QueryParam("max_degree") @DefaultValue(DEFAULT_MAX_DEGREE) long maxDegree, @QueryParam("limit") @DefaultValue(DEFAULT_ELEMENTS_LIMIT) int limit) { LOG.debug("Graph [{}] get same neighbors between '{}' and '{}' with " + "direction {}, edge label {}, max degree '{}' and limit '{}'", graph, vertex, other, direction, edgeLabel, maxDegree, limit); ApiMeasurer measure = new ApiMeasurer(); Id sourceId = VertexAPI.checkAndParseVertexId(vertex); Id targetId = VertexAPI.checkAndParseVertexId(other); Directions dir = Directions.convert(EdgeAPI.parseDirection(direction)); HugeGraph g = graph(manager, graph); SameNeighborTraverser traverser = new SameNeighborTraverser(g); Set<Id> neighbors = traverser.sameNeighbors(sourceId, targetId, dir, edgeLabel, maxDegree, limit); measure.addIterCount(traverser.vertexIterCounter.get(), traverser.edgeIterCounter.get()); return manager.serializer(g, measure.measures()) .writeList("same_neighbors", neighbors); } @POST @Timed @Produces(APPLICATION_JSON_WITH_CHARSET) public String sameNeighbors(@Context GraphManager manager, @PathParam("graph") String graph, Request request) {<FILL_FUNCTION_BODY>} private static class Request { @JsonProperty("max_degree") public long maxDegree = Long.parseLong(DEFAULT_MAX_DEGREE); @JsonProperty("limit") public int limit = Integer.parseInt(DEFAULT_ELEMENTS_LIMIT); @JsonProperty("vertex_list") private List<Object> vertexList; @JsonProperty("direction") private String direction; @JsonProperty("labels") private List<String> labels; @JsonProperty("with_vertex") private boolean withVertex = false; @Override public String toString() { return String.format("SameNeighborsBatchRequest{vertex_list=%s," + "direction=%s,label=%s,max_degree=%d," + "limit=%d,with_vertex=%s", this.vertexList, this.direction, this.labels, this.maxDegree, this.limit, this.withVertex); } } }
LOG.debug("Graph [{}] get same neighbors among batch, '{}'", graph, request.toString()); ApiMeasurer measure = new ApiMeasurer(); Directions dir = Directions.convert(EdgeAPI.parseDirection(request.direction)); HugeGraph g = graph(manager, graph); SameNeighborTraverser traverser = new SameNeighborTraverser(g); List<Object> vertexList = request.vertexList; E.checkArgument(vertexList.size() >= 2, "vertex_list size can't " + "be less than 2"); List<Id> vertexIds = new ArrayList<>(); for (Object obj : vertexList) { vertexIds.add(HugeVertex.getIdValue(obj)); } Set<Id> neighbors = traverser.sameNeighbors(vertexIds, dir, request.labels, request.maxDegree, request.limit); measure.addIterCount(traverser.vertexIterCounter.get(), traverser.edgeIterCounter.get()); Iterator<?> iterVertex; Set<Id> ids = new HashSet<>(neighbors); ids.addAll(vertexIds); if (request.withVertex && !ids.isEmpty()) { iterVertex = g.vertices(ids.toArray()); } else { iterVertex = ids.iterator(); } return manager.serializer(g, measure.measures()) .writeMap(ImmutableMap.of("same_neighbors", neighbors, "vertices", iterVertex));
783
402
1,185
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/traversers/TemplatePathsAPI.java
TemplatePathsAPI
post
class TemplatePathsAPI extends TraverserAPI { private static final Logger LOG = Log.logger(TemplatePathsAPI.class); private static List<RepeatEdgeStep> steps(HugeGraph g, List<TemplatePathStep> steps) { List<RepeatEdgeStep> edgeSteps = new ArrayList<>(steps.size()); for (TemplatePathStep step : steps) { edgeSteps.add(repeatEdgeStep(g, step)); } return edgeSteps; } private static RepeatEdgeStep repeatEdgeStep(HugeGraph graph, TemplatePathStep step) { return new RepeatEdgeStep(graph, step.direction, step.labels, step.properties, step.maxDegree, step.skipDegree, step.maxTimes); } @POST @Timed @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON_WITH_CHARSET) public String post(@Context GraphManager manager, @PathParam("graph") String graph, Request request) {<FILL_FUNCTION_BODY>} private static class Request { @JsonProperty("sources") public Vertices sources; @JsonProperty("targets") public Vertices targets; @JsonProperty("steps") public List<TemplatePathStep> steps; @JsonProperty("with_ring") public boolean withRing = false; @JsonProperty("capacity") public long capacity = Long.parseLong(DEFAULT_CAPACITY); @JsonProperty("limit") public int limit = Integer.parseInt(DEFAULT_PATHS_LIMIT); @JsonProperty("with_vertex") public boolean withVertex = false; @JsonProperty("with_edge") public boolean withEdge = false; @Override public String toString() { return String.format("TemplatePathsRequest{sources=%s,targets=%s," + "steps=%s,withRing=%s,capacity=%s,limit=%s," + "withVertex=%s,withEdge=%s}", this.sources, this.targets, this.steps, this.withRing, this.capacity, this.limit, this.withVertex, this.withEdge); } } protected static class TemplatePathStep extends Step { @JsonProperty("max_times") public int maxTimes = 1; @Override public String toString() { return String.format("TemplatePathStep{direction=%s,labels=%s," + "properties=%s,maxDegree=%s,skipDegree=%s," + "maxTimes=%s}", this.direction, this.labels, this.properties, this.maxDegree, this.skipDegree, this.maxTimes); } } }
E.checkArgumentNotNull(request, "The request body can't be null"); E.checkArgumentNotNull(request.sources, "The sources of request can't be null"); E.checkArgumentNotNull(request.targets, "The targets of request can't be null"); E.checkArgument(request.steps != null && !request.steps.isEmpty(), "The steps of request can't be empty"); LOG.debug("Graph [{}] get template paths from source vertices '{}', " + "target vertices '{}', with steps '{}', " + "capacity '{}', limit '{}', with_vertex '{}' and with_edge '{}'", graph, request.sources, request.targets, request.steps, request.capacity, request.limit, request.withVertex, request.withEdge); ApiMeasurer measure = new ApiMeasurer(); HugeGraph g = graph(manager, graph); Iterator<Vertex> sources = request.sources.vertices(g); Iterator<Vertex> targets = request.targets.vertices(g); List<RepeatEdgeStep> steps = steps(g, request.steps); TemplatePathsTraverser traverser = new TemplatePathsTraverser(g); TemplatePathsTraverser.WrappedPathSet wrappedPathSet = traverser.templatePaths(sources, targets, steps, request.withRing, request.capacity, request.limit); measure.addIterCount(traverser.vertexIterCounter.get(), traverser.edgeIterCounter.get()); Set<HugeTraverser.Path> paths = wrappedPathSet.paths(); Iterator<?> iterVertex; Set<Id> vertexIds = new HashSet<>(); for (HugeTraverser.Path path : paths) { vertexIds.addAll(path.vertices()); } if (request.withVertex && !vertexIds.isEmpty()) { iterVertex = g.vertices(vertexIds.toArray()); measure.addIterCount(vertexIds.size(), 0L); } else { iterVertex = vertexIds.iterator(); } Iterator<?> iterEdge; Set<Edge> edges = wrappedPathSet.edges(); if (request.withEdge && !edges.isEmpty()) { iterEdge = edges.iterator(); } else { iterEdge = HugeTraverser.EdgeRecord.getEdgeIds(edges).iterator(); } return manager.serializer(g, measure.measures()) .writePaths("paths", paths, false, iterVertex, iterEdge);
730
663
1,393
<methods>public non-sealed void <init>() <variables>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/traversers/TraverserAPI.java
TraverserAPI
steps
class TraverserAPI extends API { protected static EdgeStep step(HugeGraph graph, Step step) { return new EdgeStep(graph, step.direction, step.labels, step.properties, step.maxDegree, step.skipDegree); } protected static Steps steps(HugeGraph graph, VESteps steps) {<FILL_FUNCTION_BODY>} protected static class Step { @JsonProperty("direction") public Directions direction; @JsonProperty("labels") public List<String> labels; @JsonProperty("properties") public Map<String, Object> properties; @JsonAlias("degree") @JsonProperty("max_degree") public long maxDegree = Long.parseLong(DEFAULT_MAX_DEGREE); @JsonProperty("skip_degree") public long skipDegree = 0L; @Override public String toString() { return String.format("Step{direction=%s,labels=%s,properties=%s," + "maxDegree=%s,skipDegree=%s}", this.direction, this.labels, this.properties, this.maxDegree, this.skipDegree); } } protected static class VEStepEntity { @JsonProperty("label") public String label; @JsonProperty("properties") public Map<String, Object> properties; @Override public String toString() { return String.format("VEStepEntity{label=%s,properties=%s}", this.label, this.properties); } } protected static class VESteps { @JsonProperty("direction") public Directions direction; @JsonAlias("degree") @JsonProperty("max_degree") public long maxDegree = Long.parseLong(DEFAULT_MAX_DEGREE); @JsonProperty("skip_degree") public long skipDegree = 0L; @JsonProperty("vertex_steps") public List<VEStepEntity> vSteps; @JsonProperty("edge_steps") public List<VEStepEntity> eSteps; @Override public String toString() { return String.format("Steps{direction=%s,maxDegree=%s," + "skipDegree=%s,vSteps=%s,eSteps=%s}", this.direction, this.maxDegree, this.skipDegree, this.vSteps, this.eSteps); } } }
Map<String, Map<String, Object>> vSteps = new HashMap<>(); if (steps.vSteps != null) { for (VEStepEntity vStep : steps.vSteps) { vSteps.put(vStep.label, vStep.properties); } } Map<String, Map<String, Object>> eSteps = new HashMap<>(); if (steps.eSteps != null) { for (VEStepEntity eStep : steps.eSteps) { eSteps.put(eStep.label, eStep.properties); } } return new Steps(graph, steps.direction, vSteps, eSteps, steps.maxDegree, steps.skipDegree);
662
198
860
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/traversers/Vertices.java
Vertices
vertices
class Vertices { @JsonProperty("ids") public Set<Object> ids; @JsonProperty("label") public String label; @JsonProperty("properties") public Map<String, Object> properties; public Iterator<Vertex> vertices(HugeGraph g) {<FILL_FUNCTION_BODY>} @Override public String toString() { return String.format("SourceVertex{ids=%s,label=%s,properties=%s}", this.ids, this.label, this.properties); } }
Map<String, Object> props = this.properties; E.checkArgument(!((this.ids == null || this.ids.isEmpty()) && (props == null || props.isEmpty()) && this.label == null), "No source vertices provided"); Iterator<Vertex> iterator; if (this.ids != null && !this.ids.isEmpty()) { E.checkArgument(this.label == null, "Just provide one of ids or label of source vertices"); E.checkArgument(props == null || props.isEmpty(), "Just provide one of ids or properties of source vertices"); List<Id> sourceIds = new ArrayList<>(this.ids.size()); for (Object id : this.ids) { sourceIds.add(HugeVertex.getIdValue(id)); } iterator = g.vertices(sourceIds.toArray()); E.checkArgument(iterator.hasNext(), "Not exist source vertices with ids %s", this.ids); } else { ConditionQuery query = new ConditionQuery(HugeType.VERTEX); if (this.label != null) { Id label = SchemaLabel.getVertexLabelId(g, this.label); query.eq(HugeKeys.LABEL, label); } if (props != null && !props.isEmpty()) { Map<Id, Object> pks = TraversalUtil.transProperties(g, props); TraversalUtil.fillConditionQuery(query, pks, g); } assert !query.empty(); iterator = g.vertices(query); E.checkArgument(iterator.hasNext(), "Not exist source vertex " + "with label '%s' and properties '%s'", this.label, props); } return iterator;
145
451
596
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/traversers/VerticesAPI.java
VerticesAPI
list
class VerticesAPI extends API { private static final Logger LOG = Log.logger(VerticesAPI.class); @GET @Timed @Compress @Produces(APPLICATION_JSON_WITH_CHARSET) public String list(@Context GraphManager manager, @PathParam("graph") String graph, @QueryParam("ids") List<String> stringIds) {<FILL_FUNCTION_BODY>} @GET @Timed @Path("shards") @Compress @Produces(APPLICATION_JSON_WITH_CHARSET) public String shards(@Context GraphManager manager, @PathParam("graph") String graph, @QueryParam("split_size") long splitSize) { LOG.debug("Graph [{}] get vertex shards with split size '{}'", graph, splitSize); HugeGraph g = graph(manager, graph); List<Shard> shards = g.metadata(HugeType.VERTEX, "splits", splitSize); return manager.serializer(g).writeList("shards", shards); } @GET @Timed @Path("scan") @Compress @Produces(APPLICATION_JSON_WITH_CHARSET) public String scan(@Context GraphManager manager, @PathParam("graph") String graph, @QueryParam("start") String start, @QueryParam("end") String end, @QueryParam("page") String page, @QueryParam("page_limit") @DefaultValue(DEFAULT_PAGE_LIMIT) long pageLimit) { LOG.debug("Graph [{}] query vertices by shard(start: {}, end: {}, " + "page: {}) ", graph, start, end, page); HugeGraph g = graph(manager, graph); ConditionQuery query = new ConditionQuery(HugeType.VERTEX); query.scan(start, end); query.page(page); if (query.paging()) { query.limit(pageLimit); } Iterator<Vertex> vertices = g.vertices(query); return manager.serializer(g).writeVertices(vertices, query.paging()); } }
LOG.debug("Graph [{}] get vertices by ids: {}", graph, stringIds); E.checkArgument(stringIds != null && !stringIds.isEmpty(), "The ids parameter can't be null or empty"); Object[] ids = new Id[stringIds.size()]; for (int i = 0; i < ids.length; i++) { ids[i] = VertexAPI.checkAndParseVertexId(stringIds.get(i)); } HugeGraph g = graph(manager, graph); Iterator<Vertex> vertices = g.vertices(ids); return manager.serializer(g).writeVertices(vertices, false);
562
176
738
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/variables/VariablesAPI.java
VariablesAPI
get
class VariablesAPI extends API { private static final Logger LOG = Log.logger(VariablesAPI.class); @PUT @Timed @Path("{key}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON_WITH_CHARSET) public Map<String, Object> update(@Context GraphManager manager, @PathParam("graph") String graph, @PathParam("key") String key, JsonVariableValue value) { E.checkArgument(value != null && value.data != null, "The variable value can't be empty"); LOG.debug("Graph [{}] set variable for {}: {}", graph, key, value); HugeGraph g = graph(manager, graph); commit(g, () -> g.variables().set(key, value.data)); return ImmutableMap.of(key, value.data); } @GET @Timed @Produces(APPLICATION_JSON_WITH_CHARSET) public Map<String, Object> list(@Context GraphManager manager, @PathParam("graph") String graph) { LOG.debug("Graph [{}] get variables", graph); HugeGraph g = graph(manager, graph); return g.variables().asMap(); } @GET @Timed @Path("{key}") @Produces(APPLICATION_JSON_WITH_CHARSET) public Map<String, Object> get(@Context GraphManager manager, @PathParam("graph") String graph, @PathParam("key") String key) {<FILL_FUNCTION_BODY>} @DELETE @Timed @Path("{key}") @Consumes(APPLICATION_JSON) public void delete(@Context GraphManager manager, @PathParam("graph") String graph, @PathParam("key") String key) { LOG.debug("Graph [{}] remove variable by key '{}'", graph, key); HugeGraph g = graph(manager, graph); commit(g, () -> g.variables().remove(key)); } private static class JsonVariableValue { public Object data; @Override public String toString() { return String.format("JsonVariableValue{data=%s}", this.data); } } }
LOG.debug("Graph [{}] get variable by key '{}'", graph, key); HugeGraph g = graph(manager, graph); Optional<?> object = g.variables().get(key); if (!object.isPresent()) { throw new NotFoundException(String.format( "Variable '%s' does not exist", key)); } return ImmutableMap.of(key, object.get());
597
109
706
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/auth/ConfigAuthenticator.java
ConfigAuthenticator
authenticate
class ConfigAuthenticator implements HugeAuthenticator { public static final String KEY_USERNAME = CredentialGraphTokens.PROPERTY_USERNAME; public static final String KEY_PASSWORD = CredentialGraphTokens.PROPERTY_PASSWORD; private final Map<String, String> tokens; public ConfigAuthenticator() { this.tokens = new HashMap<>(); } @Override public void setup(HugeConfig config) { this.tokens.putAll(config.getMap(ServerOptions.AUTH_USER_TOKENS)); assert !this.tokens.containsKey(USER_ADMIN); this.tokens.put(USER_ADMIN, config.get(ServerOptions.AUTH_ADMIN_TOKEN)); } /** * Verify if a user is legal * * @param username the username for authentication * @param password the password for authentication * @return String No permission if return ROLE_NONE else return a role */ @Override public UserWithRole authenticate(final String username, final String password, final String token) {<FILL_FUNCTION_BODY>} @Override public void unauthorize(SecurityContext context) { } @Override public AuthManager authManager() { throw new NotImplementedException("AuthManager is unsupported by ConfigAuthenticator"); } @Override public HugeGraph graph() { throw new NotImplementedException("graph() is unsupported by ConfigAuthenticator"); } @Override public void initAdminUser(String password) { String adminToken = this.tokens.get(USER_ADMIN); E.checkArgument(Objects.equals(adminToken, password), "The password can't be changed for " + "ConfigAuthenticator"); } @Override public SaslNegotiator newSaslNegotiator(InetAddress remoteAddress) { throw new NotImplementedException("SaslNegotiator is unsupported by ConfigAuthenticator"); } }
E.checkArgumentNotNull(username, "The username parameter can't be null"); E.checkArgumentNotNull(password, "The password parameter can't be null"); E.checkArgument(token == null, "The token must be null"); RolePermission role; if (password.equals(this.tokens.get(username))) { if (username.equals(USER_ADMIN)) { role = ROLE_ADMIN; } else { // Return role with all permission, set username as owner graph role = RolePermission.all(username); } } else { role = ROLE_NONE; } return new UserWithRole(IdGenerator.of(username), username, role);
533
187
720
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/auth/ContextGremlinServer.java
ContextGremlinServer
listenChanges
class ContextGremlinServer extends GremlinServer { private static final Logger LOG = Log.logger(ContextGremlinServer.class); private static final String G_PREFIX = "__g_"; private final EventHub eventHub; static { HugeGraphAuthProxy.setContext(Context.admin()); } public ContextGremlinServer(final Settings settings, EventHub eventHub) { /* * pass custom Executor https://github.com/apache/tinkerpop/pull/813 */ super(settings, newGremlinExecutorService(settings)); this.eventHub = eventHub; this.listenChanges(); } private void listenChanges() {<FILL_FUNCTION_BODY>} private void unlistenChanges() { if (this.eventHub == null) { return; } this.eventHub.unlisten(Events.GRAPH_CREATE); this.eventHub.unlisten(Events.GRAPH_DROP); } @Override public synchronized CompletableFuture<Void> stop() { try { return super.stop(); } finally { this.unlistenChanges(); } } public void injectAuthGraph() { GraphManager manager = this.getServerGremlinExecutor() .getGraphManager(); for (String name : manager.getGraphNames()) { Graph graph = manager.getGraph(name); graph = new HugeGraphAuthProxy((HugeGraph) graph); manager.putGraph(name, graph); } } public void injectTraversalSource() { GraphManager manager = this.getServerGremlinExecutor() .getGraphManager(); for (String graph : manager.getGraphNames()) { GraphTraversalSource g = manager.getGraph(graph).traversal(); String gName = G_PREFIX + graph; if (manager.getTraversalSource(gName) != null) { throw new HugeException( "Found existing name '%s' in global bindings, " + "it may lead to gremlin query error.", gName); } // Add a traversal source for all graphs with customed rule. manager.putTraversalSource(gName, g); } } private void injectGraph(HugeGraph graph) { String name = graph.name(); GraphManager manager = this.getServerGremlinExecutor() .getGraphManager(); GremlinExecutor executor = this.getServerGremlinExecutor() .getGremlinExecutor(); manager.putGraph(name, graph); GraphTraversalSource g = manager.getGraph(name).traversal(); manager.putTraversalSource(G_PREFIX + name, g); Whitebox.invoke(executor, "globalBindings", new Class<?>[]{String.class, Object.class}, "put", name, graph); } private void removeGraph(String name) { GraphManager manager = this.getServerGremlinExecutor() .getGraphManager(); GremlinExecutor executor = this.getServerGremlinExecutor() .getGremlinExecutor(); try { manager.removeGraph(name); manager.removeTraversalSource(G_PREFIX + name); Whitebox.invoke(executor, "globalBindings", new Class<?>[]{Object.class}, "remove", name); } catch (Exception e) { throw new HugeException("Failed to remove graph '%s' from " + "gremlin server context", e, name); } } static ExecutorService newGremlinExecutorService(Settings settings) { if (settings.gremlinPool == 0) { settings.gremlinPool = CoreOptions.CPUS; } int size = settings.gremlinPool; ThreadFactory factory = ThreadFactoryUtil.create("exec-%d"); return new ContextThreadPoolExecutor(size, size, factory); } }
this.eventHub.listen(Events.GRAPH_CREATE, event -> { LOG.debug("GremlinServer accepts event '{}'", event.name()); event.checkArgs(HugeGraph.class); HugeGraph graph = (HugeGraph) event.args()[0]; this.injectGraph(graph); return null; }); this.eventHub.listen(Events.GRAPH_DROP, event -> { LOG.debug("GremlinServer accepts event '{}'", event.name()); event.checkArgs(HugeGraph.class); HugeGraph graph = (HugeGraph) event.args()[0]; this.removeGraph(graph.name()); return null; });
1,040
189
1,229
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/auth/StandardAuthenticator.java
TokenSaslAuthenticator
decode
class TokenSaslAuthenticator implements SaslNegotiator { private static final byte NUL = 0; private String username; private String password; private String token; @Override public byte[] evaluateResponse(final byte[] clientResponse) throws AuthenticationException { decode(clientResponse); return null; } @Override public boolean isComplete() { return this.username != null; } @Override public AuthenticatedUser getAuthenticatedUser() throws AuthenticationException { if (!this.isComplete()) { throw new AuthenticationException( "The SASL negotiation has not yet been completed."); } final Map<String, String> credentials = new HashMap<>(6, 1); credentials.put(KEY_USERNAME, username); credentials.put(KEY_PASSWORD, password); credentials.put(KEY_TOKEN, token); return authenticate(credentials); } /** * SASL PLAIN mechanism specifies that credentials are encoded in a * sequence of UTF-8 bytes, delimited by 0 (US-ASCII NUL). * The form is : {code}authzId<NUL>authnId<NUL>password<NUL>{code}. * * @param bytes encoded credentials string sent by the client */ private void decode(byte[] bytes) throws AuthenticationException {<FILL_FUNCTION_BODY>} }
this.username = null; this.password = null; int end = bytes.length; for (int i = bytes.length - 1; i >= 0; i--) { if (bytes[i] != NUL) { continue; } if (this.password == null) { password = new String(Arrays.copyOfRange(bytes, i + 1, end), StandardCharsets.UTF_8); } else if (this.username == null) { username = new String(Arrays.copyOfRange(bytes, i + 1, end), StandardCharsets.UTF_8); } end = i; } if (this.username == null) { throw new AuthenticationException("SASL authentication ID must not be null."); } if (this.password == null) { throw new AuthenticationException("SASL password must not be null."); } /* The trick is here. >_*/ if (password.isEmpty()) { token = username; }
378
267
645
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/auth/WsAndHttpBasicAuthHandler.java
HttpBasicAuthHandler
channelRead
class HttpBasicAuthHandler extends AbstractAuthenticationHandler { private final Base64.Decoder decoder = Base64.getUrlDecoder(); public HttpBasicAuthHandler(Authenticator authenticator) { super(authenticator); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) {<FILL_FUNCTION_BODY>} private void sendError(ChannelHandlerContext context, Object msg) { // Close the connection as soon as the error message is sent. context.writeAndFlush(new DefaultFullHttpResponse(HTTP_1_1, UNAUTHORIZED)) .addListener(ChannelFutureListener.CLOSE); ReferenceCountUtil.release(msg); } }
if (msg instanceof FullHttpMessage) { final FullHttpMessage request = (FullHttpMessage) msg; if (!request.headers().contains("Authorization")) { sendError(ctx, msg); return; } // strip off "Basic " from the Authorization header (RFC 2617) final String basic = "Basic "; final String header = request.headers().get("Authorization"); if (!header.startsWith(basic)) { sendError(ctx, msg); return; } byte[] userPass = null; try { final String encoded = header.substring(basic.length()); userPass = this.decoder.decode(encoded); } catch (IndexOutOfBoundsException iae) { sendError(ctx, msg); return; } catch (IllegalArgumentException iae) { sendError(ctx, msg); return; } String authorization = new String(userPass, StandardCharsets.UTF_8); String[] split = authorization.split(":"); if (split.length != 2) { sendError(ctx, msg); return; } String address = ctx.channel().remoteAddress().toString(); if (address.startsWith("/") && address.length() > 1) { address = address.substring(1); } final Map<String, String> credentials = new HashMap<>(); credentials.put(PROPERTY_USERNAME, split[0]); credentials.put(PROPERTY_PASSWORD, split[1]); credentials.put(HugeAuthenticator.KEY_ADDRESS, address); try { this.authenticator.authenticate(credentials); ctx.fireChannelRead(request); } catch (AuthenticationException ae) { sendError(ctx, msg); } }
186
472
658
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/metrics/MetricsModule.java
TimerSerializer
serialize
class TimerSerializer extends StdSerializer<Timer> { private static final long serialVersionUID = 6283520188524929099L; private final String rateUnit; private final double rateFactor; private final String durationUnit; private final double durationFactor; private final boolean showSamples; private TimerSerializer(TimeUnit rateUnit, TimeUnit durationUnit, boolean showSamples) { super(Timer.class); this.rateUnit = calculateRateUnit(rateUnit, "calls"); this.rateFactor = rateUnit.toSeconds(1); this.durationUnit = durationUnit.toString().toLowerCase(Locale.US); this.durationFactor = 1.0 / durationUnit.toNanos(1); this.showSamples = showSamples; } @Override public void serialize(Timer timer, JsonGenerator json, SerializerProvider provider) throws IOException {<FILL_FUNCTION_BODY>} }
json.writeStartObject(); final Snapshot snapshot = timer.getSnapshot(); json.writeNumberField("count", timer.getCount()); json.writeNumberField("min", snapshot.getMin() * this.durationFactor); json.writeNumberField("mean", snapshot.getMean() * this.durationFactor); json.writeNumberField("max", snapshot.getMax() * this.durationFactor); json.writeNumberField("stddev", snapshot.getStdDev() * this.durationFactor); json.writeNumberField("p50", snapshot.getMedian() * this.durationFactor); json.writeNumberField("p75", snapshot.get75thPercentile() * this.durationFactor); json.writeNumberField("p95", snapshot.get95thPercentile() * this.durationFactor); json.writeNumberField("p98", snapshot.get98thPercentile() * this.durationFactor); json.writeNumberField("p99", snapshot.get99thPercentile() * this.durationFactor); json.writeNumberField("p999", snapshot.get999thPercentile() * this.durationFactor); json.writeStringField("duration_unit", this.durationUnit); if (this.showSamples) { final long[] values = snapshot.getValues(); final double[] scaledValues = new double[values.length]; for (int i = 0; i < values.length; i++) { scaledValues[i] = values[i] * this.durationFactor; } json.writeObjectField("values", scaledValues); } json.writeNumberField("mean_rate", timer.getMeanRate() * this.rateFactor); json.writeNumberField("m15_rate", timer.getFifteenMinuteRate() * this.rateFactor); json.writeNumberField("m5_rate", timer.getFiveMinuteRate() * this.rateFactor); json.writeNumberField("m1_rate", timer.getOneMinuteRate() * this.rateFactor); json.writeStringField("rate_unit", this.rateUnit); json.writeEndObject();
260
586
846
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/metrics/ServerReporter.java
ServerReporter
report
class ServerReporter extends ScheduledReporter { private static volatile ServerReporter instance = null; private SortedMap<String, Gauge<?>> gauges; private SortedMap<String, Counter> counters; private SortedMap<String, Histogram> histograms; private SortedMap<String, Meter> meters; private SortedMap<String, Timer> timers; public static synchronized ServerReporter instance( MetricRegistry registry) { if (instance == null) { synchronized (ServerReporter.class) { if (instance == null) { instance = new ServerReporter(registry); } } } return instance; } public static ServerReporter instance() { E.checkNotNull(instance, "Must instantiate ServerReporter before get"); return instance; } private ServerReporter(MetricRegistry registry) { this(registry, SECONDS, MILLISECONDS, MetricFilter.ALL); } private ServerReporter(MetricRegistry registry, TimeUnit rateUnit, TimeUnit durationUnit, MetricFilter filter) { super(registry, "server-reporter", filter, rateUnit, durationUnit); this.gauges = ImmutableSortedMap.of(); this.counters = ImmutableSortedMap.of(); this.histograms = ImmutableSortedMap.of(); this.meters = ImmutableSortedMap.of(); this.timers = ImmutableSortedMap.of(); } public Map<String, Timer> timers() { return Collections.unmodifiableMap(this.timers); } public Map<String, Gauge<?>> gauges() { return Collections.unmodifiableMap(this.gauges); } public Map<String, Counter> counters() { return Collections.unmodifiableMap(this.counters); } public Map<String, Histogram> histograms() { return Collections.unmodifiableMap(this.histograms); } public Map<String, Meter> meters() { return Collections.unmodifiableMap(this.meters); } @SuppressWarnings({"rawtypes", "unchecked"}) @Override public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters, SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String, Timer> timers) {<FILL_FUNCTION_BODY>} }
this.gauges = (SortedMap) gauges; this.counters = counters; this.histograms = histograms; this.meters = meters; this.timers = timers;
681
61
742
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/metrics/SlowQueryLog.java
SlowQueryLog
toString
class SlowQueryLog { public String rawQuery; public String method; public String path; public long executeTime; public long startTime; public long thresholdTime; public SlowQueryLog(String rawQuery, String method, String path, long executeTime, long startTime, long thresholdTime) { this.rawQuery = rawQuery; this.method = method; this.path = path; this.executeTime = executeTime; this.startTime = startTime; this.thresholdTime = thresholdTime; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "SlowQueryLog{executeTime=" + executeTime + ", startTime=" + startTime + ", rawQuery='" + rawQuery + '\'' + ", method='" + method + '\'' + ", threshold=" + thresholdTime + ", path='" + path + '\'' + '}';
174
84
258
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/metrics/SystemMetrics.java
SystemMetrics
getBasicMetrics
class SystemMetrics { private static final long MB = Bytes.MB; public Map<String, Map<String, Object>> metrics() { Map<String, Map<String, Object>> metrics = new LinkedHashMap<>(); metrics.put("basic", this.getBasicMetrics()); metrics.put("heap", this.getHeapMetrics()); metrics.put("nonheap", this.getNonHeapMetrics()); metrics.put("thread", this.getThreadMetrics()); metrics.put("class_loading", this.getClassLoadingMetrics()); metrics.put("garbage_collector", this.getGarbageCollectionMetrics()); return metrics; } private Map<String, Object> getBasicMetrics() {<FILL_FUNCTION_BODY>} private static long totalNonHeapMemory() { try { return ManagementFactory.getMemoryMXBean() .getNonHeapMemoryUsage() .getCommitted(); } catch (Throwable ignored) { return 0; } } private Map<String, Object> getHeapMetrics() { Map<String, Object> metrics = new LinkedHashMap<>(); MemoryUsage memoryUsage = ManagementFactory.getMemoryMXBean() .getHeapMemoryUsage(); metrics.put("committed", memoryUsage.getCommitted() / MB); metrics.put("init", memoryUsage.getInit() / MB); metrics.put("used", memoryUsage.getUsed() / MB); metrics.put("max", memoryUsage.getMax() / MB); return metrics; } private Map<String, Object> getNonHeapMetrics() { Map<String, Object> metrics = new LinkedHashMap<>(); MemoryUsage memoryUsage = ManagementFactory.getMemoryMXBean() .getNonHeapMemoryUsage(); metrics.put("committed", memoryUsage.getCommitted() / MB); metrics.put("init", memoryUsage.getInit() / MB); metrics.put("used", memoryUsage.getUsed() / MB); metrics.put("max", memoryUsage.getMax() / MB); return metrics; } private Map<String, Object> getThreadMetrics() { Map<String, Object> metrics = new LinkedHashMap<>(); ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean(); metrics.put("peak", threadMxBean.getPeakThreadCount()); metrics.put("daemon", threadMxBean.getDaemonThreadCount()); metrics.put("total_started", threadMxBean.getTotalStartedThreadCount()); metrics.put("count", threadMxBean.getThreadCount()); return metrics; } private Map<String, Object> getClassLoadingMetrics() { Map<String, Object> metrics = new LinkedHashMap<>(); ClassLoadingMXBean classLoadingMxBean = ManagementFactory .getClassLoadingMXBean(); metrics.put("count", classLoadingMxBean.getLoadedClassCount()); metrics.put("loaded", classLoadingMxBean.getTotalLoadedClassCount()); metrics.put("unloaded", classLoadingMxBean.getUnloadedClassCount()); return metrics; } private Map<String, Object> getGarbageCollectionMetrics() { Map<String, Object> metrics = new LinkedHashMap<>(); List<GarbageCollectorMXBean> gcMxBeans = ManagementFactory .getGarbageCollectorMXBeans(); for (GarbageCollectorMXBean gcMxBean : gcMxBeans) { String name = formatName(gcMxBean.getName()); metrics.put(name + "_count", gcMxBean.getCollectionCount()); metrics.put(name + "_time", gcMxBean.getCollectionTime()); } metrics.put("time_unit", "ms"); return metrics; } private static String formatName(String name) { return StringUtils.replace(name, " ", "_").toLowerCase(); } }
Map<String, Object> metrics = new LinkedHashMap<>(); Runtime runtime = Runtime.getRuntime(); // Heap allocated memory (measured in bytes) long total = runtime.totalMemory(); // Heap free memory long free = runtime.freeMemory(); long used = total - free; metrics.put("mem", (total + totalNonHeapMemory()) / MB); metrics.put("mem_total", total / MB); metrics.put("mem_used", used / MB); metrics.put("mem_free", free / MB); metrics.put("mem_unit", "MB"); metrics.put("processors", runtime.availableProcessors()); metrics.put("uptime", ManagementFactory.getRuntimeMXBean().getUptime()); metrics.put("systemload_average", ManagementFactory.getOperatingSystemMXBean() .getSystemLoadAverage()); return metrics;
1,011
231
1,242
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/opencypher/CypherPlugin.java
CypherPlugin
getDeclaredPublicMethods
class CypherPlugin implements GremlinPlugin { private static final ImportCustomizer IMPORTS = DefaultImportCustomizer.build() .addClassImports(CustomPredicate.class) .addMethodImports( getDeclaredPublicMethods(CustomPredicate.class)) .addClassImports(CustomFunctions.class) .addMethodImports( getDeclaredPublicMethods(CustomFunctions.class)) .create(); private static List<Method> getDeclaredPublicMethods(Class<?> klass) {<FILL_FUNCTION_BODY>} @Override public String getName() { return "cypher.extra"; } public static GremlinPlugin instance() { return new CypherPlugin(); } @Override public boolean requireRestart() { return true; } @Override public Optional<Customizer[]> getCustomizers(String scriptEngineName) { return Optional.of(new Customizer[]{IMPORTS}); } }
Method[] declaredMethods = klass.getDeclaredMethods(); return Stream.of(declaredMethods) .filter(method -> Modifier.isPublic(method.getModifiers())) .collect(Collectors.toList());
263
60
323
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/rpc/RpcClientProviderWithAuth.java
RpcClientProviderWithAuth
authManager
class RpcClientProviderWithAuth extends RpcClientProvider { private final RpcConsumerConfig authConsumerConfig; public RpcClientProviderWithAuth(HugeConfig config) { super(config); String authUrl = config.get(ServerOptions.AUTH_REMOTE_URL); this.authConsumerConfig = StringUtils.isNotBlank(authUrl) ? new RpcConsumerConfig(config, authUrl) : null; } public AuthManager authManager() {<FILL_FUNCTION_BODY>} }
E.checkArgument(this.authConsumerConfig != null, "RpcClient is not enabled, please config option '%s'", ServerOptions.AUTH_REMOTE_URL.name()); return this.authConsumerConfig.serviceProxy(AuthManager.class);
137
70
207
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/server/ApplicationConfig.java
GraphManagerFactory
provide
class GraphManagerFactory extends AbstractBinder implements Factory<GraphManager> { private GraphManager manager = null; public GraphManagerFactory(HugeConfig conf, EventHub hub) { register(new ApplicationEventListener() { private final ApplicationEvent.Type eventInited = ApplicationEvent.Type.INITIALIZATION_FINISHED; private final ApplicationEvent.Type eventDestroyed = ApplicationEvent.Type.DESTROY_FINISHED; @Override public void onEvent(ApplicationEvent event) { if (event.getType() == this.eventInited) { GraphManager manager = new GraphManager(conf, hub); try { manager.init(); } catch (Throwable e) { manager.close(); throw e; } GraphManagerFactory.this.manager = manager; } else if (event.getType() == this.eventDestroyed) { if (GraphManagerFactory.this.manager != null) { GraphManagerFactory.this.manager.close(); } } } @Override public RequestEventListener onRequest(RequestEvent event) { return null; } }); } @Override protected void configure() { bindFactory(this).to(GraphManager.class).in(RequestScoped.class); } @Override public GraphManager provide() {<FILL_FUNCTION_BODY>} @Override public void dispose(GraphManager manager) { // pass } }
if (this.manager == null) { String message = "Please wait for the server to initialize"; throw new MultiException(new HugeException(message), false); } return this.manager;
385
54
439
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/server/RestServer.java
RestServer
calcMaxWriteThreads
class RestServer { private static final Logger LOG = Log.logger(RestServer.class); private final HugeConfig conf; private final EventHub eventHub; private HttpServer httpServer = null; public RestServer(HugeConfig conf, EventHub hub) { this.conf = conf; this.eventHub = hub; } public void start() throws IOException { String url = this.conf.get(ServerOptions.REST_SERVER_URL); URI uri = UriBuilder.fromUri(url).build(); ResourceConfig rc = new ApplicationConfig(this.conf, this.eventHub); this.httpServer = this.configHttpServer(uri, rc); try { // Register HttpHandler for swagger-ui this.httpServer.getServerConfiguration() .addHttpHandler(new StaticHttpHandler("swagger-ui"), "/swagger-ui"); this.httpServer.start(); } catch (Throwable e) { this.httpServer.shutdownNow(); throw e; } this.calcMaxWriteThreads(); } private HttpServer configHttpServer(URI uri, ResourceConfig rc) { String protocol = uri.getScheme(); final HttpServer server; if (protocol != null && protocol.equals("https")) { SSLContextConfigurator sslContext = new SSLContextConfigurator(); String keystoreFile = this.conf.get( ServerOptions.SSL_KEYSTORE_FILE); String keystorePass = this.conf.get( ServerOptions.SSL_KEYSTORE_PASSWORD); sslContext.setKeyStoreFile(keystoreFile); sslContext.setKeyStorePass(keystorePass); SSLEngineConfigurator sslConfig = new SSLEngineConfigurator( sslContext); sslConfig.setClientMode(false); sslConfig.setWantClientAuth(true); server = GrizzlyHttpServerFactory.createHttpServer(uri, rc, true, sslConfig); } else { server = GrizzlyHttpServerFactory.createHttpServer(uri, rc, false); } Collection<NetworkListener> listeners = server.getListeners(); E.checkState(!listeners.isEmpty(), "Http Server should have some listeners, but now is none"); NetworkListener listener = listeners.iterator().next(); // Option max_worker_threads int maxWorkerThreads = this.conf.get(ServerOptions.MAX_WORKER_THREADS); listener.getTransport() .getWorkerThreadPoolConfig() .setCorePoolSize(maxWorkerThreads) .setMaxPoolSize(maxWorkerThreads); // Option keep_alive int idleTimeout = this.conf.get(ServerOptions.CONN_IDLE_TIMEOUT); int maxRequests = this.conf.get(ServerOptions.CONN_MAX_REQUESTS); listener.getKeepAlive().setIdleTimeoutInSeconds(idleTimeout); listener.getKeepAlive().setMaxRequestsCount(maxRequests); // Option transaction timeout int transactionTimeout = this.conf.get(ServerOptions.REQUEST_TIMEOUT); listener.setTransactionTimeout(transactionTimeout); return server; } public Future<HttpServer> shutdown() { E.checkNotNull(this.httpServer, "http server"); /* * Since 2.3.x shutdown() won't call shutdownNow(), so the event * ApplicationEvent.Type.DESTROY_FINISHED also won't be triggered, * which is listened by ApplicationConfig.GraphManagerFactory, we * manually call shutdownNow() here when the future is completed. * See shutdown() change: * https://github.com/javaee/grizzly/commit/182d8bcb4e45de5609ab92f6f1d5980f95d79b04 * #diff-f6c130f38a1ec11bdf9d3cb7e0a81084c8788c79a00befe65e40a13bc989b098R388 */ CompletableFuture<HttpServer> future = new CompletableFuture<>(); future.whenComplete((server, exception) -> { this.httpServer.shutdownNow(); }); GrizzlyFuture<HttpServer> grizzlyFuture = this.httpServer.shutdown(); grizzlyFuture.addCompletionHandler(new CompletionHandler<HttpServer>() { @Override public void cancelled() { future.cancel(true); } @Override public void failed(Throwable throwable) { future.completeExceptionally(throwable); } @Override public void completed(HttpServer result) { future.complete(result); } @Override public void updated(HttpServer result) { // pass } }); return future; } public void shutdownNow() { E.checkNotNull(this.httpServer, "http server"); this.httpServer.shutdownNow(); } public static RestServer start(String conf, EventHub hub) throws Exception { LOG.info("RestServer starting..."); ApiVersion.check(); HugeConfig config = new HugeConfig(conf); RestServer server = new RestServer(config, hub); server.start(); LOG.info("RestServer started"); return server; } private void calcMaxWriteThreads() {<FILL_FUNCTION_BODY>} }
int maxWriteThreads = this.conf.get(ServerOptions.MAX_WRITE_THREADS); if (maxWriteThreads > 0) { // Use the value of MAX_WRITE_THREADS option if it's not 0 return; } assert maxWriteThreads == 0; int maxWriteRatio = this.conf.get(ServerOptions.MAX_WRITE_RATIO); assert maxWriteRatio >= 0 && maxWriteRatio <= 100; int maxWorkerThreads = this.conf.get(ServerOptions.MAX_WORKER_THREADS); maxWriteThreads = maxWorkerThreads * maxWriteRatio / 100; E.checkState(maxWriteThreads >= 0, "Invalid value of maximum batch writing threads '%s'", maxWriteThreads); if (maxWriteThreads == 0) { E.checkState(maxWriteRatio == 0, "The value of maximum batch writing threads is 0 " + "due to the max_write_ratio '%s' is too small, " + "set to '%s' at least to ensure one thread." + "If you want to disable batch write, " + "please let max_write_ratio be 0", maxWriteRatio, (int) Math.ceil(100.0 / maxWorkerThreads)); } LOG.info("The maximum batch writing threads is {} (total threads {})", maxWriteThreads, maxWorkerThreads); // NOTE: addProperty will make exist option's value become List this.conf.setProperty(ServerOptions.MAX_WRITE_THREADS.name(), String.valueOf(maxWriteThreads));
1,448
431
1,879
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-cassandra/src/main/java/com/datastax/driver/core/querybuilder/Clauses.java
BinClause
appendTo
class BinClause extends Clause { private final Clause left; private final String op; private final Clause right; public BinClause(Clause left, String op, Clause right) { this.left = left; this.op = op; this.right = right; } @Override String name() { return null; } @Override Object firstValue() { return null; } @Override boolean containsBindMarker() { return Utils.containsBindMarker(this.left) || Utils.containsBindMarker(this.right); } @Override void appendTo(StringBuilder sb, List<Object> variables, CodecRegistry codecRegistry) {<FILL_FUNCTION_BODY>} }
// NOTE: '(? AND ?)' is not supported by Cassandra: // SyntaxError: line xx missing ')' at 'AND' // sb.append("("); this.left.appendTo(sb, variables, codecRegistry); sb.append(" "); sb.append(this.op); sb.append(" "); this.right.appendTo(sb, variables, codecRegistry); // sb.append(")");
209
113
322
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-cassandra/src/main/java/org/apache/hugegraph/backend/store/cassandra/CassandraEntryIterator.java
CassandraEntryIterator
fetch
class CassandraEntryIterator extends BackendEntryIterator { private final ResultSet results; private final Iterator<Row> rows; private final BiFunction<BackendEntry, Row, BackendEntry> merger; private int fetchedPageSize; private long expected; private BackendEntry next; public CassandraEntryIterator(ResultSet results, Query query, BiFunction<BackendEntry, Row, BackendEntry> merger) { super(query); this.results = results; this.rows = results.iterator(); this.merger = merger; this.fetchedPageSize = results.getAvailableWithoutFetching(); this.next = null; if (query.paging()) { assert query.offset() == 0L; assert query.limit() >= 0L || query.noLimit() : query.limit(); // Skip page offset this.expected = PageState.fromString(query.page()).offset(); this.skipPageOffset(query.page()); // Check the number of available rows E.checkState(this.fetchedPageSize <= query.limit(), "Unexpected fetched page size: %s", this.fetchedPageSize); if (results.isFullyFetched()) { /* * All results fetched * NOTE: it may be enough or not enough for the entire page */ this.expected = this.fetchedPageSize; } else { /* * Not fully fetched, that's fetchedPageSize == query.limit(), * * NOTE: but there may be fetchedPageSize < query.limit(), means * not fetched the entire page (ScyllaDB may go here #1340), * try to fetch next page later until got the expected count. * Can simulate by: `select.setFetchSize(total - 1)` */ this.expected = query.total(); } } else { this.expected = query.total(); this.skipOffset(); } } @Override public void close() throws Exception { // pass } @Override protected final boolean fetch() {<FILL_FUNCTION_BODY>} @Override protected final long sizeOf(BackendEntry entry) { CassandraBackendEntry e = (CassandraBackendEntry) entry; int subRowsSize = e.subRows().size(); return subRowsSize > 0 ? subRowsSize : 1L; } @Override protected final long skip(BackendEntry entry, long skip) { CassandraBackendEntry e = (CassandraBackendEntry) 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 protected PageState pageState() { byte[] position; int offset = 0; int count = (int) this.count(); assert this.fetched() == count; int extra = this.availableLocal(); List<ExecutionInfo> infos = this.results.getAllExecutionInfo(); if (extra > 0 && infos.size() >= 2) { /* * Go back to the previous page if there are still available * results fetched to local memory but not consumed, and set page * offset with consumed amount of results. * * Safely, we should get the remaining size of the current page by: * `Whitebox.getInternalState(results, "currentPage").size()` * instead of * `results.getAvailableWithoutFetching()` */ ExecutionInfo previous = infos.get(infos.size() - 2); PagingState page = previous.getPagingState(); position = page.toBytes(); offset = this.fetchedPageSize - extra; } else { PagingState page = this.results.getExecutionInfo().getPagingState(); if (page == null || this.expected > 0L) { // Call isExhausted() will lead to try to fetch the next page E.checkState(this.results.isExhausted(), "Unexpected paging state with expected=%s, " + "ensure consume all the fetched results before " + "calling pageState()", this.expected); position = PageState.EMPTY_BYTES; } else { /* * Exist page position which used to fetch the next page. * Maybe it happens to the last page (that's the position is * at the end of results and next page is empty) */ position = page.toBytes(); } } return new PageState(position, offset, count); } private int availableLocal() { return this.results.getAvailableWithoutFetching(); } }
assert this.current == null; if (this.next != null) { this.current = this.next; this.next = null; } while (this.expected > 0L && this.rows.hasNext()) { // Limit expected count, due to rows.hasNext() will fetch next page this.expected--; Row row = this.rows.next(); if (this.query.paging()) { // Update fetchedPageSize if auto fetch the next page if (this.expected > 0L && this.availableLocal() == 0) { if (this.rows.hasNext()) { this.fetchedPageSize = this.availableLocal(); } } } BackendEntry merged = this.merger.apply(this.current, row); if (this.current == null) { // The first time to read this.current = merged; } else if (merged == this.current) { // The next entry belongs to the current entry assert merged != null; } else { // New entry assert this.next == null; this.next = merged; break; } } return this.current != null;
1,253
311
1,564
<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-cassandra/src/main/java/org/apache/hugegraph/backend/store/cassandra/CassandraFeatures.java
CassandraFeatures
supportsTransaction
class CassandraFeatures implements BackendFeatures { @Override public boolean supportsScanToken() { return true; } @Override public boolean supportsScanKeyPrefix() { return false; } @Override public boolean supportsScanKeyRange() { return false; } @Override public boolean supportsQuerySchemaByName() { // Cassandra support secondary index return true; } @Override public boolean supportsQueryByLabel() { // Cassandra support secondary index return true; } @Override public boolean supportsQueryWithInCondition() { return true; } @Override public boolean supportsQueryWithRangeCondition() { return true; } @Override public boolean supportsQueryWithOrderBy() { return true; } @Override public boolean supportsQueryWithContains() { return true; } @Override public boolean supportsQueryWithContainsKey() { return true; } @Override public boolean supportsQueryByPage() { return true; } @Override public boolean supportsQuerySortByInputIds() { return false; } @Override public boolean supportsDeleteEdgeByLabel() { return true; } @Override public boolean supportsUpdateVertexProperty() { return true; } @Override public boolean supportsMergeVertexProperty() { return false; } @Override public boolean supportsUpdateEdgeProperty() { return true; } @Override public boolean supportsTransaction() {<FILL_FUNCTION_BODY>} @Override public boolean supportsNumberType() { return true; } @Override public boolean supportsAggregateProperty() { return false; } @Override public boolean supportsTtl() { return true; } @Override public boolean supportsOlapProperties() { return true; } }
// Cassandra support tx(atomicity level) with batch API // https://docs.datastax.com/en/cassandra/2.1/cassandra/dml/dml_atomicity_c.html return true;
519
60
579
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-cassandra/src/main/java/org/apache/hugegraph/backend/store/cassandra/CassandraOptions.java
CassandraOptions
instance
class CassandraOptions extends OptionHolder { private CassandraOptions() { super(); } private static volatile CassandraOptions instance; public static synchronized CassandraOptions instance() {<FILL_FUNCTION_BODY>} public static final ConfigOption<String> CASSANDRA_HOST = new ConfigOption<>( "cassandra.host", "The seeds hostname or ip address of cassandra cluster.", disallowEmpty(), "localhost" ); public static final ConfigOption<Integer> CASSANDRA_PORT = new ConfigOption<>( "cassandra.port", "The seeds port address of cassandra cluster.", rangeInt(1, 65535), 9042 ); public static final ConfigOption<String> CASSANDRA_USERNAME = new ConfigOption<>( "cassandra.username", "The username to use to login to cassandra cluster.", "" ); public static final ConfigOption<String> CASSANDRA_PASSWORD = new ConfigOption<>( "cassandra.password", "The password corresponding to cassandra.username.", "" ); public static final ConfigOption<Integer> CASSANDRA_CONN_TIMEOUT = new ConfigOption<>( "cassandra.connect_timeout", "The cassandra driver connect server timeout(seconds).", rangeInt(1, 30), 5 ); public static final ConfigOption<Integer> CASSANDRA_READ_TIMEOUT = new ConfigOption<>( "cassandra.read_timeout", "The cassandra driver read from server timeout(seconds).", rangeInt(1, 120), 20 ); public static final ConfigOption<String> CASSANDRA_STRATEGY = new ConfigOption<>( "cassandra.keyspace.strategy", "The replication strategy of keyspace, valid value is " + "SimpleStrategy or NetworkTopologyStrategy.", allowValues("SimpleStrategy", "NetworkTopologyStrategy"), "SimpleStrategy" ); public static final ConfigListOption<String> CASSANDRA_REPLICATION = new ConfigListOption<>( "cassandra.keyspace.replication", "The keyspace replication factor of SimpleStrategy, " + "like '[3]'. Or replicas in each datacenter of " + "NetworkTopologyStrategy, like '[dc1:2,dc2:1]'.", disallowEmpty(), "3" ); public static final ConfigOption<String> CASSANDRA_COMPRESSION = new ConfigOption<>( "cassandra.compression_type", "The compression algorithm of cassandra transport: none/snappy/lz4.", allowValues("none", "snappy", "lz4"), "none" ); public static final ConfigOption<Integer> CASSANDRA_JMX_PORT = new ConfigOption<>( "cassandra.jmx_port", "The port of JMX API service for cassandra", rangeInt(1, 65535), 7199 ); public static final ConfigOption<Integer> AGGR_TIMEOUT = new ConfigOption<>( "cassandra.aggregation_timeout", "The timeout in seconds of waiting for aggregation.", positiveInt(), 12 * 60 * 60 ); }
if (instance == null) { instance = new CassandraOptions(); instance.registerOptions(); } return instance;
880
36
916
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-cassandra/src/main/java/org/apache/hugegraph/backend/store/cassandra/CassandraSerializer.java
CassandraSerializer
readUserdata
class CassandraSerializer extends TableSerializer { public CassandraSerializer(HugeConfig config) { super(config); } @Override public CassandraBackendEntry newBackendEntry(HugeType type, Id id) { return new CassandraBackendEntry(type, id); } @Override protected TableBackendEntry newBackendEntry(TableBackendEntry.Row row) { return new CassandraBackendEntry(row); } @Override protected TableBackendEntry newBackendEntry(HugeIndex index) { TableBackendEntry backendEntry = newBackendEntry(index.type(), index.id()); if (index.indexLabel().olap()) { backendEntry.olap(true); } return backendEntry; } @Override protected CassandraBackendEntry convertEntry(BackendEntry backendEntry) { if (!(backendEntry instanceof CassandraBackendEntry)) { throw new BackendException("Not supported by CassandraSerializer"); } return (CassandraBackendEntry) backendEntry; } @Override protected Set<Object> parseIndexElemIds(TableBackendEntry entry) { return ImmutableSet.of(entry.column(HugeKeys.ELEMENT_IDS)); } @Override protected Id toId(Number number) { return IdGenerator.of(number.longValue()); } @Override protected Id[] toIdArray(Object object) { assert object instanceof Collection; @SuppressWarnings("unchecked") Collection<Number> numbers = (Collection<Number>) object; Id[] ids = new Id[numbers.size()]; int i = 0; for (Number number : numbers) { ids[i++] = toId(number); } return ids; } @Override protected Object toLongSet(Collection<Id> ids) { Set<Long> results = InsertionOrderUtil.newSet(); for (Id id : ids) { results.add(id.asLong()); } return results; } @Override protected Object toLongList(Collection<Id> ids) { List<Long> results = new ArrayList<>(ids.size()); for (Id id : ids) { results.add(id.asLong()); } return results; } @Override protected void formatProperties(HugeElement element, TableBackendEntry.Row row) { if (!element.hasProperties() && !element.removed()) { row.column(HugeKeys.PROPERTIES, ImmutableMap.of()); } else { // Format properties for (HugeProperty<?> prop : element.getProperties()) { this.formatProperty(prop, row); } } } @Override protected void parseProperties(HugeElement element, TableBackendEntry.Row row) { Map<Number, Object> props = row.column(HugeKeys.PROPERTIES); for (Map.Entry<Number, Object> prop : props.entrySet()) { Id pkeyId = this.toId(prop.getKey()); this.parseProperty(pkeyId, prop.getValue(), element); } } @Override public BackendEntry writeOlapVertex(HugeVertex vertex) { CassandraBackendEntry entry = newBackendEntry(HugeType.OLAP, vertex.id()); entry.column(HugeKeys.ID, this.writeId(vertex.id())); Collection<HugeProperty<?>> properties = vertex.getProperties(); E.checkArgument(properties.size() == 1, "Expect only 1 property for olap vertex, but got %s", properties.size()); HugeProperty<?> property = properties.iterator().next(); PropertyKey pk = property.propertyKey(); entry.subId(pk.id()); entry.column(HugeKeys.PROPERTY_VALUE, this.writeProperty(pk, property.value())); entry.olap(true); return entry; } @Override protected Object writeProperty(PropertyKey propertyKey, Object value) { BytesBuffer buffer = BytesBuffer.allocate(BytesBuffer.BUF_PROPERTY); if (propertyKey == null) { /* * Since we can't know the type of the property value in some * scenarios so need to construct a fake property key to * serialize to reuse code. */ propertyKey = new PropertyKey(null, IdGenerator.of(0L), "fake"); propertyKey.dataType(DataType.fromClass(value.getClass())); } buffer.writeProperty(propertyKey, value); buffer.forReadWritten(); return buffer.asByteBuffer(); } @Override @SuppressWarnings("unchecked") protected <T> T readProperty(PropertyKey pkey, Object value) { BytesBuffer buffer = BytesBuffer.wrap((ByteBuffer) value); return (T) buffer.readProperty(pkey); } @Override protected Object writeId(Id id) { return IdUtil.writeBinString(id); } @Override protected Id readId(Object id) { return IdUtil.readBinString(id); } @Override protected void writeUserdata(SchemaElement schema, TableBackendEntry entry) { assert entry instanceof CassandraBackendEntry; for (Map.Entry<String, Object> e : schema.userdata().entrySet()) { entry.column(HugeKeys.USER_DATA, e.getKey(), JsonUtil.toJson(e.getValue())); } } @Override protected void readUserdata(SchemaElement schema, TableBackendEntry entry) {<FILL_FUNCTION_BODY>} }
assert entry instanceof CassandraBackendEntry; // Parse all user data of a schema element Map<String, String> userdata = entry.column(HugeKeys.USER_DATA); for (Map.Entry<String, String> e : userdata.entrySet()) { String key = e.getKey(); Object value = JsonUtil.fromJson(e.getValue(), Object.class); schema.userdata(key, value); }
1,495
113
1,608
<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-cassandra/src/main/java/org/apache/hugegraph/backend/store/cassandra/CassandraSessionPool.java
CassandraSessionPool
open
class CassandraSessionPool extends BackendSessionPool { private static final int SECOND = 1000; private Cluster cluster; private final String keyspace; public CassandraSessionPool(HugeConfig config, String keyspace, String store) { super(config, keyspace + "/" + store); this.cluster = null; this.keyspace = keyspace; } @Override public synchronized void open() {<FILL_FUNCTION_BODY>} @Override public final synchronized boolean opened() { return (this.cluster != null && !this.cluster.isClosed()); } protected final synchronized Cluster cluster() { E.checkState(this.cluster != null, "Cassandra cluster has not been initialized"); return this.cluster; } @Override public final Session session() { return (Session) super.getOrNewSession(); } @Override protected Session newSession() { E.checkState(this.cluster != null, "Cassandra cluster has not been initialized"); return new Session(); } @Override protected synchronized void doClose() { if (this.cluster != null && !this.cluster.isClosed()) { this.cluster.close(); } } public final boolean clusterConnected() { E.checkState(this.cluster != null, "Cassandra cluster has not been initialized"); return !this.cluster.isClosed(); } /** * The Session class is a wrapper of driver Session * Expect every thread hold its own session(wrapper) */ public final class Session extends AbstractBackendSession { private com.datastax.driver.core.Session session; private BatchStatement batch; public Session() { this.session = null; this.batch = new BatchStatement(); // LOGGED } public BatchStatement add(Statement statement) { return this.batch.add(statement); } @Override public void rollback() { this.batch.clear(); } @Override public ResultSet commit() { ResultSet rs = this.session.execute(this.batch); // Clear batch if execute() successfully (retained if failed) this.batch.clear(); return rs; } public void commitAsync() { Collection<Statement> statements = this.batch.getStatements(); int count = 0; int processors = Math.min(statements.size(), 1023); List<ResultSetFuture> results = new ArrayList<>(processors + 1); for (Statement s : statements) { ResultSetFuture future = this.session.executeAsync(s); results.add(future); if (++count > processors) { results.forEach(ResultSetFuture::getUninterruptibly); results.clear(); count = 0; } } for (ResultSetFuture future : results) { future.getUninterruptibly(); } // Clear batch if execute() successfully (retained if failed) this.batch.clear(); } public ResultSet query(Statement statement) { assert !this.hasChanges(); return this.execute(statement); } public ResultSet execute(Statement statement) { return this.session.execute(statement); } public ResultSet execute(String statement) { return this.session.execute(statement); } public ResultSet execute(String statement, Object... args) { return this.session.execute(statement, args); } private void tryOpen() { assert this.session == null; try { this.open(); } catch (InvalidQueryException ignored) { // ignore } } @Override public void open() { this.opened = true; assert this.session == null; this.session = cluster().connect(keyspace()); } @Override public boolean opened() { if (this.opened && this.session == null) { this.tryOpen(); } return this.opened && this.session != null; } @Override public boolean closed() { if (!this.opened || this.session == null) { return true; } return this.session.isClosed(); } @Override public void close() { assert this.closeable(); if (this.session == null) { return; } this.session.close(); this.session = null; } @Override public boolean hasChanges() { return this.batch.size() > 0; } public Collection<Statement> statements() { return this.batch.getStatements(); } public String keyspace() { return CassandraSessionPool.this.keyspace; } public Metadata metadata() { return CassandraSessionPool.this.cluster.getMetadata(); } public int aggregateTimeout() { HugeConfig conf = CassandraSessionPool.this.config(); return conf.get(CassandraOptions.AGGR_TIMEOUT); } } }
if (this.opened()) { throw new BackendException("Please close the old SessionPool " + "before opening a new one"); } HugeConfig config = this.config(); // Contact options String hosts = config.get(CassandraOptions.CASSANDRA_HOST); int port = config.get(CassandraOptions.CASSANDRA_PORT); assert this.cluster == null || this.cluster.isClosed(); /* * We disable cassandra metrics through withoutMetrics(), due to * metrics versions are incompatible, java11 glassfish use metrics 4, * but cassandra use metrics 3. * TODO: fix it after after cassandra upgrade metrics version */ Builder builder = Cluster.builder() .addContactPoints(hosts.split(",")) .withoutMetrics() .withPort(port); // Timeout options int connTimeout = config.get(CassandraOptions.CASSANDRA_CONN_TIMEOUT); int readTimeout = config.get(CassandraOptions.CASSANDRA_READ_TIMEOUT); SocketOptions socketOptions = new SocketOptions(); socketOptions.setConnectTimeoutMillis(connTimeout * SECOND); socketOptions.setReadTimeoutMillis(readTimeout * SECOND); builder.withSocketOptions(socketOptions); // Credential options String username = config.get(CassandraOptions.CASSANDRA_USERNAME); String password = config.get(CassandraOptions.CASSANDRA_PASSWORD); if (!username.isEmpty()) { builder.withCredentials(username, password); } // Compression options String compression = config.get(CassandraOptions.CASSANDRA_COMPRESSION); builder.withCompression(Compression.valueOf(compression.toUpperCase())); this.cluster = builder.build();
1,348
483
1,831
<methods>public void <init>(HugeConfig, java.lang.String) ,public boolean close() ,public boolean closed() ,public HugeConfig config() ,public void forceResetSessions() ,public final org.apache.hugegraph.backend.store.BackendSession getOrNewSession() ,public abstract void open() throws java.lang.Exception,public abstract org.apache.hugegraph.backend.store.BackendSession session() ,public java.lang.String toString() ,public org.apache.hugegraph.backend.store.BackendSession useSession() <variables>private static final Logger LOG,private final non-sealed HugeConfig config,private final non-sealed java.lang.String name,private final non-sealed long reconnectDetectInterval,private final non-sealed java.util.concurrent.atomic.AtomicInteger sessionCount,private final non-sealed Map<java.lang.Long,org.apache.hugegraph.backend.store.BackendSession> sessions,private final non-sealed ThreadLocal<org.apache.hugegraph.backend.store.BackendSession> threadLocalSession
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-cassandra/src/main/java/org/apache/hugegraph/backend/store/cassandra/CassandraShard.java
SplitCallable
call
class SplitCallable implements Callable<List<Shard>> { private final TokenRange tokenRange; private final long splitPartitions; private final long splitSize; public SplitCallable(TokenRange tokenRange, long splitPartitions, long splitSize) { if (splitSize <= 0 && splitPartitions <= 0) { throw new IllegalArgumentException(String.format( "The split-partitions must be > 0, but got %s", splitPartitions)); } if (splitSize > 0 && splitSize < MIN_SHARD_SIZE) { // splitSize should be at least 1M if passed throw new IllegalArgumentException(String.format( "The split-size must be >= %s bytes, but got %s", MIN_SHARD_SIZE, splitSize)); } this.tokenRange = tokenRange; this.splitPartitions = splitPartitions; this.splitSize = splitSize; } @Override public List<Shard> call() throws Exception {<FILL_FUNCTION_BODY>} }
ArrayList<Shard> splits = new ArrayList<>(); Map<TokenRange, Long> subSplits = getSubSplits( this.tokenRange, this.splitPartitions, this.splitSize); for (Map.Entry<TokenRange, Long> entry : subSplits.entrySet()) { List<TokenRange> ranges = entry.getKey().unwrap(); for (TokenRange subrange : ranges) { String start = !isPartitionerOpp() ? subrange.getStart().toString() : subrange.getStart().toString().substring(2); String end = !isPartitionerOpp() ? subrange.getEnd().toString() : subrange.getEnd().toString().substring(2); long length = entry.getValue(); splits.add(new Shard(start, end, length)); } } return splits;
273
229
502
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-cassandra/src/main/java/org/apache/hugegraph/backend/store/cassandra/CassandraStoreProvider.java
CassandraStoreProvider
driverVersion
class CassandraStoreProvider extends AbstractBackendStoreProvider { protected String keyspace() { return this.graph().toLowerCase(); } @Override protected BackendStore newSchemaStore(HugeConfig config, String store) { return new CassandraSchemaStore(this, this.keyspace(), store); } @Override protected BackendStore newGraphStore(HugeConfig config, String store) { return new CassandraGraphStore(this, this.keyspace(), store); } @Override protected BackendStore newSystemStore(HugeConfig config, String store) { return new CassandraSystemStore(this, this.keyspace(), store); } @Override public String type() { return "cassandra"; } @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] #455: fix scylladb backend doesn't support label query in page * [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] #661 & #680: support bin serialization for cassandra * [1.7] #691: support aggregate property * [1.8] #746: support userdata for indexlabel * [1.9] #295: support ttl for vertex and edge * [1.10] #1333: support read frequency for property key * [1.11] #1506: support olap properties * [1.11] #1533: add meta table in system store */ return "1.11";
220
328
548
<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-cassandra/src/main/java/org/apache/hugegraph/backend/store/cassandra/CassandraTables.java
VertexLabel
init
class VertexLabel extends CassandraTable { public static final String TABLE = HugeType.VERTEX_LABEL.string(); public VertexLabel() { super(TABLE); } @Override public void init(CassandraSessionPool.Session session) {<FILL_FUNCTION_BODY>} }
ImmutableMap<HugeKeys, DataType> pkeys = ImmutableMap.of( HugeKeys.ID, TYPE_SL ); ImmutableMap<HugeKeys, DataType> ckeys = ImmutableMap.of(); ImmutableMap<HugeKeys, DataType> columns = ImmutableMap .<HugeKeys, DataType>builder() .put(HugeKeys.NAME, DataType.text()) .put(HugeKeys.ID_STRATEGY, DataType.tinyint()) .put(HugeKeys.PRIMARY_KEYS, DataType.list(TYPE_PK)) .put(HugeKeys.NULLABLE_KEYS, DataType.set(TYPE_PK)) .put(HugeKeys.INDEX_LABELS, DataType.set(TYPE_IL)) .put(HugeKeys.PROPERTIES, DataType.set(TYPE_PK)) .put(HugeKeys.ENABLE_LABEL_INDEX, DataType.cboolean()) .put(HugeKeys.USER_DATA, TYPE_UD) .put(HugeKeys.STATUS, DataType.tinyint()) .put(HugeKeys.TTL, TYPE_TTL) .put(HugeKeys.TTL_START_TIME, TYPE_PK) .build(); this.createTable(session, pkeys, ckeys, columns); this.createIndex(session, NAME_INDEX, HugeKeys.NAME);
87
361
448
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/HugeException.java
HugeException
rootCause
class HugeException extends RuntimeException { private static final long serialVersionUID = -8711375282196157058L; public HugeException(String message) { super(message); } public HugeException(String message, Throwable cause) { super(message, cause); } public HugeException(String message, Object... args) { super(String.format(message, args)); } public HugeException(String message, Throwable cause, Object... args) { super(String.format(message, args), cause); } public Throwable rootCause() { return rootCause(this); } public static Throwable rootCause(Throwable e) {<FILL_FUNCTION_BODY>} public static boolean isInterrupted(Throwable e) { Throwable rootCause = HugeException.rootCause(e); return rootCause instanceof InterruptedException || rootCause instanceof TraversalInterruptedException || rootCause instanceof InterruptedIOException; } }
Throwable cause = e; while (cause.getCause() != null) { cause = cause.getCause(); } return cause;
286
45
331
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.Throwable) <variables>static final long serialVersionUID
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/HugeFactory.java
HugeFactory
open
class HugeFactory { private static final Logger LOG = Log.logger(HugeFactory.class); private static final Thread SHUT_DOWN_HOOK = new Thread(() -> { LOG.info("HugeGraph is shutting down"); HugeFactory.shutdown(30L, true); }, "hugegraph-shutdown"); static { SerialEnum.registerInternalEnums(); HugeGraph.registerTraversalStrategies(StandardHugeGraph.class); Runtime.getRuntime().addShutdownHook(SHUT_DOWN_HOOK); } private static final String NAME_REGEX = "^[A-Za-z][A-Za-z0-9_]{0,47}$"; private static final Map<String, HugeGraph> GRAPHS = new HashMap<>(); private static final AtomicBoolean SHUT_DOWN = new AtomicBoolean(false); public static synchronized HugeGraph open(Configuration config) { HugeConfig conf = config instanceof HugeConfig ? (HugeConfig) config : new HugeConfig(config); return open(conf); } public static synchronized HugeGraph open(HugeConfig config) {<FILL_FUNCTION_BODY>} public static HugeGraph open(String path) { return open(getLocalConfig(path)); } public static HugeGraph open(URL url) { return open(getRemoteConfig(url)); } public static void remove(HugeGraph graph) { String name = graph.option(CoreOptions.STORE); GRAPHS.remove(name); } public static void checkGraphName(String name, String configFile) { E.checkArgument(name.matches(NAME_REGEX), "Invalid graph name '%s' in %s, " + "valid graph name is up to 48 alpha-numeric " + "characters and underscores and only letters are " + "supported as first letter. " + "Note: letter is case insensitive", name, configFile); } public static PropertiesConfiguration getLocalConfig(String path) { File file = new File(path); E.checkArgument(file.exists() && file.isFile() && file.canRead(), "Please specify a proper config file rather than: %s", file.toString()); try { return new Configurations().properties(file); } catch (ConfigurationException e) { throw new HugeException("Unable to load config file: %s", e, path); } } public static PropertiesConfiguration getRemoteConfig(URL url) { try { return new Configurations().properties(url); } catch (ConfigurationException e) { throw new HugeException("Unable to load remote config file: %s", e, url); } } public static void shutdown(long timeout) { shutdown(timeout, false); } /** * Stop all the daemon threads * * @param timeout wait in seconds * @param ignoreException don't throw exception if true */ public static void shutdown(long timeout, boolean ignoreException) { if (!SHUT_DOWN.compareAndSet(false, true)) { return; } try { if (!EventHub.destroy(timeout)) { throw new TimeoutException(timeout + "s"); } TaskManager.instance().shutdown(timeout); OltpTraverser.destroy(); } catch (Throwable e) { LOG.error("Error while shutdown", e); SHUT_DOWN.compareAndSet(true, false); if (ignoreException) { return; } else { throw new HugeException("Failed to shutdown", e); } } LOG.info("HugeFactory shutdown"); } public static void removeShutdownHook() { Runtime.getRuntime().removeShutdownHook(SHUT_DOWN_HOOK); } }
SecurityManager sm = System.getSecurityManager(); if (sm != null) { // Not allowed to read file via Gremlin when SecurityManager enabled String configFileName; File configFile = config.file(); if (configFile == null) { configFileName = config.toString(); } else { configFileName = configFile.getName(); } sm.checkRead(configFileName); } String name = config.get(CoreOptions.STORE); checkGraphName(name, "graph config(like hugegraph.properties)"); name = name.toLowerCase(); HugeGraph graph = GRAPHS.get(name); if (graph == null || graph.closed()) { graph = new StandardHugeGraph(config); GRAPHS.put(name, graph); } else { String backend = config.get(CoreOptions.BACKEND); E.checkState(backend.equalsIgnoreCase(graph.backend()), "Graph name '%s' has been used by backend '%s'", name, graph.backend()); } return graph;
1,015
278
1,293
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/analyzer/AnalyzerFactory.java
AnalyzerFactory
analyzer
class AnalyzerFactory { private static final Map<String, Class<? extends Analyzer>> ANALYZERS; static { ANALYZERS = new ConcurrentHashMap<>(); } public static Analyzer analyzer(String name, String mode) {<FILL_FUNCTION_BODY>} private static Analyzer customizedAnalyzer(String name, String mode) { Class<? extends Analyzer> clazz = ANALYZERS.get(name); if (clazz == null) { throw new HugeException("Not exists analyzer: %s", name); } assert Analyzer.class.isAssignableFrom(clazz); try { return clazz.getConstructor(String.class).newInstance(mode); } catch (Exception e) { throw new HugeException( "Failed to construct analyzer '%s' with mode '%s'", e, name, mode); } } @SuppressWarnings({"rawtypes", "unchecked"}) public static void register(String name, String classPath) { ClassLoader classLoader = SerializerFactory.class.getClassLoader(); Class<?> clazz; try { clazz = classLoader.loadClass(classPath); } catch (Exception e) { throw new HugeException("Load class path '%s' failed", e, classPath); } // Check subclass if (!Analyzer.class.isAssignableFrom(clazz)) { throw new HugeException("Class '%s' is not a subclass of " + "class Analyzer", classPath); } // Check exists if (ANALYZERS.containsKey(name)) { throw new HugeException("Exists analyzer: %s(%s)", name, ANALYZERS.get(name).getName()); } // Register class ANALYZERS.put(name, (Class) clazz); } }
name = name.toLowerCase(); switch (name) { case "ansj": return new AnsjAnalyzer(mode); case "hanlp": return new HanLPAnalyzer(mode); case "smartcn": return new SmartCNAnalyzer(mode); case "jieba": return new JiebaAnalyzer(mode); case "jcseg": return new JcsegAnalyzer(mode); case "mmseg4j": return new MMSeg4JAnalyzer(mode); case "ikanalyzer": return new IKAnalyzer(mode); default: return customizedAnalyzer(name, mode); }
500
175
675
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/analyzer/AnsjAnalyzer.java
AnsjAnalyzer
segment
class AnsjAnalyzer implements Analyzer { public static final List<String> SUPPORT_MODES = ImmutableList.of( "BaseAnalysis", "IndexAnalysis", "ToAnalysis", "NlpAnalysis" ); private final String analysis; public AnsjAnalyzer(String mode) { if (!SUPPORT_MODES.contains(mode)) { throw new ConfigException( "Unsupported segment mode '%s' for ansj analyzer, " + "the available values are %s", mode, SUPPORT_MODES); } this.analysis = mode; } @Override public Set<String> segment(String text) {<FILL_FUNCTION_BODY>} }
Result terms; switch (this.analysis) { case "BaseAnalysis": terms = BaseAnalysis.parse(text); break; case "ToAnalysis": terms = ToAnalysis.parse(text); break; case "NlpAnalysis": terms = NlpAnalysis.parse(text); break; case "IndexAnalysis": terms = IndexAnalysis.parse(text); break; default: throw new AssertionError(String.format( "Unsupported segment mode '%s'", this.analysis)); } assert terms != null; Set<String> result = InsertionOrderUtil.newSet(); for (Term term : terms) { result.add(term.getName()); } return result;
191
195
386
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/analyzer/HanLPAnalyzer.java
HanLPAnalyzer
segment
class HanLPAnalyzer implements Analyzer { public static final List<String> SUPPORT_MODES = ImmutableList.<String>builder() .add("standard") .add("nlp") .add("index") .add("nShort") .add("shortest") .add("speed") .build(); private static final Segment N_SHORT_SEGMENT = new NShortSegment().enableCustomDictionary(false) .enablePlaceRecognize(true) .enableOrganizationRecognize(true); private static final Segment DIJKSTRA_SEGMENT = new DijkstraSegment().enableCustomDictionary(false) .enablePlaceRecognize(true) .enableOrganizationRecognize(true); private final String tokenizer; public HanLPAnalyzer(String mode) { if (!SUPPORT_MODES.contains(mode)) { throw new ConfigException( "Unsupported segment mode '%s' for hanlp analyzer, " + "the available values are %s", mode, SUPPORT_MODES); } this.tokenizer = mode; } @Override public Set<String> segment(String text) {<FILL_FUNCTION_BODY>} }
List<Term> terms; switch (this.tokenizer) { case "standard": terms = StandardTokenizer.segment(text); break; case "nlp": terms = NLPTokenizer.segment(text); break; case "index": terms = IndexTokenizer.segment(text); break; case "nShort": terms = N_SHORT_SEGMENT.seg(text); break; case "shortest": terms = DIJKSTRA_SEGMENT.seg(text); break; case "speed": terms = SpeedTokenizer.segment(text); break; default: throw new AssertionError(String.format( "Unsupported segment mode '%s'", this.tokenizer)); } assert terms != null; Set<String> result = InsertionOrderUtil.newSet(); for (Term term : terms) { result.add(term.word); } return result;
324
260
584
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/analyzer/IKAnalyzer.java
IKAnalyzer
segment
class IKAnalyzer implements Analyzer { public static final List<String> SUPPORT_MODES = ImmutableList.of( "smart", "max_word" ); private final boolean smartSegMode; public IKAnalyzer(String mode) { if (!SUPPORT_MODES.contains(mode)) { throw new ConfigException( "Unsupported segment mode '%s' for ikanalyzer, " + "the available values are %s", mode, SUPPORT_MODES); } this.smartSegMode = SUPPORT_MODES.get(0).equals(mode); } @Override public Set<String> segment(String text) {<FILL_FUNCTION_BODY>} }
Set<String> result = InsertionOrderUtil.newSet(); IKSegmenter ik = new IKSegmenter(new StringReader(text), this.smartSegMode); try { Lexeme word; while ((word = ik.next()) != null) { result.add(word.getLexemeText()); } } catch (Exception e) { throw new HugeException("IKAnalyzer segment text '%s' failed", e, text); } return result;
192
134
326
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/analyzer/JcsegAnalyzer.java
JcsegAnalyzer
segment
class JcsegAnalyzer implements Analyzer { public static final List<String> SUPPORT_MODES = ImmutableList.of( "Simple", "Complex" ); private static final SegmenterConfig CONFIG = new SegmenterConfig(); private static final ADictionary DIC = DictionaryFactory.createDefaultDictionary(CONFIG); private final ISegment.Type type; public JcsegAnalyzer(String mode) { if (!SUPPORT_MODES.contains(mode)) { throw new ConfigException( "Unsupported segment mode '%s' for jcseg analyzer, " + "the available values are %s", mode, SUPPORT_MODES); } if ("Simple".equals(mode)) { this.type = ISegment.SIMPLE; } else { this.type = ISegment.COMPLEX; } } @Override public Set<String> segment(String text) {<FILL_FUNCTION_BODY>} }
Set<String> result = InsertionOrderUtil.newSet(); try { ISegment segmentor = this.type.factory.create(CONFIG, DIC); segmentor.reset(new StringReader(text)); IWord word; while ((word = segmentor.next()) != null) { result.add(word.getValue()); } } catch (Exception e) { throw new HugeException("Jcseg segment text '%s' failed", e, text); } return result;
259
133
392
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/analyzer/JiebaAnalyzer.java
JiebaAnalyzer
segment
class JiebaAnalyzer implements Analyzer { public static final List<String> SUPPORT_MODES = ImmutableList.of( "SEARCH", "INDEX" ); private static final JiebaSegmenter JIEBA_SEGMENTER = new JiebaSegmenter(); private final JiebaSegmenter.SegMode segMode; public JiebaAnalyzer(String mode) { if (!SUPPORT_MODES.contains(mode)) { throw new ConfigException( "Unsupported segment mode '%s' for jieba analyzer, " + "the available values are %s", mode, SUPPORT_MODES); } this.segMode = JiebaSegmenter.SegMode.valueOf(mode); } @Override public Set<String> segment(String text) {<FILL_FUNCTION_BODY>} }
Set<String> result = InsertionOrderUtil.newSet(); for (SegToken token : JIEBA_SEGMENTER.process(text, this.segMode)) { result.add(token.word); } return result;
225
65
290
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/analyzer/MMSeg4JAnalyzer.java
MMSeg4JAnalyzer
segment
class MMSeg4JAnalyzer implements Analyzer { public static final List<String> SUPPORT_MODES = ImmutableList.of( "Simple", "Complex", "MaxWord" ); private static final Dictionary DIC = Dictionary.getInstance(); private final Seg seg; public MMSeg4JAnalyzer(String mode) { if (!SUPPORT_MODES.contains(mode)) { throw new ConfigException( "Unsupported segment mode '%s' for mmseg4j analyzer, " + "the available values are %s", mode, SUPPORT_MODES); } int index = SUPPORT_MODES.indexOf(mode); switch (index) { case 0: this.seg = new SimpleSeg(DIC); break; case 1: this.seg = new ComplexSeg(DIC); break; case 2: this.seg = new MaxWordSeg(DIC); break; default: throw new AssertionError(String.format( "Unsupported segment mode '%s'", mode)); } } @Override public Set<String> segment(String text) {<FILL_FUNCTION_BODY>} }
Set<String> result = InsertionOrderUtil.newSet(); MMSeg mmSeg = new MMSeg(new StringReader(text), this.seg); try { Word word; while ((word = mmSeg.next()) != null) { result.add(word.getString()); } } catch (Exception e) { throw new HugeException("MMSeg4j segment text '%s' failed", e, text); } return result;
320
124
444
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/analyzer/SmartCNAnalyzer.java
SmartCNAnalyzer
segment
class SmartCNAnalyzer implements Analyzer { private static final SmartChineseAnalyzer ANALYZER = new SmartChineseAnalyzer(); public SmartCNAnalyzer(String mode) { // pass } @Override public Set<String> segment(String text) {<FILL_FUNCTION_BODY>} }
Set<String> result = InsertionOrderUtil.newSet(); Reader reader = new StringReader(text); try (TokenStream tokenStream = ANALYZER.tokenStream("text", reader)) { tokenStream.reset(); CharTermAttribute term; while (tokenStream.incrementToken()) { term = tokenStream.getAttribute(CharTermAttribute.class); result.add(term.toString()); } } catch (Exception e) { throw new HugeException("SmartCN segment text '%s' failed", e, text); } return result;
88
150
238
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/auth/EntityManager.java
EntityManager
delete
class EntityManager<T extends Entity> { private final HugeGraphParams graph; private final String label; private final Function<Vertex, T> deser; private final ThreadLocal<Boolean> autoCommit = new ThreadLocal<>(); private static final long NO_LIMIT = -1L; public EntityManager(HugeGraphParams graph, String label, Function<Vertex, T> deser) { E.checkNotNull(graph, "graph"); this.graph = graph; this.label = label; this.deser = deser; } private GraphTransaction tx() { return this.graph.systemTransaction(); } private HugeGraph graph() { return this.graph.graph(); } private String unhideLabel() { return Hidden.unHide(this.label); } public Id add(T entity) { E.checkArgumentNotNull(entity, "Entity can't be null"); return this.save(entity, false); } public Id update(T entity) { E.checkArgumentNotNull(entity, "Entity can't be null"); entity.onUpdate(); return this.save(entity, true); } public T delete(Id id) {<FILL_FUNCTION_BODY>} public T get(Id id) { T entity = null; Iterator<Vertex> vertices = this.tx().queryVertices(id); if (vertices.hasNext()) { entity = this.deser.apply(vertices.next()); assert !vertices.hasNext(); } if (entity == null) { throw new NotFoundException("Can't find %s with id '%s'", this.unhideLabel(), id); } return entity; } public boolean exists(Id id) { Iterator<Vertex> vertices = this.tx().queryVertices(id); if (vertices.hasNext()) { Vertex vertex = vertices.next(); return this.label.equals(vertex.label()); } return false; } public List<T> list(List<Id> ids) { return toList(this.queryById(ids)); } public List<T> list(long limit) { return toList(this.queryEntity(this.label, ImmutableMap.of(), limit)); } protected List<T> query(String key, Object value, long limit) { Map<String, Object> conditions = ImmutableMap.of(key, value); return toList(this.queryEntity(this.label, conditions, limit)); } protected List<T> toList(Iterator<Vertex> vertices) { Iterator<T> iter = new MapperIterator<>(vertices, this.deser); // Convert iterator to list to avoid across thread tx accessed return (List<T>) QueryResults.toList(iter).list(); } private Iterator<Vertex> queryById(List<Id> ids) { Object[] idArray = ids.toArray(new Id[0]); return this.tx().queryVertices(idArray); } private Iterator<Vertex> queryEntity(String label, Map<String, Object> conditions, long limit) { ConditionQuery query = new ConditionQuery(HugeType.VERTEX); VertexLabel vl = this.graph().vertexLabel(label); query.eq(HugeKeys.LABEL, vl.id()); for (Map.Entry<String, Object> entry : conditions.entrySet()) { PropertyKey pkey = this.graph().propertyKey(entry.getKey()); query.query(Condition.eq(pkey.id(), entry.getValue())); } query.showHidden(true); if (limit != NO_LIMIT) { query.limit(limit); } return this.tx().queryVertices(query); } private Id save(T entity, boolean expectExists) { // Construct vertex from task HugeVertex vertex = this.constructVertex(entity); E.checkArgument(this.exists(vertex.id()) == expectExists, "Can't save %s '%s' that %s exists", this.unhideLabel(), vertex.id(), expectExists ? "not" : "already"); // Add or update user in backend store, stale index might exist vertex = this.tx().addVertex(vertex); this.commitOrRollback(); return vertex.id(); } private HugeVertex constructVertex(Entity entity) { if (!this.graph().existsVertexLabel(entity.label())) { throw new HugeException("Schema is missing for %s '%s'", entity.label(), entity.id()); } return this.tx().constructVertex(false, entity.asArray()); } private void commitOrRollback() { Boolean autoCommit = this.autoCommit.get(); if (autoCommit != null && !autoCommit) { return; } this.tx().commitOrRollback(); } public void autoCommit(boolean value) { this.autoCommit.set(value); } }
T entity = null; Iterator<Vertex> vertices = this.tx().queryVertices(id); if (vertices.hasNext()) { HugeVertex vertex = (HugeVertex) vertices.next(); entity = this.deser.apply(vertex); this.tx().removeVertex(vertex); this.commitOrRollback(); assert !vertices.hasNext(); } return entity;
1,325
108
1,433
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/auth/HugeAccess.java
HugeAccess
property
class HugeAccess extends Relationship { private static final long serialVersionUID = -7644007602408729385L; private final Id group; private final Id target; private HugePermission permission; private String description; public HugeAccess(Id group, Id target) { this(group, target, null); } public HugeAccess(Id group, Id target, HugePermission permission) { this.group = group; this.target = target; this.permission = permission; this.description = null; } @Override public ResourceType type() { return ResourceType.GRANT; } @Override public String label() { return P.ACCESS; } @Override public String sourceLabel() { return P.GROUP; } @Override public String targetLabel() { return P.TARGET; } @Override public Id source() { return this.group; } @Override public Id target() { return this.target; } public HugePermission permission() { return this.permission; } public void permission(HugePermission permission) { this.permission = permission; } public String description() { return this.description; } public void description(String description) { this.description = description; } @Override public String toString() { return String.format("HugeAccess(%s->%s)%s", this.group, this.target, this.asMap()); } @Override protected boolean property(String key, Object value) {<FILL_FUNCTION_BODY>} @Override protected Object[] asArray() { E.checkState(this.permission != null, "Access permission can't be null"); List<Object> list = new ArrayList<>(12); list.add(T.label); list.add(P.ACCESS); list.add(P.PERMISSION); list.add(this.permission.code()); if (this.description != null) { list.add(P.DESCRIPTION); list.add(this.description); } return super.asArray(list); } @Override public Map<String, Object> asMap() { E.checkState(this.permission != null, "Access permission can't be null"); Map<String, Object> map = new HashMap<>(); map.put(Hidden.unHide(P.GROUP), this.group); map.put(Hidden.unHide(P.TARGET), this.target); map.put(Hidden.unHide(P.PERMISSION), this.permission); if (this.description != null) { map.put(Hidden.unHide(P.DESCRIPTION), this.description); } return super.asMap(map); } public static HugeAccess fromEdge(Edge edge) { HugeAccess access = new HugeAccess((Id) edge.outVertex().id(), (Id) edge.inVertex().id()); return fromEdge(edge, access); } public static Schema schema(HugeGraphParams graph) { return new Schema(graph); } public static final class P { public static final String ACCESS = Hidden.hide("access"); public static final String LABEL = T.label.getAccessor(); public static final String GROUP = HugeGroup.P.GROUP; public static final String TARGET = HugeTarget.P.TARGET; public static final String PERMISSION = "~access_permission"; public static final String DESCRIPTION = "~access_description"; public static String unhide(String key) { final String prefix = Hidden.hide("access_"); if (key.startsWith(prefix)) { return key.substring(prefix.length()); } return key; } } public static final class Schema extends SchemaDefine { public Schema(HugeGraphParams graph) { super(graph, P.ACCESS); } @Override public void initSchemaIfNeeded() { if (this.existEdgeLabel(this.label)) { return; } String[] properties = this.initProperties(); // Create edge label EdgeLabel label = this.schema().edgeLabel(this.label) .sourceLabel(P.GROUP) .targetLabel(P.TARGET) .properties(properties) .nullableKeys(P.DESCRIPTION) .sortKeys(P.PERMISSION) .enableLabelIndex(true) .build(); this.graph.schemaTransaction().addEdgeLabel(label); } private String[] initProperties() { List<String> props = new ArrayList<>(); props.add(createPropertyKey(P.PERMISSION, DataType.BYTE)); props.add(createPropertyKey(P.DESCRIPTION)); return super.initProperties(props); } } }
if (super.property(key, value)) { return true; } switch (key) { case P.PERMISSION: this.permission = HugePermission.fromCode((Byte) value); break; case P.DESCRIPTION: this.description = (String) value; break; default: throw new AssertionError("Unsupported key: " + key); } return true;
1,350
113
1,463
<methods>public non-sealed void <init>() ,public static T fromEdge(Edge, T) ,public java.lang.String idString() ,public abstract org.apache.hugegraph.backend.id.Id source() ,public abstract java.lang.String sourceLabel() ,public abstract org.apache.hugegraph.backend.id.Id target() ,public abstract java.lang.String targetLabel() <variables>private static final long serialVersionUID
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/auth/HugeBelong.java
HugeBelong
property
class HugeBelong extends Relationship { private static final long serialVersionUID = -7242751631755533423L; private final Id user; private final Id group; private String description; public HugeBelong(Id user, Id group) { this.user = user; this.group = group; this.description = null; } @Override public ResourceType type() { return ResourceType.GRANT; } @Override public String label() { return P.BELONG; } @Override public String sourceLabel() { return P.USER; } @Override public String targetLabel() { return P.GROUP; } @Override public Id source() { return this.user; } @Override public Id target() { return this.group; } public String description() { return this.description; } public void description(String description) { this.description = description; } @Override public String toString() { return String.format("HugeBelong(%s->%s)%s", this.user, this.group, this.asMap()); } @Override protected boolean property(String key, Object value) {<FILL_FUNCTION_BODY>} @Override protected Object[] asArray() { List<Object> list = new ArrayList<>(10); list.add(T.label); list.add(P.BELONG); if (this.description != null) { list.add(P.DESCRIPTION); list.add(this.description); } return super.asArray(list); } @Override public Map<String, Object> asMap() { Map<String, Object> map = new HashMap<>(); map.put(Hidden.unHide(P.USER), this.user); map.put(Hidden.unHide(P.GROUP), this.group); if (this.description != null) { map.put(Hidden.unHide(P.DESCRIPTION), this.description); } return super.asMap(map); } public static HugeBelong fromEdge(Edge edge) { HugeBelong belong = new HugeBelong((Id) edge.outVertex().id(), (Id) edge.inVertex().id()); return fromEdge(edge, belong); } public static Schema schema(HugeGraphParams graph) { return new Schema(graph); } public static final class P { public static final String BELONG = Hidden.hide("belong"); public static final String LABEL = T.label.getAccessor(); public static final String USER = HugeUser.P.USER; public static final String GROUP = HugeGroup.P.GROUP; public static final String DESCRIPTION = "~belong_description"; public static String unhide(String key) { final String prefix = Hidden.hide("belong_"); if (key.startsWith(prefix)) { return key.substring(prefix.length()); } return key; } } public static final class Schema extends SchemaDefine { public Schema(HugeGraphParams graph) { super(graph, P.BELONG); } @Override public void initSchemaIfNeeded() { if (this.existEdgeLabel(this.label)) { return; } String[] properties = this.initProperties(); // Create edge label EdgeLabel label = this.schema().edgeLabel(this.label) .sourceLabel(P.USER) .targetLabel(P.GROUP) .properties(properties) .nullableKeys(P.DESCRIPTION) .enableLabelIndex(true) .build(); this.graph.schemaTransaction().addEdgeLabel(label); } private String[] initProperties() { List<String> props = new ArrayList<>(); props.add(createPropertyKey(P.DESCRIPTION)); return super.initProperties(props); } } }
if (super.property(key, value)) { return true; } if (key.equals(P.DESCRIPTION)) { this.description = (String) value; } else { throw new AssertionError("Unsupported key: " + key); } return true;
1,110
79
1,189
<methods>public non-sealed void <init>() ,public static T fromEdge(Edge, T) ,public java.lang.String idString() ,public abstract org.apache.hugegraph.backend.id.Id source() ,public abstract java.lang.String sourceLabel() ,public abstract org.apache.hugegraph.backend.id.Id target() ,public abstract java.lang.String targetLabel() <variables>private static final long serialVersionUID
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/auth/HugeGroup.java
HugeGroup
fromVertex
class HugeGroup extends Entity { private static final long serialVersionUID = 2330399818352242686L; private String name; private String description; public HugeGroup(String name) { this(null, name); } public HugeGroup(Id id) { this(id, null); } public HugeGroup(Id id, String name) { this.id = id; this.name = name; this.description = null; } @Override public ResourceType type() { return ResourceType.USER_GROUP; } @Override public String label() { return P.GROUP; } @Override public String name() { return this.name; } public String description() { return this.description; } public void description(String description) { this.description = description; } @Override public String toString() { return String.format("HugeGroup(%s)%s", this.id, this.asMap()); } @Override protected boolean property(String key, Object value) { if (super.property(key, value)) { return true; } switch (key) { case P.NAME: this.name = (String) value; break; case P.DESCRIPTION: this.description = (String) value; break; default: throw new AssertionError("Unsupported key: " + key); } return true; } @Override protected Object[] asArray() { E.checkState(this.name != null, "Group name can't be null"); List<Object> list = new ArrayList<>(12); list.add(T.label); list.add(P.GROUP); list.add(P.NAME); list.add(this.name); if (this.description != null) { list.add(P.DESCRIPTION); list.add(this.description); } return super.asArray(list); } @Override public Map<String, Object> asMap() { E.checkState(this.name != null, "Group name can't be null"); Map<String, Object> map = new HashMap<>(); map.put(Hidden.unHide(P.NAME), this.name); if (this.description != null) { map.put(Hidden.unHide(P.DESCRIPTION), this.description); } return super.asMap(map); } public static HugeGroup fromVertex(Vertex vertex) {<FILL_FUNCTION_BODY>} public static Schema schema(HugeGraphParams graph) { return new Schema(graph); } public static final class P { public static final String GROUP = Hidden.hide("group"); public static final String ID = T.id.getAccessor(); public static final String LABEL = T.label.getAccessor(); public static final String NAME = "~group_name"; public static final String DESCRIPTION = "~group_description"; public static String unhide(String key) { final String prefix = Hidden.hide("group_"); if (key.startsWith(prefix)) { return key.substring(prefix.length()); } return key; } } public static final class Schema extends SchemaDefine { public Schema(HugeGraphParams graph) { super(graph, P.GROUP); } @Override public void initSchemaIfNeeded() { if (this.existVertexLabel(this.label)) { return; } String[] properties = this.initProperties(); // Create vertex label VertexLabel label = this.schema().vertexLabel(this.label) .properties(properties) .usePrimaryKeyId() .primaryKeys(P.NAME) .nullableKeys(P.DESCRIPTION) .enableLabelIndex(true) .build(); this.graph.schemaTransaction().addVertexLabel(label); } private String[] initProperties() { List<String> props = new ArrayList<>(); props.add(createPropertyKey(P.NAME)); props.add(createPropertyKey(P.DESCRIPTION)); return super.initProperties(props); } } }
HugeGroup group = new HugeGroup((Id) vertex.id()); return fromVertex(vertex, group);
1,167
31
1,198
<methods>public non-sealed void <init>() ,public static T fromVertex(Vertex, T) ,public java.lang.String idString() <variables>private static final long serialVersionUID
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/auth/HugeTarget.java
HugeTarget
asArray
class HugeTarget extends Entity { private static final long serialVersionUID = -3361487778656878418L; private String name; private String graph; private String url; private List<HugeResource> resources; private static final List<HugeResource> EMPTY = ImmutableList.of(); public HugeTarget(Id id) { this(id, null, null, null, EMPTY); } public HugeTarget(String name, String url) { this(null, name, name, url, EMPTY); } public HugeTarget(String name, String graph, String url) { this(null, name, graph, url, EMPTY); } public HugeTarget(String name, String graph, String url, List<HugeResource> resources) { this(null, name, graph, url, resources); } private HugeTarget(Id id, String name, String graph, String url, List<HugeResource> resources) { this.id = id; this.name = name; this.graph = graph; this.url = url; this.resources = resources; } @Override public ResourceType type() { return ResourceType.TARGET; } @Override public String label() { return P.TARGET; } @Override public String name() { return this.name; } public String graph() { return this.graph; } public String url() { return this.url; } public void url(String url) { this.url = url; } public List<HugeResource> resources() { return this.resources; } public void resources(String resources) { try { this.resources = HugeResource.parseResources(resources); } catch (Exception e) { throw new HugeException("Invalid format of resources: %s", e, resources); } } public void resources(List<HugeResource> resources) { E.checkNotNull(resources, "resources"); this.resources = resources; } @Override public String toString() { return String.format("HugeTarget(%s)%s", this.id, this.asMap()); } @Override protected boolean property(String key, Object value) { if (super.property(key, value)) { return true; } switch (key) { case P.NAME: this.name = (String) value; break; case P.GRAPH: this.graph = (String) value; break; case P.URL: this.url = (String) value; break; case P.RESS: this.resources = HugeResource.parseResources((String) value); break; default: throw new AssertionError("Unsupported key: " + key); } return true; } @Override protected Object[] asArray() {<FILL_FUNCTION_BODY>} @Override public Map<String, Object> asMap() { E.checkState(this.name != null, "Target name can't be null"); E.checkState(this.url != null, "Target url can't be null"); Map<String, Object> map = new HashMap<>(); map.put(Hidden.unHide(P.NAME), this.name); map.put(Hidden.unHide(P.GRAPH), this.graph); map.put(Hidden.unHide(P.URL), this.url); if (this.resources != null && this.resources != EMPTY) { map.put(Hidden.unHide(P.RESS), this.resources); } return super.asMap(map); } public static HugeTarget fromVertex(Vertex vertex) { HugeTarget target = new HugeTarget((Id) vertex.id()); return fromVertex(vertex, target); } public static Schema schema(HugeGraphParams graph) { return new Schema(graph); } public static final class P { public static final String TARGET = Hidden.hide("target"); public static final String ID = T.id.getAccessor(); public static final String LABEL = T.label.getAccessor(); public static final String NAME = "~target_name"; public static final String GRAPH = "~target_graph"; public static final String URL = "~target_url"; public static final String RESS = "~target_resources"; public static String unhide(String key) { final String prefix = Hidden.hide("target_"); if (key.startsWith(prefix)) { return key.substring(prefix.length()); } return key; } } public static final class Schema extends SchemaDefine { public Schema(HugeGraphParams graph) { super(graph, P.TARGET); } @Override public void initSchemaIfNeeded() { if (this.existVertexLabel(this.label)) { return; } String[] properties = this.initProperties(); // Create vertex label VertexLabel label = this.schema().vertexLabel(this.label) .properties(properties) .usePrimaryKeyId() .primaryKeys(P.NAME) .nullableKeys(P.RESS) .enableLabelIndex(true) .build(); this.graph.schemaTransaction().addVertexLabel(label); } private String[] initProperties() { List<String> props = new ArrayList<>(); props.add(createPropertyKey(P.NAME)); props.add(createPropertyKey(P.GRAPH)); props.add(createPropertyKey(P.URL)); props.add(createPropertyKey(P.RESS)); return super.initProperties(props); } } }
E.checkState(this.name != null, "Target name can't be null"); E.checkState(this.url != null, "Target url can't be null"); List<Object> list = new ArrayList<>(16); list.add(T.label); list.add(P.TARGET); list.add(P.NAME); list.add(this.name); list.add(P.GRAPH); list.add(this.graph); list.add(P.URL); list.add(this.url); if (this.resources != null && this.resources != EMPTY) { list.add(P.RESS); list.add(JsonUtil.toJson(this.resources)); } return super.asArray(list);
1,570
215
1,785
<methods>public non-sealed void <init>() ,public static T fromVertex(Vertex, T) ,public java.lang.String idString() <variables>private static final long serialVersionUID
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/auth/HugeUser.java
HugeUser
property
class HugeUser extends Entity { private static final long serialVersionUID = -8951193710873772717L; private String name; private String password; private String phone; private String email; private String avatar; private String description; // This field is just for cache private RolePermission role; public HugeUser(String name) { this(null, name); } public HugeUser(Id id) { this(id, null); } public HugeUser(Id id, String name) { this.id = id; this.name = name; this.role = null; } @Override public ResourceType type() { return ResourceType.USER_GROUP; } @Override public String label() { return P.USER; } @Override public String name() { return this.name; } public String password() { return this.password; } public void password(String password) { this.password = password; } public String phone() { return this.phone; } public void phone(String phone) { this.phone = phone; } public String email() { return this.email; } public void email(String email) { this.email = email; } public String avatar() { return this.avatar; } public void avatar(String avatar) { this.avatar = avatar; } public String description() { return this.description; } public void description(String description) { this.description = description; } public RolePermission role() { return this.role; } public void role(RolePermission role) { this.role = role; } @Override public String toString() { return String.format("HugeUser(%s)%s", this.id, this.asMap()); } @Override protected boolean property(String key, Object value) {<FILL_FUNCTION_BODY>} @Override protected Object[] asArray() { E.checkState(this.name != null, "User name can't be null"); E.checkState(this.password != null, "User password can't be null"); List<Object> list = new ArrayList<>(18); list.add(T.label); list.add(P.USER); list.add(P.NAME); list.add(this.name); list.add(P.PASSWORD); list.add(this.password); if (this.phone != null) { list.add(P.PHONE); list.add(this.phone); } if (this.email != null) { list.add(P.EMAIL); list.add(this.email); } if (this.avatar != null) { list.add(P.AVATAR); list.add(this.avatar); } return super.asArray(list); } @Override public Map<String, Object> asMap() { E.checkState(this.name != null, "User name can't be null"); E.checkState(this.password != null, "User password can't be null"); Map<String, Object> map = new HashMap<>(); map.put(Hidden.unHide(P.NAME), this.name); map.put(Hidden.unHide(P.PASSWORD), this.password); if (this.phone != null) { map.put(Hidden.unHide(P.PHONE), this.phone); } if (this.email != null) { map.put(Hidden.unHide(P.EMAIL), this.email); } if (this.avatar != null) { map.put(Hidden.unHide(P.AVATAR), this.avatar); } return super.asMap(map); } public static HugeUser fromVertex(Vertex vertex) { HugeUser user = new HugeUser((Id) vertex.id()); return fromVertex(vertex, user); } public static Schema schema(HugeGraphParams graph) { return new Schema(graph); } public static final class P { public static final String USER = Hidden.hide("user"); public static final String ID = T.id.getAccessor(); public static final String LABEL = T.label.getAccessor(); public static final String NAME = "~user_name"; public static final String PASSWORD = "~user_password"; public static final String PHONE = "~user_phone"; public static final String EMAIL = "~user_email"; public static final String AVATAR = "~user_avatar"; public static String unhide(String key) { final String prefix = Hidden.hide("user_"); if (key.startsWith(prefix)) { return key.substring(prefix.length()); } return key; } } public static final class Schema extends SchemaDefine { public Schema(HugeGraphParams graph) { super(graph, P.USER); } @Override public void initSchemaIfNeeded() { if (this.existVertexLabel(this.label)) { return; } String[] properties = this.initProperties(); // Create vertex label VertexLabel label = this.schema().vertexLabel(this.label) .properties(properties) .usePrimaryKeyId() .primaryKeys(P.NAME) .nullableKeys(P.PHONE, P.EMAIL, P.AVATAR) .enableLabelIndex(true) .build(); this.graph.schemaTransaction().addVertexLabel(label); } private String[] initProperties() { List<String> props = new ArrayList<>(); props.add(createPropertyKey(P.NAME)); props.add(createPropertyKey(P.PASSWORD)); props.add(createPropertyKey(P.PHONE)); props.add(createPropertyKey(P.EMAIL)); props.add(createPropertyKey(P.AVATAR)); return super.initProperties(props); } } }
if (super.property(key, value)) { return true; } switch (key) { case P.NAME: this.name = (String) value; break; case P.PASSWORD: this.password = (String) value; break; case P.PHONE: this.phone = (String) value; break; case P.EMAIL: this.email = (String) value; break; case P.AVATAR: this.avatar = (String) value; break; default: throw new AssertionError("Unsupported key: " + key); } return true;
1,697
176
1,873
<methods>public non-sealed void <init>() ,public static T fromVertex(Vertex, T) ,public java.lang.String idString() <variables>private static final long serialVersionUID
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/auth/RelationshipManager.java
RelationshipManager
commitOrRollback
class RelationshipManager<T extends Relationship> { private final HugeGraphParams graph; private final String label; private final Function<Edge, T> deser; private final ThreadLocal<Boolean> autoCommit = new ThreadLocal<>(); private static final long NO_LIMIT = -1L; public RelationshipManager(HugeGraphParams graph, String label, Function<Edge, T> deser) { E.checkNotNull(graph, "graph"); this.graph = graph; this.label = label; this.deser = deser; this.autoCommit.set(true); } private GraphTransaction tx() { return this.graph.systemTransaction(); } private HugeGraph graph() { return this.graph.graph(); } private String unhideLabel() { return Hidden.unHide(this.label); } public Id add(T relationship) { E.checkArgumentNotNull(relationship, "Relationship can't be null"); return this.save(relationship, false); } public Id update(T relationship) { E.checkArgumentNotNull(relationship, "Relationship can't be null"); relationship.onUpdate(); return this.save(relationship, true); } public T delete(Id id) { T relationship = null; Iterator<Edge> edges = this.tx().queryEdges(id); if (edges.hasNext()) { HugeEdge edge = (HugeEdge) edges.next(); relationship = this.deser.apply(edge); this.tx().removeEdge(edge); this.commitOrRollback(); assert !edges.hasNext(); } return relationship; } public T get(Id id) { T relationship = null; Iterator<Edge> edges = this.tx().queryEdges(id); if (edges.hasNext()) { relationship = this.deser.apply(edges.next()); assert !edges.hasNext(); } if (relationship == null) { throw new NotFoundException("Can't find %s with id '%s'", this.unhideLabel(), id); } return relationship; } public boolean exists(Id id) { Iterator<Edge> edges = this.tx().queryEdges(id); if (edges.hasNext()) { Edge edge = edges.next(); return this.label.equals(edge.label()); } return false; } public List<T> list(List<Id> ids) { return toList(this.queryById(ids)); } public List<T> list(long limit) { Iterator<Edge> edges = this.queryRelationship(null, null, this.label, ImmutableMap.of(), limit); return toList(edges); } public List<T> list(Id source, Directions direction, String label, long limit) { Iterator<Edge> edges = this.queryRelationship(source, direction, label, ImmutableMap.of(), limit); return toList(edges); } public List<T> list(Id source, Directions direction, String label, String key, Object value, long limit) { Map<String, Object> conditions = ImmutableMap.of(key, value); Iterator<Edge> edges = this.queryRelationship(source, direction, label, conditions, limit); return toList(edges); } protected List<T> toList(Iterator<Edge> edges) { Iterator<T> iter = new MapperIterator<>(edges, this.deser); // Convert iterator to list to avoid across thread tx accessed return (List<T>) QueryResults.toList(iter).list(); } private Iterator<Edge> queryById(List<Id> ids) { Object[] idArray = ids.toArray(new Id[0]); return this.tx().queryEdges(idArray); } private Iterator<Edge> queryRelationship(Id source, Directions direction, String label, Map<String, Object> conditions, long limit) { ConditionQuery query = new ConditionQuery(HugeType.EDGE); EdgeLabel el = this.graph().edgeLabel(label); if (direction == null) { direction = Directions.OUT; } if (source != null) { query.eq(HugeKeys.OWNER_VERTEX, source); query.eq(HugeKeys.DIRECTION, direction); } if (label != null) { query.eq(HugeKeys.LABEL, el.id()); } for (Map.Entry<String, Object> entry : conditions.entrySet()) { PropertyKey pk = this.graph().propertyKey(entry.getKey()); query.query(Condition.eq(pk.id(), entry.getValue())); } query.showHidden(true); if (limit != NO_LIMIT) { query.limit(limit); } Iterator<Edge> edges = this.tx().queryEdges(query); if (limit == NO_LIMIT) { return edges; } long[] size = new long[1]; return new MapperIterator<>(edges, edge -> { if (++size[0] > limit) { return null; } return edge; }); } private Id save(T relationship, boolean expectExists) { if (!this.graph().existsEdgeLabel(relationship.label())) { throw new HugeException("Schema is missing for %s '%s'", relationship.label(), relationship.source()); } HugeVertex source = this.newVertex(relationship.source(), relationship.sourceLabel()); HugeVertex target = this.newVertex(relationship.target(), relationship.targetLabel()); HugeEdge edge = source.constructEdge(relationship.label(), target, relationship.asArray()); E.checkArgument(this.exists(edge.id()) == expectExists, "Can't save %s '%s' that %s exists", this.unhideLabel(), edge.id(), expectExists ? "not" : "already"); this.tx().addEdge(edge); this.commitOrRollback(); return edge.id(); } private HugeVertex newVertex(Object id, String label) { VertexLabel vl = this.graph().vertexLabel(label); Id idValue = HugeVertex.getIdValue(id); return HugeVertex.create(this.tx(), idValue, vl); } private void commitOrRollback() {<FILL_FUNCTION_BODY>} public void autoCommit(boolean value) { autoCommit.set(value); } }
Boolean autoCommit = this.autoCommit.get(); if (autoCommit != null && !autoCommit) { return; } this.tx().commitOrRollback();
1,773
54
1,827
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/auth/ResourceObject.java
ResourceObject
of
class ResourceObject<V> { private final String graph; private final ResourceType type; private final V operated; public ResourceObject(String graph, ResourceType type, V operated) { E.checkNotNull(graph, "graph"); E.checkNotNull(type, "type"); E.checkNotNull(operated, "operated"); this.graph = graph; this.type = type; this.operated = operated; } public String graph() { return this.graph; } public ResourceType type() { return this.type; } public V operated() { return this.operated; } @Override public String toString() { Object operated = this.operated; if (this.type.isAuth()) { operated = ((AuthElement) this.operated).idString(); } String typeStr = this.type.toString(); String operatedStr = operated.toString(); int capacity = this.graph.length() + typeStr.length() + operatedStr.length() + 36; StringBuilder sb = new StringBuilder(capacity); return sb.append("Resource{graph=").append(this.graph) .append(",type=").append(typeStr) .append(",operated=").append(operatedStr) .append("}").toString(); } public static ResourceObject<SchemaElement> of(String graph, SchemaElement elem) {<FILL_FUNCTION_BODY>} public static ResourceObject<HugeElement> of(String graph, HugeElement elem) { ResourceType resType = ResourceType.from(elem.type()); return new ResourceObject<>(graph, resType, elem); } public static ResourceObject<AuthElement> of(String graph, AuthElement elem) { return new ResourceObject<>(graph, elem.type(), elem); } public static ResourceObject<?> of(String graph, ResourceType type, Nameable elem) { return new ResourceObject<>(graph, type, elem); } }
ResourceType resType = ResourceType.from(elem.type()); return new ResourceObject<>(graph, resType, elem);
536
34
570
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/auth/RolePermission.java
RolePermission
contains
class RolePermission { public static final RolePermission NONE = RolePermission.role( "none", HugePermission.NONE); public static final RolePermission ADMIN = RolePermission.role( "admin", HugePermission.ANY); static { SimpleModule module = new SimpleModule(); module.addSerializer(RolePermission.class, new RolePermissionSer()); module.addDeserializer(RolePermission.class, new RolePermissionDeser()); JsonUtil.registerModule(module); } // Mapping of: graph -> action -> resource @JsonProperty("roles") private final Map<String, Map<HugePermission, List<HugeResource>>> roles; public RolePermission() { this(new TreeMap<>()); } private RolePermission(Map<String, Map<HugePermission, List<HugeResource>>> roles) { this.roles = roles; } protected void add(String graph, String action, List<HugeResource> resources) { this.add(graph, HugePermission.valueOf(action), resources); } protected void add(String graph, HugePermission action, List<HugeResource> resources) { Map<HugePermission, List<HugeResource>> permissions = this.roles.get(graph); if (permissions == null) { permissions = new TreeMap<>(); this.roles.put(graph, permissions); } List<HugeResource> mergedResources = permissions.get(action); if (mergedResources == null) { mergedResources = new ArrayList<>(); permissions.put(action, mergedResources); } mergedResources.addAll(resources); } public Map<String, Map<HugePermission, List<HugeResource>>> map() { return Collections.unmodifiableMap(this.roles); } public boolean contains(RolePermission other) {<FILL_FUNCTION_BODY>} @Override public boolean equals(Object object) { if (!(object instanceof RolePermission)) { return false; } RolePermission other = (RolePermission) object; return Objects.equals(this.roles, other.roles); } public int hashCode() { return Objects.hash(this.roles); } @Override public String toString() { return this.roles.toString(); } public String toJson() { return JsonUtil.toJson(this); } public static RolePermission fromJson(Object json) { RolePermission role; if (json instanceof String) { role = JsonUtil.fromJson((String) json, RolePermission.class); } else { // Optimized json with RolePermission object E.checkArgument(json instanceof RolePermission, "Invalid role value: %s", json); role = (RolePermission) json; } return role; } public static RolePermission all(String graph) { return role(graph, HugePermission.ANY); } public static RolePermission role(String graph, HugePermission perm) { RolePermission role = new RolePermission(); role.add(graph, perm, HugeResource.ALL_RES); return role; } public static RolePermission none() { return NONE; } public static RolePermission admin() { return ADMIN; } public static RolePermission builtin(RolePermission role) { E.checkNotNull(role, "role"); if (role == ADMIN || role.equals(ADMIN)) { return ADMIN; } if (role == NONE || role.equals(NONE)) { return NONE; } return role; } private static class RolePermissionSer extends StdSerializer<RolePermission> { private static final long serialVersionUID = -2533310506459479383L; public RolePermissionSer() { super(RolePermission.class); } @Override public void serialize(RolePermission role, JsonGenerator generator, SerializerProvider provider) throws IOException { generator.writeStartObject(); generator.writeObjectField("roles", role.roles); generator.writeEndObject(); } } private static class RolePermissionDeser extends StdDeserializer<RolePermission> { private static final long serialVersionUID = -2038234657843260957L; public RolePermissionDeser() { super(RolePermission.class); } @Override public RolePermission deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException { TypeReference<?> type = new TypeReference<TreeMap<String, TreeMap<HugePermission, List<HugeResource>>>>() { }; if ("roles".equals(parser.nextFieldName())) { parser.nextValue(); return new RolePermission(parser.readValueAs(type)); } throw JsonMappingException.from(parser, "Expect field roles"); } } }
for (Map.Entry<String, Map<HugePermission, List<HugeResource>>> e1 : other.roles.entrySet()) { String g = e1.getKey(); Map<HugePermission, List<HugeResource>> perms = this.roles.get(g); if (perms == null) { return false; } for (Map.Entry<HugePermission, List<HugeResource>> e2 : e1.getValue().entrySet()) { List<HugeResource> ress = perms.get(e2.getKey()); if (ress == null) { return false; } for (HugeResource r : e2.getValue()) { boolean contains = false; for (HugeResource res : ress) { if (res.contains(r)) { contains = true; break; } } if (!contains) { return false; } } } } return true;
1,347
256
1,603
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/auth/SchemaDefine.java
AuthElement
asMap
class AuthElement implements Serializable { private static final long serialVersionUID = 8746691160192814973L; protected static final String CREATE = "create"; protected static final String UPDATE = "update"; protected static final String CREATOR = "creator"; protected Id id; protected Date create; protected Date update; protected String creator; public AuthElement() { this.create = new Date(); this.update = this.create; } public Id id() { return this.id; } public void id(Id id) { this.id = id; } public String idString() { return Hidden.unHide(this.label()) + "(" + this.id + ")"; } public Date create() { return this.create; } public void create(Date create) { this.create = create; } public Date update() { return this.update; } public void update(Date update) { this.update = update; } public void onUpdate() { this.update = new Date(); } public String creator() { return this.creator; } public void creator(String creator) { this.creator = creator; } protected Map<String, Object> asMap(Map<String, Object> map) {<FILL_FUNCTION_BODY>} protected boolean property(String key, Object value) { E.checkNotNull(key, "property key"); if (key.equals(hideField(this.label(), CREATE))) { this.create = (Date) value; return true; } if (key.equals(hideField(this.label(), UPDATE))) { this.update = (Date) value; return true; } if (key.equals(hideField(this.label(), CREATOR))) { this.creator = (String) value; return true; } return false; } protected Object[] asArray(List<Object> list) { E.checkState(this.create != null, "Property %s time can't be null", CREATE); E.checkState(this.update != null, "Property %s time can't be null", UPDATE); E.checkState(this.creator != null, "Property %s can't be null", CREATOR); list.add(hideField(this.label(), CREATE)); list.add(this.create); list.add(hideField(this.label(), UPDATE)); list.add(this.update); list.add(hideField(this.label(), CREATOR)); list.add(this.creator); return list.toArray(); } public abstract ResourceType type(); public abstract String label(); public abstract Map<String, Object> asMap(); protected abstract Object[] asArray(); }
E.checkState(this.create != null, "Property %s time can't be null", CREATE); E.checkState(this.update != null, "Property %s time can't be null", UPDATE); E.checkState(this.creator != null, "Property %s can't be null", CREATOR); if (this.id != null) { // The id is null when creating map.put(Hidden.unHide(P.ID), this.id); } map.put(unhideField(this.label(), CREATE), this.create); map.put(unhideField(this.label(), UPDATE), this.update); map.put(unhideField(this.label(), CREATOR), this.creator); return map;
781
208
989
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/auth/TokenGenerator.java
TokenGenerator
verify
class TokenGenerator { private final SecretKey key; public TokenGenerator(HugeConfig config) { String secretKey = config.get(AuthOptions.AUTH_TOKEN_SECRET); this.key = Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8)); } public String create(Map<String, ?> payload, long expire) { return Jwts.builder() .setClaims(payload) .setExpiration(new Date(System.currentTimeMillis() + expire)) .signWith(this.key, SignatureAlgorithm.HS256) .compact(); } public Claims verify(String token) {<FILL_FUNCTION_BODY>} }
try { Jws<Claims> claimsJws = Jwts.parserBuilder() .setSigningKey(key) .build() .parseClaimsJws(token); return claimsJws.getBody(); } catch (ExpiredJwtException e) { throw new NotAuthorizedException("The token is expired", e); } catch (JwtException e) { throw new NotAuthorizedException("Invalid token", e); }
200
120
320
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/LocalCounter.java
LocalCounter
nextId
class LocalCounter { private final Map<HugeType, AtomicLong> counters; public LocalCounter() { this.counters = new ConcurrentHashMap<>(); } public synchronized Id nextId(HugeType type) {<FILL_FUNCTION_BODY>} public long getCounter(HugeType type) { AtomicLong counter = this.counters.get(type); if (counter == null) { counter = new AtomicLong(0); AtomicLong previous = this.counters.putIfAbsent(type, counter); if (previous != null) { counter = previous; } } return counter.longValue(); } public synchronized void increaseCounter(HugeType type, long increment) { AtomicLong counter = this.counters.get(type); if (counter == null) { counter = new AtomicLong(0); AtomicLong previous = this.counters.putIfAbsent(type, counter); if (previous != null) { counter = previous; } } long oldValue = counter.longValue(); AtomicLong value = new AtomicLong(oldValue + increment); this.counters.put(type, value); } public void reset() { this.counters.clear(); } }
AtomicLong counter = this.counters.get(type); if (counter == null) { counter = new AtomicLong(0); AtomicLong previous = this.counters.putIfAbsent(type, counter); if (previous != null) { counter = previous; } } return IdGenerator.of(counter.incrementAndGet());
344
97
441
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/cache/AbstractCache.java
AbstractCache
tick
class AbstractCache<K, V> implements Cache<K, V> { public static final int MB = 1024 * 1024; public static final int DEFAULT_SIZE = 1 * MB; public static final int MAX_INIT_CAP = 100 * MB; protected static final Logger LOG = Log.logger(AbstractCache.class); // The unit of expired time is ms private volatile long expire; // Enabled cache metrics may cause performance penalty private volatile boolean enabledMetrics; private final LongAdder hits; private final LongAdder miss; // NOTE: the count in number of items, not in bytes private final long capacity; // For user attachment private final AtomicReference<Object> attachment; public AbstractCache() { this(DEFAULT_SIZE); } public AbstractCache(long capacity) { if (capacity < 0L) { capacity = 0L; } this.capacity = capacity; this.attachment = new AtomicReference<>(); this.expire = 0L; this.enabledMetrics = false; this.hits = new LongAdder(); this.miss = new LongAdder(); } @Watched(prefix = "cache") @Override public V get(K id) { if (id == null || this.capacity <= 0L) { return null; } V value = this.access(id); if (this.enabledMetrics) { this.collectMetrics(id, value); } return value; } @Watched(prefix = "cache") @Override public V getOrFetch(K id, Function<K, V> fetcher) { if (id == null || this.capacity <= 0L) { return null; } V value = this.access(id); if (this.enabledMetrics) { this.collectMetrics(id, value); } // Do fetch and update the cache if cache missed if (value == null) { value = fetcher.apply(id); this.update(id, value); } return value; } private void collectMetrics(K key, V value) { if (value == null) { this.miss.add(1L); if (LOG.isDebugEnabled()) { LOG.debug("Cache missed '{}' (miss={}, hits={})", key, this.miss, this.hits); } } else { this.hits.add(1L); if (LOG.isDebugEnabled()) { LOG.debug("Cache cached '{}' (hits={}, miss={})", key, this.hits, this.miss); } } } @Override public boolean update(K id, V value) { return this.update(id, value, 0L); } @Watched(prefix = "cache") @Override public boolean update(K id, V value, long timeOffset) { if (id == null || value == null || this.capacity <= 0L) { return false; } return this.write(id, value, timeOffset); } @Watched(prefix = "cache") @Override public boolean updateIfAbsent(K id, V value) { if (id == null || value == null || this.capacity <= 0L || this.containsKey(id)) { return false; } return this.write(id, value, 0L); } @Watched(prefix = "cache") @Override public boolean updateIfPresent(K id, V value) { if (id == null || value == null || this.capacity <= 0L || !this.containsKey(id)) { return false; } return this.write(id, value, 0L); } @Watched(prefix = "cache") @Override public void invalidate(K id) { if (id == null || this.capacity <= 0L || !this.containsKey(id)) { return; } this.remove(id); } @Override public void expire(long ms) { this.expire = ms; } @Override public final long expire() { return this.expire; } @Override public long tick() {<FILL_FUNCTION_BODY>} @Override public boolean enableMetrics(boolean enabled) { boolean old = this.enabledMetrics; if (!enabled) { this.hits.reset(); this.miss.reset(); } this.enabledMetrics = enabled; return old; } @Override public final long hits() { return this.hits.sum(); } @Override public final long miss() { return this.miss.sum(); } @Override public final long capacity() { return this.capacity; } @Override public <T> T attachment(T object) { this.attachment.compareAndSet(null, object); return this.attachment(); } @Override public <T> T attachment() { @SuppressWarnings("unchecked") T attachment = (T) this.attachment.get(); return attachment; } protected abstract V access(K id); protected abstract boolean write(K id, V value, long timeOffset); protected abstract void remove(K id); protected abstract Iterator<CacheNode<K, V>> nodes(); protected static final long now() { return System.currentTimeMillis(); } protected static class CacheNode<K, V> { private final K key; private final V value; private final long time; public CacheNode(K key, V value, long timeOffset) { assert key != null; this.time = now() + timeOffset; this.key = key; this.value = value; } public final K key() { return this.key; } public final V value() { return this.value; } public long time() { return this.time; } @Override public String toString() { return this.key.toString(); } @Override public int hashCode() { return this.key.hashCode(); } @Override public boolean equals(Object object) { if (!(object instanceof CacheNode)) { return false; } @SuppressWarnings("unchecked") CacheNode<K, V> other = (CacheNode<K, V>) object; return this.key.equals(other.key()); } } }
long expireTime = this.expire; if (expireTime <= 0) { return 0L; } int expireItems = 0; long current = now(); for (Iterator<CacheNode<K, V>> it = this.nodes(); it.hasNext(); ) { CacheNode<K, V> node = it.next(); if (current - node.time() >= expireTime) { // Remove item while iterating map (it must be ConcurrentMap) this.remove(node.key()); expireItems++; } } if (expireItems > 0) { LOG.debug("Cache expired {} items cost {}ms (size {}, expire {}ms)", expireItems, now() - current, this.size(), expireTime); } return expireItems;
1,771
213
1,984
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/cache/CacheManager.java
CacheManager
cache
class CacheManager { private static final Logger LOG = Log.logger(CacheManager.class); private static final CacheManager INSTANCE = new CacheManager(); // Check the cache expiration every 30s by default private static final long TIMER_TICK_PERIOD = 30; // Log if tick cost time > 1000ms private static final long LOG_TICK_COST_TIME = 1000L; private final Map<String, Cache<Id, ?>> caches; private final Timer timer; public static CacheManager instance() { return INSTANCE; } public static boolean cacheEnableMetrics(String name, boolean enabled) { Cache<Id, ?> cache = INSTANCE.caches.get(name); E.checkArgument(cache != null, "Not found cache named '%s'", name); return cache.enableMetrics(enabled); } private CacheManager() { this.caches = new ConcurrentHashMap<>(); this.timer = new Timer("cache-expirer", true); this.scheduleTimer(TIMER_TICK_PERIOD); } private TimerTask scheduleTimer(float period) { TimerTask task = new TimerTask() { @Override public void run() { try { for (Entry<String, Cache<Id, Object>> entry : caches().entrySet()) { this.tick(entry.getKey(), entry.getValue()); } } catch (Throwable e) { LOG.warn("An exception occurred when running tick", e); } } private void tick(String name, Cache<Id, Object> cache) { long start = System.currentTimeMillis(); long items = cache.tick(); long cost = System.currentTimeMillis() - start; if (cost > LOG_TICK_COST_TIME) { LOG.info("Cache '{}' expired {} items cost {}ms > {}ms " + "(size {}, expire {}ms)", name, items, cost, LOG_TICK_COST_TIME, cache.size(), cache.expire()); } LOG.debug("Cache '{}' expiration tick cost {}ms", name, cost); } }; // Schedule task with the period in seconds this.timer.schedule(task, 0, (long) (period * 1000.0)); return task; } public <V> Map<String, Cache<Id, V>> caches() { @SuppressWarnings({"rawtypes", "unchecked"}) Map<String, Cache<Id, V>> caches = (Map) this.caches; return Collections.unmodifiableMap(caches); } public <V> Cache<Id, V> cache(String name) { return this.cache(name, RamCache.DEFAULT_SIZE); } public <V> Cache<Id, V> cache(String name, long capacity) {<FILL_FUNCTION_BODY>} public <V> Cache<Id, V> offheapCache(HugeGraph graph, String name, long capacity, long avgElemSize) { if (!this.caches.containsKey(name)) { OffheapCache cache = new OffheapCache(graph, capacity, avgElemSize); this.caches.putIfAbsent(name, cache); LOG.info("Init OffheapCache for '{}' with capacity {}", name, capacity); } @SuppressWarnings("unchecked") Cache<Id, V> cache = (Cache<Id, V>) this.caches.get(name); E.checkArgument(cache instanceof OffheapCache, "Invalid cache implement: %s", cache.getClass()); return cache; } public <V> Cache<Id, V> levelCache(HugeGraph graph, String name, long capacity1, long capacity2, long avgElemSize) { if (!this.caches.containsKey(name)) { RamCache cache1 = new RamCache(capacity1); OffheapCache cache2 = new OffheapCache(graph, capacity2, avgElemSize); this.caches.putIfAbsent(name, new LevelCache(cache1, cache2)); LOG.info("Init LevelCache for '{}' with capacity {}:{}", name, capacity1, capacity2); } @SuppressWarnings("unchecked") Cache<Id, V> cache = (Cache<Id, V>) this.caches.get(name); E.checkArgument(cache instanceof LevelCache, "Invalid cache implement: %s", cache.getClass()); return cache; } }
if (!this.caches.containsKey(name)) { this.caches.putIfAbsent(name, new RamCache(capacity)); LOG.info("Init RamCache for '{}' with capacity {}", name, capacity); } @SuppressWarnings("unchecked") Cache<Id, V> cache = (Cache<Id, V>) this.caches.get(name); E.checkArgument(cache instanceof RamCache, "Invalid cache implement: %s", cache.getClass()); return cache;
1,210
136
1,346
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/cache/CachedBackendStore.java
CachedBackendStore
query
class CachedBackendStore implements BackendStore { private BackendStore store = null; private Cache<Id, Object> cache = null; public CachedBackendStore(BackendStore store) { this.store = store; this.cache = CacheManager.instance().cache("store-" + store()); // Set expire 30s this.cache.expire(30 * 1000L); } @Override public String store() { return this.store.store(); } @Override public String storedVersion() { return this.store.storedVersion(); } @Override public String database() { return this.store.database(); } @Override public BackendStoreProvider provider() { return this.store.provider(); } @Override public SystemSchemaStore systemSchemaStore() { return this.store.systemSchemaStore(); } @Override public void open(HugeConfig config) { this.store.open(config); } @Override public void close() { this.store.close(); } @Override public boolean opened() { return this.store.opened(); } @Override public void init() { this.store.init(); } @Override public void clear(boolean clearSpace) { this.store.clear(clearSpace); } @Override public boolean initialized() { return this.store.initialized(); } @Override public void truncate() { this.store.truncate(); } @Override public void beginTx() { this.store.beginTx(); } @Override public void commitTx() { this.store.commitTx(); } @Override public void rollbackTx() { this.store.rollbackTx(); } @Override public <R> R metadata(HugeType type, String meta, Object[] args) { return this.store.metadata(type, meta, args); } @Override public BackendFeatures features() { return this.store.features(); } @Override public Id nextId(HugeType type) { return this.store.nextId(type); } @Override public void increaseCounter(HugeType type, long increment) { this.store.increaseCounter(type, increment); } @Override public long getCounter(HugeType type) { return this.store.getCounter(type); } @Override public boolean isSchemaStore() { return this.store.isSchemaStore(); } @Override public void mutate(BackendMutation mutation) { // TODO: invalid cache, or set expire time at least this.store.mutate(mutation); } @SuppressWarnings("unchecked") @Override public Iterator<BackendEntry> query(Query query) {<FILL_FUNCTION_BODY>} @Override public Number queryNumber(Query query) { return this.store.queryNumber(query); } /** * Query as an Id for cache */ static class QueryId implements Id { private String query; private int hashCode; public QueryId(Query q) { this.query = q.toString(); this.hashCode = q.hashCode(); } @Override public IdType type() { return IdType.UNKNOWN; } @Override public int hashCode() { return this.hashCode; } @Override public boolean equals(Object other) { if (!(other instanceof QueryId)) { return false; } return this.query.equals(((QueryId) other).query); } @Override public int compareTo(Id o) { return this.query.compareTo(o.asString()); } @Override public Object asObject() { return this.query; } @Override public String asString() { return this.query; } @Override public long asLong() { // TODO: improve return 0L; } @Override public byte[] asBytes() { return StringEncoding.encode(this.query); } @Override public String toString() { return this.query; } @Override public int length() { return this.query.length(); } } }
if (query.empty()) { return this.store.query(query); } QueryId id = new QueryId(query); Object result = this.cache.get(id); if (result != null) { return (Iterator<BackendEntry>) result; } else { Iterator<BackendEntry> rs = this.store.query(query); if (rs.hasNext()) { this.cache.update(id, rs); } return rs; }
1,200
135
1,335
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/cache/CachedSchemaTransaction.java
SchemaCaches
set
class SchemaCaches<V extends SchemaElement> { private final int size; private final IntObjectMap<V> pks; private final IntObjectMap<V> vls; private final IntObjectMap<V> els; private final IntObjectMap<V> ils; private final CachedTypes cachedTypes; public SchemaCaches(int size) { // TODO: improve size of each type for optimized array cache this.size = size; this.pks = new IntObjectMap<>(size); this.vls = new IntObjectMap<>(size); this.els = new IntObjectMap<>(size); this.ils = new IntObjectMap<>(size); this.cachedTypes = new CachedTypes(); } public void updateIfNeeded(V schema) { if (schema == null) { return; } Id id = schema.id(); if (id.number() && id.asLong() > 0L) { this.set(schema.type(), id, schema); } } @Watched public V get(HugeType type, Id id) { assert id.number(); long longId = id.asLong(); if (longId <= 0L) { assert false : id; return null; } int key = (int) longId; if (key >= this.size) { return null; } switch (type) { case PROPERTY_KEY: return this.pks.get(key); case VERTEX_LABEL: return this.vls.get(key); case EDGE_LABEL: return this.els.get(key); case INDEX_LABEL: return this.ils.get(key); default: return null; } } public void set(HugeType type, Id id, V value) {<FILL_FUNCTION_BODY>} public void remove(HugeType type, Id id) { assert id.number(); long longId = id.asLong(); if (longId <= 0L) { return; } int key = (int) longId; if (key >= this.size) { return; } this.setValue(type, key, null); } public void clear() { this.pks.clear(); this.vls.clear(); this.els.clear(); this.ils.clear(); this.cachedTypes.clear(); } public CachedTypes cachedTypes() { return this.cachedTypes; } private void setValue(HugeType type, int key, V value) { switch (type) { case PROPERTY_KEY: this.pks.set(key, value); break; case VERTEX_LABEL: this.vls.set(key, value); break; case EDGE_LABEL: this.els.set(key, value); break; case INDEX_LABEL: this.ils.set(key, value); break; default: // pass break; } } }
assert id.number(); long longId = id.asLong(); if (longId <= 0L) { assert false : id; return; } int key = (int) longId; if (key >= this.size) { return; } this.setValue(type, key, value);
842
89
931
<methods>public void <init>(org.apache.hugegraph.HugeGraphParams, org.apache.hugegraph.backend.store.BackendStore) ,public void addEdgeLabel(org.apache.hugegraph.schema.EdgeLabel) ,public void addIndexLabel(org.apache.hugegraph.schema.SchemaLabel, org.apache.hugegraph.schema.IndexLabel) ,public org.apache.hugegraph.backend.id.Id addPropertyKey(org.apache.hugegraph.schema.PropertyKey) ,public void addVertexLabel(org.apache.hugegraph.schema.VertexLabel) ,public void checkSchemaName(java.lang.String) ,public org.apache.hugegraph.backend.id.Id clearOlapPk(org.apache.hugegraph.schema.PropertyKey) ,public void createIndexLabelForOlapPk(org.apache.hugegraph.schema.PropertyKey) ,public org.apache.hugegraph.backend.id.Id createOlapPk(org.apache.hugegraph.schema.PropertyKey) ,public boolean existsSchemaId(org.apache.hugegraph.type.HugeType, org.apache.hugegraph.backend.id.Id) ,public org.apache.hugegraph.schema.EdgeLabel getEdgeLabel(org.apache.hugegraph.backend.id.Id) ,public org.apache.hugegraph.schema.EdgeLabel getEdgeLabel(java.lang.String) ,public List<org.apache.hugegraph.schema.EdgeLabel> getEdgeLabels() ,public org.apache.hugegraph.schema.IndexLabel getIndexLabel(org.apache.hugegraph.backend.id.Id) ,public org.apache.hugegraph.schema.IndexLabel getIndexLabel(java.lang.String) ,public List<org.apache.hugegraph.schema.IndexLabel> getIndexLabels() ,public org.apache.hugegraph.backend.id.Id getNextId(org.apache.hugegraph.type.HugeType) ,public org.apache.hugegraph.backend.id.Id getNextSystemId() ,public org.apache.hugegraph.schema.PropertyKey getPropertyKey(org.apache.hugegraph.backend.id.Id) ,public org.apache.hugegraph.schema.PropertyKey getPropertyKey(java.lang.String) ,public List<org.apache.hugegraph.schema.PropertyKey> getPropertyKeys() ,public org.apache.hugegraph.schema.VertexLabel getVertexLabel(org.apache.hugegraph.backend.id.Id) ,public org.apache.hugegraph.schema.VertexLabel getVertexLabel(java.lang.String) ,public List<org.apache.hugegraph.schema.VertexLabel> getVertexLabels() ,public org.apache.hugegraph.backend.id.Id rebuildIndex(org.apache.hugegraph.schema.SchemaElement) ,public org.apache.hugegraph.backend.id.Id rebuildIndex(org.apache.hugegraph.schema.SchemaElement, Set<org.apache.hugegraph.backend.id.Id>) ,public org.apache.hugegraph.backend.id.Id removeEdgeLabel(org.apache.hugegraph.backend.id.Id) ,public org.apache.hugegraph.backend.id.Id removeIndexLabel(org.apache.hugegraph.backend.id.Id) ,public void removeIndexLabelFromBaseLabel(org.apache.hugegraph.schema.IndexLabel) ,public org.apache.hugegraph.backend.id.Id removeOlapPk(org.apache.hugegraph.schema.PropertyKey) ,public org.apache.hugegraph.backend.id.Id removePropertyKey(org.apache.hugegraph.backend.id.Id) ,public org.apache.hugegraph.backend.id.Id removeVertexLabel(org.apache.hugegraph.backend.id.Id) ,public void setNextIdLowest(org.apache.hugegraph.type.HugeType, long) ,public void updateEdgeLabel(org.apache.hugegraph.schema.EdgeLabel) ,public void updateIndexLabel(org.apache.hugegraph.schema.IndexLabel) ,public void updatePropertyKey(org.apache.hugegraph.schema.PropertyKey) ,public void updateSchemaStatus(org.apache.hugegraph.schema.SchemaElement, org.apache.hugegraph.type.define.SchemaStatus) ,public void updateVertexLabel(org.apache.hugegraph.schema.VertexLabel) ,public org.apache.hugegraph.backend.id.Id validOrGenerateId(org.apache.hugegraph.type.HugeType, org.apache.hugegraph.backend.id.Id, java.lang.String) <variables>private final non-sealed org.apache.hugegraph.backend.LocalCounter counter,private final non-sealed org.apache.hugegraph.backend.tx.SchemaIndexTransaction indexTx,private final non-sealed org.apache.hugegraph.backend.store.SystemSchemaStore systemSchemaStore
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/cache/LevelCache.java
LevelCache
access
class LevelCache extends AbstractCache<Id, Object> { // For multi-layer caches private final AbstractCache<Id, Object>[] caches; @SuppressWarnings("unchecked") public LevelCache(AbstractCache<Id, Object> lavel1, AbstractCache<Id, Object> lavel2) { super(lavel2.capacity()); super.expire(lavel2.expire()); this.caches = new AbstractCache[]{lavel1, lavel2}; } @Override public void traverse(Consumer<Object> consumer) { this.last().traverse(consumer); } @Override public long size() { return this.last().size(); } @Override public void clear() { for (AbstractCache<Id, Object> cache : this.caches) { cache.clear(); } } @Override public void expire(long ms) { super.expire(ms); for (AbstractCache<Id, Object> cache : this.caches) { cache.expire(ms); } } @Override public boolean containsKey(Id id) { for (AbstractCache<Id, Object> cache : this.caches) { if (cache.containsKey(id)) { return true; } } return false; } @Override protected Object access(Id id) {<FILL_FUNCTION_BODY>} @Override protected boolean write(Id id, Object value, long timeOffset) { boolean success = false; for (AbstractCache<Id, Object> cache : this.caches) { success |= cache.write(id, value, timeOffset); } return success; } @Override protected void remove(Id id) { for (AbstractCache<Id, Object> cache : this.caches) { cache.remove(id); } } @Override protected Iterator<CacheNode<Id, Object>> nodes() { ExtendableIterator<CacheNode<Id, Object>> iters; iters = new ExtendableIterator<>(); for (AbstractCache<Id, Object> cache : this.caches) { iters.extend(cache.nodes()); } return iters; } protected AbstractCache<Id, Object> last() { final int length = this.caches.length; E.checkState(length > 0, "Expect at least one cache in LevelCache, but got %s", length); return this.caches[length - 1]; } }
for (AbstractCache<Id, Object> cache : this.caches) { // Priority access to the previous level Object value = cache.access(id); if (value != null) { return value; } } return null;
674
69
743
<methods>public void <init>() ,public void <init>(long) ,public T attachment(T) ,public T attachment() ,public final long capacity() ,public boolean enableMetrics(boolean) ,public void expire(long) ,public final long expire() ,public java.lang.Object get(org.apache.hugegraph.backend.id.Id) ,public java.lang.Object getOrFetch(org.apache.hugegraph.backend.id.Id, Function<org.apache.hugegraph.backend.id.Id,java.lang.Object>) ,public final long hits() ,public void invalidate(org.apache.hugegraph.backend.id.Id) ,public final long miss() ,public long tick() ,public boolean update(org.apache.hugegraph.backend.id.Id, java.lang.Object) ,public boolean update(org.apache.hugegraph.backend.id.Id, java.lang.Object, long) ,public boolean updateIfAbsent(org.apache.hugegraph.backend.id.Id, java.lang.Object) ,public boolean updateIfPresent(org.apache.hugegraph.backend.id.Id, java.lang.Object) <variables>public static final int DEFAULT_SIZE,protected static final Logger LOG,public static final int MAX_INIT_CAP,public static final int MB,private final non-sealed AtomicReference<java.lang.Object> attachment,private final non-sealed long capacity,private volatile boolean enabledMetrics,private volatile long expire,private final non-sealed java.util.concurrent.atomic.LongAdder hits,private final non-sealed java.util.concurrent.atomic.LongAdder miss
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/id/IdGenerator.java
UuidId
fromBytes
class UuidId implements Id { private final UUID uuid; public UuidId(String string) { this(StringEncoding.uuid(string)); } public UuidId(byte[] bytes) { this(fromBytes(bytes)); } public UuidId(UUID uuid) { E.checkArgument(uuid != null, "The uuid can't be null"); this.uuid = uuid; } @Override public IdType type() { return IdType.UUID; } @Override public Object asObject() { return this.uuid; } @Override public String asString() { return this.uuid.toString(); } @Override public long asLong() { throw new UnsupportedOperationException(); } @Override public byte[] asBytes() { BytesBuffer buffer = BytesBuffer.allocate(16); buffer.writeLong(this.uuid.getMostSignificantBits()); buffer.writeLong(this.uuid.getLeastSignificantBits()); return buffer.bytes(); } private static UUID fromBytes(byte[] bytes) {<FILL_FUNCTION_BODY>} @Override public int length() { return UUID_LENGTH; } @Override public int compareTo(Id other) { E.checkNotNull(other, "compare id"); int cmp = compareType(this, other); if (cmp != 0) { return cmp; } return this.uuid.compareTo(((UuidId) other).uuid); } @Override public int hashCode() { return this.uuid.hashCode(); } @Override public boolean equals(Object other) { if (!(other instanceof UuidId)) { return false; } return this.uuid.equals(((UuidId) other).uuid); } @Override public String toString() { return this.uuid.toString(); } }
E.checkArgument(bytes != null, "The UUID can't be null"); BytesBuffer buffer = BytesBuffer.wrap(bytes); long high = buffer.readLong(); long low = buffer.readLong(); return new UUID(high, low);
533
69
602
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/id/IdUtil.java
IdUtil
unescape
class IdUtil { public static String writeStoredString(Id id) { String idString; switch (id.type()) { case LONG: case STRING: case UUID: idString = IdGenerator.asStoredString(id); break; case EDGE: idString = EdgeId.asStoredString(id); break; default: throw new AssertionError("Invalid id type " + id.type()); } return id.type().prefix() + idString; } public static Id readStoredString(String id) { IdType type = IdType.valueOfPrefix(id); String idContent = id.substring(1); switch (type) { case LONG: case STRING: case UUID: return IdGenerator.ofStoredString(idContent, type); case EDGE: return EdgeId.parseStoredString(idContent); default: throw new IllegalArgumentException("Invalid id: " + id); } } public static Object writeBinString(Id id) { int len = id.edge() ? BytesBuffer.BUF_EDGE_ID : id.length() + 1; BytesBuffer buffer = BytesBuffer.allocate(len).writeId(id); buffer.forReadWritten(); return buffer.asByteBuffer(); } public static Id readBinString(Object id) { BytesBuffer buffer = BytesBuffer.wrap((ByteBuffer) id); return buffer.readId(); } public static String writeString(Id id) { String idString = id.asString(); return id.type().prefix() + idString; } public static Id readString(String id) { IdType type = IdType.valueOfPrefix(id); String idContent = id.substring(1); switch (type) { case LONG: return IdGenerator.of(Long.parseLong(idContent)); case STRING: case UUID: return IdGenerator.of(idContent, type == IdType.UUID); case EDGE: return EdgeId.parse(idContent); default: throw new IllegalArgumentException("Invalid id: " + id); } } public static String writeLong(Id id) { return String.valueOf(id.asLong()); } public static Id readLong(String id) { return IdGenerator.of(Long.parseLong(id)); } public static String escape(char splitor, char escape, String... values) { int length = values.length + 4; for (String value : values) { length += value.length(); } StringBuilder escaped = new StringBuilder(length); // Do escape for every item in values for (String value : values) { if (escaped.length() > 0) { escaped.append(splitor); } if (value.indexOf(splitor) == -1) { escaped.append(value); continue; } // Do escape for current item for (int i = 0, n = value.length(); i < n; i++) { char ch = value.charAt(i); if (ch == splitor) { escaped.append(escape); } escaped.append(ch); } } return escaped.toString(); } public static String[] unescape(String id, String splitor, String escape) {<FILL_FUNCTION_BODY>} }
/* * Note that the `splitter`/`escape` maybe special characters in regular * expressions, but this is a frequently called method, for faster * execution, we forbid the use of special characters as delimiter * or escape sign. * * The `limit` param -1 in split method can ensure empty string be * split to a part. */ String[] parts = id.split("(?<!" + escape + ")" + splitor, -1); for (int i = 0; i < parts.length; i++) { parts[i] = StringUtils.replace(parts[i], escape + splitor, splitor); } return parts;
898
176
1,074
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/id/SnowflakeIdGenerator.java
SnowflakeIdGenerator
instance
class SnowflakeIdGenerator extends IdGenerator { private static final Logger LOG = Log.logger(SnowflakeIdGenerator.class); private static final Map<String, SnowflakeIdGenerator> INSTANCES = new ConcurrentHashMap<>(); private final boolean forceString; private final IdWorker idWorker; public static SnowflakeIdGenerator init(HugeGraphParams graph) { String graphName = graph.name(); SnowflakeIdGenerator generator = INSTANCES.get(graphName); if (generator == null) { synchronized (INSTANCES) { if (!INSTANCES.containsKey(graphName)) { HugeConfig conf = graph.configuration(); INSTANCES.put(graphName, new SnowflakeIdGenerator(conf)); } generator = INSTANCES.get(graphName); assert generator != null; } } return generator; } public static SnowflakeIdGenerator instance(HugeGraph graph) {<FILL_FUNCTION_BODY>} private SnowflakeIdGenerator(HugeConfig config) { long workerId = config.get(CoreOptions.SNOWFLAKE_WORKER_ID); long datacenterId = config.get(CoreOptions.SNOWFLAKE_DATACENTER_ID); this.forceString = config.get(CoreOptions.SNOWFLAKE_FORCE_STRING); this.idWorker = new IdWorker(workerId, datacenterId); LOG.debug("SnowflakeId Worker started: datacenter id {}, " + "worker id {}, forced string id {}", datacenterId, workerId, this.forceString); } public Id generate() { if (this.idWorker == null) { throw new HugeException("Please initialize before using"); } Id id = of(this.idWorker.nextId()); if (!this.forceString) { return id; } else { return IdGenerator.of(id.asString()); } } @Override public Id generate(HugeVertex vertex) { return this.generate(); } private static class IdWorker { private final long workerId; private final long datacenterId; private long sequence = 0L; // AtomicLong private long lastTimestamp = -1L; private static final long WORKER_BIT = 5L; private static final long MAX_WORKER_ID = -1L ^ (-1L << WORKER_BIT); private static final long DC_BIT = 5L; private static final long MAX_DC_ID = -1L ^ (-1L << DC_BIT); private static final long SEQUENCE_BIT = 12L; private static final long SEQUENCE_MASK = -1L ^ (-1L << SEQUENCE_BIT); private static final long WORKER_SHIFT = SEQUENCE_BIT; private static final long DC_SHIFT = WORKER_SHIFT + WORKER_BIT; private static final long TIMESTAMP_SHIFT = DC_SHIFT + DC_BIT; public IdWorker(long workerId, long datacenterId) { // Sanity check for workerId if (workerId > MAX_WORKER_ID || workerId < 0) { throw new IllegalArgumentException(String.format( "Worker id can't > %d or < 0", MAX_WORKER_ID)); } if (datacenterId > MAX_DC_ID || datacenterId < 0) { throw new IllegalArgumentException(String.format( "Datacenter id can't > %d or < 0", MAX_DC_ID)); } this.workerId = workerId; this.datacenterId = datacenterId; LOG.debug("Id Worker starting. timestamp left shift {}," + "datacenter id bits {}, worker id bits {}," + "sequence bits {}", TIMESTAMP_SHIFT, DC_BIT, WORKER_BIT, SEQUENCE_BIT); } public synchronized long nextId() { long timestamp = TimeUtil.timeGen(); if (timestamp > this.lastTimestamp) { this.sequence = 0L; } else if (timestamp == this.lastTimestamp) { this.sequence = (this.sequence + 1) & SEQUENCE_MASK; if (this.sequence == 0) { timestamp = TimeUtil.tillNextMillis(this.lastTimestamp); } } else { LOG.error("Clock is moving backwards, " + "rejecting requests until {}.", this.lastTimestamp); throw new HugeException("Clock moved backwards. Refusing to " + "generate id for %d milliseconds", this.lastTimestamp - timestamp); } this.lastTimestamp = timestamp; return (timestamp << TIMESTAMP_SHIFT) | (this.datacenterId << DC_SHIFT) | (this.workerId << WORKER_SHIFT) | (this.sequence); } } }
String graphName = graph.name(); SnowflakeIdGenerator generator = INSTANCES.get(graphName); E.checkState(generator != null, "SnowflakeIdGenerator of graph '%s' is not initialized", graphName); return generator;
1,316
73
1,389
<methods>public non-sealed void <init>() ,public static java.lang.String asStoredString(org.apache.hugegraph.backend.id.Id) ,public abstract org.apache.hugegraph.backend.id.Id generate(org.apache.hugegraph.structure.HugeVertex) ,public static org.apache.hugegraph.backend.id.Id.IdType idType(org.apache.hugegraph.backend.id.Id) ,public static org.apache.hugegraph.backend.id.Id of(java.lang.String) ,public static org.apache.hugegraph.backend.id.Id of(java.util.UUID) ,public static org.apache.hugegraph.backend.id.Id of(java.lang.String, boolean) ,public static org.apache.hugegraph.backend.id.Id of(long) ,public static org.apache.hugegraph.backend.id.Id of(java.lang.Object) ,public static org.apache.hugegraph.backend.id.Id of(byte[], org.apache.hugegraph.backend.id.Id.IdType) ,public static org.apache.hugegraph.backend.id.Id ofStoredString(java.lang.String, org.apache.hugegraph.backend.id.Id.IdType) <variables>public static final org.apache.hugegraph.backend.id.Id ZERO
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/id/SplicingIdGenerator.java
SplicingIdGenerator
instance
class SplicingIdGenerator extends IdGenerator { private static volatile SplicingIdGenerator instance; public static SplicingIdGenerator instance() {<FILL_FUNCTION_BODY>} /* * The following defines can't be java regex special characters: * "\^$.|?*+()[{" * See: http://www.regular-expressions.info/characters.html */ private static final char ESCAPE = '`'; private static final char IDS_SPLITOR = '>'; private static final char ID_SPLITOR = ':'; private static final char NAME_SPLITOR = '!'; public static final String ESCAPE_STR = String.valueOf(ESCAPE); public static final String IDS_SPLITOR_STR = String.valueOf(IDS_SPLITOR); public static final String ID_SPLITOR_STR = String.valueOf(ID_SPLITOR); /****************************** id generate ******************************/ /** * Generate a string id of HugeVertex from Vertex name */ @Override public Id generate(HugeVertex vertex) { /* * Hash for row-key which will be evenly distributed. * We can also use LongEncoding.encode() to encode the int/long hash * if needed. * id = String.format("%s%s%s", HashUtil.hash(id), ID_SPLITOR, id); */ // TODO: use binary Id with binary fields instead of string id return splicing(vertex.schemaLabel().id().asString(), vertex.name()); } /** * Concat multiple ids into one composite id with IDS_SPLITOR * * @param ids the string id values to be concatted * @return concatted string value */ public static String concat(String... ids) { // NOTE: must support string id when using this method return IdUtil.escape(IDS_SPLITOR, ESCAPE, ids); } /** * Split a composite id into multiple ids with IDS_SPLITOR * * @param ids the string id value to be splitted * @return splitted string values */ public static String[] split(String ids) { return IdUtil.unescape(ids, IDS_SPLITOR_STR, ESCAPE_STR); } /** * Concat property values with NAME_SPLITOR * * @param values the property values to be concatted * @return concatted string value */ public static String concatValues(List<?> values) { // Convert the object list to string array int valuesSize = values.size(); String[] parts = new String[valuesSize]; for (int i = 0; i < valuesSize; i++) { parts[i] = values.get(i).toString(); } return IdUtil.escape(NAME_SPLITOR, ESCAPE, parts); } /** * Concat property values with NAME_SPLITOR * * @param values the property values to be concatted * @return concatted string value */ public static String concatValues(Object... values) { return concatValues(Arrays.asList(values)); } /** * Concat multiple parts into a single id with ID_SPLITOR * * @param parts the string id values to be spliced * @return spliced id object */ public static Id splicing(String... parts) { String escaped = IdUtil.escape(ID_SPLITOR, ESCAPE, parts); return IdGenerator.of(escaped); } /** * Parse a single id into multiple parts with ID_SPLITOR * * @param id the id object to be parsed * @return parsed string id parts */ public static String[] parse(Id id) { return IdUtil.unescape(id.asString(), ID_SPLITOR_STR, ESCAPE_STR); } }
if (instance == null) { synchronized (SplicingIdGenerator.class) { if (instance == null) { instance = new SplicingIdGenerator(); } } } return instance;
1,055
60
1,115
<methods>public non-sealed void <init>() ,public static java.lang.String asStoredString(org.apache.hugegraph.backend.id.Id) ,public abstract org.apache.hugegraph.backend.id.Id generate(org.apache.hugegraph.structure.HugeVertex) ,public static org.apache.hugegraph.backend.id.Id.IdType idType(org.apache.hugegraph.backend.id.Id) ,public static org.apache.hugegraph.backend.id.Id of(java.lang.String) ,public static org.apache.hugegraph.backend.id.Id of(java.util.UUID) ,public static org.apache.hugegraph.backend.id.Id of(java.lang.String, boolean) ,public static org.apache.hugegraph.backend.id.Id of(long) ,public static org.apache.hugegraph.backend.id.Id of(java.lang.Object) ,public static org.apache.hugegraph.backend.id.Id of(byte[], org.apache.hugegraph.backend.id.Id.IdType) ,public static org.apache.hugegraph.backend.id.Id ofStoredString(java.lang.String, org.apache.hugegraph.backend.id.Id.IdType) <variables>public static final org.apache.hugegraph.backend.id.Id ZERO
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/page/IdHolder.java
BatchIdHolder
fetchNext
class BatchIdHolder extends IdHolder implements CIter<IdHolder> { private final Iterator<BackendEntry> entries; private final Function<Long, Set<Id>> fetcher; private long count; private PageIds currentBatch; public BatchIdHolder(ConditionQuery query, Iterator<BackendEntry> entries, Function<Long, Set<Id>> fetcher) { super(query); this.entries = entries; this.fetcher = fetcher; this.count = 0L; this.currentBatch = null; } @Override public boolean paging() { return false; } @Override public boolean hasNext() { if (this.currentBatch != null) { return true; } if (this.exhausted) { return false; } boolean hasNext = this.entries.hasNext(); if (!hasNext) { this.close(); } return hasNext; } @Override public IdHolder next() { if (!hasNext()) { throw new NoSuchElementException(); } return this; } @Override public PageIds fetchNext(String page, long batchSize) {<FILL_FUNCTION_BODY>} @Override public Set<Id> all() { try { Set<Id> ids = this.fetcher.apply(this.remaining()); if (this.currentBatch != null) { ids.addAll(this.getFromCurrentBatch(Query.NO_LIMIT).ids()); } this.count += ids.size(); return ids; } finally { this.close(); } } public PageIds peekNext(long size) { E.checkArgument(this.currentBatch == null, "Can't call peekNext() twice"); this.currentBatch = this.fetchNext(null, size); return this.currentBatch; } private PageIds getFromCurrentBatch(long batchSize) { assert this.currentBatch != null; PageIds result = this.currentBatch; this.currentBatch = null; return result; } private long remaining() { if (this.query.noLimit()) { return Query.NO_LIMIT; } else { return this.query.total() - this.count; } } @Override public void close() { if (this.exhausted) { return; } this.exhausted = true; CloseableIterator.closeIterator(this.entries); } @Override public Object metadata(String meta, Object... args) { E.checkState(this.entries instanceof Metadatable, "Invalid iterator for Metadatable: %s", this.entries.getClass()); return ((Metadatable) this.entries).metadata(meta, args); } }
E.checkArgument(page == null, "Not support page parameter by BatchIdHolder"); E.checkArgument(batchSize >= 0L, "Invalid batch size value: %s", batchSize); if (this.currentBatch != null) { return this.getFromCurrentBatch(batchSize); } if (!this.query.noLimit()) { long remaining = this.remaining(); if (remaining < batchSize) { batchSize = remaining; } } assert batchSize >= 0L : batchSize; Set<Id> ids = this.fetcher.apply(batchSize); int size = ids.size(); this.count += size; if (size < batchSize || size == 0) { this.close(); } // If there is no data, the entries is not a Metadatable object if (size == 0) { return PageIds.EMPTY; } else { return new PageIds(ids, PageState.EMPTY); }
773
266
1,039
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/page/IdHolderList.java
IdHolderList
empty
class IdHolderList extends ArrayList<IdHolder> { private static final IdHolderList EMPTY_P = new IdHolderList(true); private static final IdHolderList EMPTY_NP = new IdHolderList(false); private static final long serialVersionUID = -738694176552424990L; private final boolean paging; public static IdHolderList empty(boolean paging) {<FILL_FUNCTION_BODY>} public IdHolderList(boolean paging) { this.paging = paging; } public boolean paging() { return this.paging; } @Override public boolean add(IdHolder holder) { E.checkArgument(this.paging == holder.paging(), "The IdHolder to be linked must be " + "in same paging mode"); return super.add(holder); } @Override public boolean addAll(Collection<? extends IdHolder> idHolders) { for (IdHolder idHolder : idHolders) { this.add(idHolder); } return true; } }
IdHolderList empty = paging ? EMPTY_P : EMPTY_NP; empty.clear(); return empty;
298
36
334
<methods>public void <init>() ,public void <init>(int) ,public void <init>(Collection<? extends org.apache.hugegraph.backend.page.IdHolder>) ,public boolean add(org.apache.hugegraph.backend.page.IdHolder) ,public void add(int, org.apache.hugegraph.backend.page.IdHolder) ,public boolean addAll(Collection<? extends org.apache.hugegraph.backend.page.IdHolder>) ,public boolean addAll(int, Collection<? extends org.apache.hugegraph.backend.page.IdHolder>) ,public void clear() ,public java.lang.Object clone() ,public boolean contains(java.lang.Object) ,public void ensureCapacity(int) ,public boolean equals(java.lang.Object) ,public void forEach(Consumer<? super org.apache.hugegraph.backend.page.IdHolder>) ,public org.apache.hugegraph.backend.page.IdHolder get(int) ,public int hashCode() ,public int indexOf(java.lang.Object) ,public boolean isEmpty() ,public Iterator<org.apache.hugegraph.backend.page.IdHolder> iterator() ,public int lastIndexOf(java.lang.Object) ,public ListIterator<org.apache.hugegraph.backend.page.IdHolder> listIterator() ,public ListIterator<org.apache.hugegraph.backend.page.IdHolder> listIterator(int) ,public org.apache.hugegraph.backend.page.IdHolder remove(int) ,public boolean remove(java.lang.Object) ,public boolean removeAll(Collection<?>) ,public boolean removeIf(Predicate<? super org.apache.hugegraph.backend.page.IdHolder>) ,public void replaceAll(UnaryOperator<org.apache.hugegraph.backend.page.IdHolder>) ,public boolean retainAll(Collection<?>) ,public org.apache.hugegraph.backend.page.IdHolder set(int, org.apache.hugegraph.backend.page.IdHolder) ,public int size() ,public void sort(Comparator<? super org.apache.hugegraph.backend.page.IdHolder>) ,public Spliterator<org.apache.hugegraph.backend.page.IdHolder> spliterator() ,public List<org.apache.hugegraph.backend.page.IdHolder> subList(int, int) ,public java.lang.Object[] toArray() ,public T[] toArray(T[]) ,public void trimToSize() <variables>private static final java.lang.Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA,private static final int DEFAULT_CAPACITY,private static final java.lang.Object[] EMPTY_ELEMENTDATA,transient java.lang.Object[] elementData,private static final long serialVersionUID,private int size
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/page/PageEntryIterator.java
PageEntryIterator
parsePageInfo
class PageEntryIterator<R> implements CIter<R> { private final QueryList<R> queries; private final long pageSize; private final PageInfo pageInfo; private final QueryResults<R> queryResults; // for upper layer private QueryList.PageResults<R> pageResults; private long remaining; public PageEntryIterator(QueryList<R> queries, long pageSize) { this.queries = queries; this.pageSize = pageSize; this.pageInfo = this.parsePageInfo(); this.queryResults = new QueryResults<>(this, queries.parent()); this.pageResults = QueryList.PageResults.emptyIterator(); this.remaining = queries.parent().limit(); } private PageInfo parsePageInfo() {<FILL_FUNCTION_BODY>} @Override public boolean hasNext() { if (this.pageResults.get().hasNext()) { return true; } return this.fetch(); } private boolean fetch() { if ((this.remaining != Query.NO_LIMIT && this.remaining <= 0L) || this.pageInfo.offset() >= this.queries.total()) { return false; } long pageSize = this.pageSize; if (this.remaining != Query.NO_LIMIT && this.remaining < pageSize) { pageSize = this.remaining; } this.closePageResults(); this.pageResults = this.queries.fetchNext(this.pageInfo, pageSize); assert this.pageResults != null; this.queryResults.setQuery(this.pageResults.query()); if (this.pageResults.get().hasNext()) { if (!this.pageResults.hasNextPage()) { this.pageInfo.increase(); } else { this.pageInfo.page(this.pageResults.page()); } this.remaining -= this.pageResults.total(); return true; } else { this.pageInfo.increase(); return this.fetch(); } } private void closePageResults() { if (this.pageResults != QueryList.PageResults.EMPTY) { CloseableIterator.closeIterator(this.pageResults.get()); } } @Override public R next() { if (!this.hasNext()) { throw new NoSuchElementException(); } return this.pageResults.get().next(); } @Override public Object metadata(String meta, Object... args) { if (PageInfo.PAGE.equals(meta)) { if (this.pageInfo.offset() >= this.queries.total()) { return null; } return this.pageInfo; } throw new NotSupportException("Invalid meta '%s'", meta); } @Override public void close() throws Exception { this.closePageResults(); } public QueryResults<R> results() { return this.queryResults; } }
String page = this.queries.parent().pageWithoutCheck(); PageInfo pageInfo = PageInfo.fromString(page); E.checkState(pageInfo.offset() < this.queries.total(), "Invalid page '%s' with an offset '%s' exceeds " + "the size of IdHolderList", page, pageInfo.offset()); return pageInfo;
779
94
873
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/page/PageIds.java
PageIds
page
class PageIds { public static final PageIds EMPTY = new PageIds(ImmutableSet.of(), PageState.EMPTY); private final Set<Id> ids; private final PageState pageState; public PageIds(Set<Id> ids, PageState pageState) { this.ids = ids; this.pageState = pageState; } public Set<Id> ids() { return this.ids; } public String page() {<FILL_FUNCTION_BODY>} public PageState pageState() { return this.pageState; } public boolean empty() { return this.ids.isEmpty(); } }
if (this.pageState == null) { return null; } return this.pageState.toString();
185
33
218
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/page/PageInfo.java
PageInfo
fromBytes
class PageInfo { public static final String PAGE = "page"; public static final String PAGE_NONE = ""; private int offset; private String page; public PageInfo(int offset, String page) { E.checkArgument(offset >= 0, "The offset must be >= 0"); E.checkNotNull(page, "page"); this.offset = offset; this.page = page; } public void increase() { this.offset++; this.page = PAGE_NONE; } public int offset() { return this.offset; } public void page(String page) { this.page = page; } public String page() { return this.page; } @Override public String toString() { return StringEncoding.encodeBase64(this.toBytes()); } public byte[] toBytes() { byte[] pageState = PageState.toBytes(this.page); int length = 2 + BytesBuffer.INT_LEN + pageState.length; BytesBuffer buffer = BytesBuffer.allocate(length); buffer.writeInt(this.offset); buffer.writeBytes(pageState); return buffer.bytes(); } public static PageInfo fromString(String page) { byte[] bytes; try { bytes = StringEncoding.decodeBase64(page); } catch (Exception e) { throw new HugeException("Invalid page: '%s'", e, page); } return fromBytes(bytes); } public static PageInfo fromBytes(byte[] bytes) {<FILL_FUNCTION_BODY>} public static PageState pageState(Iterator<?> iterator) { E.checkState(iterator instanceof Metadatable, "Invalid paging iterator: %s", iterator.getClass()); Object page = ((Metadatable) iterator).metadata(PAGE); E.checkState(page instanceof PageState, "Invalid PageState '%s'", page); return (PageState) page; } public static String pageInfo(Iterator<?> iterator) { E.checkState(iterator instanceof Metadatable, "Invalid paging iterator: %s", iterator.getClass()); Object page = ((Metadatable) iterator).metadata(PAGE); return page == null ? null : page.toString(); } }
if (bytes.length == 0) { // The first page return new PageInfo(0, PAGE_NONE); } try { BytesBuffer buffer = BytesBuffer.wrap(bytes); int offset = buffer.readInt(); byte[] pageState = buffer.readBytes(); String page = PageState.toString(pageState); return new PageInfo(offset, page); } catch (Exception e) { throw new HugeException("Invalid page: '0x%s'", e, Bytes.toHex(bytes)); }
617
146
763
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/page/PageState.java
PageState
fromString
class PageState { public static final byte[] EMPTY_BYTES = new byte[0]; public static final PageState EMPTY = new PageState(EMPTY_BYTES, 0, 0); public static final char SPACE = ' '; public static final char PLUS = '+'; private final byte[] position; private final int offset; private final int total; public PageState(byte[] position, int offset, int total) { E.checkNotNull(position, "position"); this.position = position; this.offset = offset; this.total = total; } public byte[] position() { return this.position; } public int offset() { return this.offset; } public long total() { return this.total; } @Override public String toString() { if (Bytes.equals(this.position(), EMPTY_BYTES)) { return null; } return toString(this.toBytes()); } private byte[] toBytes() { assert this.position.length > 0; int length = 2 + this.position.length + 2 * BytesBuffer.INT_LEN; BytesBuffer buffer = BytesBuffer.allocate(length); buffer.writeBytes(this.position); buffer.writeInt(this.offset); buffer.writeInt(this.total); return buffer.bytes(); } public static PageState fromString(String page) {<FILL_FUNCTION_BODY>} public static PageState fromBytes(byte[] bytes) { if (bytes.length == 0) { // The first page return EMPTY; } try { BytesBuffer buffer = BytesBuffer.wrap(bytes); return new PageState(buffer.readBytes(), buffer.readInt(), buffer.readInt()); } catch (Exception e) { throw new BackendException("Invalid page: '0x%s'", e, Bytes.toHex(bytes)); } } public static String toString(byte[] bytes) { return StringEncoding.encodeBase64(bytes); } public static byte[] toBytes(String page) { try { return StringEncoding.decodeBase64(page); } catch (Exception e) { throw new BackendException("Invalid page: '%s'", e, page); } } }
E.checkNotNull(page, "page"); /* * URLDecoder will auto decode '+' to space in url due to the request * of HTML4, so we choose to replace the space to '+' after getting it * More details refer to #1437 */ page = page.replace(SPACE, PLUS); return fromBytes(toBytes(page));
628
100
728
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/page/QueryList.java
IndexQuery
updateOffsetIfNeeded
class IndexQuery implements FlattenQuery<R> { // One IdHolder each sub-query private final IdHolderList holders; // Fetching ids size each time, default 100 private final long batchSize; public IndexQuery(IdHolderList holders, long batchSize) { this.holders = holders; this.batchSize = batchSize; } @Override public QueryResults<R> iterator() { // Iterate all if (this.holders.size() == 1) { return this.each(this.holders.get(0)); } return QueryResults.flatMap(this.holders.iterator(), this::each); } private QueryResults<R> each(IdHolder holder) { assert !holder.paging(); Query bindQuery = holder.query(); this.updateResultsFilter(bindQuery); this.updateOffsetIfNeeded(bindQuery); // Iterate by all if (holder instanceof FixedIdHolder) { // The search or joint index query may come here. Set<Id> ids = holder.all(); ids = bindQuery.skipOffsetIfNeeded(ids); if (ids.isEmpty()) { return null; } /* * Sort by input ids because search index results need to keep * in order by ids weight. In addition all the ids (IdQuery) * can be collected by upper layer. */ return this.queryByIndexIds(ids, holder.keepOrder()); } // Iterate by batch assert holder instanceof BatchIdHolder; return QueryResults.flatMap((BatchIdHolder) holder, h -> { assert ((BatchIdHolder) holder).hasNext(); long remaining = bindQuery.remaining(); assert remaining >= 0L || remaining == Query.NO_LIMIT; if (remaining > this.batchSize || remaining == Query.NO_LIMIT) { /* * Avoid too many ids in one time query, * Assume it will get one result by each id */ remaining = this.batchSize; } Set<Id> ids = h.fetchNext(null, remaining).ids(); ids = bindQuery.skipOffsetIfNeeded(ids); if (ids.isEmpty()) { return null; } return this.queryByIndexIds(ids); }); } @Override public PageResults<R> iterator(int index, String page, long pageSize) { // Iterate by paging E.checkArgument(0 <= index && index <= this.holders.size(), "Invalid page index %s", index); IdHolder holder = this.holders.get(index); Query bindQuery = holder.query(); this.updateResultsFilter(bindQuery); PageIds pageIds = holder.fetchNext(page, pageSize); if (pageIds.empty()) { return PageResults.emptyIterator(); } QueryResults<R> results = this.queryByIndexIds(pageIds.ids()); return new PageResults<>(results, pageIds.pageState()); } @Override public int total() { return this.holders.size(); } @Override public String toString() { return String.format("IndexQuery{%s}", this.holders); } private void updateOffsetIfNeeded(Query query) {<FILL_FUNCTION_BODY>} private void updateResultsFilter(Query query) { while (query != null) { if (query instanceof ConditionQuery) { ((ConditionQuery) query).updateResultsFilter(); return; } query = query.originQuery(); } } private QueryResults<R> queryByIndexIds(Set<Id> ids) { return this.queryByIndexIds(ids, false); } private QueryResults<R> queryByIndexIds(Set<Id> ids, boolean inOrder) { IdQuery query = new IdQuery(parent(), ids); query.mustSortByInput(inOrder); return fetcher().apply(query); } }
Query parent = parent(); assert parent instanceof ConditionQuery; OptimizedType optimized = ((ConditionQuery) parent).optimized(); if (optimized == OptimizedType.INDEX_FILTER) { return; } // Others sub-query may update parent offset, so copy to this query query.copyOffset(parent);
1,041
85
1,126
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/page/SortByCountIdHolderList.java
SortByCountIdHolderList
add
class SortByCountIdHolderList extends IdHolderList { private static final long serialVersionUID = -7779357582250824558L; private final List<IdHolder> mergedHolders; public SortByCountIdHolderList(boolean paging) { super(paging); this.mergedHolders = new ArrayList<>(); } @Override public boolean add(IdHolder holder) {<FILL_FUNCTION_BODY>} private class SortByCountIdHolder extends FixedIdHolder { private final Map<Id, Integer> ids; public SortByCountIdHolder(Query parent) { super(new MergedQuery(parent), ImmutableSet.of()); this.ids = InsertionOrderUtil.newMap(); } public void merge(IdHolder holder) { for (Id id : holder.all()) { this.ids.compute(id, (k, v) -> v == null ? 1 : v + 1); Query.checkForceCapacity(this.ids.size()); } } @Override public boolean keepOrder() { return true; } @Override public Set<Id> all() { return CollectionUtil.sortByValue(this.ids, false).keySet(); } @Override public String toString() { return String.format("%s{merged:%s}", this.getClass().getSimpleName(), this.query); } } private class MergedQuery extends Query { public MergedQuery(Query parent) { super(parent.resultType(), parent); } @Override public String toString() { return SortByCountIdHolderList.this.mergedHolders.toString(); } } }
if (this.paging()) { return super.add(holder); } this.mergedHolders.add(holder); if (super.isEmpty()) { Query parent = holder.query().originQuery(); super.add(new SortByCountIdHolder(parent)); } SortByCountIdHolder sortHolder = (SortByCountIdHolder) this.get(0); sortHolder.merge(holder); return true;
469
116
585
<methods>public void <init>(boolean) ,public boolean add(org.apache.hugegraph.backend.page.IdHolder) ,public boolean addAll(Collection<? extends org.apache.hugegraph.backend.page.IdHolder>) ,public static org.apache.hugegraph.backend.page.IdHolderList empty(boolean) ,public boolean paging() <variables>private static final org.apache.hugegraph.backend.page.IdHolderList EMPTY_NP,private static final org.apache.hugegraph.backend.page.IdHolderList EMPTY_P,private final non-sealed boolean paging,private static final long serialVersionUID
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/query/Aggregate.java
Aggregate
reduce
class Aggregate { private final AggregateFunc func; private final String column; public Aggregate(AggregateFunc func, String column) { this.func = func; this.column = column; } public AggregateFunc func() { return this.func; } public String column() { return this.column; } public boolean countAll() { return this.func == AggregateFunc.COUNT && this.column == null; } public Number reduce(Iterator<Number> results) { return this.func.reduce(results); } public Number defaultValue() { return this.func.defaultValue(); } @Override public String toString() { return String.format("%s(%s)", this.func.string(), this.column == null ? "*" : this.column); } public enum AggregateFunc { COUNT("count", 0L, NumberHelper::add), MAX("max", -Double.MAX_VALUE, NumberHelper::max), MIN("min", Double.MAX_VALUE, NumberHelper::min), AVG("avg", 0D, NumberHelper::add), SUM("sum", 0L, NumberHelper::add); private final String name; private final Number defaultValue; private final BiFunction<Number, Number, Number> merger; AggregateFunc(String name, Number defaultValue, BiFunction<Number, Number, Number> merger) { this.name = name; this.defaultValue = defaultValue; this.merger = merger; } public String string() { return this.name; } public Number defaultValue() { return this.defaultValue; } public Number reduce(Iterator<Number> results) {<FILL_FUNCTION_BODY>} } }
Number number; long count = 0L; if (results.hasNext()) { number = results.next(); count++; } else { return this.defaultValue; } while (results.hasNext()) { number = this.merger.apply(number, results.next()); count++; } if (this == AVG) { number = NumberHelper.div(number, count); } return number;
486
121
607
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/query/BatchConditionQuery.java
BatchConditionQuery
mergeToIN
class BatchConditionQuery extends ConditionQuery { private Condition.Relation in; private final int batchSize; public BatchConditionQuery(HugeType resultType, int batchSize) { super(resultType); this.in = null; this.batchSize = batchSize; } public void mergeToIN(ConditionQuery query, HugeKeys key) {<FILL_FUNCTION_BODY>} protected boolean sameQueryExceptKeyIN(ConditionQuery query) { List<Condition.Relation> relations = query.relations(); if (relations.size() != this.relations().size()) { return false; } for (Condition.Relation r : this.relations()) { if (r.relation() == RelationType.IN) { continue; } Object key = r.key(); if (!Objects.equals(this.condition(key), query.condition(key))) { return false; } } return true; } }
Object value = query.condition(key); if (this.in == null) { assert !this.containsRelation(RelationType.IN); this.resetConditions(InsertionOrderUtil.newList( (List<Condition>) query.conditions())); this.unsetCondition(key); List<Object> list = new ArrayList<>(this.batchSize); list.add(value); // TODO: ensure not flatten BatchQuery this.in = (Condition.Relation) Condition.in(key, list); this.query(this.in); } else { E.checkArgument(this.in.key().equals(key), "Invalid key '%s'", key); E.checkArgument(this.sameQueryExceptKeyIN(query), "Can't merge query with different keys"); @SuppressWarnings("unchecked") List<Object> values = ((List<Object>) this.in.value()); values.add(value); }
254
254
508
<methods>public void <init>(org.apache.hugegraph.type.HugeType) ,public void <init>(org.apache.hugegraph.type.HugeType, org.apache.hugegraph.backend.query.Query) ,public boolean allRelation() ,public boolean allSysprop() ,public void checkFlattened() ,public static java.lang.String concatValues(List<?>) ,public static java.lang.String concatValues(java.lang.Object) ,public T condition(java.lang.Object) ,public Collection<org.apache.hugegraph.backend.query.Condition> conditions() ,public int conditionsSize() ,public boolean containsCondition(org.apache.hugegraph.type.define.HugeKeys) ,public boolean containsContainsCondition(org.apache.hugegraph.backend.id.Id) ,public boolean containsRelation(org.apache.hugegraph.type.define.HugeKeys, org.apache.hugegraph.backend.query.Condition.RelationType) ,public boolean containsRelation(org.apache.hugegraph.backend.query.Condition.RelationType) ,public boolean containsScanRelation() ,public org.apache.hugegraph.backend.query.ConditionQuery copy() ,public org.apache.hugegraph.backend.query.ConditionQuery copyAndResetUnshared() ,public org.apache.hugegraph.backend.query.Condition.Relation copyRelationAndUpdateQuery(java.lang.Object) ,public org.apache.hugegraph.backend.query.ConditionQuery eq(org.apache.hugegraph.type.define.HugeKeys, java.lang.Object) ,public boolean existLeftIndex(org.apache.hugegraph.backend.id.Id) ,public Set<org.apache.hugegraph.backend.query.ConditionQuery.LeftIndex> getLeftIndexOfElement(org.apache.hugegraph.backend.id.Id) ,public org.apache.hugegraph.backend.query.ConditionQuery gt(org.apache.hugegraph.type.define.HugeKeys, java.lang.Object) ,public org.apache.hugegraph.backend.query.ConditionQuery gte(org.apache.hugegraph.type.define.HugeKeys, java.lang.Object) ,public boolean hasNeqCondition() ,public boolean hasRangeCondition() ,public boolean hasSearchCondition() ,public boolean hasSecondaryCondition() ,public boolean isFlattened() ,public org.apache.hugegraph.backend.query.ConditionQuery key(org.apache.hugegraph.type.define.HugeKeys, java.lang.Object) ,public org.apache.hugegraph.backend.query.ConditionQuery lt(org.apache.hugegraph.type.define.HugeKeys, java.lang.Object) ,public org.apache.hugegraph.backend.query.ConditionQuery lte(org.apache.hugegraph.type.define.HugeKeys, java.lang.Object) ,public boolean matchUserpropKeys(List<org.apache.hugegraph.backend.id.Id>) ,public boolean mayHasDupKeys(Set<org.apache.hugegraph.type.define.HugeKeys>) ,public org.apache.hugegraph.backend.query.ConditionQuery neq(org.apache.hugegraph.type.define.HugeKeys, java.lang.Object) ,public void optimized(org.apache.hugegraph.backend.query.ConditionQuery.OptimizedType) ,public org.apache.hugegraph.backend.query.ConditionQuery.OptimizedType optimized() ,public org.apache.hugegraph.backend.query.ConditionQuery originConditionQuery() ,public org.apache.hugegraph.backend.query.ConditionQuery prefix(org.apache.hugegraph.type.define.HugeKeys, org.apache.hugegraph.backend.id.Id) ,public org.apache.hugegraph.backend.query.ConditionQuery query(org.apache.hugegraph.backend.query.Condition) ,public org.apache.hugegraph.backend.query.ConditionQuery query(List<org.apache.hugegraph.backend.query.Condition>) ,public void recordIndexValue(org.apache.hugegraph.backend.id.Id, org.apache.hugegraph.backend.id.Id, java.lang.Object) ,public void registerResultsFilter(org.apache.hugegraph.backend.query.ConditionQuery.ResultsFilter) ,public org.apache.hugegraph.backend.query.Condition.Relation relation(org.apache.hugegraph.backend.id.Id) ,public List<org.apache.hugegraph.backend.query.Condition.Relation> relations() ,public void removeElementLeftIndex(org.apache.hugegraph.backend.id.Id) ,public void resetConditions(List<org.apache.hugegraph.backend.query.Condition>) ,public void resetConditions() ,public void resetUserpropConditions() ,public org.apache.hugegraph.backend.query.ConditionQuery scan(java.lang.String, java.lang.String) ,public void selectedIndexField(org.apache.hugegraph.backend.id.Id) ,public List<org.apache.hugegraph.backend.query.Condition> syspropConditions() ,public List<org.apache.hugegraph.backend.query.Condition> syspropConditions(org.apache.hugegraph.type.define.HugeKeys) ,public boolean test(org.apache.hugegraph.structure.HugeElement) ,public void unsetCondition(java.lang.Object) ,public void updateResultsFilter() ,public List<org.apache.hugegraph.backend.query.Condition> userpropConditions() ,public List<org.apache.hugegraph.backend.query.Condition> userpropConditions(org.apache.hugegraph.backend.id.Id) ,public Set<org.apache.hugegraph.backend.id.Id> userpropKeys() ,public List<org.apache.hugegraph.backend.query.Condition.Relation> userpropRelations() ,public java.lang.Object userpropValue(org.apache.hugegraph.backend.id.Id) ,public Set<java.lang.Object> userpropValues(org.apache.hugegraph.backend.id.Id) ,public java.lang.String userpropValuesString(List<org.apache.hugegraph.backend.id.Id>) <variables>private static final List<org.apache.hugegraph.backend.query.Condition> EMPTY_CONDITIONS,public static final non-sealed Set<java.lang.String> IGNORE_SYM_SET,public static final java.lang.String INDEX_SYM_EMPTY,public static final java.lang.String INDEX_SYM_ENDING,public static final char INDEX_SYM_MAX,public static final char INDEX_SYM_MIN,public static final java.lang.String INDEX_SYM_NULL,public static final java.lang.String INDEX_VALUE_EMPTY,public static final java.lang.String INDEX_VALUE_NULL,private List<org.apache.hugegraph.backend.query.Condition> conditions,private org.apache.hugegraph.backend.query.ConditionQuery.Element2IndexValueMap element2IndexValueMap,private org.apache.hugegraph.backend.query.ConditionQuery.OptimizedType optimizedType,private org.apache.hugegraph.backend.query.ConditionQuery.ResultsFilter resultsFilter
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/query/Condition.java
BinCondition
toString
class BinCondition extends Condition { private Condition left; private Condition right; public BinCondition(Condition left, Condition right) { E.checkNotNull(left, "left condition"); E.checkNotNull(right, "right condition"); this.left = left; this.right = right; } public Condition left() { return this.left; } public Condition right() { return this.right; } @Override public boolean isSysprop() { return this.left.isSysprop() && this.right.isSysprop(); } @Override public List<? extends Relation> relations() { List<Relation> list = new ArrayList<>(this.left.relations()); list.addAll(this.right.relations()); return list; } @Override public Condition replace(Relation from, Relation to) { this.left = this.left.replace(from, to); this.right = this.right.replace(from, to); return this; } @Override public String toString() {<FILL_FUNCTION_BODY>} @Override public boolean equals(Object object) { if (!(object instanceof BinCondition)) { return false; } BinCondition other = (BinCondition) object; return this.type().equals(other.type()) && this.left().equals(other.left()) && this.right().equals(other.right()); } @Override public int hashCode() { return this.type().hashCode() ^ this.left().hashCode() ^ this.right().hashCode(); } }
StringBuilder sb = new StringBuilder(64); sb.append(this.left).append(' '); sb.append(this.type().name()).append(' '); sb.append(this.right); return sb.toString();
440
63
503
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/query/EdgesQueryIterator.java
EdgesQueryIterator
next
class EdgesQueryIterator implements Iterator<Query> { private final List<Id> labels; private final Directions directions; private final long limit; private final Iterator<Id> sources; public EdgesQueryIterator(Iterator<Id> sources, Directions directions, List<Id> labels, long limit) { this.sources = sources; this.labels = labels; this.directions = directions; // Traverse NO_LIMIT 和 Query.NO_LIMIT 不同 this.limit = limit < 0 ? Query.NO_LIMIT : limit; } @Override public boolean hasNext() { return sources.hasNext(); } @Override public Query next() {<FILL_FUNCTION_BODY>} }
Id sourceId = this.sources.next(); ConditionQuery query = GraphTransaction.constructEdgesQuery(sourceId, this.directions, this.labels); if (this.limit != Query.NO_LIMIT) { query.limit(this.limit); query.capacity(this.limit); } else { query.capacity(Query.NO_CAPACITY); } return query;
204
114
318
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/query/IdPrefixQuery.java
IdPrefixQuery
toString
class IdPrefixQuery extends Query { private final Id start; private final boolean inclusiveStart; private final Id prefix; public IdPrefixQuery(HugeType resultType, Id prefix) { this(resultType, null, prefix, true, prefix); } public IdPrefixQuery(Query originQuery, Id prefix) { this(originQuery.resultType(), originQuery, prefix, true, prefix); } public IdPrefixQuery(Query originQuery, Id start, Id prefix) { this(originQuery.resultType(), originQuery, start, true, prefix); } public IdPrefixQuery(Query originQuery, Id start, boolean inclusive, Id prefix) { this(originQuery.resultType(), originQuery, start, inclusive, prefix); } public IdPrefixQuery(HugeType resultType, Query originQuery, Id start, boolean inclusive, Id prefix) { super(resultType, originQuery); E.checkArgumentNotNull(start, "The start parameter can't be null"); this.start = start; this.inclusiveStart = inclusive; this.prefix = prefix; if (originQuery != null) { this.copyBasic(originQuery); } } public Id start() { return this.start; } public boolean inclusiveStart() { return this.inclusiveStart; } public Id prefix() { return this.prefix; } @Override public boolean empty() { return false; } @Override public boolean test(HugeElement element) { byte[] elem = element.id().asBytes(); int cmp = Bytes.compare(elem, this.start.asBytes()); boolean matchedStart = this.inclusiveStart ? cmp >= 0 : cmp > 0; boolean matchedPrefix = Bytes.prefixWith(elem, this.prefix.asBytes()); return matchedStart && matchedPrefix; } @Override public IdPrefixQuery copy() { return (IdPrefixQuery) super.copy(); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
StringBuilder sb = new StringBuilder(super.toString()); assert sb.length() > 0; sb.deleteCharAt(sb.length() - 1); // Remove the last "`" sb.append(" id prefix with ").append(this.prefix); if (this.start != this.prefix) { sb.append(" and start with ").append(this.start) .append("(") .append(this.inclusiveStart ? "inclusive" : "exclusive") .append(")"); } sb.append("`"); return sb.toString();
543
150
693
<methods>public void <init>(org.apache.hugegraph.type.HugeType) ,public void <init>(org.apache.hugegraph.type.HugeType, org.apache.hugegraph.backend.query.Query) ,public long actualOffset() ,public org.apache.hugegraph.backend.query.Aggregate aggregate() ,public void aggregate(org.apache.hugegraph.backend.query.Aggregate.AggregateFunc, java.lang.String) ,public void aggregate(org.apache.hugegraph.backend.query.Aggregate) ,public org.apache.hugegraph.backend.query.Aggregate aggregateNotNull() ,public boolean bigCapacity() ,public long capacity() ,public void capacity(long) ,public void checkCapacity(long) throws org.apache.hugegraph.exception.LimitExceedException,public static void checkForceCapacity(long) throws org.apache.hugegraph.exception.LimitExceedException,public Collection<org.apache.hugegraph.backend.query.Condition> conditions() ,public int conditionsSize() ,public org.apache.hugegraph.backend.query.Query copy() ,public void copyBasic(org.apache.hugegraph.backend.query.Query) ,public void copyOffset(org.apache.hugegraph.backend.query.Query) ,public static long defaultCapacity(long) ,public static long defaultCapacity() ,public boolean empty() ,public boolean equals(java.lang.Object) ,public long goOffset(long) ,public int hashCode() ,public Collection<org.apache.hugegraph.backend.id.Id> ids() ,public int idsSize() ,public long limit() ,public void limit(long) ,public boolean noLimit() ,public boolean noLimitAndOffset() ,public long offset() ,public void offset(long) ,public void olap(boolean) ,public boolean olap() ,public void olapPk(org.apache.hugegraph.backend.id.Id) ,public void olapPks(Set<org.apache.hugegraph.backend.id.Id>) ,public Set<org.apache.hugegraph.backend.id.Id> olapPks() ,public void order(org.apache.hugegraph.type.define.HugeKeys, org.apache.hugegraph.backend.query.Query.Order) ,public Map<org.apache.hugegraph.type.define.HugeKeys,org.apache.hugegraph.backend.query.Query.Order> orders() ,public void orders(Map<org.apache.hugegraph.type.define.HugeKeys,org.apache.hugegraph.backend.query.Query.Order>) ,public org.apache.hugegraph.backend.query.Query originQuery() ,public java.lang.String page() ,public void page(java.lang.String) ,public java.lang.String pageWithoutCheck() ,public boolean paging() ,public long range(long, long) ,public boolean reachLimit(long) ,public long remaining() ,public void resetActualOffset() ,public org.apache.hugegraph.type.HugeType resultType() ,public void resultType(org.apache.hugegraph.type.HugeType) ,public org.apache.hugegraph.backend.query.Query rootOriginQuery() ,public boolean showDeleting() ,public void showDeleting(boolean) ,public boolean showExpired() ,public void showExpired(boolean) ,public boolean showHidden() ,public void showHidden(boolean) ,public Set<T> skipOffsetIfNeeded(Set<T>) ,public boolean test(org.apache.hugegraph.structure.HugeElement) ,public java.lang.String toString() ,public long total() <variables>private static final ThreadLocal<java.lang.Long> CAPACITY_CONTEXT,public static final long COMMIT_BATCH,public static final long DEFAULT_CAPACITY,private static final Set<org.apache.hugegraph.backend.id.Id> EMPTY_OLAP_PKS,protected static final org.apache.hugegraph.backend.query.Query NONE,public static final long NO_CAPACITY,public static final long NO_LIMIT,public static final long QUERY_BATCH,private long actualOffset,private long actualStoreOffset,private org.apache.hugegraph.backend.query.Aggregate aggregate,private long capacity,private long limit,private long offset,private boolean olap,private Set<org.apache.hugegraph.backend.id.Id> olapPks,private Map<org.apache.hugegraph.type.define.HugeKeys,org.apache.hugegraph.backend.query.Query.Order> orders,private org.apache.hugegraph.backend.query.Query originQuery,private java.lang.String page,private org.apache.hugegraph.type.HugeType resultType,private boolean showDeleting,private boolean showExpired,private boolean showHidden
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/query/IdQuery.java
OneIdQuery
query
class OneIdQuery extends IdQuery { private Id id; public OneIdQuery(HugeType resultType, Id id) { super(resultType); super.mustSortByInput = false; this.id = id; } public OneIdQuery(Query originQuery, Id id) { super(originQuery.resultType(), originQuery); super.mustSortByInput = false; this.id = id; } public Id id() { return this.id; } public void resetId(Id id) { this.id = id; } @Override public int idsSize() { return this.id == null ? 0 : 1; } @Override public Set<Id> ids() { return this.id == null ? ImmutableSet.of() : ImmutableSet.of(this.id); } @Override public void resetIds() { this.id = null; } @Override public IdQuery query(Id id) {<FILL_FUNCTION_BODY>} @Override public boolean test(HugeElement element) { if (this.id == null) { return true; } return this.id.equals(element.id()); } @Override public IdQuery copy() { OneIdQuery query = (OneIdQuery) super.copy(); assert this.id.equals(query.id); return query; } }
E.checkArgumentNotNull(id, "Query id can't be null"); this.id = id; return this;
391
35
426
<methods>public void <init>(org.apache.hugegraph.type.HugeType) ,public void <init>(org.apache.hugegraph.type.HugeType, org.apache.hugegraph.backend.query.Query) ,public long actualOffset() ,public org.apache.hugegraph.backend.query.Aggregate aggregate() ,public void aggregate(org.apache.hugegraph.backend.query.Aggregate.AggregateFunc, java.lang.String) ,public void aggregate(org.apache.hugegraph.backend.query.Aggregate) ,public org.apache.hugegraph.backend.query.Aggregate aggregateNotNull() ,public boolean bigCapacity() ,public long capacity() ,public void capacity(long) ,public void checkCapacity(long) throws org.apache.hugegraph.exception.LimitExceedException,public static void checkForceCapacity(long) throws org.apache.hugegraph.exception.LimitExceedException,public Collection<org.apache.hugegraph.backend.query.Condition> conditions() ,public int conditionsSize() ,public org.apache.hugegraph.backend.query.Query copy() ,public void copyBasic(org.apache.hugegraph.backend.query.Query) ,public void copyOffset(org.apache.hugegraph.backend.query.Query) ,public static long defaultCapacity(long) ,public static long defaultCapacity() ,public boolean empty() ,public boolean equals(java.lang.Object) ,public long goOffset(long) ,public int hashCode() ,public Collection<org.apache.hugegraph.backend.id.Id> ids() ,public int idsSize() ,public long limit() ,public void limit(long) ,public boolean noLimit() ,public boolean noLimitAndOffset() ,public long offset() ,public void offset(long) ,public void olap(boolean) ,public boolean olap() ,public void olapPk(org.apache.hugegraph.backend.id.Id) ,public void olapPks(Set<org.apache.hugegraph.backend.id.Id>) ,public Set<org.apache.hugegraph.backend.id.Id> olapPks() ,public void order(org.apache.hugegraph.type.define.HugeKeys, org.apache.hugegraph.backend.query.Query.Order) ,public Map<org.apache.hugegraph.type.define.HugeKeys,org.apache.hugegraph.backend.query.Query.Order> orders() ,public void orders(Map<org.apache.hugegraph.type.define.HugeKeys,org.apache.hugegraph.backend.query.Query.Order>) ,public org.apache.hugegraph.backend.query.Query originQuery() ,public java.lang.String page() ,public void page(java.lang.String) ,public java.lang.String pageWithoutCheck() ,public boolean paging() ,public long range(long, long) ,public boolean reachLimit(long) ,public long remaining() ,public void resetActualOffset() ,public org.apache.hugegraph.type.HugeType resultType() ,public void resultType(org.apache.hugegraph.type.HugeType) ,public org.apache.hugegraph.backend.query.Query rootOriginQuery() ,public boolean showDeleting() ,public void showDeleting(boolean) ,public boolean showExpired() ,public void showExpired(boolean) ,public boolean showHidden() ,public void showHidden(boolean) ,public Set<T> skipOffsetIfNeeded(Set<T>) ,public boolean test(org.apache.hugegraph.structure.HugeElement) ,public java.lang.String toString() ,public long total() <variables>private static final ThreadLocal<java.lang.Long> CAPACITY_CONTEXT,public static final long COMMIT_BATCH,public static final long DEFAULT_CAPACITY,private static final Set<org.apache.hugegraph.backend.id.Id> EMPTY_OLAP_PKS,protected static final org.apache.hugegraph.backend.query.Query NONE,public static final long NO_CAPACITY,public static final long NO_LIMIT,public static final long QUERY_BATCH,private long actualOffset,private long actualStoreOffset,private org.apache.hugegraph.backend.query.Aggregate aggregate,private long capacity,private long limit,private long offset,private boolean olap,private Set<org.apache.hugegraph.backend.id.Id> olapPks,private Map<org.apache.hugegraph.type.define.HugeKeys,org.apache.hugegraph.backend.query.Query.Order> orders,private org.apache.hugegraph.backend.query.Query originQuery,private java.lang.String page,private org.apache.hugegraph.type.HugeType resultType,private boolean showDeleting,private boolean showExpired,private boolean showHidden
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/query/IdRangeQuery.java
IdRangeQuery
toString
class IdRangeQuery extends Query { private final Id start; private final Id end; private final boolean inclusiveStart; private final boolean inclusiveEnd; public IdRangeQuery(HugeType resultType, Id start, Id end) { this(resultType, null, start, end); } public IdRangeQuery(HugeType resultType, Query originQuery, Id start, Id end) { this(resultType, originQuery, start, true, end, false); } public IdRangeQuery(Query originQuery, Id start, boolean inclusiveStart, Id end, boolean inclusiveEnd) { this(originQuery.resultType(), originQuery, start, inclusiveStart, end, inclusiveEnd); } public IdRangeQuery(HugeType resultType, Query originQuery, Id start, boolean inclusiveStart, Id end, boolean inclusiveEnd) { super(resultType, originQuery); E.checkArgumentNotNull(start, "The start parameter can't be null"); this.start = start; this.end = end; this.inclusiveStart = inclusiveStart; this.inclusiveEnd = inclusiveEnd; if (originQuery != null) { this.copyBasic(originQuery); } } public Id start() { return this.start; } public Id end() { return this.end; } public boolean inclusiveStart() { return this.inclusiveStart; } public boolean inclusiveEnd() { return this.inclusiveEnd; } @Override public boolean empty() { return false; } @Override public boolean test(HugeElement element) { int cmp1 = Bytes.compare(element.id().asBytes(), this.start.asBytes()); int cmp2 = Bytes.compare(element.id().asBytes(), this.end.asBytes()); return (this.inclusiveStart ? cmp1 >= 0 : cmp1 > 0) && (this.inclusiveEnd ? cmp2 <= 0 : cmp2 < 0); } @Override public IdRangeQuery copy() { return (IdRangeQuery) super.copy(); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
StringBuilder builder = new StringBuilder(super.toString()); assert builder.length() > 0; builder.deleteCharAt(builder.length() - 1); // Remove the last "`" builder.append(" id in range ") .append(this.inclusiveStart ? "[" : "(") .append(this.start) .append(", ") .append(this.end) .append(this.inclusiveEnd ? "]" : ")") .append("`"); return builder.toString();
585
132
717
<methods>public void <init>(org.apache.hugegraph.type.HugeType) ,public void <init>(org.apache.hugegraph.type.HugeType, org.apache.hugegraph.backend.query.Query) ,public long actualOffset() ,public org.apache.hugegraph.backend.query.Aggregate aggregate() ,public void aggregate(org.apache.hugegraph.backend.query.Aggregate.AggregateFunc, java.lang.String) ,public void aggregate(org.apache.hugegraph.backend.query.Aggregate) ,public org.apache.hugegraph.backend.query.Aggregate aggregateNotNull() ,public boolean bigCapacity() ,public long capacity() ,public void capacity(long) ,public void checkCapacity(long) throws org.apache.hugegraph.exception.LimitExceedException,public static void checkForceCapacity(long) throws org.apache.hugegraph.exception.LimitExceedException,public Collection<org.apache.hugegraph.backend.query.Condition> conditions() ,public int conditionsSize() ,public org.apache.hugegraph.backend.query.Query copy() ,public void copyBasic(org.apache.hugegraph.backend.query.Query) ,public void copyOffset(org.apache.hugegraph.backend.query.Query) ,public static long defaultCapacity(long) ,public static long defaultCapacity() ,public boolean empty() ,public boolean equals(java.lang.Object) ,public long goOffset(long) ,public int hashCode() ,public Collection<org.apache.hugegraph.backend.id.Id> ids() ,public int idsSize() ,public long limit() ,public void limit(long) ,public boolean noLimit() ,public boolean noLimitAndOffset() ,public long offset() ,public void offset(long) ,public void olap(boolean) ,public boolean olap() ,public void olapPk(org.apache.hugegraph.backend.id.Id) ,public void olapPks(Set<org.apache.hugegraph.backend.id.Id>) ,public Set<org.apache.hugegraph.backend.id.Id> olapPks() ,public void order(org.apache.hugegraph.type.define.HugeKeys, org.apache.hugegraph.backend.query.Query.Order) ,public Map<org.apache.hugegraph.type.define.HugeKeys,org.apache.hugegraph.backend.query.Query.Order> orders() ,public void orders(Map<org.apache.hugegraph.type.define.HugeKeys,org.apache.hugegraph.backend.query.Query.Order>) ,public org.apache.hugegraph.backend.query.Query originQuery() ,public java.lang.String page() ,public void page(java.lang.String) ,public java.lang.String pageWithoutCheck() ,public boolean paging() ,public long range(long, long) ,public boolean reachLimit(long) ,public long remaining() ,public void resetActualOffset() ,public org.apache.hugegraph.type.HugeType resultType() ,public void resultType(org.apache.hugegraph.type.HugeType) ,public org.apache.hugegraph.backend.query.Query rootOriginQuery() ,public boolean showDeleting() ,public void showDeleting(boolean) ,public boolean showExpired() ,public void showExpired(boolean) ,public boolean showHidden() ,public void showHidden(boolean) ,public Set<T> skipOffsetIfNeeded(Set<T>) ,public boolean test(org.apache.hugegraph.structure.HugeElement) ,public java.lang.String toString() ,public long total() <variables>private static final ThreadLocal<java.lang.Long> CAPACITY_CONTEXT,public static final long COMMIT_BATCH,public static final long DEFAULT_CAPACITY,private static final Set<org.apache.hugegraph.backend.id.Id> EMPTY_OLAP_PKS,protected static final org.apache.hugegraph.backend.query.Query NONE,public static final long NO_CAPACITY,public static final long NO_LIMIT,public static final long QUERY_BATCH,private long actualOffset,private long actualStoreOffset,private org.apache.hugegraph.backend.query.Aggregate aggregate,private long capacity,private long limit,private long offset,private boolean olap,private Set<org.apache.hugegraph.backend.id.Id> olapPks,private Map<org.apache.hugegraph.type.define.HugeKeys,org.apache.hugegraph.backend.query.Query.Order> orders,private org.apache.hugegraph.backend.query.Query originQuery,private java.lang.String page,private org.apache.hugegraph.type.HugeType resultType,private boolean showDeleting,private boolean showExpired,private boolean showHidden
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/serializer/AbstractSerializer.java
AbstractSerializer
writeQuery
class AbstractSerializer implements GraphSerializer, SchemaSerializer { protected HugeConfig config; public AbstractSerializer() { // TODO: default constructor } public AbstractSerializer(HugeConfig config) { this.config = config; } protected BackendEntry convertEntry(BackendEntry entry) { return entry; } protected abstract BackendEntry newBackendEntry(HugeType type, Id id); protected abstract Id writeQueryId(HugeType type, Id id); protected abstract Query writeQueryEdgeCondition(Query query); protected abstract Query writeQueryCondition(Query query); @Override public Query writeQuery(Query query) {<FILL_FUNCTION_BODY>} }
HugeType type = query.resultType(); // Serialize edge condition query (TODO: add VEQ(for EOUT/EIN)) if (type.isEdge() && query.conditionsSize() > 0) { if (query.idsSize() > 0) { throw new BackendException("Not supported query edge by id " + "and by condition at the same time"); } Query result = this.writeQueryEdgeCondition(query); if (result != null) { return result; } } // Serialize id in query if (query.idsSize() == 1 && query instanceof IdQuery.OneIdQuery) { IdQuery.OneIdQuery result = (IdQuery.OneIdQuery) query.copy(); result.resetId(this.writeQueryId(type, result.id())); query = result; } else if (query.idsSize() > 0 && query instanceof IdQuery) { IdQuery result = (IdQuery) query.copy(); result.resetIds(); for (Id id : query.ids()) { result.query(this.writeQueryId(type, id)); } query = result; } // Serialize condition(key/value) in query if (query instanceof ConditionQuery && query.conditionsSize() > 0) { query = this.writeQueryCondition(query); } return query;
185
350
535
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/serializer/BinaryBackendEntry.java
BinaryId
asBytes
class BinaryId implements Id { private final byte[] bytes; private final Id id; public BinaryId(byte[] bytes, Id id) { this.bytes = bytes; this.id = id; } public Id origin() { return this.id; } @Override public IdType type() { return IdType.UNKNOWN; } @Override public Object asObject() { return ByteBuffer.wrap(this.bytes); } @Override public String asString() { throw new UnsupportedOperationException(); } @Override public long asLong() { throw new UnsupportedOperationException(); } @Override public int compareTo(Id other) { return Bytes.compare(this.bytes, other.asBytes()); } @Override public byte[] asBytes() { return this.bytes; } public byte[] asBytes(int offset) {<FILL_FUNCTION_BODY>} @Override public int length() { return this.bytes.length; } @Override public int hashCode() { return ByteBuffer.wrap(this.bytes).hashCode(); } @Override public boolean equals(Object other) { if (!(other instanceof BinaryId)) { return false; } return Arrays.equals(this.bytes, ((BinaryId) other).bytes); } @Override public String toString() { return "0x" + Bytes.toHex(this.bytes); } }
E.checkArgument(offset < this.bytes.length, "Invalid offset %s, must be < length %s", offset, this.bytes.length); return Arrays.copyOfRange(this.bytes, offset, this.bytes.length);
418
65
483
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/serializer/BinaryEntryIterator.java
BinaryEntryIterator
fetch
class BinaryEntryIterator<Elem> extends BackendEntryIterator { protected final BackendIterator<Elem> results; protected final BiFunction<BackendEntry, Elem, BackendEntry> merger; protected BackendEntry next; public BinaryEntryIterator(BackendIterator<Elem> results, Query query, BiFunction<BackendEntry, Elem, BackendEntry> m) { super(query); E.checkNotNull(results, "results"); E.checkNotNull(m, "merger"); this.results = results; this.merger = m; this.next = null; if (query.paging()) { assert query.offset() == 0L; assert PageState.fromString(query.page()).offset() == 0; this.skipPageOffset(query.page()); } else { this.skipOffset(); } } @Override public void close() throws Exception { this.results.close(); } @Override protected final boolean fetch() {<FILL_FUNCTION_BODY>} @Override protected final long sizeOf(BackendEntry entry) { return sizeOfEntry(entry); } @Override protected final long skip(BackendEntry entry, long skip) { BinaryBackendEntry e = (BinaryBackendEntry) entry; E.checkState(e.columnsSize() > skip, "Invalid entry to skip"); for (long i = 0; i < skip; i++) { e.removeColumn(0); } return e.columnsSize(); } @Override protected PageState pageState() { byte[] position = this.results.position(); if (position == null) { position = PageState.EMPTY_BYTES; } return new PageState(position, 0, (int) this.count()); } private void removeLastRecord() { int lastOne = this.current.columnsSize() - 1; ((BinaryBackendEntry) this.current).removeColumn(lastOne); } public static long sizeOfEntry(BackendEntry entry) { /* * 3 cases: * 1) one vertex per entry * 2) one edge per column (one entry <==> a vertex), * 3) one element id per column (one entry <==> an index) */ if (entry.type().isEdge() || entry.type().isIndex()) { return entry.columnsSize(); } return 1L; } }
assert this.current == null; if (this.next != null) { this.current = this.next; this.next = null; } while (this.results.hasNext()) { Elem elem = this.results.next(); BackendEntry merged = this.merger.apply(this.current, elem); E.checkState(merged != null, "Error when merging entry"); if (this.current == null) { // The first time to read this.current = merged; } else if (merged == this.current) { // The next entry belongs to the current entry assert this.current != null; if (this.sizeOf(this.current) >= INLINE_BATCH_SIZE) { break; } } else { // New entry assert this.next == null; this.next = merged; break; } // When limit exceed, stop fetching if (this.reachLimit(this.fetched() - 1)) { // Need remove last one because fetched limit + 1 records this.removeLastRecord(); this.results.close(); break; } } return this.current != null;
652
318
970
<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-core/src/main/java/org/apache/hugegraph/backend/serializer/BinaryScatterSerializer.java
BinaryScatterSerializer
readVertex
class BinaryScatterSerializer extends BinarySerializer { public BinaryScatterSerializer(HugeConfig config) { super(true, true, false); } @Override public BackendEntry writeVertex(HugeVertex vertex) { BinaryBackendEntry entry = newBackendEntry(vertex); if (vertex.removed()) { return entry; } // Write vertex label entry.column(this.formatLabel(vertex)); // Write all properties of a Vertex for (HugeProperty<?> prop : vertex.getProperties()) { entry.column(this.formatProperty(prop)); } return entry; } @Override public HugeVertex readVertex(HugeGraph graph, BackendEntry bytesEntry) {<FILL_FUNCTION_BODY>} @Override public BackendEntry writeVertexProperty(HugeVertexProperty<?> prop) { BinaryBackendEntry entry = newBackendEntry(prop.element()); entry.column(this.formatProperty(prop)); entry.subId(IdGenerator.of(prop.key())); return entry; } }
if (bytesEntry == null) { return null; } BinaryBackendEntry entry = this.convertEntry(bytesEntry); // Parse label final byte[] VL = this.formatSyspropName(entry.id(), HugeKeys.LABEL); BackendColumn vl = entry.column(VL); VertexLabel vertexLabel = VertexLabel.NONE; if (vl != null) { Id labelId = BytesBuffer.wrap(vl.value).readId(); vertexLabel = graph.vertexLabelOrNone(labelId); } // Parse id Id id = entry.id().origin(); HugeVertex vertex = new HugeVertex(graph, id, vertexLabel); // Parse all properties and edges of a Vertex for (BackendColumn col : entry.columns()) { this.parseColumn(col, vertex); } return vertex;
290
237
527
<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-core/src/main/java/org/apache/hugegraph/backend/serializer/MergeIterator.java
MergeIterator
fetch
class MergeIterator<T, R> extends WrappedIterator<T> { private final Iterator<T> originIterator; private final BiFunction<T, R, Boolean> merger; private final List<Iterator<R>> iterators = new ArrayList<>(); private final List<R> headElements; public MergeIterator(Iterator<T> originIterator, List<Iterator<R>> iterators, BiFunction<T, R, Boolean> merger) { E.checkArgumentNotNull(originIterator, "The origin iterator of " + "MergeIterator can't be null"); E.checkArgument(iterators != null && !iterators.isEmpty(), "The iterators of MergeIterator can't be " + "null or empty"); E.checkArgumentNotNull(merger, "The merger function of " + "MergeIterator can't be null"); this.originIterator = originIterator; this.headElements = new ArrayList<>(); for (Iterator<R> iterator : iterators) { if (iterator.hasNext()) { this.iterators.add(iterator); this.headElements.add(iterator.next()); } } this.merger = merger; } @Override public void close() throws Exception { for (Iterator<R> iter : this.iterators) { if (iter instanceof AutoCloseable) { ((AutoCloseable) iter).close(); } } } @Override protected Iterator<T> originIterator() { return this.originIterator; } @Override protected final boolean fetch() {<FILL_FUNCTION_BODY>} }
if (!this.originIterator.hasNext()) { return false; } T next = this.originIterator.next(); for (int i = 0; i < this.iterators.size(); i++) { R element = this.headElements.get(i); if (element == none()) { continue; } if (this.merger.apply(next, element)) { Iterator<R> iter = this.iterators.get(i); if (iter.hasNext()) { this.headElements.set(i, iter.next()); } else { this.headElements.set(i, none()); close(iter); } } } assert this.current == none(); this.current = next; return true;
428
206
634
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/serializer/SerializerFactory.java
SerializerFactory
serializer
class SerializerFactory { private static final Map<String, Class<? extends AbstractSerializer>> serializers; static { serializers = new ConcurrentHashMap<>(); } public static AbstractSerializer serializer(HugeConfig config, String name) {<FILL_FUNCTION_BODY>} @SuppressWarnings({"rawtypes", "unchecked"}) public static void register(String name, String classPath) { ClassLoader classLoader = SerializerFactory.class.getClassLoader(); Class<?> clazz; try { clazz = classLoader.loadClass(classPath); } catch (Exception e) { throw new BackendException("Invalid class: '%s'", e, classPath); } // Check subclass if (!AbstractSerializer.class.isAssignableFrom(clazz)) { throw new BackendException("Class is not a subclass of class " + "AbstractSerializer: '%s'", classPath); } // Check exists if (serializers.containsKey(name)) { throw new BackendException("Exists serializer: %s(Class '%s')", name, serializers.get(name).getName()); } // Register class serializers.put(name, (Class) clazz); } }
name = name.toLowerCase(); switch (name) { case "binary": return new BinarySerializer(config); case "binaryscatter": return new BinaryScatterSerializer(config); case "text": return new TextSerializer(config); default: } Class<? extends AbstractSerializer> clazz = serializers.get(name); if (clazz == null) { throw new BackendException("Not exists serializer: '%s'", name); } assert AbstractSerializer.class.isAssignableFrom(clazz); try { return clazz.getConstructor(HugeConfig.class).newInstance(config); } catch (Exception e) { throw new BackendException(e); }
328
194
522
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/serializer/TableBackendEntry.java
Row
mergeable
class Row { private HugeType type; private Id id; private Id subId; private final Map<HugeKeys, Object> columns; private long ttl; public Row(HugeType type) { this(type, null); } public Row(HugeType type, Id id) { this.type = type; this.id = id; this.subId = null; this.columns = new ConcurrentHashMap<>(); this.ttl = 0L; } public HugeType type() { return this.type; } public Id id() { return this.id; } public Map<HugeKeys, Object> columns() { return this.columns; } @SuppressWarnings("unchecked") public <T> T column(HugeKeys key) { // The T must be primitive type, or list/set/map of primitive type return (T) this.columns.get(key); } public <T> void column(HugeKeys key, T value) { this.columns.put(key, value); } public <T> void column(HugeKeys key, T value, Cardinality c) { switch (c) { case SINGLE: this.column(key, value); break; case SET: // Avoid creating new Set when the key exists if (!this.columns.containsKey(key)) { this.columns.putIfAbsent(key, new LinkedHashSet<>()); } this.<Set<T>>column(key).add(value); break; case LIST: // Avoid creating new List when the key exists if (!this.columns.containsKey(key)) { this.columns.putIfAbsent(key, new LinkedList<>()); } this.<List<T>>column(key).add(value); break; default: throw new AssertionError("Unsupported cardinality: " + c); } } public <T> void column(HugeKeys key, Object name, T value) { if (!this.columns.containsKey(key)) { this.columns.putIfAbsent(key, new ConcurrentHashMap<>()); } this.<Map<Object, T>>column(key).put(name, value); } public void ttl(long ttl) { this.ttl = ttl; } public long ttl() { return this.ttl; } @Override public String toString() { return String.format("Row{type=%s, id=%s, columns=%s}", this.type, this.id, this.columns); } } private final Row row; private final List<Row> subRows; // NOTE: selfChanged is false when the row has not changed but subRows has. private boolean selfChanged; private boolean olap; public TableBackendEntry(Id id) { this(null, id); } public TableBackendEntry(HugeType type) { this(type, null); } public TableBackendEntry(HugeType type, Id id) { this(new Row(type, id)); } public TableBackendEntry(Row row) { this.row = row; this.subRows = new ArrayList<>(); this.selfChanged = true; this.olap = false; } @Override public HugeType type() { return this.row.type; } public void type(HugeType type) { this.row.type = type; } @Override public Id id() { return this.row.id; } @Override public Id originId() { return this.row.id; } public void id(Id id) { this.row.id = id; } @Override public Id subId() { return this.row.subId; } public void subId(Id subId) { this.row.subId = subId; } public void selfChanged(boolean changed) { this.selfChanged = changed; } public boolean selfChanged() { return this.selfChanged; } public void olap(boolean olap) { this.olap = olap; } @Override public boolean olap() { return this.olap; } public Row row() { return this.row; } public Map<HugeKeys, Object> columnsMap() { return this.row.columns(); } public <T> void column(HugeKeys key, T value) { this.row.column(key, value); } public <T> void column(HugeKeys key, Object name, T value) { this.row.column(key, name, value); } public <T> void column(HugeKeys key, T value, Cardinality c) { this.row.column(key, value, c); } public <T> T column(HugeKeys key) { return this.row.column(key); } public void subRow(Row row) { this.subRows.add(row); } public List<Row> subRows() { return this.subRows; } public void ttl(long ttl) { this.row.ttl(ttl); } @Override public long ttl() { return this.row.ttl(); } @Override public String toString() { return String.format("TableBackendEntry{%s, sub-rows: %s}", this.row.toString(), this.subRows.toString()); } @Override public int columnsSize() { throw new NotImplementedException("Not supported by table backend"); } @Override public Collection<BackendEntry.BackendColumn> columns() { throw new NotImplementedException("Not supported by table backend"); } @Override public void columns(Collection<BackendEntry.BackendColumn> bytesColumns) { throw new NotImplementedException("Not supported by table backend"); } @Override public void columns(BackendEntry.BackendColumn bytesColumn) { throw new NotImplementedException("Not supported by table backend"); } @Override public void merge(BackendEntry other) { throw new NotImplementedException("Not supported by table backend"); } @Override public boolean mergeable(BackendEntry other) {<FILL_FUNCTION_BODY>
if (!(other instanceof TableBackendEntry)) { return false; } TableBackendEntry tableEntry = (TableBackendEntry) other; Object selfId = this.column(HugeKeys.ID); Object otherId = tableEntry.column(HugeKeys.ID); if (!selfId.equals(otherId)) { return false; } Id key = tableEntry.subId(); Object value = tableEntry.row().column(HugeKeys.PROPERTY_VALUE); this.row().column(HugeKeys.PROPERTIES, key.asLong(), value); return true;
1,744
156
1,900
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/store/AbstractBackendStore.java
AbstractBackendStore
metadata
class AbstractBackendStore<Session extends BackendSession> implements BackendStore { // TODO: move SystemSchemaStore into backend like MetaStore private final SystemSchemaStore systemSchemaStore; private final MetaDispatcher<Session> dispatcher; public AbstractBackendStore() { this.systemSchemaStore = new SystemSchemaStore(); this.dispatcher = new MetaDispatcher<>(); } protected MetaDispatcher<Session> metaDispatcher() { return this.dispatcher; } public void registerMetaHandler(String name, MetaHandler<Session> handler) { this.dispatcher.registerMetaHandler(name, handler); } @Override public String storedVersion() { throw new UnsupportedOperationException( "AbstractBackendStore.storedVersion()"); } @Override public SystemSchemaStore systemSchemaStore() { return this.systemSchemaStore; } // Get metadata by key @Override public <R> R metadata(HugeType type, String meta, Object[] args) {<FILL_FUNCTION_BODY>} protected void checkOpened() throws ConnectionException { if (!this.opened()) { throw new ConnectionException( "The '%s' store of %s has not been opened", this.database(), this.provider().type()); } } @Override public String toString() { return String.format("%s/%s", this.database(), this.store()); } protected abstract BackendTable<Session, ?> table(HugeType type); // NOTE: Need to support passing null protected abstract Session session(HugeType type); }
Session session = this.session(type); MetaDispatcher<Session> dispatcher; if (type == null) { dispatcher = this.metaDispatcher(); } else { BackendTable<Session, ?> table = this.table(type); dispatcher = table.metaDispatcher(); } return dispatcher.dispatchMetaHandler(session, meta, args);
425
99
524
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/store/AbstractBackendStoreProvider.java
AbstractBackendStoreProvider
initialized
class AbstractBackendStoreProvider implements BackendStoreProvider { private static final Logger LOG = Log.logger(AbstractBackendStoreProvider.class); private String graph = null; private final EventHub storeEventHub = new EventHub("store"); protected Map<String, BackendStore> stores = null; protected final void notifyAndWaitEvent(String event) { Future<?> future = this.storeEventHub.notify(event, this); try { future.get(); } catch (Throwable e) { LOG.warn("Error when waiting for event execution: {}", event, e); } } protected final void checkOpened() { E.checkState(this.graph != null && this.stores != null, "The BackendStoreProvider has not been opened"); } protected abstract BackendStore newSchemaStore(HugeConfig config, String store); protected abstract BackendStore newGraphStore(HugeConfig config, String store); protected abstract BackendStore newSystemStore(HugeConfig config, String store); @Override public void listen(EventListener listener) { this.storeEventHub.listen(EventHub.ANY_EVENT, listener); } @Override public void unlisten(EventListener listener) { this.storeEventHub.unlisten(EventHub.ANY_EVENT, listener); } @Override public String storedVersion() { return this.loadSystemStore(null).storedVersion(); } @Override public String graph() { this.checkOpened(); return this.graph; } @Override public void open(String graph) { LOG.debug("Graph '{}' open StoreProvider", this.graph); E.checkArgument(graph != null, "The graph name can't be null"); E.checkArgument(!graph.isEmpty(), "The graph name can't be empty"); this.graph = graph; this.stores = new ConcurrentHashMap<>(); this.storeEventHub.notify(Events.STORE_OPEN, this); } @Override public void waitReady(RpcServer rpcServer) { // passs } @Override public void close() throws BackendException { LOG.debug("Graph '{}' close StoreProvider", this.graph); this.checkOpened(); this.storeEventHub.notify(Events.STORE_CLOSE, this); } @Override public void init() { this.checkOpened(); for (BackendStore store : this.stores.values()) { store.init(); } this.notifyAndWaitEvent(Events.STORE_INIT); LOG.debug("Graph '{}' store has been initialized", this.graph); } @Override public void clear() throws BackendException { this.checkOpened(); for (BackendStore store : this.stores.values()) { // Just clear tables of store, not clear space store.clear(false); } for (BackendStore store : this.stores.values()) { // Only clear space of store store.clear(true); } this.notifyAndWaitEvent(Events.STORE_CLEAR); LOG.debug("Graph '{}' store has been cleared", this.graph); } @Override public void truncate() { this.checkOpened(); for (BackendStore store : this.stores.values()) { store.truncate(); } this.notifyAndWaitEvent(Events.STORE_TRUNCATE); LOG.debug("Graph '{}' store has been truncated", this.graph); } @Override public boolean initialized() {<FILL_FUNCTION_BODY>} @Override public void createSnapshot() { String snapshotPrefix = StoreSnapshotFile.SNAPSHOT_DIR; for (BackendStore store : this.stores.values()) { store.createSnapshot(snapshotPrefix); } } @Override public void resumeSnapshot() { String snapshotPrefix = StoreSnapshotFile.SNAPSHOT_DIR; for (BackendStore store : this.stores.values()) { store.resumeSnapshot(snapshotPrefix, true); } } @Override public BackendStore loadSchemaStore(HugeConfig config) { String name = SCHEMA_STORE; LOG.debug("The '{}' StoreProvider load SchemaStore '{}'", this.type(), name); this.checkOpened(); if (!this.stores.containsKey(name)) { BackendStore s = this.newSchemaStore(config, name); this.stores.putIfAbsent(name, s); } BackendStore store = this.stores.get(name); E.checkNotNull(store, "store"); return store; } @Override public BackendStore loadGraphStore(HugeConfig config) { String name = GRAPH_STORE; LOG.debug("The '{}' StoreProvider load GraphStore '{}'", this.type(), name); this.checkOpened(); if (!this.stores.containsKey(name)) { BackendStore s = this.newGraphStore(config, name); this.stores.putIfAbsent(name, s); } BackendStore store = this.stores.get(name); E.checkNotNull(store, "store"); return store; } @Override public BackendStore loadSystemStore(HugeConfig config) { String name = SYSTEM_STORE; LOG.debug("The '{}' StoreProvider load SystemStore '{}'", this.type(), name); this.checkOpened(); if (!this.stores.containsKey(name)) { BackendStore s = this.newSystemStore(config, name); this.stores.putIfAbsent(name, s); } BackendStore store = this.stores.get(name); E.checkNotNull(store, "store"); return store; } @Override public EventHub storeEventHub() { return this.storeEventHub; } @Override public void onCloneConfig(HugeConfig config, String newGraph) { config.setProperty(CoreOptions.STORE.name(), newGraph); } @Override public void onDeleteConfig(HugeConfig config) { // pass } }
this.checkOpened(); for (BackendStore store : this.stores.values()) { if (!store.initialized()) { return false; } } return true;
1,678
54
1,732
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/store/BackendEntryIterator.java
BackendEntryIterator
reachLimit
class BackendEntryIterator implements CIter<BackendEntry> { private static final Logger LOG = Log.logger(BackendEntryIterator.class); public static final long INLINE_BATCH_SIZE = Query.COMMIT_BATCH; protected final Query query; protected BackendEntry current; private long count; public BackendEntryIterator(Query query) { E.checkNotNull(query, "query"); this.query = query; this.count = 0L; this.current = null; } @Override public boolean hasNext() { if (this.reachLimit()) { return false; } if (this.current != null) { return true; } return this.fetch(); } @Override public BackendEntry next() { // Stop if reach capacity this.checkCapacity(); // Stop if reach limit if (this.reachLimit()) { throw new NoSuchElementException(); } if (this.current == null) { this.fetch(); } BackendEntry current = this.current; if (current == null) { throw new NoSuchElementException(); } this.current = null; this.count += this.sizeOf(current); return current; } @Override public Object metadata(String meta, Object... args) { if (PageInfo.PAGE.equals(meta)) { return this.pageState(); } throw new NotSupportException("Invalid meta '%s'", meta); } public static final void checkInterrupted() { if (Thread.interrupted()) { throw new BackendException("Interrupted, maybe it is timed out", new InterruptedException()); } } protected final void checkCapacity() throws LimitExceedException { // Stop if reach capacity this.query.checkCapacity(this.count()); } protected final boolean reachLimit() { /* * TODO: if the query is separated with multi sub-queries(like query * id in [id1, id2, ...]), then each BackendEntryIterator is only * result(s) of one sub-query, so the query offset/limit is inaccurate. */ // Stop if it has reached limit after the previous next() return this.reachLimit(this.count); } protected final boolean reachLimit(long count) {<FILL_FUNCTION_BODY>} protected final long count() { return this.count; } protected final long fetched() { long ccount = this.current == null ? 0 : this.sizeOf(this.current); return this.count + ccount; } protected final void skipPageOffset(String page) { PageState pageState = PageState.fromString(page); int pageOffset = pageState.offset(); if (pageOffset > 0) { /* * Don't update this.count even if skipped page offset, * because the skipped records belongs to the last page. */ this.skipOffset(pageOffset); } } protected void skipOffset() { long offset = this.query.offset() - this.query.actualOffset(); if (offset <= 0L) { return; } long skipped = this.skipOffset(offset); this.count += skipped; this.query.goOffset(skipped); } protected long skipOffset(long offset) { assert offset >= 0L; long skipped = 0L; // Skip offset while (skipped < offset && this.fetch()) { assert this.current != null; final long size = this.sizeOf(this.current); skipped += size; if (skipped > offset) { // Skip part of sub-items in an entry final long skip = size - (skipped - offset); skipped -= this.skip(this.current, skip); assert skipped == offset; } else { // Skip entry this.current = null; } } return skipped; } protected long sizeOf(BackendEntry entry) { return 1; } protected long skip(BackendEntry entry, long skip) { assert this.sizeOf(entry) == 1; // Return the remained sub-items(items) return this.sizeOf(entry); } protected abstract boolean fetch(); protected abstract PageState pageState(); public static final class EmptyIterator extends BackendEntryIterator { public EmptyIterator(Query query) { super(query); } @Override protected boolean fetch() { return false; } @Override protected PageState pageState() { return PageState.EMPTY; } @Override public void close() throws Exception { } } }
try { checkInterrupted(); } catch (Throwable e) { try { this.close(); } catch (Throwable ex) { LOG.warn("Failed to close backend entry iterator for interrupted query", ex); } throw e; } return this.query.reachLimit(count);
1,263
85
1,348
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/backend/store/BackendProviderFactory.java
BackendProviderFactory
open
class BackendProviderFactory { private static final Logger LOG = Log.logger(BackendProviderFactory.class); private static Map<String, Class<? extends BackendStoreProvider>> providers; static { providers = new ConcurrentHashMap<>(); } public static BackendStoreProvider open(HugeGraphParams params) {<FILL_FUNCTION_BODY>} private static BackendStoreProvider newProvider(HugeConfig config) { String backend = config.get(CoreOptions.BACKEND).toLowerCase(); String graph = config.get(CoreOptions.STORE); if (InMemoryDBStoreProvider.matchType(backend)) { return InMemoryDBStoreProvider.instance(graph); } Class<? extends BackendStoreProvider> clazz = providers.get(backend); BackendException.check(clazz != null, "Not exists BackendStoreProvider: %s", backend); assert BackendStoreProvider.class.isAssignableFrom(clazz); BackendStoreProvider instance = null; try { instance = clazz.newInstance(); } catch (Exception e) { throw new BackendException(e); } BackendException.check(backend.equals(instance.type()), "BackendStoreProvider with type '%s' " + "can't be opened by key '%s'", instance.type(), backend); return instance; } @SuppressWarnings({"rawtypes", "unchecked"}) public static void register(String name, String classPath) { ClassLoader classLoader = BackendProviderFactory.class.getClassLoader(); Class<?> clazz = null; try { clazz = classLoader.loadClass(classPath); } catch (Exception e) { throw new BackendException(e); } // Check subclass boolean subclass = BackendStoreProvider.class.isAssignableFrom(clazz); BackendException.check(subclass, "Class '%s' is not a subclass of " + "class BackendStoreProvider", classPath); // Check exists BackendException.check(!providers.containsKey(name), "Exists BackendStoreProvider: %s (%s)", name, providers.get(name)); // Register class providers.put(name, (Class) clazz); } }
HugeConfig config = params.configuration(); String backend = config.get(CoreOptions.BACKEND).toLowerCase(); String graph = config.get(CoreOptions.STORE); boolean raftMode = config.get(CoreOptions.RAFT_MODE); BackendStoreProvider provider = newProvider(config); if (raftMode) { LOG.info("Opening backend store '{}' in raft mode for graph '{}'", backend, graph); provider = new RaftBackendStoreProvider(params, provider); } provider.open(graph); return provider;
603
151
754
<no_super_class>