diff --git a/hugegraph-api/src/main/java/com/baidu/hugegraph/api/API.java b/hugegraph-api/src/main/java/com/baidu/hugegraph/api/API.java index 0ecee3f9e5..36febb1ad1 100644 --- a/hugegraph-api/src/main/java/com/baidu/hugegraph/api/API.java +++ b/hugegraph-api/src/main/java/com/baidu/hugegraph/api/API.java @@ -59,13 +59,13 @@ public class API { public static final String ACTION_ELIMINATE = "eliminate"; public static final String ACTION_CLEAR = "clear"; - private static final Meter succeedMeter = + private static final Meter SUCCEED_METER = MetricsUtil.registerMeter(API.class, "commit-succeed"); - private static final Meter illegalArgErrorMeter = + private static final Meter ILLEGAL_ARG_ERROR_METER = MetricsUtil.registerMeter(API.class, "illegal-arg"); - private static final Meter expectedErrorMeter = + private static final Meter EXPECTED_ERROR_METER = MetricsUtil.registerMeter(API.class, "expected-error"); - private static final Meter unknownErrorMeter = + private static final Meter UNKNOWN_ERROR_METER = MetricsUtil.registerMeter(API.class, "unknown-error"); public static HugeGraph graph(GraphManager manager, String graph) { @@ -96,19 +96,19 @@ public static R commit(HugeGraph g, Callable callable) { try { R result = callable.call(); g.tx().commit(); - succeedMeter.mark(); + SUCCEED_METER.mark(); return result; } catch (IllegalArgumentException | NotFoundException | ForbiddenException e) { - illegalArgErrorMeter.mark(); + ILLEGAL_ARG_ERROR_METER.mark(); rollback.accept(null); throw e; } catch (RuntimeException e) { - expectedErrorMeter.mark(); + EXPECTED_ERROR_METER.mark(); rollback.accept(e); throw e; } catch (Throwable e) { - unknownErrorMeter.mark(); + UNKNOWN_ERROR_METER.mark(); rollback.accept(e); // TODO: throw the origin exception 'e' throw new HugeException("Failed to commit", e); @@ -171,7 +171,9 @@ protected static Map parseProperties(String properties) { Map props = null; try { props = JsonUtil.fromJson(properties, Map.class); - } catch (Exception ignored) {} + } catch (Exception ignored) { + // ignore + } // If properties is the string "null", props will be null E.checkArgument(props != null, diff --git a/hugegraph-api/src/main/java/com/baidu/hugegraph/api/auth/ProjectAPI.java b/hugegraph-api/src/main/java/com/baidu/hugegraph/api/auth/ProjectAPI.java index 4eb9573fda..8cdaddb1f1 100644 --- a/hugegraph-api/src/main/java/com/baidu/hugegraph/api/auth/ProjectAPI.java +++ b/hugegraph-api/src/main/java/com/baidu/hugegraph/api/auth/ProjectAPI.java @@ -176,6 +176,7 @@ public void delete(@Context GraphManager manager, throw new IllegalArgumentException("Invalid project id: " + id); } } + public static boolean isAddGraph(String action) { return ACTION_ADD_GRAPH.equals(action); } @@ -267,6 +268,6 @@ public void checkUpdate() { this.description != null, "Must specify 'graphs' or 'description' " + "field that need to be updated"); - } } + } } diff --git a/hugegraph-api/src/main/java/com/baidu/hugegraph/api/graph/BatchAPI.java b/hugegraph-api/src/main/java/com/baidu/hugegraph/api/graph/BatchAPI.java index ebc54be66e..08e19ecc19 100644 --- a/hugegraph-api/src/main/java/com/baidu/hugegraph/api/graph/BatchAPI.java +++ b/hugegraph-api/src/main/java/com/baidu/hugegraph/api/graph/BatchAPI.java @@ -47,11 +47,11 @@ public class BatchAPI extends API { private static final Logger LOG = Log.logger(BatchAPI.class); // NOTE: VertexAPI and EdgeAPI should share a counter - private static final AtomicInteger batchWriteThreads = new AtomicInteger(0); + private static final AtomicInteger BATCH_WRITE_THREADS = new AtomicInteger(0); static { MetricsUtil.registerGauge(RestServer.class, "batch-write-threads", - () -> batchWriteThreads.intValue()); + BATCH_WRITE_THREADS::intValue); } private final Meter batchMeter; @@ -64,24 +64,24 @@ public BatchAPI() { public R commit(HugeConfig config, HugeGraph g, int size, Callable callable) { int maxWriteThreads = config.get(ServerOptions.MAX_WRITE_THREADS); - int writingThreads = batchWriteThreads.incrementAndGet(); + int writingThreads = BATCH_WRITE_THREADS.incrementAndGet(); if (writingThreads > maxWriteThreads) { - batchWriteThreads.decrementAndGet(); + BATCH_WRITE_THREADS.decrementAndGet(); throw new HugeException("The rest server is too busy to write"); } - LOG.debug("The batch writing threads is {}", batchWriteThreads); + LOG.debug("The batch writing threads is {}", BATCH_WRITE_THREADS); try { R result = commit(g, callable); this.batchMeter.mark(size); return result; } finally { - batchWriteThreads.decrementAndGet(); + BATCH_WRITE_THREADS.decrementAndGet(); } } @JsonIgnoreProperties(value = {"type"}) - protected static abstract class JsonElement implements Checkable { + protected abstract static class JsonElement implements Checkable { @JsonProperty("id") public Object id; diff --git a/hugegraph-api/src/main/java/com/baidu/hugegraph/api/gremlin/GremlinAPI.java b/hugegraph-api/src/main/java/com/baidu/hugegraph/api/gremlin/GremlinAPI.java index d071c45f73..469bed7922 100644 --- a/hugegraph-api/src/main/java/com/baidu/hugegraph/api/gremlin/GremlinAPI.java +++ b/hugegraph-api/src/main/java/com/baidu/hugegraph/api/gremlin/GremlinAPI.java @@ -50,9 +50,9 @@ @Singleton public class GremlinAPI extends API { - private static final Histogram gremlinInputHistogram = + private static final Histogram GREMLIN_INPUT_HISTOGRAM = MetricsUtil.registerHistogram(GremlinAPI.class, "gremlin-input"); - private static final Histogram gremlinOutputHistogram = + private static final Histogram GREMLIN_OUTPUT_HISTOGRAM = MetricsUtil.registerHistogram(GremlinAPI.class, "gremlin-output"); private static final Set FORBIDDEN_REQUEST_EXCEPTIONS = @@ -99,14 +99,14 @@ public Response post(@Context HugeConfig conf, // .build(); String auth = headers.getHeaderString(HttpHeaders.AUTHORIZATION); Response response = this.client().doPostRequest(auth, request); - gremlinInputHistogram.update(request.length()); - gremlinOutputHistogram.update(response.getLength()); + GREMLIN_INPUT_HISTOGRAM.update(request.length()); + GREMLIN_OUTPUT_HISTOGRAM.update(response.getLength()); return transformResponseIfNeeded(response); } @GET @Timed - @Compress(buffer=(1024 * 40)) + @Compress(buffer = (1024 * 40)) @Produces(APPLICATION_JSON_WITH_CHARSET) public Response get(@Context HugeConfig conf, @Context HttpHeaders headers, @@ -115,8 +115,8 @@ public Response get(@Context HugeConfig conf, String query = uriInfo.getRequestUri().getRawQuery(); MultivaluedMap params = uriInfo.getQueryParameters(); Response response = this.client().doGetRequest(auth, params); - gremlinInputHistogram.update(query.length()); - gremlinOutputHistogram.update(response.getLength()); + GREMLIN_INPUT_HISTOGRAM.update(query.length()); + GREMLIN_OUTPUT_HISTOGRAM.update(response.getLength()); return transformResponseIfNeeded(response); } diff --git a/hugegraph-api/src/main/java/com/baidu/hugegraph/api/job/GremlinAPI.java b/hugegraph-api/src/main/java/com/baidu/hugegraph/api/job/GremlinAPI.java index 8c5afe12c9..02952132dd 100644 --- a/hugegraph-api/src/main/java/com/baidu/hugegraph/api/job/GremlinAPI.java +++ b/hugegraph-api/src/main/java/com/baidu/hugegraph/api/job/GremlinAPI.java @@ -65,7 +65,7 @@ public class GremlinAPI extends API { private static final int MAX_NAME_LENGTH = 256; - private static final Histogram gremlinJobInputHistogram = + private static final Histogram GREMLIN_JOB_INPUT_HISTOGRAM = MetricsUtil.registerHistogram(GremlinAPI.class, "gremlin-input"); @POST @@ -79,7 +79,7 @@ public Map post(@Context GraphManager manager, GremlinRequest request) { LOG.debug("Graph [{}] schedule gremlin job: {}", graph, request); checkCreatingBody(request); - gremlinJobInputHistogram.update(request.gremlin.length()); + GREMLIN_JOB_INPUT_HISTOGRAM.update(request.gremlin.length()); HugeGraph g = graph(manager, graph); request.aliase(graph, "graph"); diff --git a/hugegraph-api/src/main/java/com/baidu/hugegraph/api/profile/ProfileAPI.java b/hugegraph-api/src/main/java/com/baidu/hugegraph/api/profile/ProfileAPI.java index 5860117f5b..6825cb9047 100644 --- a/hugegraph-api/src/main/java/com/baidu/hugegraph/api/profile/ProfileAPI.java +++ b/hugegraph-api/src/main/java/com/baidu/hugegraph/api/profile/ProfileAPI.java @@ -146,11 +146,9 @@ public APIProfiles() { public void put(APICategory category, APIProfile profile) { Map> categories; - categories = this.apis.computeIfAbsent(category.dir, - k -> new TreeMap<>()); + categories = this.apis.computeIfAbsent(category.dir, k -> new TreeMap<>()); List profiles = categories.computeIfAbsent( - category.category, - k -> new ArrayList<>()); + category.category, k -> new ArrayList<>()); profiles.add(profile); } } diff --git a/hugegraph-api/src/main/java/com/baidu/hugegraph/api/schema/IndexLabelAPI.java b/hugegraph-api/src/main/java/com/baidu/hugegraph/api/schema/IndexLabelAPI.java index 5aa6c50814..2c2f8608cb 100644 --- a/hugegraph-api/src/main/java/com/baidu/hugegraph/api/schema/IndexLabelAPI.java +++ b/hugegraph-api/src/main/java/com/baidu/hugegraph/api/schema/IndexLabelAPI.java @@ -104,8 +104,8 @@ public String update(@Context GraphManager manager, HugeGraph g = graph(manager, graph); IndexLabel.Builder builder = jsonIndexLabel.convert2Builder(g); - IndexLabel IndexLabel = append ? builder.append() : builder.eliminate(); - return manager.serializer(g).writeIndexlabel(mapIndexLabel(IndexLabel)); + IndexLabel indexLabel = append ? builder.append() : builder.eliminate(); + return manager.serializer(g).writeIndexlabel(mapIndexLabel(indexLabel)); } @GET diff --git a/hugegraph-api/src/main/java/com/baidu/hugegraph/api/traversers/JaccardSimilarityAPI.java b/hugegraph-api/src/main/java/com/baidu/hugegraph/api/traversers/JaccardSimilarityAPI.java index 9aef1013b7..dba9ceb867 100644 --- a/hugegraph-api/src/main/java/com/baidu/hugegraph/api/traversers/JaccardSimilarityAPI.java +++ b/hugegraph-api/src/main/java/com/baidu/hugegraph/api/traversers/JaccardSimilarityAPI.java @@ -84,7 +84,7 @@ public String get(@Context GraphManager manager, double similarity; try (JaccardSimilarTraverser traverser = new JaccardSimilarTraverser(g)) { - similarity = traverser.jaccardSimilarity(sourceId, targetId, dir, + similarity = traverser.jaccardSimilarity(sourceId, targetId, dir, edgeLabel, maxDegree); } return JsonUtil.toJson(ImmutableMap.of("jaccard_similarity", diff --git a/hugegraph-api/src/main/java/com/baidu/hugegraph/auth/HugeAuthenticator.java b/hugegraph-api/src/main/java/com/baidu/hugegraph/auth/HugeAuthenticator.java index 362bb95bf2..771367efd4 100644 --- a/hugegraph-api/src/main/java/com/baidu/hugegraph/auth/HugeAuthenticator.java +++ b/hugegraph-api/src/main/java/com/baidu/hugegraph/auth/HugeAuthenticator.java @@ -43,35 +43,33 @@ public interface HugeAuthenticator extends Authenticator { - public static final String KEY_USERNAME = - CredentialGraphTokens.PROPERTY_USERNAME; - public static final String KEY_PASSWORD = - CredentialGraphTokens.PROPERTY_PASSWORD; - public static final String KEY_TOKEN = "token"; - public static final String KEY_ROLE = "role"; - public static final String KEY_ADDRESS = "address"; - public static final String KEY_PATH = "path"; + String KEY_USERNAME = CredentialGraphTokens.PROPERTY_USERNAME; + String KEY_PASSWORD = CredentialGraphTokens.PROPERTY_PASSWORD; + String KEY_TOKEN = "token"; + String KEY_ROLE = "role"; + String KEY_ADDRESS = "address"; + String KEY_PATH = "path"; - public static final String USER_SYSTEM = "system"; - public static final String USER_ADMIN = "admin"; - public static final String USER_ANONY = AuthenticatedUser.ANONYMOUS_USERNAME; + String USER_SYSTEM = "system"; + String USER_ADMIN = "admin"; + String USER_ANONY = AuthenticatedUser.ANONYMOUS_USERNAME; - public static final RolePermission ROLE_NONE = RolePermission.none(); - public static final RolePermission ROLE_ADMIN = RolePermission.admin(); + RolePermission ROLE_NONE = RolePermission.none(); + RolePermission ROLE_ADMIN = RolePermission.admin(); - public static final String VAR_PREFIX = "$"; - public static final String KEY_OWNER = VAR_PREFIX + "owner"; - public static final String KEY_DYNAMIC = VAR_PREFIX + "dynamic"; - public static final String KEY_ACTION = VAR_PREFIX + "action"; + String VAR_PREFIX = "$"; + String KEY_OWNER = VAR_PREFIX + "owner"; + String KEY_DYNAMIC = VAR_PREFIX + "dynamic"; + String KEY_ACTION = VAR_PREFIX + "action"; - public void setup(HugeConfig config); + void setup(HugeConfig config); - public UserWithRole authenticate(String username, String password, - String token); - public AuthManager authManager(); + UserWithRole authenticate(String username, String password, String token); + + AuthManager authManager(); @Override - public default void setup(final Map config) { + default void setup(final Map config) { E.checkState(config != null, "Must provide a 'config' in the 'authentication'"); String path = (String) config.get("tokens"); @@ -82,7 +80,7 @@ public default void setup(final Map config) { } @Override - public default User authenticate(final Map credentials) + default User authenticate(final Map credentials) throws AuthenticationException { HugeGraphAuthProxy.resetContext(); @@ -114,21 +112,17 @@ public default User authenticate(final Map credentials) } @Override - public default boolean requireAuthentication() { + default boolean requireAuthentication() { return true; } - public default boolean verifyRole(RolePermission role) { - if (role == ROLE_NONE || role == null) { - return false; - } else { - return true; - } + default boolean verifyRole(RolePermission role) { + return role != ROLE_NONE && role != null; } - public void initAdminUser(String password) throws Exception; + void initAdminUser(String password) throws Exception; - public static HugeAuthenticator loadAuthenticator(HugeConfig conf) { + static HugeAuthenticator loadAuthenticator(HugeConfig conf) { String authClass = conf.get(ServerOptions.AUTHENTICATOR); if (authClass.isEmpty()) { return null; @@ -149,7 +143,7 @@ public static HugeAuthenticator loadAuthenticator(HugeConfig conf) { return authenticator; } - public static class User extends AuthenticatedUser { + class User extends AuthenticatedUser { public static final User ADMIN = new User(USER_ADMIN, ROLE_ADMIN); public static final User ANONYMOUS = new User(USER_ANONY, ROLE_ADMIN); @@ -254,7 +248,7 @@ public static class UserJson { } } - public static class RolePerm { + class RolePerm { @JsonProperty("roles") // graph -> action -> resource private Map> roles; @@ -394,7 +388,7 @@ public static boolean match(Object role, RolePermission grant, } } - public static class RequiredPerm { + class RequiredPerm { @JsonProperty("owner") private String owner; diff --git a/hugegraph-api/src/main/java/com/baidu/hugegraph/auth/HugeFactoryAuthProxy.java b/hugegraph-api/src/main/java/com/baidu/hugegraph/auth/HugeFactoryAuthProxy.java index fb81867829..db250c654a 100644 --- a/hugegraph-api/src/main/java/com/baidu/hugegraph/auth/HugeFactoryAuthProxy.java +++ b/hugegraph-api/src/main/java/com/baidu/hugegraph/auth/HugeFactoryAuthProxy.java @@ -28,6 +28,7 @@ import java.util.Map; import java.util.Set; +import com.baidu.hugegraph.util.Log; import org.apache.commons.configuration.Configuration; import com.baidu.hugegraph.HugeException; @@ -60,17 +61,20 @@ import com.baidu.hugegraph.variables.HugeVariables; import com.google.common.collect.ImmutableSet; +import org.slf4j.Logger; import sun.reflect.Reflection; public final class HugeFactoryAuthProxy { + private static final Logger LOG = Log.logger(HugeFactoryAuthProxy.class); + public static final String GRAPH_FACTORY = - "gremlin.graph=com.baidu.hugegraph.auth.HugeFactoryAuthProxy"; + "gremlin.graph=com.baidu.hugegraph.auth.HugeFactoryAuthProxy"; private static final Set PROTECT_METHODS = ImmutableSet.of( - "instance"); + "instance"); - private static final Map graphs = new HashMap<>(); + private static final Map GRAPHS = new HashMap<>(); static { HugeGraphAuthProxy.setContext(HugeGraphAuthProxy.Context.admin()); @@ -83,10 +87,10 @@ public static synchronized HugeGraph open(Configuration config) { * TODO: Add verify to StandardHugeGraph() to prevent dynamic creation */ HugeGraph graph = HugeFactory.open(config); - HugeGraph proxy = graphs.get(graph); + HugeGraph proxy = GRAPHS.get(graph); if (proxy == null) { proxy = new HugeGraphAuthProxy(graph); - graphs.put(graph, proxy); + GRAPHS.put(graph, proxy); } return proxy; } @@ -122,16 +126,16 @@ private static void registerPrivateActions() { Reflection.registerFieldsToFilter(com.baidu.hugegraph.auth.HugeGraphAuthProxy.ContextTask.class, "runner", "context"); Reflection.registerFieldsToFilter(com.baidu.hugegraph.StandardHugeGraph.class, "LOG", "started", "closed", "mode", "variables", "name", "params", "configuration", "schemaEventHub", "graphEventHub", "indexEventHub", "writeRateLimiter", "readRateLimiter", "taskManager", "authManager", "features", "storeProvider", "tx", "ramtable", "$assertionsDisabled"); Reflection.registerMethodsToFilter(com.baidu.hugegraph.StandardHugeGraph.class, "lambda$0", "access$3", "access$4", "access$2", "access$5", "access$6", "access$7", "waitUntilAllTasksCompleted", "access$8", "loadStoreProvider", "graphTransaction", "schemaTransaction", "openSchemaTransaction", "checkGraphNotClosed", "openSystemTransaction", "openGraphTransaction", "systemTransaction", "access$9", "access$10", "access$11", "access$12", "access$13", "access$14", "access$15", "access$16", "access$17", "access$18", "serializer", "loadSchemaStore", "loadSystemStore", "loadGraphStore", "closeTx", "analyzer", "serverInfoManager", "reloadRamtable", "reloadRamtable", "access$19", "access$20", "access$21"); - Reflection.registerFieldsToFilter(c("com.baidu.hugegraph.StandardHugeGraph$StandardHugeGraphParams"), "graph", "this$0"); - Reflection.registerMethodsToFilter(c("com.baidu.hugegraph.StandardHugeGraph$StandardHugeGraphParams"), "access$1", "graph"); - Reflection.registerFieldsToFilter(c("com.baidu.hugegraph.StandardHugeGraph$TinkerPopTransaction"), "refs", "opened", "transactions", "this$0", "$assertionsDisabled"); - Reflection.registerMethodsToFilter(c("com.baidu.hugegraph.StandardHugeGraph$TinkerPopTransaction"), "lambda$0", "access$3", "access$2", "lambda$1", "graphTransaction", "schemaTransaction", "systemTransaction", "access$1", "setOpened", "doCommit", "verifyOpened", "doRollback", "doClose", "destroyTransaction", "doOpen", "setClosed", "getOrNewTransaction", "access$0", "resetState"); + Reflection.registerFieldsToFilter(loadClass("com.baidu.hugegraph.StandardHugeGraph$StandardHugeGraphParams"), "graph", "this$0"); + Reflection.registerMethodsToFilter(loadClass("com.baidu.hugegraph.StandardHugeGraph$StandardHugeGraphParams"), "access$1", "graph"); + Reflection.registerFieldsToFilter(loadClass("com.baidu.hugegraph.StandardHugeGraph$TinkerPopTransaction"), "refs", "opened", "transactions", "this$0", "$assertionsDisabled"); + Reflection.registerMethodsToFilter(loadClass("com.baidu.hugegraph.StandardHugeGraph$TinkerPopTransaction"), "lambda$0", "access$3", "access$2", "lambda$1", "graphTransaction", "schemaTransaction", "systemTransaction", "access$1", "setOpened", "doCommit", "verifyOpened", "doRollback", "doClose", "destroyTransaction", "doOpen", "setClosed", "getOrNewTransaction", "access$0", "resetState"); Reflection.registerFieldsToFilter(org.apache.tinkerpop.gremlin.structure.util.AbstractThreadLocalTransaction.class, "readWriteConsumerInternal", "closeConsumerInternal", "transactionListeners"); Reflection.registerMethodsToFilter(org.apache.tinkerpop.gremlin.structure.util.AbstractThreadLocalTransaction.class, "doClose", "fireOnCommit", "fireOnRollback", "doReadWrite", "lambda$fireOnRollback$1", "lambda$fireOnCommit$0"); Reflection.registerFieldsToFilter(org.apache.tinkerpop.gremlin.structure.util.AbstractTransaction.class, "g"); Reflection.registerMethodsToFilter(org.apache.tinkerpop.gremlin.structure.util.AbstractTransaction.class, "doCommit", "doRollback", "doClose", "doOpen", "fireOnCommit", "fireOnRollback", "doReadWrite"); - Reflection.registerFieldsToFilter(c("com.baidu.hugegraph.StandardHugeGraph$Txs"), "schemaTx", "systemTx", "graphTx", "openedTime", "$assertionsDisabled"); - Reflection.registerMethodsToFilter(c("com.baidu.hugegraph.StandardHugeGraph$Txs"), "access$2", "access$1", "access$0"); + Reflection.registerFieldsToFilter(loadClass("com.baidu.hugegraph.StandardHugeGraph$Txs"), "schemaTx", "systemTx", "graphTx", "openedTime", "$assertionsDisabled"); + Reflection.registerMethodsToFilter(loadClass("com.baidu.hugegraph.StandardHugeGraph$Txs"), "access$2", "access$1", "access$0"); Reflection.registerFieldsToFilter(com.baidu.hugegraph.backend.tx.GraphTransaction.class, "indexTx", "addedVertices", "removedVertices", "addedEdges", "removedEdges", "addedProps", "removedProps", "updatedVertices", "updatedEdges", "updatedOldestProps", "locksTable", "checkCustomVertexExist", "checkAdjacentVertexExist", "lazyLoadAdjacentVertex", "ignoreInvalidEntry", "commitPartOfAdjacentEdges", "batchSize", "pageSize", "verticesCapacity", "edgesCapacity", "$assertionsDisabled", "$SWITCH_TABLE$com$baidu$hugegraph$type$define$IdStrategy"); Reflection.registerMethodsToFilter(com.baidu.hugegraph.backend.tx.GraphTransaction.class, "lambda$0", "lambda$1", "lambda$2", "lambda$3", "lambda$4", "lambda$5", "lambda$6", "lambda$7", "lambda$8", "lambda$9", "lambda$10", "lambda$11", "lambda$12", "lambda$13", "lambda$14", "lambda$15", "lambda$16", "lambda$17", "lambda$18", "lambda$19", "access$1", "$SWITCH_TABLE$com$baidu$hugegraph$type$define$IdStrategy", "indexTransaction", "indexTransaction", "beforeWrite", "prepareCommit", "verticesInTxSize", "edgesInTxSize", "checkTxVerticesCapacity", "checkTxEdgesCapacity", "verticesInTxUpdated", "verticesInTxRemoved", "removingEdgeOwner", "prepareDeletions", "prepareDeletions", "prepareUpdates", "prepareAdditions", "checkVertexExistIfCustomizedId", "checkAggregateProperty", "checkAggregateProperty", "checkNonnullProperty", "queryEdgesFromBackend", "commitPartOfEdgeDeletions", "optimizeQueries", "checkVertexLabel", "checkId", "queryVerticesFromBackend", "joinTxVertices", "joinTxEdges", "lockForUpdateProperty", "optimizeQuery", "verifyVerticesConditionQuery", "verifyEdgesConditionQuery", "indexQuery", "joinTxRecords", "propertyUpdated", "parseEntry", "traverseByLabel", "reset", "queryVerticesByIds", "filterUnmatchedRecords", "skipOffsetOrStopLimit", "filterExpiredResultFromFromBackend", "queryEdgesByIds", "matchEdgeSortKeys", "rightResultFromIndexQuery"); Reflection.registerFieldsToFilter(com.baidu.hugegraph.backend.tx.IndexableTransaction.class, "$assertionsDisabled"); @@ -280,7 +284,7 @@ private static void registerPrivateActions(Class clazz) { List methods = new ArrayList<>(); for (Method method : clazz.getDeclaredMethods()) { if (!Modifier.isPublic(method.getModifiers()) || - PROTECT_METHODS.contains(method.getName())) { + PROTECT_METHODS.contains(method.getName())) { methods.add(method.getName()); } } @@ -293,7 +297,7 @@ private static boolean registerClass(Class clazz, List fields, List methods) { if (clazz.getName().startsWith("java") || - fields.isEmpty() && methods.isEmpty()) { + fields.isEmpty() && methods.isEmpty()) { return false; } final String[] array = new String[fields.size()]; @@ -309,21 +313,21 @@ private static boolean registerClass(Class clazz, String code; code = String.format("Reflection.registerFieldsToFilter(%s.class, \"%s\");", - clazz.getCanonicalName(), String.join("\", \"", fields)); + clazz.getCanonicalName(), String.join("\", \"", fields)); if (!fields.isEmpty()) { - System.out.println(code); + LOG.info(code); } code = String.format("Reflection.registerMethodsToFilter(%s.class, \"%s\");", - clazz.getCanonicalName(), String.join("\", \"", methods)); + clazz.getCanonicalName(), String.join("\", \"", methods)); if (!methods.isEmpty()) { - System.out.println(code); + LOG.info(code); } return true; } - private static Class c(String clazz) { + private static Class loadClass(String clazz) { try { return Class.forName(clazz); } catch (ClassNotFoundException e) { diff --git a/hugegraph-api/src/main/java/com/baidu/hugegraph/auth/HugeGraphAuthProxy.java b/hugegraph-api/src/main/java/com/baidu/hugegraph/auth/HugeGraphAuthProxy.java index 3add4ab17e..f862fc1c7e 100644 --- a/hugegraph-api/src/main/java/com/baidu/hugegraph/auth/HugeGraphAuthProxy.java +++ b/hugegraph-api/src/main/java/com/baidu/hugegraph/auth/HugeGraphAuthProxy.java @@ -210,16 +210,12 @@ public Collection propertyKeys() { @Override public PropertyKey propertyKey(String key) { - return verifySchemaPermission(HugePermission.READ, () -> { - return this.hugegraph.propertyKey(key); - }); + return verifySchemaPermission(HugePermission.READ, () -> this.hugegraph.propertyKey(key)); } @Override public PropertyKey propertyKey(Id key) { - return verifySchemaPermission(HugePermission.READ, () -> { - return this.hugegraph.propertyKey(key); - }); + return verifySchemaPermission(HugePermission.READ, () -> this.hugegraph.propertyKey(key)); } @Override @@ -249,23 +245,18 @@ public Collection vertexLabels() { @Override public VertexLabel vertexLabel(String label) { - return verifySchemaPermission(HugePermission.READ, () -> { - return this.hugegraph.vertexLabel(label); - }); + return verifySchemaPermission(HugePermission.READ, () -> this.hugegraph.vertexLabel(label)); } @Override public VertexLabel vertexLabel(Id label) { - return verifySchemaPermission(HugePermission.READ, () -> { - return this.hugegraph.vertexLabel(label); - }); + return verifySchemaPermission(HugePermission.READ, () -> this.hugegraph.vertexLabel(label)); } @Override public VertexLabel vertexLabelOrNone(Id label) { - return verifySchemaPermission(HugePermission.READ, () -> { - return this.hugegraph.vertexLabelOrNone(label); - }); + return verifySchemaPermission(HugePermission.READ, + () -> this.hugegraph.vertexLabelOrNone(label)); } @Override @@ -302,23 +293,18 @@ public Collection edgeLabels() { @Override public EdgeLabel edgeLabel(String label) { - return verifySchemaPermission(HugePermission.READ, () -> { - return this.hugegraph.edgeLabel(label); - }); + return verifySchemaPermission(HugePermission.READ, () -> this.hugegraph.edgeLabel(label)); } @Override public EdgeLabel edgeLabel(Id label) { - return verifySchemaPermission(HugePermission.READ, () -> { - return this.hugegraph.edgeLabel(label); - }); + return verifySchemaPermission(HugePermission.READ, () -> this.hugegraph.edgeLabel(label)); } @Override public EdgeLabel edgeLabelOrNone(Id label) { - return verifySchemaPermission(HugePermission.READ, () -> { - return this.hugegraph.edgeLabelOrNone(label); - }); + return verifySchemaPermission(HugePermission.READ, + () -> this.hugegraph.edgeLabelOrNone(label)); } @Override @@ -362,16 +348,12 @@ public Collection indexLabels() { @Override public IndexLabel indexLabel(String label) { - return verifySchemaPermission(HugePermission.READ, () -> { - return this.hugegraph.indexLabel(label); - }); + return verifySchemaPermission(HugePermission.READ, () -> this.hugegraph.indexLabel(label)); } @Override public IndexLabel indexLabel(Id label) { - return verifySchemaPermission(HugePermission.READ, () -> { - return this.hugegraph.indexLabel(label); - }); + return verifySchemaPermission(HugePermission.READ, () -> this.hugegraph.indexLabel(label)); } @Override @@ -382,9 +364,8 @@ public boolean existsIndexLabel(String label) { @Override public Vertex addVertex(Object... keyValues) { - return verifyElemPermission(HugePermission.WRITE, () -> { - return (HugeVertex) this.hugegraph.addVertex(keyValues); - }); + return verifyElemPermission(HugePermission.WRITE, + () -> (HugeVertex) this.hugegraph.addVertex(keyValues)); } @Override @@ -412,9 +393,8 @@ public void removeVertexProperty(VertexProperty property) { @Override public Edge addEdge(Edge edge) { - return verifyElemPermission(HugePermission.WRITE, () -> { - return (HugeEdge) this.hugegraph.addEdge(edge); - }); + return verifyElemPermission(HugePermission.WRITE, + () -> (HugeEdge) this.hugegraph.addEdge(edge)); } @Override @@ -959,9 +939,8 @@ else if (ro.type().isGrantOrUser()) { // Log user action, limit rate for each user Id usrId = context.user().userId(); - RateLimiter auditLimiter = this.auditLimiters.getOrFetch(usrId, id -> { - return RateLimiter.create(this.auditLogMaxRate); - }); + RateLimiter auditLimiter = this.auditLimiters.getOrFetch(usrId, + id -> RateLimiter.create(this.auditLogMaxRate)); if (!(actionPerm == HugePermission.READ && ro.type().isSchema()) && auditLimiter.tryAcquire()) { @@ -1094,9 +1073,8 @@ private HugeTask verifyTaskPermission(HugePermission actionPerm, private Iterator> verifyTaskPermission( HugePermission actionPerm, Iterator> tasks) { - return new FilterIterator<>(tasks, task -> { - return verifyTaskPermission(actionPerm, false, task) != null; - }); + return new FilterIterator<>(tasks, + task -> verifyTaskPermission(actionPerm, false, task) != null); } private HugeTask verifyTaskPermission(HugePermission actionPerm, @@ -1107,9 +1085,7 @@ private HugeTask verifyTaskPermission(HugePermission actionPerm, String name = task.id().toString(); Nameable elem = HugeResource.NameObject.of(name); return ResourceObject.of(graph, ResourceType.TASK, elem); - }, () -> { - return hasTaskPermission(task); - }); + }, () -> hasTaskPermission(task)); return r == null ? null : task; } @@ -1490,9 +1466,8 @@ public UserWithRole validateUser(String username, String password) { try { Id userKey = IdGenerator.of(username + password); - return HugeGraphAuthProxy.this.usersRoleCache.getOrFetch(userKey, id -> { - return this.authManager.validateUser(username, password); - }); + return HugeGraphAuthProxy.this.usersRoleCache.getOrFetch(userKey, + id -> this.authManager.validateUser(username, password)); } catch (Exception e) { LOG.error("Failed to validate user {} with error: ", username, e); @@ -1509,9 +1484,8 @@ public UserWithRole validateUser(String token) { try { Id userKey = IdGenerator.of(token); - return HugeGraphAuthProxy.this.usersRoleCache.getOrFetch(userKey, id -> { - return this.authManager.validateUser(token); - }); + return HugeGraphAuthProxy.this.usersRoleCache.getOrFetch(userKey, + id -> this.authManager.validateUser(token)); } catch (Exception e) { LOG.error("Failed to validate token {} with error: ", token, e); throw e; @@ -1644,7 +1618,7 @@ public TraversalStrategies addStrategies(TraversalStrategy... return this.strategies.addStrategies(strategies); } - @SuppressWarnings({ "rawtypes", "unchecked" }) + @SuppressWarnings({ "unchecked" }) @Override public TraversalStrategies removeStrategies( Class... strategyClasses) { @@ -1674,20 +1648,20 @@ private String translate(Bytecode bytecode) { } } - private static final ThreadLocal contexts = + private static final ThreadLocal CONTEXTS = new InheritableThreadLocal<>(); - protected static final Context setContext(Context context) { - Context old = contexts.get(); - contexts.set(context); + protected static Context setContext(Context context) { + Context old = CONTEXTS.get(); + CONTEXTS.set(context); return old; } - protected static final void resetContext() { - contexts.remove(); + protected static void resetContext() { + CONTEXTS.remove(); } - protected static final Context getContext() { + protected static Context getContext() { // Return task context first String taskContext = TaskManager.getContext(); User user = User.fromJson(taskContext); @@ -1695,10 +1669,10 @@ protected static final Context getContext() { return new Context(user); } - return contexts.get(); + return CONTEXTS.get(); } - protected static final String getContextString() { + protected static String getContextString() { Context context = getContext(); if (context == null) { return null; @@ -1706,7 +1680,7 @@ protected static final String getContextString() { return context.user().toJson(); } - protected static final void logUser(User user, String path) { + protected static void logUser(User user, String path) { LOG.info("User '{}' login from client [{}] with path '{}'", user.username(), user.client(), path); } @@ -1757,7 +1731,7 @@ public static class ContextThreadPoolExecutor extends ThreadPoolExecutor { public ContextThreadPoolExecutor(int corePoolSize, int maxPoolSize, ThreadFactory threadFactory) { super(corePoolSize, maxPoolSize, 0L, TimeUnit.MILLISECONDS, - new LinkedBlockingQueue(), threadFactory); + new LinkedBlockingQueue<>(), threadFactory); } @Override diff --git a/hugegraph-api/src/main/java/com/baidu/hugegraph/auth/StandardAuthenticator.java b/hugegraph-api/src/main/java/com/baidu/hugegraph/auth/StandardAuthenticator.java index 5d56169f0e..c97efe9a99 100644 --- a/hugegraph-api/src/main/java/com/baidu/hugegraph/auth/StandardAuthenticator.java +++ b/hugegraph-api/src/main/java/com/baidu/hugegraph/auth/StandardAuthenticator.java @@ -24,6 +24,7 @@ import java.util.Map; import java.util.Scanner; +import com.baidu.hugegraph.util.Log; import org.apache.commons.lang.NotImplementedException; import org.apache.commons.lang.StringUtils; import org.apache.tinkerpop.gremlin.structure.util.GraphFactory; @@ -36,9 +37,12 @@ import com.baidu.hugegraph.util.ConfigUtil; import com.baidu.hugegraph.util.E; import com.baidu.hugegraph.util.StringEncoding; +import org.slf4j.Logger; public class StandardAuthenticator implements HugeAuthenticator { + private static final Logger LOG = Log.logger(StandardAuthenticator.class); + private static final String INITING_STORE = "initing_store"; private HugeGraph graph = null; @@ -95,7 +99,7 @@ private String inputPassword() { if (!password.isEmpty()) { return password; } - System.out.println(notEmptyPrompt); + LOG.info(notEmptyPrompt); } } diff --git a/hugegraph-api/src/main/java/com/baidu/hugegraph/auth/WsAndHttpBasicAuthHandler.java b/hugegraph-api/src/main/java/com/baidu/hugegraph/auth/WsAndHttpBasicAuthHandler.java index 60a3b772cf..c52d652e2a 100644 --- a/hugegraph-api/src/main/java/com/baidu/hugegraph/auth/WsAndHttpBasicAuthHandler.java +++ b/hugegraph-api/src/main/java/com/baidu/hugegraph/auth/WsAndHttpBasicAuthHandler.java @@ -19,24 +19,6 @@ package com.baidu.hugegraph.auth; -import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION; -import static io.netty.handler.codec.http.HttpHeaderNames.UPGRADE; -import static io.netty.handler.codec.http.HttpResponseStatus.UNAUTHORIZED; -import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; -import static org.apache.tinkerpop.gremlin.groovy.jsr223.dsl.credential.CredentialGraphTokens.PROPERTY_PASSWORD; -import static org.apache.tinkerpop.gremlin.groovy.jsr223.dsl.credential.CredentialGraphTokens.PROPERTY_USERNAME; - -import java.nio.charset.Charset; -import java.util.Base64; -import java.util.HashMap; -import java.util.Map; - -import org.apache.tinkerpop.gremlin.server.Settings; -import org.apache.tinkerpop.gremlin.server.auth.AuthenticationException; -import org.apache.tinkerpop.gremlin.server.auth.Authenticator; -import org.apache.tinkerpop.gremlin.server.handler.AbstractAuthenticationHandler; -import org.apache.tinkerpop.gremlin.server.handler.SaslAuthenticationHandler; - import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; @@ -45,6 +27,23 @@ import io.netty.handler.codec.http.FullHttpMessage; import io.netty.handler.codec.http.HttpMessage; import io.netty.util.ReferenceCountUtil; +import org.apache.tinkerpop.gremlin.server.Settings; +import org.apache.tinkerpop.gremlin.server.auth.AuthenticationException; +import org.apache.tinkerpop.gremlin.server.auth.Authenticator; +import org.apache.tinkerpop.gremlin.server.handler.AbstractAuthenticationHandler; +import org.apache.tinkerpop.gremlin.server.handler.SaslAuthenticationHandler; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.HashMap; +import java.util.Map; + +import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION; +import static io.netty.handler.codec.http.HttpHeaderNames.UPGRADE; +import static io.netty.handler.codec.http.HttpResponseStatus.UNAUTHORIZED; +import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; +import static org.apache.tinkerpop.gremlin.groovy.jsr223.dsl.credential.CredentialGraphTokens.PROPERTY_PASSWORD; +import static org.apache.tinkerpop.gremlin.groovy.jsr223.dsl.credential.CredentialGraphTokens.PROPERTY_USERNAME; /** * An Authentication Handler for doing WebSocket and Http Basic auth @@ -114,19 +113,16 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) { sendError(ctx, msg); return; } - byte[] userPass = null; + byte[] userPass; try { final String encoded = header.substring(basic.length()); userPass = this.decoder.decode(encoded); - } catch (IndexOutOfBoundsException iae) { - sendError(ctx, msg); - return; - } catch (IllegalArgumentException iae) { + } catch (IndexOutOfBoundsException | IllegalArgumentException iae) { sendError(ctx, msg); return; } String authorization = new String(userPass, - Charset.forName("UTF-8")); + StandardCharsets.UTF_8); String[] split = authorization.split(":"); if (split.length != 2) { sendError(ctx, msg); @@ -155,7 +151,7 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) { private void sendError(ChannelHandlerContext ctx, Object msg) { // Close the connection as soon as the error message is sent. ctx.writeAndFlush(new DefaultFullHttpResponse(HTTP_1_1, UNAUTHORIZED)) - .addListener(ChannelFutureListener.CLOSE); + .addListener(ChannelFutureListener.CLOSE); ReferenceCountUtil.release(msg); } } diff --git a/hugegraph-api/src/main/java/com/baidu/hugegraph/license/LicenseVerifier.java b/hugegraph-api/src/main/java/com/baidu/hugegraph/license/LicenseVerifier.java index c48ca93bf2..e9fd7cebe9 100644 --- a/hugegraph-api/src/main/java/com/baidu/hugegraph/license/LicenseVerifier.java +++ b/hugegraph-api/src/main/java/com/baidu/hugegraph/license/LicenseVerifier.java @@ -55,7 +55,7 @@ private LicenseVerifier() { public static LicenseVerifier instance() { if (INSTANCE == null) { - synchronized(LicenseVerifier.class) { + synchronized (LicenseVerifier.class) { if (INSTANCE == null) { INSTANCE = new LicenseVerifier(); } diff --git a/hugegraph-api/src/main/java/com/baidu/hugegraph/metrics/MetricsUtil.java b/hugegraph-api/src/main/java/com/baidu/hugegraph/metrics/MetricsUtil.java index 576af23a88..e582d12410 100644 --- a/hugegraph-api/src/main/java/com/baidu/hugegraph/metrics/MetricsUtil.java +++ b/hugegraph-api/src/main/java/com/baidu/hugegraph/metrics/MetricsUtil.java @@ -30,27 +30,27 @@ public class MetricsUtil { - private static final MetricRegistry registry = + private static final MetricRegistry METRIC_REGISTRY = MetricManager.INSTANCE.getRegistry(); public static Gauge registerGauge(Class clazz, String name, Gauge gauge) { - return registry.register(MetricRegistry.name(clazz, name), gauge); + return METRIC_REGISTRY.register(MetricRegistry.name(clazz, name), gauge); } public static Counter registerCounter(Class clazz, String name) { - return registry.counter(MetricRegistry.name(clazz, name)); + return METRIC_REGISTRY.counter(MetricRegistry.name(clazz, name)); } public static Histogram registerHistogram(Class clazz, String name) { - return registry.histogram(MetricRegistry.name(clazz, name)); + return METRIC_REGISTRY.histogram(MetricRegistry.name(clazz, name)); } public static Meter registerMeter(Class clazz, String name) { - return registry.meter(MetricRegistry.name(clazz, name)); + return METRIC_REGISTRY.meter(MetricRegistry.name(clazz, name)); } public static Timer registerTimer(Class clazz, String name) { - return registry.timer(MetricRegistry.name(clazz, name)); + return METRIC_REGISTRY.timer(MetricRegistry.name(clazz, name)); } } diff --git a/hugegraph-api/src/main/java/com/baidu/hugegraph/server/ApplicationConfig.java b/hugegraph-api/src/main/java/com/baidu/hugegraph/server/ApplicationConfig.java index 69949009a8..09c1eabe54 100644 --- a/hugegraph-api/src/main/java/com/baidu/hugegraph/server/ApplicationConfig.java +++ b/hugegraph-api/src/main/java/com/baidu/hugegraph/server/ApplicationConfig.java @@ -71,7 +71,7 @@ public ApplicationConfig(HugeConfig conf, EventHub hub) { private class ConfFactory extends AbstractBinder implements Factory { - private HugeConfig conf = null; + private HugeConfig conf; public ConfFactory(HugeConfig conf) { E.checkNotNull(conf, "configuration"); @@ -101,16 +101,11 @@ private class GraphManagerFactory extends AbstractBinder public GraphManagerFactory(HugeConfig conf, EventHub hub) { register(new ApplicationEventListener() { - private final ApplicationEvent.Type EVENT_INITED = - ApplicationEvent.Type.INITIALIZATION_FINISHED; - private final ApplicationEvent.Type EVENT_DESTROYED = - ApplicationEvent.Type.DESTROY_FINISHED; - @Override public void onEvent(ApplicationEvent event) { - if (event.getType() == this.EVENT_INITED) { + if (event.getType() == ApplicationEvent.Type.INITIALIZATION_FINISHED) { GraphManagerFactory.this.manager = new GraphManager(conf, hub); - } else if (event.getType() == this.EVENT_DESTROYED) { + } else if (event.getType() == ApplicationEvent.Type.DESTROY_FINISHED) { if (GraphManagerFactory.this.manager != null) { GraphManagerFactory.this.manager.close(); }