com.baidu.hugegraph.util.JsonUtil Java Examples

The following examples show how to use com.baidu.hugegraph.util.JsonUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: VertexAPI.java    From hugegraph with Apache License 2.0 6 votes vote down vote up
public static Id checkAndParseVertexId(String idValue) {
    if (idValue == null) {
        return null;
    }
    boolean uuid = idValue.startsWith("U\"");
    if (uuid) {
        idValue = idValue.substring(1);
    }
    try {
        Object id = JsonUtil.fromJson(idValue, Object.class);
        return uuid ? Text.uuid((String) id) : HugeVertex.getIdValue(id);
    } catch (Exception e) {
        throw new IllegalArgumentException(String.format(
                  "The vertex id must be formatted as Number/String/UUID" +
                  ", but got '%s'", idValue));
    }
}
 
Example #2
Source File: JsonUtilTest.java    From hugegraph with Apache License 2.0 6 votes vote down vote up
@Test
public void testSerializeVertexLabel() {
    FakeObjects fakeObject = new FakeObjects();
    PropertyKey name = fakeObject.newPropertyKey(IdGenerator.of(1), "name");
    PropertyKey age = fakeObject.newPropertyKey(IdGenerator.of(2), "age",
                                                 DataType.INT,
                                                 Cardinality.SINGLE);
    PropertyKey city = fakeObject.newPropertyKey(IdGenerator.of(3), "city");

    VertexLabel vl = fakeObject.newVertexLabel(IdGenerator.of(1), "person",
                                               IdStrategy.CUSTOMIZE_NUMBER,
                                               name.id(), age.id(),
                                               city.id());
    Mockito.when(fakeObject.graph().mapPkId2Name(vl.properties()))
           .thenReturn(Arrays.asList(name.name(), age.name(), city.name()));

    String json = JsonUtil.toJson(vl);
    Assert.assertEquals("{\"id\":1,\"name\":\"person\"," +
                        "\"id_strategy\":\"CUSTOMIZE_NUMBER\"," +
                        "\"primary_keys\":[],\"nullable_keys\":[]," +
                        "\"index_labels\":[]," +
                        "\"properties\":[\"name\",\"age\",\"city\"]," +
                        "\"status\":\"CREATED\"," +
                        "\"ttl\":0,\"enable_label_index\":true," +
                        "\"user_data\":{}}", json);
}
 
Example #3
Source File: JsonUtilTest.java    From hugegraph with Apache License 2.0 6 votes vote down vote up
@Test
public void testSerializePropertyKey() {
    FakeObjects fakeObject = new FakeObjects();
    PropertyKey name = fakeObject.newPropertyKey(IdGenerator.of(1), "name");
    String json = JsonUtil.toJson(name);
    Assert.assertEquals("{\"id\":1,\"name\":\"name\"," +
                        "\"data_type\":\"TEXT\"," +
                        "\"cardinality\":\"SINGLE\"," +
                        "\"aggregate_type\":\"NONE\"," +
                        "\"properties\":[],\"status\":\"CREATED\"," +
                        "\"user_data\":{}}", json);

    PropertyKey rate = fakeObject.newPropertyKey(IdGenerator.of(2), "rate",
                                                 DataType.INT,
                                                 Cardinality.LIST);
    json = JsonUtil.toJson(rate);
    Assert.assertEquals("{\"id\":2,\"name\":\"rate\"," +
                        "\"data_type\":\"INT\",\"cardinality\":\"LIST\"," +
                        "\"aggregate_type\":\"NONE\",\"properties\":[]," +
                        "\"status\":\"CREATED\",\"user_data\":{}}", json);
}
 
Example #4
Source File: TextSerializer.java    From hugegraph with Apache License 2.0 6 votes vote down vote up
@Override
public BackendEntry writeIndex(HugeIndex index) {
    TextBackendEntry entry = newBackendEntry(index.type(), index.id());
    if (index.fieldValues() == null && index.elementIds().size() == 0) {
        /*
         * When field-values is null and elementIds size is 0, it is
         * meaningful for deletion of index data in secondary/range index.
         */
        entry.column(HugeKeys.INDEX_LABEL_ID,
                     writeId(index.indexLabelId()));
    } else {
        // TODO: field-values may be a number (range index)
        entry.column(formatSyspropName(HugeKeys.FIELD_VALUES),
                     JsonUtil.toJson(index.fieldValues()));
        entry.column(formatSyspropName(HugeKeys.INDEX_LABEL_ID),
                     writeId(index.indexLabelId()));
        entry.column(formatSyspropName(HugeKeys.ELEMENT_IDS),
                     writeElementId(index.elementId(), index.expiredTime()));
        entry.subId(index.elementId());
    }
    return entry;
}
 
Example #5
Source File: JaccardSimilarityAPI.java    From hugegraph with Apache License 2.0 6 votes vote down vote up
@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_DEGREE) long degree) {
    LOG.debug("Graph [{}] get jaccard similarity between '{}' and '{}' " +
              "with direction {}, edge label {} and max degree '{}'",
              graph, vertex, other, direction, edgeLabel, degree);

    Id sourceId = VertexAPI.checkAndParseVertexId(vertex);
    Id targetId = VertexAPI.checkAndParseVertexId(other);
    Directions dir = Directions.convert(EdgeAPI.parseDirection(direction));

    HugeGraph g = graph(manager, graph);
    HugeTraverser traverser = new HugeTraverser(g);
    double similarity = traverser.jaccardSimilarity(sourceId, targetId, dir,
                                                    edgeLabel, degree);
    return JsonUtil.toJson(ImmutableMap.of("jaccard_similarity",
                                           similarity));
}
 
Example #6
Source File: TraversalUtil.java    From hugegraph with Apache License 2.0 6 votes vote down vote up
private static Number predicateNumber(String value) {
    try {
        return JsonUtil.fromJson(value, Number.class);
    } catch (Exception e) {
        // Try to parse date
        if (e.getMessage().contains("not a valid number") ||
            e.getMessage().contains("Unexpected character ('-'")) {
            try {
                if (value.startsWith("\"")) {
                    value = JsonUtil.fromJson(value, String.class);
                }
                return DateUtil.parse(value).getTime();
            } catch (Exception ignored) {}
        }

        throw new HugeException(
                  "Invalid value '%s', expect a number", e, value);
    }
}
 
Example #7
Source File: GremlinAPI.java    From hugegraph with Apache License 2.0 6 votes vote down vote up
public static GremlinRequest fromJson(String json) {
    @SuppressWarnings("unchecked")
    Map<String, Object> map = JsonUtil.fromJson(json, Map.class);
    String gremlin = (String) map.get("gremlin");
    @SuppressWarnings("unchecked")
    Map<String, Object> bindings = (Map<String, Object>)
                                   map.get("bindings");
    String language = (String) map.get("language");
    @SuppressWarnings("unchecked")
    Map<String, String> aliases = (Map<String, String>)
                                  map.get("aliases");

    GremlinRequest request = new GremlinRequest();
    request.gremlin(gremlin);
    request.bindings(bindings);
    request.language(language);
    request.aliases(aliases);
    return request;
}
 
Example #8
Source File: TextSerializer.java    From hugegraph with Apache License 2.0 6 votes vote down vote up
@Override
public BackendEntry writeVertexLabel(VertexLabel vertexLabel) {
    TextBackendEntry entry = newBackendEntry(vertexLabel);
    entry.column(HugeKeys.NAME, JsonUtil.toJson(vertexLabel.name()));
    entry.column(HugeKeys.ID_STRATEGY,
                 JsonUtil.toJson(vertexLabel.idStrategy()));
    entry.column(HugeKeys.PROPERTIES,
                 writeIds(vertexLabel.properties()));
    entry.column(HugeKeys.PRIMARY_KEYS,
                 writeIds(vertexLabel.primaryKeys()));
    entry.column(HugeKeys.NULLABLE_KEYS,
                 writeIds(vertexLabel.nullableKeys()));
    entry.column(HugeKeys.INDEX_LABELS,
                 writeIds(vertexLabel.indexLabels()));
    entry.column(HugeKeys.ENABLE_LABEL_INDEX,
                 JsonUtil.toJson(vertexLabel.enableLabelIndex()));
    writeUserdata(vertexLabel, entry);
    entry.column(HugeKeys.STATUS,
                 JsonUtil.toJson(vertexLabel.status()));
    return entry;
}
 
Example #9
Source File: MetricsAPI.java    From hugegraph with Apache License 2.0 6 votes vote down vote up
@GET
@Timed
@Path("backend")
@Produces(APPLICATION_JSON_WITH_CHARSET)
@RolesAllowed("admin")
public String backend(@Context GraphManager manager) {
    Map<String, Map<String, Object>> results = InsertionOrderUtil.newMap();
    for (String graph : manager.graphs()) {
        HugeGraph g = manager.graph(graph);
        Map<String, Object> metrics = InsertionOrderUtil.newMap();
        metrics.put(BackendMetrics.BACKEND, g.backend());
        try {
            metrics.putAll(g.metadata(null, "metrics"));
        } catch (Throwable e) {
            metrics.put(BackendMetrics.EXCEPTION, e.toString());
            LOG.debug("Failed to get backend metrics", e);
        }
        results.put(graph, metrics);
    }
    return JsonUtil.toJson(results);
}
 
Example #10
Source File: JsonSerializer.java    From hugegraph with Apache License 2.0 6 votes vote down vote up
@Override
public String writePaths(String name, Collection<HugeTraverser.Path> paths,
                         boolean withCrossPoint,
                         Iterator<Vertex> vertices) {
    List<Map<String, Object>> pathList = new ArrayList<>(paths.size());
    for (HugeTraverser.Path path : paths) {
        pathList.add(path.toMap(withCrossPoint));
    }

    Map<String, Object> results;
    if (vertices == null) {
        results = ImmutableMap.of(name, pathList);
    } else {
        results = ImmutableMap.of(name, pathList, "vertices", vertices);
    }
    return JsonUtil.toJson(results);
}
 
Example #11
Source File: TextSerializer.java    From hugegraph with Apache License 2.0 6 votes vote down vote up
@Override
public BackendEntry writeEdgeLabel(EdgeLabel edgeLabel) {
    TextBackendEntry entry = newBackendEntry(edgeLabel);
    entry.column(HugeKeys.NAME, JsonUtil.toJson(edgeLabel.name()));
    entry.column(HugeKeys.SOURCE_LABEL, writeId(edgeLabel.sourceLabel()));
    entry.column(HugeKeys.TARGET_LABEL, writeId(edgeLabel.targetLabel()));
    entry.column(HugeKeys.FREQUENCY,
                 JsonUtil.toJson(edgeLabel.frequency()));
    entry.column(HugeKeys.PROPERTIES, writeIds(edgeLabel.properties()));
    entry.column(HugeKeys.SORT_KEYS, writeIds(edgeLabel.sortKeys()));
    entry.column(HugeKeys.NULLABLE_KEYS,
                 writeIds(edgeLabel.nullableKeys()));
    entry.column(HugeKeys.INDEX_LABELS, writeIds(edgeLabel.indexLabels()));
    entry.column(HugeKeys.ENABLE_LABEL_INDEX,
                 JsonUtil.toJson(edgeLabel.enableLabelIndex()));
    writeUserdata(edgeLabel, entry);
    entry.column(HugeKeys.STATUS,
                 JsonUtil.toJson(edgeLabel.status()));
    entry.column(HugeKeys.TTL, JsonUtil.toJson(edgeLabel.ttl()));
    entry.column(HugeKeys.TTL_START_TIME,
                 writeId(edgeLabel.ttlStartTime()));
    return entry;
}
 
Example #12
Source File: HugeTarget.java    From hugegraph with Apache License 2.0 6 votes vote down vote up
@Override
protected Object[] asArray() {
    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);
}
 
Example #13
Source File: TextSerializer.java    From hugegraph with Apache License 2.0 6 votes vote down vote up
@Override
public BackendEntry writePropertyKey(PropertyKey propertyKey) {
    TextBackendEntry entry = newBackendEntry(propertyKey);
    entry.column(HugeKeys.NAME, JsonUtil.toJson(propertyKey.name()));
    entry.column(HugeKeys.DATA_TYPE,
                 JsonUtil.toJson(propertyKey.dataType()));
    entry.column(HugeKeys.CARDINALITY,
                 JsonUtil.toJson(propertyKey.cardinality()));
    entry.column(HugeKeys.AGGREGATE_TYPE,
                 JsonUtil.toJson(propertyKey.aggregateType()));
    entry.column(HugeKeys.PROPERTIES, writeIds(propertyKey.properties()));
    writeUserdata(propertyKey, entry);
    entry.column(HugeKeys.STATUS,
                 JsonUtil.toJson(propertyKey.status()));
    return entry;
}
 
Example #14
Source File: JsonSerializer.java    From hugegraph with Apache License 2.0 6 votes vote down vote up
@Override
public String writeCrosspoints(CrosspointsPaths paths,
                               Iterator<Vertex> iterator,
                               boolean withPath) {
    Map<String, Object> results;
    List<Map<String, Object>> pathList;
    if (withPath) {
        pathList = new ArrayList<>();
        for (HugeTraverser.Path path : paths.paths()) {
            pathList.add(path.toMap(false));
        }
    } else {
        pathList = ImmutableList.of();
    }
    results = ImmutableMap.of("crosspoints", paths.crosspoints(),
                              "paths", pathList,
                              "vertices", iterator);
    return JsonUtil.toJson(results);
}
 
Example #15
Source File: MysqlSerializer.java    From hugegraph with Apache License 2.0 6 votes vote down vote up
@Override
protected void parseProperties(HugeElement element,
                               TableBackendEntry.Row row) {
    String properties = row.column(HugeKeys.PROPERTIES);
    // Query edge will wraped by a vertex, whose properties is empty
    if (properties.isEmpty()) {
        return;
    }

    @SuppressWarnings("unchecked")
    Map<String, Object> props = JsonUtil.fromJson(properties, Map.class);
    for (Map.Entry<String, Object> prop : props.entrySet()) {
        /*
         * The key is string instead of int, because the key in json
         * must be string
         */
        Id pkeyId = this.toId(Long.valueOf(prop.getKey()));
        String colJson = JsonUtil.toJson(prop.getValue());
        this.parseProperty(pkeyId, colJson, element);
    }
}
 
Example #16
Source File: TextSerializer.java    From hugegraph with Apache License 2.0 6 votes vote down vote up
@Override
public IndexLabel readIndexLabel(HugeGraph graph,
                                 BackendEntry backendEntry) {
    if (backendEntry == null) {
        return null;
    }

    TextBackendEntry entry = this.convertEntry(backendEntry);
    Id id = readId(entry.id());
    String name = JsonUtil.fromJson(entry.column(HugeKeys.NAME),
                                    String.class);
    String baseType = entry.column(HugeKeys.BASE_TYPE);
    String baseValue = entry.column(HugeKeys.BASE_VALUE);
    String indexType = entry.column(HugeKeys.INDEX_TYPE);
    String indexFields = entry.column(HugeKeys.FIELDS);
    String status = entry.column(HugeKeys.STATUS);

    IndexLabel indexLabel = new IndexLabel(graph, id, name);
    indexLabel.baseType(JsonUtil.fromJson(baseType, HugeType.class));
    indexLabel.baseValue(readId(baseValue));
    indexLabel.indexType(JsonUtil.fromJson(indexType, IndexType.class));
    indexLabel.indexFields(readIds(indexFields));
    readUserdata(indexLabel, entry);
    indexLabel.status(JsonUtil.fromJson(status, SchemaStatus.class));
    return indexLabel;
}
 
Example #17
Source File: IndexLabelTest.java    From hugegraph-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testIndexLabelV49() {
    IndexLabel.Builder builder = new IndexLabel.BuilderImpl("personByAge",
                                                            null);
    IndexLabel indexLabel = builder.onV("person")
                                   .secondary()
                                   .by("age")
                                   .build();

    IndexLabel.IndexLabelV49 indexLabelV49 = indexLabel.switchV49();
    // Without userdata
    String json = "{\"id\":0,\"name\":\"personByAge\"," +
                  "\"check_exist\":true,\"base_type\":\"VERTEX_LABEL\"," +
                  "\"base_value\":\"person\"," +
                  "\"index_type\":\"SECONDARY\",\"fields\":[\"age\"]}";
    Assert.assertEquals(json, JsonUtil.toJson(indexLabelV49));
    Assert.assertEquals(HugeType.INDEX_LABEL.string(),
                        indexLabelV49.type());

    Assert.assertThrows(NotSupportException.class, () -> {
        indexLabelV49.userdata();
    });
}
 
Example #18
Source File: IndexLabelTest.java    From hugegraph-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testIndexLabel() {
    IndexLabel.Builder builder = new IndexLabel.BuilderImpl("personByAge",
                                                            null);
    IndexLabel indexLabel = builder.onV("person")
                                   .secondary()
                                   .by("age")
                                   .build();

    String json = "{\"name\":\"personByAge\",\"id\":0," +
                  "\"check_exist\":true,\"user_data\":{}," +
                  "\"base_type\":\"VERTEX_LABEL\"," +
                  "\"base_value\":\"person\"," +
                  "\"index_type\":\"SECONDARY\",\"fields\":[\"age\"]}";
    Assert.assertEquals(json, JsonUtil.toJson(indexLabel));
    Assert.assertEquals(HugeType.INDEX_LABEL.string(), indexLabel.type());
}
 
Example #19
Source File: API.java    From hugegraph with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected static Map<String, Object> parseProperties(String properties) {
    if (properties == null || properties.isEmpty()) {
        return ImmutableMap.of();
    }

    Map<String, Object> props = null;
    try {
        props = JsonUtil.fromJson(properties, Map.class);
    } catch (Exception ignored) {}

    // If properties is the string "null", props will be null
    E.checkArgument(props != null,
                    "Invalid request with properties: %s", properties);
    return props;
}
 
Example #20
Source File: GraphAPI.java    From hugegraph-client with Apache License 2.0 6 votes vote down vote up
public static String formatVertexId(Object id, boolean allowNull) {
    if (!allowNull) {
        E.checkArgumentNotNull(id, "The vertex id can't be null");
    } else {
        if (id == null) {
            return null;
        }
    }
    boolean uuid = id instanceof UUID;
    if (uuid) {
        id = id.toString();
    }
    E.checkArgument(id instanceof String || id instanceof Number,
                    "The vertex id must be either String or " +
                    "Number, but got '%s'", id);
    return (uuid ? "U" : "") + JsonUtil.toJson(id);
}
 
Example #21
Source File: MetricsAPI.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
@GET
@Timed
@Path("timers")
@Produces(APPLICATION_JSON_WITH_CHARSET)
@RolesAllowed("admin")
public String timers() {
    ServerReporter reporter = ServerReporter.instance();
    return JsonUtil.toJson(reporter.timers());
}
 
Example #22
Source File: MetricsAPI.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
@GET
@Timed
@Path("meters")
@Produces(APPLICATION_JSON_WITH_CHARSET)
@RolesAllowed("admin")
public String meters() {
    ServerReporter reporter = ServerReporter.instance();
    return JsonUtil.toJson(reporter.meters());
}
 
Example #23
Source File: MetricsAPI.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
@GET
@Timed
@Path("histograms")
@Produces(APPLICATION_JSON_WITH_CHARSET)
@RolesAllowed("admin")
public String histograms() {
    ServerReporter reporter = ServerReporter.instance();
    return JsonUtil.toJson(reporter.histograms());
}
 
Example #24
Source File: TextSerializer.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
private static String writeElementId(Id id, long expiredTime) {
    Object[] array = new Object[1];
    Object idValue = id.number() ? id.asLong() : id.asString();
    if (expiredTime <= 0L) {
        array[0] = id;
    } else {
        array[0] = ImmutableMap.of(HugeKeys.ID.string(), idValue,
                                   HugeKeys.EXPIRED_TIME.string(),
                                   expiredTime);
    }
    return JsonUtil.toJson(array);
}
 
Example #25
Source File: JsonUtilTest.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
@Test
public void testSerializeEdgeId() {
    Id id = new EdgeId(IdGenerator.of("1:marko"), Directions.OUT,
                       IdGenerator.of(1), "",
                       IdGenerator.of("1:josh"));
    String json = JsonUtil.toJson(id);
    Assert.assertEquals("\"S1:marko>1>>S1:josh\"", json);
}
 
Example #26
Source File: JsonUtilTest.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
@Test
public void testSerializeUuidId() {
    UUID uuid = UUID.randomUUID();
    Id id = IdGenerator.of(uuid);
    String json = JsonUtil.toJson(id);
    Assert.assertEquals("\"" + uuid + "\"", json);
}
 
Example #27
Source File: TextSerializer.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
private static String writeId(Id id) {
    if (id.number()) {
        return JsonUtil.toJson(id.asLong());
    } else {
        return JsonUtil.toJson(id.asString());
    }
}
 
Example #28
Source File: MysqlEntryIterator.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
public static PagePosition fromBytes(byte[] bytes) {
    String json = StringEncoding.decode(bytes);
    @SuppressWarnings("unchecked")
    Map<String, Object> columns = JsonUtil.fromJson(json, Map.class);
    Map<HugeKeys, Object> keyColumns = new LinkedHashMap<>();
    for (Map.Entry<String, Object> entry : columns.entrySet()) {
        HugeKeys key = MysqlTable.parseKey(entry.getKey());
        keyColumns.put(key, entry.getValue());
    }
    return new PagePosition(keyColumns);
}
 
Example #29
Source File: MysqlSerializer.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
@Override
protected Object toLongList(Collection<Id> ids) {
    long[] values = new long[ids.size()];
    int i = 0;
    for (Id id : ids) {
        values[i++] = id.asLong();
    }
    return JsonUtil.toJson(values);
}
 
Example #30
Source File: MysqlSerializer.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
@Override
protected void formatProperties(HugeElement element,
                                TableBackendEntry.Row row) {
    Map<Number, Object> properties = new HashMap<>();
    // Add all properties of a Vertex
    for (HugeProperty<?> prop : element.getProperties().values()) {
        Number key = prop.propertyKey().id().asLong();
        Object val = prop.value();
        properties.put(key, val);
    }
    row.column(HugeKeys.PROPERTIES, JsonUtil.toJson(properties));
}