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 5 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,7 +462,7 @@ public Object[] properties() {
}
if (this.id != null) {
newProps[appendIndex++] = T.id;
newProps[appendIndex++] = this.id;
newProps[appendIndex] = this.id;
imbajin marked this conversation as resolved.
Show resolved Hide resolved
}
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 @@ -45,7 +45,6 @@
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.backend.query.Query;
import com.baidu.hugegraph.backend.query.QueryResults;
import com.baidu.hugegraph.core.GraphManager;
import com.baidu.hugegraph.server.RestServer;
Expand Down Expand Up @@ -135,7 +134,7 @@ public String post(@Context GraphManager manager,
}

long size = results.size();
if (request.limit != Query.NO_LIMIT && size > request.limit) {
if (size > request.limit) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

resume request.limit != Query.NO_LIMIT && to don't depend on NO_LIMIT value is LONG_MAX

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fine, the root problem is we consider not use Long.Max in future, otherwise it may lead a lot redundant condition & type casting

size = request.limit;
}
List<Id> neighbors = request.countOnly ?
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@
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.backend.query.Query;
import com.baidu.hugegraph.backend.query.QueryResults;
import com.baidu.hugegraph.core.GraphManager;
import com.baidu.hugegraph.server.RestServer;
Expand Down Expand Up @@ -144,7 +143,7 @@ public String post(@Context GraphManager manager,
}

long size = results.size();
if (request.limit != Query.NO_LIMIT && size > request.limit) {
if (size > request.limit) {
size = request.limit;
}
List<Id> neighbors = request.countOnly ?
Expand All @@ -154,6 +153,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 @@ -117,12 +117,13 @@ public final class ApiVersion {
* [0.65] Issue-1506: Support olap property key
* [0.66] Issue-1567: Support get schema RESTful API
* [0.67] Issue-1065: Support dynamically add/remove graph
* [0.68] Issue-1741: Support adamic-adar & resource-allocation API
*/

// 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
Loading