Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refact: fix some bugs & clean code #1741

Merged
merged 9 commits into from
Mar 21, 2022
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@

public class API {

private static final Logger LOG = Log.logger(RestServer.class);
protected static final Logger LOG = Log.logger(RestServer.class);

public static final String CHARSET = "UTF-8";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,7 @@ private static void checkUpdate(BatchVertexRequest req) {
E.checkArgument(req.updateStrategies != null &&
!req.updateStrategies.isEmpty(),
"Parameter 'update_strategies' can't be empty");
E.checkArgument(req.createIfNotExist == true,
E.checkArgument(req.createIfNotExist,
"Parameter 'create_if_not_exist' " +
"dose not support false now");
}
Expand Down Expand Up @@ -462,6 +462,7 @@ public Object[] properties() {
}
if (this.id != null) {
newProps[appendIndex++] = T.id;
// Keep value++ to avoid code trap
newProps[appendIndex++] = this.id;
}
return newProps;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/*
* Copyright 2022 HugeGraph Authors
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
* licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/

package com.baidu.hugegraph.api.traversers;

import static com.baidu.hugegraph.traversal.algorithm.HugeTraverser.DEFAULT_ELEMENTS_LIMIT;
import static com.baidu.hugegraph.traversal.algorithm.HugeTraverser.DEFAULT_MAX_DEGREE;

import javax.inject.Singleton;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;

import com.baidu.hugegraph.HugeGraph;
import com.baidu.hugegraph.api.API;
import com.baidu.hugegraph.api.graph.EdgeAPI;
import com.baidu.hugegraph.api.graph.VertexAPI;
import com.baidu.hugegraph.backend.id.Id;
import com.baidu.hugegraph.core.GraphManager;
import com.baidu.hugegraph.traversal.algorithm.PredictionTraverser;
import com.baidu.hugegraph.type.define.Directions;
import com.baidu.hugegraph.util.E;
import com.baidu.hugegraph.util.JsonUtil;
import com.codahale.metrics.annotation.Timed;
import com.google.common.collect.ImmutableMap;

/**
* This API include similar prediction algorithms, now include:
* - Adamic Adar
* - Resource Allocation
*
* Could add more prediction algorithms in future
*/
@Path("graphs/{graph}/traversers/adamicadar")
@Singleton
public class AdamicAdarAPI extends API {

@GET
@Timed
@Produces(APPLICATION_JSON_WITH_CHARSET)
public String get(@Context GraphManager manager,
imbajin marked this conversation as resolved.
Show resolved Hide resolved
@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) long limit) {
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);
PredictionTraverser traverser = new PredictionTraverser(g);
double score = traverser.adamicAdar(sourceId, targetId, dir,
edgeLabel, maxDegree, limit);
return JsonUtil.toJson(ImmutableMap.of("adamic_adar", score));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ public String post(@Context GraphManager manager,
if (request.withPath) {
paths.addAll(results.paths(request.limit));
}

Iterator<Vertex> iter = QueryResults.emptyIterator();
if (request.withVertex && !request.countOnly) {
Set<Id> ids = new HashSet<>(neighbors);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/*
* Copyright 2022 HugeGraph Authors
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
* licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/

package com.baidu.hugegraph.api.traversers;

import static com.baidu.hugegraph.traversal.algorithm.HugeTraverser.DEFAULT_ELEMENTS_LIMIT;
import static com.baidu.hugegraph.traversal.algorithm.HugeTraverser.DEFAULT_MAX_DEGREE;

import javax.inject.Singleton;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;

import com.baidu.hugegraph.HugeGraph;
import com.baidu.hugegraph.api.API;
import com.baidu.hugegraph.api.graph.EdgeAPI;
import com.baidu.hugegraph.api.graph.VertexAPI;
import com.baidu.hugegraph.backend.id.Id;
import com.baidu.hugegraph.core.GraphManager;
import com.baidu.hugegraph.traversal.algorithm.PredictionTraverser;
import com.baidu.hugegraph.type.define.Directions;
import com.baidu.hugegraph.util.E;
import com.baidu.hugegraph.util.JsonUtil;
import com.codahale.metrics.annotation.Timed;
import com.google.common.collect.ImmutableMap;

/**
* This API include similar prediction algorithms, now include:
* - Adamic Adar
* - Resource Allocation
*
* Could add more prediction algorithms in future
*/
@Path("graphs/{graph}/traversers/resourceallocation")
@Singleton
public 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) long limit) {
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);
PredictionTraverser traverser = new PredictionTraverser(g);
double score = traverser.resourceAllocation(sourceId, targetId, dir,
edgeLabel, maxDegree,
limit);
return JsonUtil.toJson(ImmutableMap.of("resource_allocation", score));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ private String inputPassword() {
String notEmptyPrompt = "The admin password can't be empty";
Console console = System.console();
while (true) {
String password = "";
String password;
if (console != null) {
char[] chars = console.readPassword(inputPrompt);
password = new String(chars);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,9 +120,9 @@ public final class ApiVersion {
*/

// The second parameter of Version.of() is for IDE running without JAR
public static final Version VERSION = Version.of(ApiVersion.class, "0.67");
public static final Version VERSION = Version.of(ApiVersion.class, "0.68");

public static final void check() {
public static void check() {
// Check version of hugegraph-core. Firstly do check from version 0.3
VersionUtil.check(CoreVersion.VERSION, "0.12", "0.13", CoreVersion.NAME);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -933,7 +933,7 @@ public void drop() {
*/
this.close();
} catch (Throwable e) {
LOG.warn("Failed to close graph {}", e, this);
LOG.warn("Failed to close graph {} {}", this, e);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,9 +118,7 @@ public boolean exists(Id id) {
Iterator<Vertex> vertices = this.tx().queryVertices(id);
if (vertices.hasNext()) {
Vertex vertex = vertices.next();
if (this.label.equals(vertex.label())) {
return true;
}
return this.label.equals(vertex.label());
}
return false;
}
Expand All @@ -145,7 +143,7 @@ protected List<T> toList(Iterator<Vertex> vertices) {
}

private Iterator<Vertex> queryById(List<Id> ids) {
Object[] idArray = ids.toArray(new Id[ids.size()]);
Object[] idArray = ids.toArray(new Id[0]);
return this.tx().queryVertices(idArray);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,9 +138,7 @@ public boolean filter(ResourceObject<?> resourceObject) {
private boolean filter(AuthElement element) {
assert this.type.match(element.type());
if (element instanceof Namifiable) {
if (!this.filter((Namifiable) element)) {
return false;
}
return this.filter((Namifiable) element);
}
return true;
}
Expand All @@ -149,10 +147,7 @@ private boolean filter(Namifiable element) {
assert !(element instanceof Typifiable) || this.type.match(
ResourceType.from(((Typifiable) element).type()));

if (!this.matchLabel(element.name())) {
return false;
}
return true;
return this.matchLabel(element.name());
}

private boolean filter(HugeElement element) {
Expand Down Expand Up @@ -193,10 +188,7 @@ private boolean matchLabel(String other) {
return false;
}
// It's ok if wildcard match or regular match
if (!this.label.equals(ANY) && !other.matches(this.label)) {
return false;
}
return true;
return this.label.equals(ANY) || other.matches(this.label);
}

private boolean matchProperties(Map<String, Object> other) {
Expand Down Expand Up @@ -229,10 +221,7 @@ protected boolean contains(HugeResource other) {
if (!this.matchLabel(other.label)) {
return false;
}
if (!this.matchProperties(other.properties)) {
return false;
}
return true;
return this.matchProperties(other.properties);
}

@Override
Expand Down Expand Up @@ -260,9 +249,7 @@ public static boolean allowed(ResourceObject<?> resourceObject) {
// Allowed to access system(hidden) schema by anyone
if (resourceObject.type().isSchema()) {
Namifiable schema = (Namifiable) resourceObject.operated();
if (Hidden.isHidden(schema.name())) {
return true;
}
return Hidden.isHidden(schema.name());
}

return false;
Expand Down Expand Up @@ -339,19 +326,19 @@ public HugeResource deserialize(JsonParser parser,
HugeResource res = new HugeResource();
while (parser.nextToken() != JsonToken.END_OBJECT) {
String key = parser.getCurrentName();
if (key.equals("type")) {
if ("type".equals(key)) {
if (parser.nextToken() != JsonToken.VALUE_NULL) {
res.type = ctxt.readValue(parser, ResourceType.class);
} else {
res.type = null;
}
} else if (key.equals("label")) {
} else if ("label".equals(key)) {
if (parser.nextToken() != JsonToken.VALUE_NULL) {
res.label = parser.getValueAsString();
} else {
res.label = null;
}
} else if (key.equals("properties")) {
} else if ("properties".equals(key)) {
if (parser.nextToken() != JsonToken.VALUE_NULL) {
@SuppressWarnings("unchecked")
Map<String, Object> prop = ctxt.readValue(parser,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,9 +122,7 @@ public boolean exists(Id id) {
Iterator<Edge> edges = this.tx().queryEdges(id);
if (edges.hasNext()) {
Edge edge = edges.next();
if (this.label.equals(edge.label())) {
return true;
}
return this.label.equals(edge.label());
}
return false;
}
Expand Down Expand Up @@ -161,7 +159,7 @@ protected List<T> toList(Iterator<Edge> edges) {
}

private Iterator<Edge> queryById(List<Id> ids) {
Object[] idArray = ids.toArray(new Id[ids.size()]);
Object[] idArray = ids.toArray(new Id[0]);
return this.tx().queryEdges(idArray);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
public final class LevelCache extends AbstractCache<Id, Object> {

// For multi-layer caches
private final AbstractCache<Id, Object> caches[];
private final AbstractCache<Id, Object>[] caches;

@SuppressWarnings("unchecked")
public LevelCache(AbstractCache<Id, Object> lavel1,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,12 +134,13 @@ public static String escape(char splitor, char escape, String... values) {

public static String[] unescape(String id, String splitor, String escape) {
/*
* Note that the `splitor`/`escape` maybe special characters in regular
* 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
* splited to a part.
* split to a part.
*/
String[] parts = id.split("(?<!" + escape + ")" + splitor, -1);
for (int i = 0; i < parts.length; i++) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ public enum RelationType implements BiPredicate<Object, Object> {
assert v2 != null;
/*
* TODO: we still have no way to determine accurately, since
* some backends may scan with token(column) like cassandra.
* some backends may scan with token(column) like cassandra.
*/
return true;
});
Expand Down
Loading