From f6bcd1b80a758e9dd5e52af1ec6dd24c5ae45a31 Mon Sep 17 00:00:00 2001 From: Simon Brandhof Date: Fri, 25 Jan 2013 18:00:45 +0100 Subject: SONAR-4087 fix compatibility of Tinkerpop Blueprints with Java 5 --- .../java/org/sonar/core/component/GraphReader.java | 8 +- .../java/org/sonar/core/graph/GraphSONReader.java | 135 --- .../java/org/sonar/core/graph/GraphSONUtility.java | 702 ------------ .../java/org/sonar/core/graph/GraphSONWriter.java | 129 --- .../java/org/sonar/core/graph/GraphWriter.java | 5 +- .../sonar/core/graph/graphson/ElementFactory.java | 47 + .../core/graph/graphson/ElementPropertyConfig.java | 87 ++ .../sonar/core/graph/graphson/GraphSONMode.java | 45 + .../sonar/core/graph/graphson/GraphSONReader.java | 81 ++ .../sonar/core/graph/graphson/GraphSONTokens.java | 49 + .../sonar/core/graph/graphson/GraphSONWriter.java | 79 ++ .../core/graph/graphson/GraphSonException.java | 30 + .../sonar/core/graph/graphson/GraphsonUtil.java | 698 ++++++++++++ .../org/sonar/core/graph/GraphSONReaderTest.java | 343 ------ .../org/sonar/core/graph/GraphSONUtilityTest.java | 1156 -------------------- .../org/sonar/core/graph/GraphSONWriterTest.java | 136 --- .../core/graph/graphson/GraphsonReaderTest.java | 339 ++++++ .../core/graph/graphson/GraphsonUtilTest.java | 1151 +++++++++++++++++++ .../core/graph/graphson/GraphsonWriterTest.java | 133 +++ 19 files changed, 2744 insertions(+), 2609 deletions(-) delete mode 100644 sonar-core/src/main/java/org/sonar/core/graph/GraphSONReader.java delete mode 100644 sonar-core/src/main/java/org/sonar/core/graph/GraphSONUtility.java delete mode 100644 sonar-core/src/main/java/org/sonar/core/graph/GraphSONWriter.java create mode 100644 sonar-core/src/main/java/org/sonar/core/graph/graphson/ElementFactory.java create mode 100644 sonar-core/src/main/java/org/sonar/core/graph/graphson/ElementPropertyConfig.java create mode 100644 sonar-core/src/main/java/org/sonar/core/graph/graphson/GraphSONMode.java create mode 100644 sonar-core/src/main/java/org/sonar/core/graph/graphson/GraphSONReader.java create mode 100644 sonar-core/src/main/java/org/sonar/core/graph/graphson/GraphSONTokens.java create mode 100644 sonar-core/src/main/java/org/sonar/core/graph/graphson/GraphSONWriter.java create mode 100644 sonar-core/src/main/java/org/sonar/core/graph/graphson/GraphSonException.java create mode 100644 sonar-core/src/main/java/org/sonar/core/graph/graphson/GraphsonUtil.java delete mode 100644 sonar-core/src/test/java/org/sonar/core/graph/GraphSONReaderTest.java delete mode 100644 sonar-core/src/test/java/org/sonar/core/graph/GraphSONUtilityTest.java delete mode 100644 sonar-core/src/test/java/org/sonar/core/graph/GraphSONWriterTest.java create mode 100644 sonar-core/src/test/java/org/sonar/core/graph/graphson/GraphsonReaderTest.java create mode 100644 sonar-core/src/test/java/org/sonar/core/graph/graphson/GraphsonUtilTest.java create mode 100644 sonar-core/src/test/java/org/sonar/core/graph/graphson/GraphsonWriterTest.java (limited to 'sonar-core') diff --git a/sonar-core/src/main/java/org/sonar/core/component/GraphReader.java b/sonar-core/src/main/java/org/sonar/core/component/GraphReader.java index 5a7722e9db0..965d3316b0f 100644 --- a/sonar-core/src/main/java/org/sonar/core/component/GraphReader.java +++ b/sonar-core/src/main/java/org/sonar/core/component/GraphReader.java @@ -21,11 +21,9 @@ package org.sonar.core.component; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.impls.tg.TinkerGraph; -import org.json.simple.parser.ParseException; -import org.sonar.core.graph.GraphSONReader; +import com.tinkerpop.blueprints.util.io.graphson.GraphSONReader; import java.io.ByteArrayInputStream; -import java.io.IOException; public class GraphReader { @@ -36,9 +34,7 @@ public class GraphReader { GraphSONReader.inputGraph(graph, input); Vertex root = graph.getVertex(rootVertexId); return new ComponentGraph(graph, root); - } catch (IOException e) { - throw new IllegalStateException(e); - } catch (ParseException e) { + } catch (Exception e) { throw new IllegalStateException(e); } } diff --git a/sonar-core/src/main/java/org/sonar/core/graph/GraphSONReader.java b/sonar-core/src/main/java/org/sonar/core/graph/GraphSONReader.java deleted file mode 100644 index 6216f00aa5f..00000000000 --- a/sonar-core/src/main/java/org/sonar/core/graph/GraphSONReader.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Sonar, open source software quality management tool. - * Copyright (C) 2008-2012 SonarSource - * mailto:contact AT sonarsource DOT com - * - * Sonar is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * Sonar is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with Sonar; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ - -package org.sonar.core.graph; - -import com.tinkerpop.blueprints.Graph; -import com.tinkerpop.blueprints.Vertex; -import com.tinkerpop.blueprints.util.io.graphson.ElementFactory; -import com.tinkerpop.blueprints.util.io.graphson.GraphElementFactory; -import com.tinkerpop.blueprints.util.io.graphson.GraphSONMode; -import com.tinkerpop.blueprints.util.io.graphson.GraphSONTokens; -import com.tinkerpop.blueprints.util.wrappers.batch.BatchGraph; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; - -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.Set; - -/** - * GraphSONReader reads the data from a TinkerPop JSON stream to a graph. - * - * @author Stephen Mallette (http://stephen.genoprime.com) - */ -public class GraphSONReader { - - private final Graph graph; - - /** - * @param graph the graph to populate with the JSON data - */ - public GraphSONReader(final Graph graph) { - this.graph = graph; - } - - /** - * Input the JSON stream data into the graph. - * In practice, usually the provided graph is empty. - * - * @param graph the graph to populate with the JSON data - * @param jsonInputStream an InputStream of JSON data - * @throws java.io.IOException thrown when the JSON data is not correctly formatted - */ - public static void inputGraph(final Graph graph, final InputStream jsonInputStream) throws IOException, ParseException { - inputGraph(graph, jsonInputStream, 1000); - } - - public static void inputGraph(final Graph inputGraph, final InputStream jsonInputStream, int bufferSize) throws IOException, ParseException { - inputGraph(inputGraph, jsonInputStream, bufferSize, null, null); - } - - /** - * Input the JSON stream data into the graph. - * More control over how data is streamed is provided by this method. - * - * @param inputGraph the graph to populate with the JSON data - * @param jsonInputStream an InputStream of JSON data - * @param bufferSize the amount of elements to hold in memory before committing a transactions (only valid for TransactionalGraphs) - * @throws java.io.IOException thrown when the JSON data is not correctly formatted - */ - public static void inputGraph(final Graph inputGraph, final InputStream jsonInputStream, int bufferSize, - final Set edgePropertyKeys, final Set vertexPropertyKeys) throws ParseException, IOException { - - JSONParser parser = new JSONParser(); - JSONObject json = (JSONObject) parser.parse(new InputStreamReader(jsonInputStream)); - - // if this is a transactional graph then we're buffering - final BatchGraph graph = BatchGraph.wrap(inputGraph, bufferSize); - - final ElementFactory elementFactory = new GraphElementFactory(graph); - - final GraphSONMode mode = GraphSONMode.valueOf(json.get(GraphSONTokens.MODE).toString()); - GraphSONUtility graphson = new GraphSONUtility(mode, elementFactory, vertexPropertyKeys, edgePropertyKeys); - - JSONArray vertices = (JSONArray) json.get(GraphSONTokens.VERTICES); - for (Object vertice : vertices) { - graphson.vertexFromJson((JSONObject) vertice); - } - - JSONArray edges = (JSONArray) json.get(GraphSONTokens.EDGES); - for (Object edgeObject : edges) { - JSONObject edge = (JSONObject) edgeObject; - - final Vertex inV = graph.getVertex(edge.get(GraphSONTokens._IN_V)); - final Vertex outV = graph.getVertex(edge.get(GraphSONTokens._OUT_V)); - graphson.edgeFromJson(edge, outV, inV); - } - graph.shutdown(); - } - - /** - * Input the JSON stream data into the graph. - * In practice, usually the provided graph is empty. - * - * @param jsonInputStream an InputStream of JSON data - * @throws java.io.IOException thrown when the JSON data is not correctly formatted - */ - public void inputGraph(final InputStream jsonInputStream) throws IOException, ParseException { - GraphSONReader.inputGraph(this.graph, jsonInputStream, 1000); - } - - /** - * Input the JSON stream data into the graph. - * In practice, usually the provided graph is empty. - * - * @param jsonInputStream an InputStream of JSON data - * @param bufferSize the amount of elements to hold in memory before committing a transactions (only valid for TransactionalGraphs) - * @throws java.io.IOException thrown when the JSON data is not correctly formatted - */ - public void inputGraph(final InputStream jsonInputStream, int bufferSize) throws IOException, ParseException { - GraphSONReader.inputGraph(this.graph, jsonInputStream, bufferSize); - } - - -} diff --git a/sonar-core/src/main/java/org/sonar/core/graph/GraphSONUtility.java b/sonar-core/src/main/java/org/sonar/core/graph/GraphSONUtility.java deleted file mode 100644 index 5e521aefa8f..00000000000 --- a/sonar-core/src/main/java/org/sonar/core/graph/GraphSONUtility.java +++ /dev/null @@ -1,702 +0,0 @@ -/* - * Sonar, open source software quality management tool. - * Copyright (C) 2008-2012 SonarSource - * mailto:contact AT sonarsource DOT com - * - * Sonar is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * Sonar is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with Sonar; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ - -package org.sonar.core.graph; - -import com.tinkerpop.blueprints.Direction; -import com.tinkerpop.blueprints.Edge; -import com.tinkerpop.blueprints.Element; -import com.tinkerpop.blueprints.Vertex; -import com.tinkerpop.blueprints.util.io.graphson.ElementFactory; -import com.tinkerpop.blueprints.util.io.graphson.ElementPropertyConfig; -import com.tinkerpop.blueprints.util.io.graphson.GraphSONMode; -import com.tinkerpop.blueprints.util.io.graphson.GraphSONTokens; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; - -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import static com.tinkerpop.blueprints.util.io.graphson.ElementPropertyConfig.ElementPropertiesRule; - -/** - * Helps write individual graph elements to TinkerPop JSON format known as GraphSON. - * - * @author Stephen Mallette (http://stephen.genoprime.com) - */ -public final class GraphSONUtility { - - private final GraphSONMode mode; - private final Set vertexPropertyKeys; - private final Set edgePropertyKeys; - private final ElementFactory factory; - private final boolean hasEmbeddedTypes; - private final ElementPropertiesRule vertexPropertiesRule; - private final ElementPropertiesRule edgePropertiesRule; - private final boolean includeReservedVertexId; - private final boolean includeReservedEdgeId; - private final boolean includeReservedVertexType; - private final boolean includeReservedEdgeType; - private final boolean includeReservedEdgeLabel; - private final boolean includeReservedEdgeOutV; - private final boolean includeReservedEdgeInV; - private JSONParser parser = new JSONParser(); - - /** - * A GraphSONUtiltiy that includes all properties of vertices and edges. - */ - public GraphSONUtility(final GraphSONMode mode, final ElementFactory factory) { - this(mode, factory, ElementPropertyConfig.AllProperties); - } - - /** - * A GraphSONUtility that includes the specified properties. - */ - public GraphSONUtility(final GraphSONMode mode, final ElementFactory factory, - final Set vertexPropertyKeys, final Set edgePropertyKeys) { - this(mode, factory, ElementPropertyConfig.IncludeProperties(vertexPropertyKeys, edgePropertyKeys)); - } - - public GraphSONUtility(final GraphSONMode mode, final ElementFactory factory, - final ElementPropertyConfig config) { - this.vertexPropertyKeys = config.getVertexPropertyKeys(); - this.edgePropertyKeys = config.getEdgePropertyKeys(); - this.vertexPropertiesRule = config.getVertexPropertiesRule(); - this.edgePropertiesRule = config.getEdgePropertiesRule(); - - this.mode = mode; - this.factory = factory; - this.hasEmbeddedTypes = mode == GraphSONMode.EXTENDED; - - this.includeReservedVertexId = includeReservedKey(mode, GraphSONTokens._ID, vertexPropertyKeys, this.vertexPropertiesRule); - this.includeReservedEdgeId = includeReservedKey(mode, GraphSONTokens._ID, edgePropertyKeys, this.edgePropertiesRule); - this.includeReservedVertexType = includeReservedKey(mode, GraphSONTokens._TYPE, vertexPropertyKeys, this.vertexPropertiesRule); - this.includeReservedEdgeType = includeReservedKey(mode, GraphSONTokens._TYPE, edgePropertyKeys, this.edgePropertiesRule); - this.includeReservedEdgeLabel = includeReservedKey(mode, GraphSONTokens._LABEL, edgePropertyKeys, this.edgePropertiesRule); - this.includeReservedEdgeOutV = includeReservedKey(mode, GraphSONTokens._OUT_V, edgePropertyKeys, this.edgePropertiesRule); - this.includeReservedEdgeInV = includeReservedKey(mode, GraphSONTokens._IN_V, edgePropertyKeys, this.edgePropertiesRule); - } - - /** - * Creates a Jettison JSONObject from a graph element. - * - * @param element the graph element to convert to JSON. - * @param propertyKeys The property keys at the root of the element to serialize. If null, then all keys are serialized. - * @param mode the type of GraphSON to be generated. - */ - public static JSONObject jsonFromElement(final Element element, final Set propertyKeys, - final GraphSONMode mode) { - final GraphSONUtility graphson = element instanceof Edge ? new GraphSONUtility(mode, null, null, propertyKeys) - : new GraphSONUtility(mode, null, propertyKeys, null); - return graphson.jsonFromElement(element); - } - - /** - * Creates a Jackson ObjectNode from a graph element. - * - * @param element the graph element to convert to JSON. - * @param propertyKeys The property keys at the root of the element to serialize. If null, then all keys are serialized. - * @param mode The type of GraphSON to generate. - */ - public static JSONObject objectNodeFromElement(final Element element, final Set propertyKeys, final GraphSONMode mode) { - final GraphSONUtility graphson = element instanceof Edge ? new GraphSONUtility(mode, null, null, propertyKeys) - : new GraphSONUtility(mode, null, propertyKeys, null); - return graphson.objectNodeFromElement(element); - } - - /** - * Reads an individual Vertex from JSON. The vertex must match the accepted GraphSON format. - * - * @param json a single vertex in GraphSON format as Jettison JSONObject - * @param factory the factory responsible for constructing graph elements - * @param mode the mode of the GraphSON - * @param propertyKeys a list of keys to include on reading of element properties - */ - public static Vertex vertexFromJson(final JSONObject json, final ElementFactory factory, final GraphSONMode mode, - final Set propertyKeys) throws IOException { - final GraphSONUtility graphson = new GraphSONUtility(mode, factory, propertyKeys, null); - return graphson.vertexFromJson(json); - } - - /** - * Reads an individual Vertex from JSON. The vertex must match the accepted GraphSON format. - * - * @param json a single vertex in GraphSON format as a String. - * @param factory the factory responsible for constructing graph elements - * @param mode the mode of the GraphSON - * @param propertyKeys a list of keys to include on reading of element properties - */ - public static Vertex vertexFromJson(final String json, final ElementFactory factory, final GraphSONMode mode, - final Set propertyKeys) throws ParseException { - final GraphSONUtility graphson = new GraphSONUtility(mode, factory, propertyKeys, null); - return graphson.vertexFromJson(json); - } - - /** - * Reads an individual Vertex from JSON. The vertex must match the accepted GraphSON format. - * - * @param json a single vertex in GraphSON format as an InputStream. - * @param factory the factory responsible for constructing graph elements - * @param mode the mode of the GraphSON - * @param propertyKeys a list of keys to include on reading of element properties - */ - public static Vertex vertexFromJson(final InputStream json, final ElementFactory factory, final GraphSONMode mode, - final Set propertyKeys) throws IOException, ParseException { - final GraphSONUtility graphson = new GraphSONUtility(mode, factory, propertyKeys, null); - return graphson.vertexFromJson(json); - } - - private static boolean includeReservedKey(final GraphSONMode mode, final String key, - final Set propertyKeys, - final ElementPropertiesRule rule) { - // the key is always included in modes other than compact. if it is compact, then validate that the - // key is in the property key list - return mode != GraphSONMode.COMPACT || includeKey(key, propertyKeys, rule); - } - - private static boolean includeKey(final String key, final Set propertyKeys, - final ElementPropertiesRule rule) { - if (propertyKeys == null) { - // when null always include the key and shortcut this piece - return true; - } - - // default the key situation. if it's included then it should be explicitly defined in the - // property keys list to be included or the reverse otherwise - boolean keySituation = rule == ElementPropertiesRule.INCLUDE; - - switch (rule) { - case INCLUDE: - keySituation = propertyKeys.contains(key); - break; - case EXCLUDE: - keySituation = !propertyKeys.contains(key); - break; - } - - return keySituation; - } - - /** - * Reads an individual Edge from JSON. The edge must match the accepted GraphSON format. - * - * @param json a single edge in GraphSON format as a String - * @param factory the factory responsible for constructing graph elements - * @param mode the mode of the GraphSON - * @param propertyKeys a list of keys to include when reading of element properties - */ - public static Edge edgeFromJson(final String json, final Vertex out, final Vertex in, - final ElementFactory factory, final GraphSONMode mode, - final Set propertyKeys) throws IOException, ParseException { - final GraphSONUtility graphson = new GraphSONUtility(mode, factory, null, propertyKeys); - return graphson.edgeFromJson(json, out, in); - } - - /** - * Reads an individual Edge from JSON. The edge must match the accepted GraphSON format. - * - * @param json a single edge in GraphSON format as an InputStream - * @param factory the factory responsible for constructing graph elements - * @param mode the mode of the GraphSON - * @param propertyKeys a list of keys to include when reading of element properties - */ - public static Edge edgeFromJson(final InputStream json, final Vertex out, final Vertex in, - final ElementFactory factory, final GraphSONMode mode, - final Set propertyKeys) throws IOException, ParseException { - final GraphSONUtility graphson = new GraphSONUtility(mode, factory, null, propertyKeys); - return graphson.edgeFromJson(json, out, in); - } - - /** - * Reads an individual Edge from JSON. The edge must match the accepted GraphSON format. - * - * @param json a single edge in GraphSON format as a Jackson JsonNode - * @param factory the factory responsible for constructing graph elements - * @param mode the mode of the GraphSON - * @param propertyKeys a list of keys to include when reading of element properties - */ - public static Edge edgeFromJson(final JSONObject json, final Vertex out, final Vertex in, - final ElementFactory factory, final GraphSONMode mode, - final Set propertyKeys) throws IOException { - final GraphSONUtility graphson = new GraphSONUtility(mode, factory, null, propertyKeys); - return graphson.edgeFromJson(json, out, in); - } - - static Map readProperties(final JSONObject node, final boolean ignoreReservedKeys, final boolean hasEmbeddedTypes) { - final Map map = new HashMap(); - - for (Object objKey : node.keySet()) { - String key = (String) objKey; - Object value = node.get(key); - - if (!ignoreReservedKeys || !isReservedKey(key)) { - map.put(key, readProperty(value, hasEmbeddedTypes)); - } - } - - return map; - } - - private static boolean isReservedKey(final String key) { - return key.equals(GraphSONTokens._ID) || key.equals(GraphSONTokens._TYPE) || key.equals(GraphSONTokens._LABEL) - || key.equals(GraphSONTokens._OUT_V) || key.equals(GraphSONTokens._IN_V); - } - - private static JSONArray createJSONList(final List list, final Set propertyKeys, final boolean showTypes) { - JSONArray jsonList = new JSONArray(); - for (Object item : list) { - if (item instanceof Element) { - jsonList.add(objectNodeFromElement((Element) item, propertyKeys, - showTypes ? GraphSONMode.EXTENDED : GraphSONMode.NORMAL)); - } else if (item instanceof List) { - jsonList.add(createJSONList((List) item, propertyKeys, showTypes)); - } else if (item instanceof Map) { - jsonList.add(createJSONMap((Map) item, propertyKeys, showTypes)); - } else if (item != null && item.getClass().isArray()) { - jsonList.add(createJSONList(convertArrayToList(item), propertyKeys, showTypes)); - } else { - addObject(jsonList, item); - } - } - return jsonList; - } - - // - private static JSONObject createJSONMap(final Map map, final Set propertyKeys, final boolean showTypes) { - final JSONObject jsonMap = new JSONObject(); - for (Object key : map.keySet()) { - Object value = map.get(key); - if (value != null) { - if (value instanceof List) { - value = createJSONList((List) value, propertyKeys, showTypes); - } else if (value instanceof Map) { - value = createJSONMap((Map) value, propertyKeys, showTypes); - } else if (value instanceof Element) { - value = objectNodeFromElement((Element) value, propertyKeys, - showTypes ? GraphSONMode.EXTENDED : GraphSONMode.NORMAL); - } else if (value.getClass().isArray()) { - value = createJSONList(convertArrayToList(value), propertyKeys, showTypes); - } - } - - putObject(jsonMap, key.toString(), getValue(value, showTypes)); - } - return jsonMap; - - } - - private static Object readProperty(final Object node, final boolean hasEmbeddedTypes) { - Object propertyValue; - - if (hasEmbeddedTypes) { - JSONObject json = (JSONObject) node; - if (json.get(GraphSONTokens.TYPE).equals(GraphSONTokens.TYPE_UNKNOWN)) { - propertyValue = null; - } else if (json.get(GraphSONTokens.TYPE).equals(GraphSONTokens.TYPE_BOOLEAN)) { - propertyValue = json.get(GraphSONTokens.VALUE); - } else if (json.get(GraphSONTokens.TYPE).equals(GraphSONTokens.TYPE_FLOAT)) { - propertyValue = ((Double) json.get(GraphSONTokens.VALUE)).floatValue(); - } else if (json.get(GraphSONTokens.TYPE).equals(GraphSONTokens.TYPE_DOUBLE)) { - propertyValue = json.get(GraphSONTokens.VALUE); - } else if (json.get(GraphSONTokens.TYPE).equals(GraphSONTokens.TYPE_INTEGER)) { - propertyValue = ((Long) json.get(GraphSONTokens.VALUE)).intValue(); - } else if (json.get(GraphSONTokens.TYPE).equals(GraphSONTokens.TYPE_LONG)) { - propertyValue = json.get(GraphSONTokens.VALUE); - } else if (json.get(GraphSONTokens.TYPE).equals(GraphSONTokens.TYPE_STRING)) { - propertyValue = json.get(GraphSONTokens.VALUE); - } else if (json.get(GraphSONTokens.TYPE).equals(GraphSONTokens.TYPE_LIST)) { - propertyValue = readProperties(((JSONArray) json.get(GraphSONTokens.VALUE)).iterator(), hasEmbeddedTypes); - } else if (json.get(GraphSONTokens.TYPE).equals(GraphSONTokens.TYPE_MAP)) { - propertyValue = readProperties((JSONObject) json.get(GraphSONTokens.VALUE), false, hasEmbeddedTypes); - } else { - propertyValue = node.toString(); - } - } else { - if (node == null) { - propertyValue = null; - } else if (node instanceof Boolean) { - propertyValue = node; - } else if (node instanceof Double) { - propertyValue = node; - } else if (node instanceof Integer) { - propertyValue = node; - } else if (node instanceof Long) { - propertyValue = node; - } else if (node instanceof String) { - propertyValue = node; - } else if (node instanceof JSONArray) { - propertyValue = readProperties(((JSONArray) node).iterator(), hasEmbeddedTypes); - } else if (node instanceof JSONObject) { - propertyValue = readProperties((JSONObject) node, false, hasEmbeddedTypes); - } else { - propertyValue = node; - } - } - - return propertyValue; - } - - private static void putObject(final JSONObject jsonMap, final String key, final Object value) { - if (value == null) { - jsonMap.put(key, null); - } else if (value instanceof Boolean) { - jsonMap.put(key, value); - } else if (value instanceof Long) { - jsonMap.put(key, value); - } else if (value instanceof Integer) { - jsonMap.put(key, value); - } else if (value instanceof Float) { - jsonMap.put(key, value); - } else if (value instanceof Double) { - jsonMap.put(key, value); - } else if (value instanceof String) { - jsonMap.put(key, value); - } else if (value instanceof JSONObject) { - jsonMap.put(key, value); - } else if (value instanceof JSONArray) { - jsonMap.put(key, value); - } else { - jsonMap.put(key, value.toString()); - } - } - - private static List readProperties(final Iterator listOfNodes, final boolean hasEmbeddedTypes) { - final List array = new ArrayList(); - - while (listOfNodes.hasNext()) { - array.add(readProperty(listOfNodes.next(), hasEmbeddedTypes)); - } - - return array; - } - - private static void addObject(final JSONArray jsonList, final Object value) { - if (value == null) { - jsonList.add(null); - } else if (value instanceof Boolean) { - jsonList.add(value); - } else if (value instanceof Long) { - jsonList.add(value); - } else if (value instanceof Integer) { - jsonList.add(value); - } else if (value instanceof Float) { - jsonList.add(value); - } else if (value instanceof Double) { - jsonList.add(value); - } else if (value instanceof String) { - jsonList.add(value); - } else if (value instanceof JSONObject) { - jsonList.add(value); - } else if (value instanceof JSONArray) { - jsonList.add(value); - } else { - jsonList.add(value.toString()); - } - } - - private static Map createPropertyMap(final Element element, final Set propertyKeys, final ElementPropertiesRule rule) { - final Map map = new HashMap(); - - if (propertyKeys == null) { - for (String key : element.getPropertyKeys()) { - map.put(key, element.getProperty(key)); - } - } else { - if (rule == ElementPropertiesRule.INCLUDE) { - for (String key : propertyKeys) { - Object valToPutInMap = element.getProperty(key); - if (valToPutInMap != null) { - map.put(key, valToPutInMap); - } - } - } else { - for (String key : element.getPropertyKeys()) { - if (!propertyKeys.contains(key)) { - map.put(key, element.getProperty(key)); - } - } - } - } - - return map; - } - - private static Object getValue(Object value, final boolean includeType) { - - Object returnValue = value; - - // if the includeType is set to true then show the data types of the properties - if (includeType) { - - // type will be one of: map, list, string, long, int, double, float. - // in the event of a complex object it will call a toString and store as a - // string - String type = determineType(value); - - JSONObject valueAndType = new JSONObject(); - valueAndType.put(GraphSONTokens.TYPE, type); - - if (type.equals(GraphSONTokens.TYPE_LIST)) { - - // values of lists must be accumulated as ObjectNode objects under the value key. - // will return as a ArrayNode. called recursively to traverse the entire - // object graph of each item in the array. - JSONArray list = (JSONArray) value; - - // there is a set of values that must be accumulated as an array under a key - JSONArray valueArray = new JSONArray(); - valueAndType.put(GraphSONTokens.VALUE, valueArray); - for (int ix = 0; ix < list.size(); ix++) { - // the value of each item in the array is a node object from an ArrayNode...must - // get the value of it. - addObject(valueArray, getValue(list.get(ix), includeType)); - } - - } else if (type.equals(GraphSONTokens.TYPE_MAP)) { - - // maps are converted to a ObjectNode. called recursively to traverse - // the entire object graph within the map. - JSONObject convertedMap = new JSONObject(); - JSONObject jsonObject = (JSONObject) value; - - for (Object key : jsonObject.keySet()) { - - // no need to getValue() here as this is already a ObjectNode and should have type info - convertedMap.put(key, jsonObject.get(key)); - } - - valueAndType.put(GraphSONTokens.VALUE, convertedMap); - - } else { - - // this must be a primitive value or a complex object. if a complex - // object it will be handled by a call to toString and stored as a - // string value - putObject(valueAndType, GraphSONTokens.VALUE, value); - } - - // this goes back as a JSONObject with data type and value - returnValue = valueAndType; - } - - return returnValue; - } - - private static List convertArrayToList(final Object value) { - - // is there seriously no better way to do this...bah! - List list = new ArrayList(); - if (value instanceof int[]) { - int[] arr = (int[]) value; - for (int ix = 0; ix < arr.length; ix++) { - list.add(arr[ix]); - } - } else if (value instanceof double[]) { - double[] arr = (double[]) value; - for (int ix = 0; ix < arr.length; ix++) { - list.add(arr[ix]); - } - } else if (value instanceof float[]) { - float[] arr = (float[]) value; - for (int ix = 0; ix < arr.length; ix++) { - list.add(arr[ix]); - } - } else if (value instanceof long[]) { - long[] arr = (long[]) value; - for (int ix = 0; ix < arr.length; ix++) { - list.add(arr[ix]); - } - } else if (value instanceof boolean[]) { - boolean[] arr = (boolean[]) value; - for (int ix = 0; ix < arr.length; ix++) { - list.add(arr[ix]); - } - } else { - list = Arrays.asList((Object[]) value); - } - - return list; - } - - private static String determineType(final Object value) { - String type = GraphSONTokens.TYPE_STRING; - if (value == null) { - type = "unknown"; - } else if (value instanceof Double) { - type = GraphSONTokens.TYPE_DOUBLE; - } else if (value instanceof Float) { - type = GraphSONTokens.TYPE_FLOAT; - } else if (value instanceof Integer) { - type = GraphSONTokens.TYPE_INTEGER; - } else if (value instanceof Long) { - type = GraphSONTokens.TYPE_LONG; - } else if (value instanceof Boolean) { - type = GraphSONTokens.TYPE_BOOLEAN; - } else if (value instanceof JSONArray) { - type = GraphSONTokens.TYPE_LIST; - } else if (value instanceof JSONObject) { - type = GraphSONTokens.TYPE_MAP; - } - - return type; - } - - /** - * Creates a vertex from GraphSON using settings supplied in the constructor. - */ - public Vertex vertexFromJson(final InputStream json) throws ParseException, IOException { - return this.vertexFromJson((JSONObject) parser.parse(new InputStreamReader(json))); - } - - /** - * Creates an edge from GraphSON using settings supplied in the constructor. - */ - public Edge edgeFromJson(final String json, final Vertex out, final Vertex in) throws IOException, ParseException { - return this.edgeFromJson((JSONObject) parser.parse(json), out, in); - } - - /** - * Creates an edge from GraphSON using settings supplied in the constructor. - */ - public Edge edgeFromJson(final InputStream json, final Vertex out, final Vertex in) throws IOException, ParseException { - return this.edgeFromJson((JSONObject) parser.parse(new InputStreamReader(json)), out, in); - } - - /** - * Creates an edge from GraphSON using settings supplied in the constructor. - */ - public Edge edgeFromJson(final JSONObject json, final Vertex out, final Vertex in) throws IOException { - final Map props = GraphSONUtility.readProperties(json, true, this.hasEmbeddedTypes); - -// final Object edgeId = getTypedValueFromJsonNode(json.get(GraphSONTokens._ID)); - final Object edgeId = json.get(GraphSONTokens._ID); - - final Object nodeLabel = json.get(GraphSONTokens._LABEL); - final String label = nodeLabel == null ? null : nodeLabel.toString(); - - final Edge e = factory.createEdge(edgeId, out, in, label); - - for (Map.Entry entry : props.entrySet()) { - // if (this.edgePropertyKeys == null || this.edgePropertyKeys.contains(entry.getKey())) { - if (includeKey(entry.getKey(), edgePropertyKeys, this.edgePropertiesRule)) { - e.setProperty(entry.getKey(), entry.getValue()); - } - } - - return e; - } - - /** - * Creates a vertex from GraphSON using settings supplied in the constructor. - */ - public Vertex vertexFromJson(final String json) throws ParseException { - return this.vertexFromJson((JSONObject) parser.parse(json)); - } - - /** - * Creates a vertex from GraphSON using settings supplied in the constructor. - */ - public Vertex vertexFromJson(final JSONObject json) { - final Map props = readProperties(json, true, this.hasEmbeddedTypes); - - //final Object vertexId = getTypedValueFromJsonNode((JSONObject)json.get(GraphSONTokens._ID)); - final Object vertexId = json.get(GraphSONTokens._ID); - final Vertex v = factory.createVertex(vertexId); - - for (Map.Entry entry : props.entrySet()) { - //if (this.vertexPropertyKeys == null || vertexPropertyKeys.contains(entry.getKey())) { - if (includeKey(entry.getKey(), vertexPropertyKeys, this.vertexPropertiesRule)) { - v.setProperty(entry.getKey(), entry.getValue()); - } - } - - return v; - } - - /** - * Creates GraphSON for a single graph element. - */ - public JSONObject jsonFromElement(final Element element) { - final JSONObject objectNode = this.objectNodeFromElement(element); - return objectNode; - } - - /** - * Creates GraphSON for a single graph element. - */ - public org.json.simple.JSONObject objectNodeFromElement(final Element element) { - final boolean isEdge = element instanceof Edge; - final boolean showTypes = mode == GraphSONMode.EXTENDED; - final Set propertyKeys = isEdge ? this.edgePropertyKeys : this.vertexPropertyKeys; - final ElementPropertiesRule elementPropertyConfig = isEdge ? this.edgePropertiesRule : this.vertexPropertiesRule; - - final org.json.simple.JSONObject jsonElement = createJSONMap(createPropertyMap(element, propertyKeys, elementPropertyConfig), propertyKeys, showTypes); - - if ((isEdge && this.includeReservedEdgeId) || (!isEdge && this.includeReservedVertexId)) { - putObject(jsonElement, GraphSONTokens._ID, element.getId()); - } - - // it's important to keep the order of these straight. check Edge first and then Vertex because there - // are graph implementations that have Edge extend from Vertex - if (element instanceof Edge) { - final Edge edge = (Edge) element; - - if (this.includeReservedEdgeId) { - putObject(jsonElement, GraphSONTokens._ID, element.getId()); - } - - if (this.includeReservedEdgeType) { - jsonElement.put(GraphSONTokens._TYPE, GraphSONTokens.EDGE); - } - - if (this.includeReservedEdgeOutV) { - putObject(jsonElement, GraphSONTokens._OUT_V, edge.getVertex(Direction.OUT).getId()); - } - - if (this.includeReservedEdgeInV) { - putObject(jsonElement, GraphSONTokens._IN_V, edge.getVertex(Direction.IN).getId()); - } - - if (this.includeReservedEdgeLabel) { - jsonElement.put(GraphSONTokens._LABEL, edge.getLabel()); - } - } else if (element instanceof Vertex) { - if (this.includeReservedVertexId) { - putObject(jsonElement, GraphSONTokens._ID, element.getId()); - } - - if (this.includeReservedVertexType) { - jsonElement.put(GraphSONTokens._TYPE, GraphSONTokens.VERTEX); - } - } - - return jsonElement; - } -} diff --git a/sonar-core/src/main/java/org/sonar/core/graph/GraphSONWriter.java b/sonar-core/src/main/java/org/sonar/core/graph/GraphSONWriter.java deleted file mode 100644 index 6455a34e065..00000000000 --- a/sonar-core/src/main/java/org/sonar/core/graph/GraphSONWriter.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Sonar, open source software quality management tool. - * Copyright (C) 2008-2012 SonarSource - * mailto:contact AT sonarsource DOT com - * - * Sonar is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * Sonar is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with Sonar; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ - -package org.sonar.core.graph; - - -import com.tinkerpop.blueprints.Edge; -import com.tinkerpop.blueprints.Graph; -import com.tinkerpop.blueprints.Vertex; -import com.tinkerpop.blueprints.util.io.graphson.GraphSONMode; -import com.tinkerpop.blueprints.util.io.graphson.GraphSONTokens; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; - -import java.io.IOException; -import java.io.OutputStream; -import java.util.Set; - -/** - * GraphSONWriter writes a Graph to a TinkerPop JSON OutputStream. - * - * @author Stephen Mallette - */ -public class GraphSONWriter { - - private final Graph graph; - - /** - * @param graph the Graph to pull the data from - */ - public GraphSONWriter(final Graph graph) { - this.graph = graph; - } - - /** - * Write the data in a Graph to a JSON OutputStream. All keys are written to JSON. Utilizing - * GraphSONMode.NORMAL. - * - * @param graph the graph to serialize to JSON - * @param jsonOutputStream the JSON OutputStream to write the Graph data to - * @throws java.io.IOException thrown if there is an error generating the JSON data - */ - public static void outputGraph(final Graph graph, final OutputStream jsonOutputStream) throws IOException { - final GraphSONWriter writer = new GraphSONWriter(graph); - writer.outputGraph(jsonOutputStream, null, null, GraphSONMode.NORMAL); - } - - /** - * Write the data in a Graph to a JSON OutputStream. All keys are written to JSON. - * - * @param graph the graph to serialize to JSON - * @param jsonOutputStream the JSON OutputStream to write the Graph data to - * @param mode determines the format of the GraphSON - * @throws java.io.IOException thrown if there is an error generating the JSON data - */ - public static void outputGraph(final Graph graph, final OutputStream jsonOutputStream, - final GraphSONMode mode) throws IOException { - final GraphSONWriter writer = new GraphSONWriter(graph); - writer.outputGraph(jsonOutputStream, null, null, mode); - } - - /** - * Write the data in a Graph to a JSON OutputStream. - * - * @param graph the graph to serialize to JSON - * @param jsonOutputStream the JSON OutputStream to write the Graph data to - * @param vertexPropertyKeys the keys of the vertex elements to write to JSON - * @param edgePropertyKeys the keys of the edge elements to write to JSON - * @param mode determines the format of the GraphSON - * @throws java.io.IOException thrown if there is an error generating the JSON data - */ - public static void outputGraph(final Graph graph, final OutputStream jsonOutputStream, - final Set vertexPropertyKeys, final Set edgePropertyKeys, - final GraphSONMode mode) throws IOException { - final GraphSONWriter writer = new GraphSONWriter(graph); - writer.outputGraph(jsonOutputStream, vertexPropertyKeys, edgePropertyKeys, mode); - } - - /** - * Write the data in a Graph to a JSON OutputStream. - * - * @param jsonOutputStream the JSON OutputStream to write the Graph data to - * @param vertexPropertyKeys the keys of the vertex elements to write to JSON - * @param edgePropertyKeys the keys of the edge elements to write to JSON - * @param mode determines the format of the GraphSON - * @throws java.io.IOException thrown if there is an error generating the JSON data - */ - public void outputGraph(final OutputStream jsonOutputStream, final Set vertexPropertyKeys, - final Set edgePropertyKeys, final GraphSONMode mode) throws IOException { - - JSONObject root = new JSONObject(); - - final GraphSONUtility graphson = new GraphSONUtility(mode, null, vertexPropertyKeys, edgePropertyKeys); - - root.put(GraphSONTokens.MODE, mode.toString()); - - JSONArray verticesArray = new JSONArray(); - for (Vertex v : this.graph.getVertices()) { - verticesArray.add(graphson.objectNodeFromElement(v)); - } - root.put(GraphSONTokens.VERTICES, verticesArray); - - JSONArray edgesArray = new JSONArray(); - for (Edge e : this.graph.getEdges()) { - edgesArray.add(graphson.objectNodeFromElement(e)); - } - root.put(GraphSONTokens.EDGES, edgesArray); - - jsonOutputStream.write(root.toString().getBytes()); - } - -} diff --git a/sonar-core/src/main/java/org/sonar/core/graph/GraphWriter.java b/sonar-core/src/main/java/org/sonar/core/graph/GraphWriter.java index ac08fc7d516..ac8b01a8efc 100644 --- a/sonar-core/src/main/java/org/sonar/core/graph/GraphWriter.java +++ b/sonar-core/src/main/java/org/sonar/core/graph/GraphWriter.java @@ -20,8 +20,9 @@ package org.sonar.core.graph; import com.tinkerpop.blueprints.Graph; -import com.tinkerpop.blueprints.util.io.graphson.GraphSONMode; import org.apache.commons.io.IOUtils; +import org.sonar.core.graph.graphson.GraphSONMode; +import org.sonar.core.graph.graphson.GraphSONWriter; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -31,7 +32,7 @@ public class GraphWriter { public String write(Graph graph) { ByteArrayOutputStream output = new ByteArrayOutputStream(); try { - GraphSONWriter.outputGraph(graph, output, GraphSONMode.COMPACT); + new GraphSONWriter().write(graph, output, GraphSONMode.COMPACT); output.flush(); output.close(); return new String(output.toByteArray()); diff --git a/sonar-core/src/main/java/org/sonar/core/graph/graphson/ElementFactory.java b/sonar-core/src/main/java/org/sonar/core/graph/graphson/ElementFactory.java new file mode 100644 index 00000000000..e7458c2ef66 --- /dev/null +++ b/sonar-core/src/main/java/org/sonar/core/graph/graphson/ElementFactory.java @@ -0,0 +1,47 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2008-2012 SonarSource + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.core.graph.graphson; + +import com.tinkerpop.blueprints.Edge; +import com.tinkerpop.blueprints.Graph; +import com.tinkerpop.blueprints.Vertex; + +/** + * The standard factory used for most graph element creation. It uses an actual + * Graph implementation to construct vertices and edges + * + * @author Stephen Mallette (http://stephen.genoprime.com) + */ +class ElementFactory { + + private final Graph graph; + + ElementFactory(Graph g) { + this.graph = g; + } + + Edge createEdge(Object id, Vertex out, Vertex in, String label) { + return this.graph.addEdge(id, out, in, label); + } + + Vertex createVertex(Object id) { + return this.graph.addVertex(id); + } +} diff --git a/sonar-core/src/main/java/org/sonar/core/graph/graphson/ElementPropertyConfig.java b/sonar-core/src/main/java/org/sonar/core/graph/graphson/ElementPropertyConfig.java new file mode 100644 index 00000000000..a82265a9362 --- /dev/null +++ b/sonar-core/src/main/java/org/sonar/core/graph/graphson/ElementPropertyConfig.java @@ -0,0 +1,87 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2008-2012 SonarSource + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.core.graph.graphson; + +import java.util.Set; + +/** + * Configure how the GraphSON utility treats edge and vertex properties. + * + * @author Stephen Mallette (http://stephen.genoprime.com) + */ +class ElementPropertyConfig { + + static enum ElementPropertiesRule { + INCLUDE, EXCLUDE + } + + private final Set vertexPropertyKeys; + private final Set edgePropertyKeys; + private final ElementPropertiesRule vertexPropertiesRule; + private final ElementPropertiesRule edgePropertiesRule; + + /** + * A configuration that includes all properties of vertices and edges. + */ + static ElementPropertyConfig AllProperties = new ElementPropertyConfig(null, null, + ElementPropertiesRule.INCLUDE, ElementPropertiesRule.INCLUDE); + + ElementPropertyConfig(Set vertexPropertyKeys, Set edgePropertyKeys, + ElementPropertiesRule vertexPropertiesRule, ElementPropertiesRule edgePropertiesRule) { + this.vertexPropertiesRule = vertexPropertiesRule; + this.vertexPropertyKeys = vertexPropertyKeys; + this.edgePropertiesRule = edgePropertiesRule; + this.edgePropertyKeys = edgePropertyKeys; + } + + /** + * Construct a configuration that includes the specified properties from both vertices and edges. + */ + static ElementPropertyConfig includeProperties(Set vertexPropertyKeys, + Set edgePropertyKeys) { + return new ElementPropertyConfig(vertexPropertyKeys, edgePropertyKeys, ElementPropertiesRule.INCLUDE, + ElementPropertiesRule.INCLUDE); + } + + /** + * Construct a configuration that excludes the specified properties from both vertices and edges. + */ + static ElementPropertyConfig excludeProperties(Set vertexPropertyKeys, + Set edgePropertyKeys) { + return new ElementPropertyConfig(vertexPropertyKeys, edgePropertyKeys, ElementPropertiesRule.EXCLUDE, + ElementPropertiesRule.EXCLUDE); + } + + Set getVertexPropertyKeys() { + return vertexPropertyKeys; + } + + Set getEdgePropertyKeys() { + return edgePropertyKeys; + } + + ElementPropertiesRule getVertexPropertiesRule() { + return vertexPropertiesRule; + } + + ElementPropertiesRule getEdgePropertiesRule() { + return edgePropertiesRule; + } +} diff --git a/sonar-core/src/main/java/org/sonar/core/graph/graphson/GraphSONMode.java b/sonar-core/src/main/java/org/sonar/core/graph/graphson/GraphSONMode.java new file mode 100644 index 00000000000..3fde6287c08 --- /dev/null +++ b/sonar-core/src/main/java/org/sonar/core/graph/graphson/GraphSONMode.java @@ -0,0 +1,45 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2008-2012 SonarSource + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.core.graph.graphson; + +/** + * Modes of operation of the GraphSONUtility. + * + * @author Stephen Mallette + */ +public enum GraphSONMode { + /** + * COMPACT constructs GraphSON on the assumption that all property keys + * are fair game for exclusion including _type, _inV, _outV, _label and _id. + * It is possible to write GraphSON that cannot be read back into Graph, + * if some or all of these keys are excluded. + */ + COMPACT, + + /** + * NORMAL includes the _type field and JSON data typing. + */ + NORMAL, + + /** + * EXTENDED includes the _type field and explicit data typing. + */ + EXTENDED +} diff --git a/sonar-core/src/main/java/org/sonar/core/graph/graphson/GraphSONReader.java b/sonar-core/src/main/java/org/sonar/core/graph/graphson/GraphSONReader.java new file mode 100644 index 00000000000..1b3aee4d009 --- /dev/null +++ b/sonar-core/src/main/java/org/sonar/core/graph/graphson/GraphSONReader.java @@ -0,0 +1,81 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2008-2012 SonarSource + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.core.graph.graphson; + +import com.tinkerpop.blueprints.Graph; +import com.tinkerpop.blueprints.Vertex; +import com.tinkerpop.blueprints.util.wrappers.batch.BatchGraph; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; + +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.Set; + +/** + * Greatly inspired by the Blueprints implementation based on Jettison/Jackson + */ +public class GraphSONReader { + + public Graph read(InputStream jsonInput, Graph toGraph) { + return read(jsonInput, toGraph, 1000, null, null); + } + + /** + * Input the JSON stream data into the graph. + * More control over how data is streamed is provided by this method. + * + * @param toGraph the graph to populate with the JSON data + * @param jsonInput an InputStream of JSON data + * @param bufferSize the amount of elements to hold in memory before committing a transactions (only valid for TransactionalGraphs) + */ + public Graph read(InputStream jsonInput, Graph toGraph, int bufferSize, Set edgePropertyKeys, Set vertexPropertyKeys) { + try { + JSONParser parser = new JSONParser(); + JSONObject json = (JSONObject) parser.parse(new InputStreamReader(jsonInput)); + + // if this is a transactional graph then we're buffering + final BatchGraph batchGraph = BatchGraph.wrap(toGraph, bufferSize); + + ElementFactory elementFactory = new ElementFactory(batchGraph); + + final GraphSONMode mode = GraphSONMode.valueOf(json.get(GraphSONTokens.MODE).toString()); + GraphsonUtil graphson = new GraphsonUtil(mode, elementFactory, vertexPropertyKeys, edgePropertyKeys); + + JSONArray vertices = (JSONArray) json.get(GraphSONTokens.VERTICES); + for (Object vertice : vertices) { + graphson.vertexFromJson((JSONObject) vertice); + } + + JSONArray edges = (JSONArray) json.get(GraphSONTokens.EDGES); + for (Object edgeObject : edges) { + JSONObject edge = (JSONObject) edgeObject; + final Vertex inV = batchGraph.getVertex(edge.get(GraphSONTokens._IN_V)); + final Vertex outV = batchGraph.getVertex(edge.get(GraphSONTokens._OUT_V)); + graphson.edgeFromJson(edge, outV, inV); + } + batchGraph.shutdown(); + return toGraph; + } catch (Exception e) { + throw new GraphSonException("Unable to parse GraphSON", e); + } + } +} diff --git a/sonar-core/src/main/java/org/sonar/core/graph/graphson/GraphSONTokens.java b/sonar-core/src/main/java/org/sonar/core/graph/graphson/GraphSONTokens.java new file mode 100644 index 00000000000..b67e713ca64 --- /dev/null +++ b/sonar-core/src/main/java/org/sonar/core/graph/graphson/GraphSONTokens.java @@ -0,0 +1,49 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2008-2012 SonarSource + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.core.graph.graphson; + +/** + * @author Marko A. Rodriguez (http://markorodriguez.com) + * @author Stephen Mallette + */ +class GraphSONTokens { + public static final String VERTEX = "vertex"; + public static final String EDGE = "edge"; + public static final String _ID = "_id"; + public static final String _LABEL = "_label"; + public static final String _TYPE = "_type"; + public static final String _OUT_V = "_outV"; + public static final String _IN_V = "_inV"; + public static final String VALUE = "value"; + public static final String TYPE = "type"; + public static final String TYPE_LIST = "list"; + public static final String TYPE_STRING = "string"; + public static final String TYPE_DOUBLE = "double"; + public static final String TYPE_INTEGER = "integer"; + public static final String TYPE_FLOAT = "float"; + public static final String TYPE_MAP = "map"; + public static final String TYPE_BOOLEAN = "boolean"; + public static final String TYPE_LONG = "long"; + public static final String TYPE_UNKNOWN = "unknown"; + + public static final String VERTICES = "vertices"; + public static final String EDGES = "edges"; + public static final String MODE = "mode"; +} diff --git a/sonar-core/src/main/java/org/sonar/core/graph/graphson/GraphSONWriter.java b/sonar-core/src/main/java/org/sonar/core/graph/graphson/GraphSONWriter.java new file mode 100644 index 00000000000..a48a24db336 --- /dev/null +++ b/sonar-core/src/main/java/org/sonar/core/graph/graphson/GraphSONWriter.java @@ -0,0 +1,79 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2008-2012 SonarSource + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.core.graph.graphson; + +import com.google.common.base.Charsets; +import com.tinkerpop.blueprints.Edge; +import com.tinkerpop.blueprints.Graph; +import com.tinkerpop.blueprints.Vertex; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; + +import javax.annotation.Nullable; + +import java.io.OutputStream; +import java.util.Set; + +/** + * GraphSONWriter writes a Graph to a TinkerPop JSON OutputStream. + * + * @author Stephen Mallette + */ +public class GraphSONWriter { + + public void write(Graph graph, OutputStream jsonOutputStream, GraphSONMode mode) { + write(graph, jsonOutputStream, mode, null, null); + } + + /** + * Write the data in a Graph to a JSON OutputStream. + * + * @param jsonOutputStream the JSON OutputStream to write the Graph data to + * @param vertexPropertyKeys the keys of the vertex elements to write to JSON + * @param edgePropertyKeys the keys of the edge elements to write to JSON + * @param mode determines the format of the GraphSON + * @throws java.io.IOException thrown if there is an error generating the JSON data + */ + public void write(Graph graph, OutputStream jsonOutputStream, GraphSONMode mode, @Nullable Set vertexPropertyKeys, @Nullable Set edgePropertyKeys) { + try { + JSONObject root = new JSONObject(); + GraphsonUtil graphson = new GraphsonUtil(mode, null, vertexPropertyKeys, edgePropertyKeys); + + root.put(GraphSONTokens.MODE, mode.toString()); + + JSONArray verticesArray = new JSONArray(); + for (Vertex v : graph.getVertices()) { + verticesArray.add(graphson.objectNodeFromElement(v)); + } + root.put(GraphSONTokens.VERTICES, verticesArray); + + JSONArray edgesArray = new JSONArray(); + for (Edge e : graph.getEdges()) { + edgesArray.add(graphson.objectNodeFromElement(e)); + } + root.put(GraphSONTokens.EDGES, edgesArray); + + jsonOutputStream.write(root.toString().getBytes("UTF-8")); + } catch (Exception e) { + throw new GraphSonException("Fail to generate GraphSON", e); + } + } + +} diff --git a/sonar-core/src/main/java/org/sonar/core/graph/graphson/GraphSonException.java b/sonar-core/src/main/java/org/sonar/core/graph/graphson/GraphSonException.java new file mode 100644 index 00000000000..f037e76249f --- /dev/null +++ b/sonar-core/src/main/java/org/sonar/core/graph/graphson/GraphSonException.java @@ -0,0 +1,30 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2008-2012 SonarSource + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.core.graph.graphson; + +public class GraphSonException extends RuntimeException { + public GraphSonException(String message) { + super(message); + } + + public GraphSonException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/sonar-core/src/main/java/org/sonar/core/graph/graphson/GraphsonUtil.java b/sonar-core/src/main/java/org/sonar/core/graph/graphson/GraphsonUtil.java new file mode 100644 index 00000000000..60c213c33fb --- /dev/null +++ b/sonar-core/src/main/java/org/sonar/core/graph/graphson/GraphsonUtil.java @@ -0,0 +1,698 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2008-2012 SonarSource + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.core.graph.graphson; + +import com.tinkerpop.blueprints.Direction; +import com.tinkerpop.blueprints.Edge; +import com.tinkerpop.blueprints.Element; +import com.tinkerpop.blueprints.Vertex; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + +import javax.annotation.Nullable; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.sonar.core.graph.graphson.ElementPropertyConfig.ElementPropertiesRule; + +/** + * Helps write individual graph elements to TinkerPop JSON format known as GraphSON. + * + * @author Stephen Mallette (http://stephen.genoprime.com) + */ +class GraphsonUtil { + + private final GraphSONMode mode; + private final Set vertexPropertyKeys; + private final Set edgePropertyKeys; + private final ElementFactory factory; + private final boolean hasEmbeddedTypes; + private final ElementPropertiesRule vertexPropertiesRule; + private final ElementPropertiesRule edgePropertiesRule; + private final boolean includeReservedVertexId; + private final boolean includeReservedEdgeId; + private final boolean includeReservedVertexType; + private final boolean includeReservedEdgeType; + private final boolean includeReservedEdgeLabel; + private final boolean includeReservedEdgeOutV; + private final boolean includeReservedEdgeInV; + private JSONParser parser = new JSONParser(); + + /** + * A GraphSONUtiltiy that includes all properties of vertices and edges. + */ + GraphsonUtil(GraphSONMode mode, ElementFactory factory) { + this(mode, factory, ElementPropertyConfig.AllProperties); + } + + /** + * A GraphSONUtility that includes the specified properties. + */ + GraphsonUtil(GraphSONMode mode, ElementFactory factory, + Set vertexPropertyKeys, Set edgePropertyKeys) { + this(mode, factory, ElementPropertyConfig.includeProperties(vertexPropertyKeys, edgePropertyKeys)); + } + + GraphsonUtil(GraphSONMode mode, ElementFactory factory, + ElementPropertyConfig config) { + this.vertexPropertyKeys = config.getVertexPropertyKeys(); + this.edgePropertyKeys = config.getEdgePropertyKeys(); + this.vertexPropertiesRule = config.getVertexPropertiesRule(); + this.edgePropertiesRule = config.getEdgePropertiesRule(); + + this.mode = mode; + this.factory = factory; + this.hasEmbeddedTypes = mode == GraphSONMode.EXTENDED; + + this.includeReservedVertexId = includeReservedKey(mode, GraphSONTokens._ID, vertexPropertyKeys, this.vertexPropertiesRule); + this.includeReservedEdgeId = includeReservedKey(mode, GraphSONTokens._ID, edgePropertyKeys, this.edgePropertiesRule); + this.includeReservedVertexType = includeReservedKey(mode, GraphSONTokens._TYPE, vertexPropertyKeys, this.vertexPropertiesRule); + this.includeReservedEdgeType = includeReservedKey(mode, GraphSONTokens._TYPE, edgePropertyKeys, this.edgePropertiesRule); + this.includeReservedEdgeLabel = includeReservedKey(mode, GraphSONTokens._LABEL, edgePropertyKeys, this.edgePropertiesRule); + this.includeReservedEdgeOutV = includeReservedKey(mode, GraphSONTokens._OUT_V, edgePropertyKeys, this.edgePropertiesRule); + this.includeReservedEdgeInV = includeReservedKey(mode, GraphSONTokens._IN_V, edgePropertyKeys, this.edgePropertiesRule); + } + + /** + * Creates a Jettison JSONObject from a graph element. + * + * @param element the graph element to convert to JSON. + * @param propertyKeys The property keys at the root of the element to serialize. If null, then all keys are serialized. + * @param mode the type of GraphSON to be generated. + */ + static JSONObject jsonFromElement(Element element, @Nullable Set propertyKeys, GraphSONMode mode) { + GraphsonUtil graphson = element instanceof Edge ? new GraphsonUtil(mode, null, null, propertyKeys) + : new GraphsonUtil(mode, null, propertyKeys, null); + return graphson.jsonFromElement(element); + } + + /** + * Creates a Jackson ObjectNode from a graph element. + * + * @param element the graph element to convert to JSON. + * @param propertyKeys The property keys at the root of the element to serialize. If null, then all keys are serialized. + * @param mode The type of GraphSON to generate. + */ + static JSONObject objectNodeFromElement(Element element, Set propertyKeys, GraphSONMode mode) { + GraphsonUtil graphson = element instanceof Edge ? new GraphsonUtil(mode, null, null, propertyKeys) + : new GraphsonUtil(mode, null, propertyKeys, null); + return graphson.objectNodeFromElement(element); + } + + /** + * Reads an individual Vertex from JSON. The vertex must match the accepted GraphSON format. + * + * @param json a single vertex in GraphSON format as Jettison JSONObject + * @param factory the factory responsible for constructing graph elements + * @param mode the mode of the GraphSON + * @param propertyKeys a list of keys to include on reading of element properties + */ + static Vertex vertexFromJson(JSONObject json, ElementFactory factory, GraphSONMode mode, + Set propertyKeys) throws IOException { + GraphsonUtil graphson = new GraphsonUtil(mode, factory, propertyKeys, null); + return graphson.vertexFromJson(json); + } + + /** + * Reads an individual Vertex from JSON. The vertex must match the accepted GraphSON format. + * + * @param json a single vertex in GraphSON format as a String. + * @param factory the factory responsible for constructing graph elements + * @param mode the mode of the GraphSON + * @param propertyKeys a list of keys to include on reading of element properties + */ + static Vertex vertexFromJson(String json, ElementFactory factory, GraphSONMode mode, + Set propertyKeys) throws ParseException { + GraphsonUtil graphson = new GraphsonUtil(mode, factory, propertyKeys, null); + return graphson.vertexFromJson(json); + } + + /** + * Reads an individual Vertex from JSON. The vertex must match the accepted GraphSON format. + * + * @param json a single vertex in GraphSON format as an InputStream. + * @param factory the factory responsible for constructing graph elements + * @param mode the mode of the GraphSON + * @param propertyKeys a list of keys to include on reading of element properties + */ + static Vertex vertexFromJson(InputStream json, ElementFactory factory, GraphSONMode mode, + Set propertyKeys) throws IOException, ParseException { + GraphsonUtil graphson = new GraphsonUtil(mode, factory, propertyKeys, null); + return graphson.vertexFromJson(json); + } + + private static boolean includeReservedKey(GraphSONMode mode, String key, + Set propertyKeys, + ElementPropertiesRule rule) { + // the key is always included in modes other than compact. if it is compact, then validate that the + // key is in the property key list + return mode != GraphSONMode.COMPACT || includeKey(key, propertyKeys, rule); + } + + private static boolean includeKey(String key, Set propertyKeys, + ElementPropertiesRule rule) { + if (propertyKeys == null) { + // when null always include the key and shortcut this piece + return true; + } + + // default the key situation. if it's included then it should be explicitly defined in the + // property keys list to be included or the reverse otherwise + boolean keySituation = rule == ElementPropertiesRule.INCLUDE; + + switch (rule) { + case INCLUDE: + keySituation = propertyKeys.contains(key); + break; + case EXCLUDE: + keySituation = !propertyKeys.contains(key); + break; + } + + return keySituation; + } + + /** + * Reads an individual Edge from JSON. The edge must match the accepted GraphSON format. + * + * @param json a single edge in GraphSON format as a String + * @param factory the factory responsible for constructing graph elements + * @param mode the mode of the GraphSON + * @param propertyKeys a list of keys to include when reading of element properties + */ + static Edge edgeFromJson(String json, Vertex out, Vertex in, + ElementFactory factory, GraphSONMode mode, + Set propertyKeys) throws IOException, ParseException { + GraphsonUtil graphson = new GraphsonUtil(mode, factory, null, propertyKeys); + return graphson.edgeFromJson(json, out, in); + } + + /** + * Reads an individual Edge from JSON. The edge must match the accepted GraphSON format. + * + * @param json a single edge in GraphSON format as an InputStream + * @param factory the factory responsible for constructing graph elements + * @param mode the mode of the GraphSON + * @param propertyKeys a list of keys to include when reading of element properties + */ + static Edge edgeFromJson(InputStream json, Vertex out, Vertex in, + ElementFactory factory, GraphSONMode mode, + Set propertyKeys) throws IOException, ParseException { + GraphsonUtil graphson = new GraphsonUtil(mode, factory, null, propertyKeys); + return graphson.edgeFromJson(json, out, in); + } + + /** + * Reads an individual Edge from JSON. The edge must match the accepted GraphSON format. + * + * @param json a single edge in GraphSON format as a Jackson JsonNode + * @param factory the factory responsible for constructing graph elements + * @param mode the mode of the GraphSON + * @param propertyKeys a list of keys to include when reading of element properties + */ + static Edge edgeFromJson(JSONObject json, Vertex out, Vertex in, + ElementFactory factory, GraphSONMode mode, + Set propertyKeys) throws IOException { + GraphsonUtil graphson = new GraphsonUtil(mode, factory, null, propertyKeys); + return graphson.edgeFromJson(json, out, in); + } + + static Map readProperties(JSONObject node, boolean ignoreReservedKeys, boolean hasEmbeddedTypes) { + Map map = new HashMap(); + + for (Object objKey : node.keySet()) { + String key = (String) objKey; + Object value = node.get(key); + + if (!ignoreReservedKeys || !isReservedKey(key)) { + map.put(key, readProperty(value, hasEmbeddedTypes)); + } + } + + return map; + } + + private static boolean isReservedKey(String key) { + return key.equals(GraphSONTokens._ID) || key.equals(GraphSONTokens._TYPE) || key.equals(GraphSONTokens._LABEL) + || key.equals(GraphSONTokens._OUT_V) || key.equals(GraphSONTokens._IN_V); + } + + private static JSONArray createJSONList(List list, Set propertyKeys, boolean showTypes) { + JSONArray jsonList = new JSONArray(); + for (Object item : list) { + if (item instanceof Element) { + jsonList.add(objectNodeFromElement((Element) item, propertyKeys, + showTypes ? GraphSONMode.EXTENDED : GraphSONMode.NORMAL)); + } else if (item instanceof List) { + jsonList.add(createJSONList((List) item, propertyKeys, showTypes)); + } else if (item instanceof Map) { + jsonList.add(createJSONMap((Map) item, propertyKeys, showTypes)); + } else if (item != null && item.getClass().isArray()) { + jsonList.add(createJSONList(convertArrayToList(item), propertyKeys, showTypes)); + } else { + addObject(jsonList, item); + } + } + return jsonList; + } + + // + private static JSONObject createJSONMap(Map map, Set propertyKeys, boolean showTypes) { + JSONObject jsonMap = new JSONObject(); + for (Object key : map.keySet()) { + Object value = map.get(key); + if (value != null) { + if (value instanceof List) { + value = createJSONList((List) value, propertyKeys, showTypes); + } else if (value instanceof Map) { + value = createJSONMap((Map) value, propertyKeys, showTypes); + } else if (value instanceof Element) { + value = objectNodeFromElement((Element) value, propertyKeys, + showTypes ? GraphSONMode.EXTENDED : GraphSONMode.NORMAL); + } else if (value.getClass().isArray()) { + value = createJSONList(convertArrayToList(value), propertyKeys, showTypes); + } + } + + putObject(jsonMap, key.toString(), getValue(value, showTypes)); + } + return jsonMap; + + } + + private static Object readProperty(Object node, boolean hasEmbeddedTypes) { + Object propertyValue; + + if (hasEmbeddedTypes) { + JSONObject json = (JSONObject) node; + if (json.get(GraphSONTokens.TYPE).equals(GraphSONTokens.TYPE_UNKNOWN)) { + propertyValue = null; + } else if (json.get(GraphSONTokens.TYPE).equals(GraphSONTokens.TYPE_BOOLEAN)) { + propertyValue = json.get(GraphSONTokens.VALUE); + } else if (json.get(GraphSONTokens.TYPE).equals(GraphSONTokens.TYPE_FLOAT)) { + propertyValue = ((Double) json.get(GraphSONTokens.VALUE)).floatValue(); + } else if (json.get(GraphSONTokens.TYPE).equals(GraphSONTokens.TYPE_DOUBLE)) { + propertyValue = json.get(GraphSONTokens.VALUE); + } else if (json.get(GraphSONTokens.TYPE).equals(GraphSONTokens.TYPE_INTEGER)) { + propertyValue = ((Long) json.get(GraphSONTokens.VALUE)).intValue(); + } else if (json.get(GraphSONTokens.TYPE).equals(GraphSONTokens.TYPE_LONG)) { + propertyValue = json.get(GraphSONTokens.VALUE); + } else if (json.get(GraphSONTokens.TYPE).equals(GraphSONTokens.TYPE_STRING)) { + propertyValue = json.get(GraphSONTokens.VALUE); + } else if (json.get(GraphSONTokens.TYPE).equals(GraphSONTokens.TYPE_LIST)) { + propertyValue = readProperties(((JSONArray) json.get(GraphSONTokens.VALUE)).iterator(), hasEmbeddedTypes); + } else if (json.get(GraphSONTokens.TYPE).equals(GraphSONTokens.TYPE_MAP)) { + propertyValue = readProperties((JSONObject) json.get(GraphSONTokens.VALUE), false, hasEmbeddedTypes); + } else { + propertyValue = node.toString(); + } + } else { + if (node == null) { + propertyValue = null; + } else if (node instanceof Boolean) { + propertyValue = node; + } else if (node instanceof Double) { + propertyValue = node; + } else if (node instanceof Integer) { + propertyValue = node; + } else if (node instanceof Long) { + propertyValue = node; + } else if (node instanceof String) { + propertyValue = node; + } else if (node instanceof JSONArray) { + propertyValue = readProperties(((JSONArray) node).iterator(), hasEmbeddedTypes); + } else if (node instanceof JSONObject) { + propertyValue = readProperties((JSONObject) node, false, hasEmbeddedTypes); + } else { + propertyValue = node; + } + } + + return propertyValue; + } + + private static void putObject(JSONObject jsonMap, String key, Object value) { + if (value == null) { + jsonMap.put(key, null); + } else if (value instanceof Boolean) { + jsonMap.put(key, value); + } else if (value instanceof Long) { + jsonMap.put(key, value); + } else if (value instanceof Integer) { + jsonMap.put(key, value); + } else if (value instanceof Float) { + jsonMap.put(key, value); + } else if (value instanceof Double) { + jsonMap.put(key, value); + } else if (value instanceof String) { + jsonMap.put(key, value); + } else if (value instanceof JSONObject) { + jsonMap.put(key, value); + } else if (value instanceof JSONArray) { + jsonMap.put(key, value); + } else { + jsonMap.put(key, value.toString()); + } + } + + private static List readProperties(Iterator listOfNodes, boolean hasEmbeddedTypes) { + List array = new ArrayList(); + + while (listOfNodes.hasNext()) { + array.add(readProperty(listOfNodes.next(), hasEmbeddedTypes)); + } + + return array; + } + + private static void addObject(JSONArray jsonList, Object value) { + if (value == null) { + jsonList.add(null); + } else if (value instanceof Boolean) { + jsonList.add(value); + } else if (value instanceof Long) { + jsonList.add(value); + } else if (value instanceof Integer) { + jsonList.add(value); + } else if (value instanceof Float) { + jsonList.add(value); + } else if (value instanceof Double) { + jsonList.add(value); + } else if (value instanceof String) { + jsonList.add(value); + } else if (value instanceof JSONObject) { + jsonList.add(value); + } else if (value instanceof JSONArray) { + jsonList.add(value); + } else { + jsonList.add(value.toString()); + } + } + + private static Map createPropertyMap(Element element, Set propertyKeys, ElementPropertiesRule rule) { + Map map = new HashMap(); + + if (propertyKeys == null) { + for (String key : element.getPropertyKeys()) { + map.put(key, element.getProperty(key)); + } + } else { + if (rule == ElementPropertiesRule.INCLUDE) { + for (String key : propertyKeys) { + Object valToPutInMap = element.getProperty(key); + if (valToPutInMap != null) { + map.put(key, valToPutInMap); + } + } + } else { + for (String key : element.getPropertyKeys()) { + if (!propertyKeys.contains(key)) { + map.put(key, element.getProperty(key)); + } + } + } + } + + return map; + } + + private static Object getValue(Object value, boolean includeType) { + + Object returnValue = value; + + // if the includeType is set to true then show the data types of the properties + if (includeType) { + + // type will be one of: map, list, string, long, int, double, float. + // in the event of a complex object it will call a toString and store as a + // string + String type = determineType(value); + + JSONObject valueAndType = new JSONObject(); + valueAndType.put(GraphSONTokens.TYPE, type); + + if (type.equals(GraphSONTokens.TYPE_LIST)) { + + // values of lists must be accumulated as ObjectNode objects under the value key. + // will return as a ArrayNode. called recursively to traverse the entire + // object graph of each item in the array. + JSONArray list = (JSONArray) value; + + // there is a set of values that must be accumulated as an array under a key + JSONArray valueArray = new JSONArray(); + valueAndType.put(GraphSONTokens.VALUE, valueArray); + for (int ix = 0; ix < list.size(); ix++) { + // the value of each item in the array is a node object from an ArrayNode...must + // get the value of it. + addObject(valueArray, getValue(list.get(ix), includeType)); + } + + } else if (type.equals(GraphSONTokens.TYPE_MAP)) { + + // maps are converted to a ObjectNode. called recursively to traverse + // the entire object graph within the map. + JSONObject convertedMap = new JSONObject(); + JSONObject jsonObject = (JSONObject) value; + + for (Object key : jsonObject.keySet()) { + + // no need to getValue() here as this is already a ObjectNode and should have type info + convertedMap.put(key, jsonObject.get(key)); + } + + valueAndType.put(GraphSONTokens.VALUE, convertedMap); + + } else { + + // this must be a primitive value or a complex object. if a complex + // object it will be handled by a call to toString and stored as a + // string value + putObject(valueAndType, GraphSONTokens.VALUE, value); + } + + // this goes back as a JSONObject with data type and value + returnValue = valueAndType; + } + + return returnValue; + } + + private static List convertArrayToList(Object value) { + + // is there seriously no better way to do this...bah! + List list = new ArrayList(); + if (value instanceof int[]) { + int[] arr = (int[]) value; + for (int ix = 0; ix < arr.length; ix++) { + list.add(arr[ix]); + } + } else if (value instanceof double[]) { + double[] arr = (double[]) value; + for (int ix = 0; ix < arr.length; ix++) { + list.add(arr[ix]); + } + } else if (value instanceof float[]) { + float[] arr = (float[]) value; + for (int ix = 0; ix < arr.length; ix++) { + list.add(arr[ix]); + } + } else if (value instanceof long[]) { + long[] arr = (long[]) value; + for (int ix = 0; ix < arr.length; ix++) { + list.add(arr[ix]); + } + } else if (value instanceof boolean[]) { + boolean[] arr = (boolean[]) value; + for (int ix = 0; ix < arr.length; ix++) { + list.add(arr[ix]); + } + } else { + list = Arrays.asList((Object[]) value); + } + + return list; + } + + private static String determineType(Object value) { + String type = GraphSONTokens.TYPE_STRING; + if (value == null) { + type = "unknown"; + } else if (value instanceof Double) { + type = GraphSONTokens.TYPE_DOUBLE; + } else if (value instanceof Float) { + type = GraphSONTokens.TYPE_FLOAT; + } else if (value instanceof Integer) { + type = GraphSONTokens.TYPE_INTEGER; + } else if (value instanceof Long) { + type = GraphSONTokens.TYPE_LONG; + } else if (value instanceof Boolean) { + type = GraphSONTokens.TYPE_BOOLEAN; + } else if (value instanceof JSONArray) { + type = GraphSONTokens.TYPE_LIST; + } else if (value instanceof JSONObject) { + type = GraphSONTokens.TYPE_MAP; + } + + return type; + } + + /** + * Creates a vertex from GraphSON using settings supplied in the constructor. + */ + Vertex vertexFromJson(InputStream json) throws ParseException, IOException { + return this.vertexFromJson((JSONObject) parser.parse(new InputStreamReader(json))); + } + + /** + * Creates an edge from GraphSON using settings supplied in the constructor. + */ + Edge edgeFromJson(String json, Vertex out, Vertex in) throws IOException, ParseException { + return this.edgeFromJson((JSONObject) parser.parse(json), out, in); + } + + /** + * Creates an edge from GraphSON using settings supplied in the constructor. + */ + Edge edgeFromJson(InputStream json, Vertex out, Vertex in) throws IOException, ParseException { + return this.edgeFromJson((JSONObject) parser.parse(new InputStreamReader(json)), out, in); + } + + /** + * Creates an edge from GraphSON using settings supplied in the constructor. + */ + Edge edgeFromJson(JSONObject json, Vertex out, Vertex in) throws IOException { + Map props = GraphsonUtil.readProperties(json, true, this.hasEmbeddedTypes); + +// Object edgeId = getTypedValueFromJsonNode(json.get(GraphSONTokens._ID)); + Object edgeId = json.get(GraphSONTokens._ID); + + Object nodeLabel = json.get(GraphSONTokens._LABEL); + String label = nodeLabel == null ? null : nodeLabel.toString(); + + Edge e = factory.createEdge(edgeId, out, in, label); + + for (Map.Entry entry : props.entrySet()) { + // if (this.edgePropertyKeys == null || this.edgePropertyKeys.contains(entry.getKey())) { + if (includeKey(entry.getKey(), edgePropertyKeys, this.edgePropertiesRule)) { + e.setProperty(entry.getKey(), entry.getValue()); + } + } + + return e; + } + + /** + * Creates a vertex from GraphSON using settings supplied in the constructor. + */ + Vertex vertexFromJson(String json) throws ParseException { + return this.vertexFromJson((JSONObject) parser.parse(json)); + } + + /** + * Creates a vertex from GraphSON using settings supplied in the constructor. + */ + Vertex vertexFromJson(JSONObject json) { + Map props = readProperties(json, true, this.hasEmbeddedTypes); + + //Object vertexId = getTypedValueFromJsonNode((JSONObject)json.get(GraphSONTokens._ID)); + Object vertexId = json.get(GraphSONTokens._ID); + Vertex v = factory.createVertex(vertexId); + + for (Map.Entry entry : props.entrySet()) { + //if (this.vertexPropertyKeys == null || vertexPropertyKeys.contains(entry.getKey())) { + if (includeKey(entry.getKey(), vertexPropertyKeys, this.vertexPropertiesRule)) { + v.setProperty(entry.getKey(), entry.getValue()); + } + } + + return v; + } + + /** + * Creates GraphSON for a single graph element. + */ + JSONObject jsonFromElement(Element element) { + JSONObject objectNode = this.objectNodeFromElement(element); + return objectNode; + } + + /** + * Creates GraphSON for a single graph element. + */ + org.json.simple.JSONObject objectNodeFromElement(Element element) { + boolean isEdge = element instanceof Edge; + boolean showTypes = mode == GraphSONMode.EXTENDED; + Set propertyKeys = isEdge ? this.edgePropertyKeys : this.vertexPropertyKeys; + ElementPropertiesRule elementPropertyConfig = isEdge ? this.edgePropertiesRule : this.vertexPropertiesRule; + + org.json.simple.JSONObject jsonElement = createJSONMap(createPropertyMap(element, propertyKeys, elementPropertyConfig), propertyKeys, showTypes); + + if ((isEdge && this.includeReservedEdgeId) || (!isEdge && this.includeReservedVertexId)) { + putObject(jsonElement, GraphSONTokens._ID, element.getId()); + } + + // it's important to keep the order of these straight. check Edge first and then Vertex because there + // are graph implementations that have Edge extend from Vertex + if (element instanceof Edge) { + Edge edge = (Edge) element; + + if (this.includeReservedEdgeId) { + putObject(jsonElement, GraphSONTokens._ID, element.getId()); + } + + if (this.includeReservedEdgeType) { + jsonElement.put(GraphSONTokens._TYPE, GraphSONTokens.EDGE); + } + + if (this.includeReservedEdgeOutV) { + putObject(jsonElement, GraphSONTokens._OUT_V, edge.getVertex(Direction.OUT).getId()); + } + + if (this.includeReservedEdgeInV) { + putObject(jsonElement, GraphSONTokens._IN_V, edge.getVertex(Direction.IN).getId()); + } + + if (this.includeReservedEdgeLabel) { + jsonElement.put(GraphSONTokens._LABEL, edge.getLabel()); + } + } else if (element instanceof Vertex) { + if (this.includeReservedVertexId) { + putObject(jsonElement, GraphSONTokens._ID, element.getId()); + } + + if (this.includeReservedVertexType) { + jsonElement.put(GraphSONTokens._TYPE, GraphSONTokens.VERTEX); + } + } + + return jsonElement; + } +} diff --git a/sonar-core/src/test/java/org/sonar/core/graph/GraphSONReaderTest.java b/sonar-core/src/test/java/org/sonar/core/graph/GraphSONReaderTest.java deleted file mode 100644 index 69ba8119e4a..00000000000 --- a/sonar-core/src/test/java/org/sonar/core/graph/GraphSONReaderTest.java +++ /dev/null @@ -1,343 +0,0 @@ -/* - * Sonar, open source software quality management tool. - * Copyright (C) 2008-2012 SonarSource - * mailto:contact AT sonarsource DOT com - * - * Sonar is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * Sonar is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with Sonar; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ - -package org.sonar.core.graph; - - -import com.tinkerpop.blueprints.Direction; -import com.tinkerpop.blueprints.Edge; -import com.tinkerpop.blueprints.Vertex; -import com.tinkerpop.blueprints.impls.tg.TinkerGraph; -import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; -import com.tinkerpop.blueprints.util.io.graphson.GraphSONMode; -import com.tinkerpop.blueprints.util.io.graphson.GraphSONTokens; -import org.junit.Assert; -import org.junit.Test; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -public class GraphSONReaderTest { - - @Test - public void inputGraphModeExtended() throws Exception { - TinkerGraph graph = new TinkerGraph(); - - String json = "{ \"mode\":\"EXTENDED\", \"vertices\": [ {\"_id\":1, \"_type\":\"vertex\", \"test\": { \"type\":\"string\", \"value\":\"please work\"}, \"testlist\":{\"type\":\"list\", \"value\":[{\"type\":\"int\", \"value\":1}, {\"type\":\"int\",\"value\":2}, {\"type\":\"int\",\"value\":3}, {\"type\":\"unknown\",\"value\":null}]}, \"testmap\":{\"type\":\"map\", \"value\":{\"big\":{\"type\":\"long\", \"value\":10000000000}, \"small\":{\"type\":\"double\", \"value\":0.4954959595959}, \"nullKey\":{\"type\":\"unknown\", \"value\":null}}}}, {\"_id\":2, \"_type\":\"vertex\", \"testagain\":{\"type\":\"string\", \"value\":\"please work again\"}}], \"edges\":[{\"_id\":100, \"_type\":\"edge\", \"_outV\":1, \"_inV\":2, \"_label\":\"works\", \"teste\": {\"type\":\"string\", \"value\":\"please worke\"}, \"keyNull\":{\"type\":\"unknown\", \"value\":null}}]}"; - - byte[] bytes = json.getBytes(); - InputStream inputStream = new ByteArrayInputStream(bytes); - - GraphSONReader.inputGraph(graph, inputStream); - - Assert.assertEquals(2, getIterableCount(graph.getVertices())); - Assert.assertEquals(1, getIterableCount(graph.getEdges())); - - Vertex v1 = graph.getVertex(1); - Assert.assertNotNull(v1); - Assert.assertEquals("please work", v1.getProperty("test")); - - Map map = (Map) v1.getProperty("testmap"); - Assert.assertNotNull(map); - Assert.assertEquals(10000000000l, Long.parseLong(map.get("big").toString())); - Assert.assertEquals(0.4954959595959, Double.parseDouble(map.get("small").toString()), 0); - Assert.assertNull(map.get("nullKey")); - - List list = (List) v1.getProperty("testlist"); - Assert.assertEquals(4, list.size()); - - boolean foundNull = false; - for (int ix = 0; ix < list.size(); ix++) { - if (list.get(ix) == null) { - foundNull = true; - break; - } - } - - Assert.assertTrue(foundNull); - - Vertex v2 = graph.getVertex(2); - Assert.assertNotNull(v2); - Assert.assertEquals("please work again", v2.getProperty("testagain")); - - Edge e = graph.getEdge(100); - Assert.assertNotNull(e); - Assert.assertEquals("works", e.getLabel()); - Assert.assertEquals(v1, e.getVertex(Direction.OUT)); - Assert.assertEquals(v2, e.getVertex(Direction.IN)); - Assert.assertEquals("please worke", e.getProperty("teste")); - Assert.assertNull(e.getProperty("keyNull")); - - } - - @Test - public void inputGraphModeNormal() throws Exception { - TinkerGraph graph = new TinkerGraph(); - - String json = "{ \"mode\":\"NORMAL\",\"vertices\": [ {\"_id\":1, \"_type\":\"vertex\", \"test\": \"please work\", \"testlist\":[1, 2, 3, null], \"testmap\":{\"big\":10000000000, \"small\":0.4954959595959, \"nullKey\":null}}, {\"_id\":2, \"_type\":\"vertex\", \"testagain\":\"please work again\"}], \"edges\":[{\"_id\":100, \"_type\":\"edge\", \"_outV\":1, \"_inV\":2, \"_label\":\"works\", \"teste\": \"please worke\", \"keyNull\":null}]}"; - - byte[] bytes = json.getBytes(); - InputStream inputStream = new ByteArrayInputStream(bytes); - - GraphSONReader.inputGraph(graph, inputStream); - - Assert.assertEquals(2, getIterableCount(graph.getVertices())); - Assert.assertEquals(1, getIterableCount(graph.getEdges())); - - Vertex v1 = graph.getVertex(1); - Assert.assertNotNull(v1); - Assert.assertEquals("please work", v1.getProperty("test")); - - Map map = (Map) v1.getProperty("testmap"); - Assert.assertNotNull(map); - Assert.assertEquals(10000000000l, Long.parseLong(map.get("big").toString())); - Assert.assertEquals(0.4954959595959, Double.parseDouble(map.get("small").toString()), 0); - Assert.assertNull(map.get("nullKey")); - - List list = (List) v1.getProperty("testlist"); - Assert.assertEquals(4, list.size()); - - boolean foundNull = false; - for (int ix = 0; ix < list.size(); ix++) { - if (list.get(ix) == null) { - foundNull = true; - break; - } - } - - Assert.assertTrue(foundNull); - - Vertex v2 = graph.getVertex(2); - Assert.assertNotNull(v2); - Assert.assertEquals("please work again", v2.getProperty("testagain")); - - Edge e = graph.getEdge(100); - Assert.assertNotNull(e); - Assert.assertEquals("works", e.getLabel()); - Assert.assertEquals(v1, e.getVertex(Direction.OUT)); - Assert.assertEquals(v2, e.getVertex(Direction.IN)); - Assert.assertEquals("please worke", e.getProperty("teste")); - Assert.assertNull(e.getProperty("keyNull")); - - } - - @Test - public void inputGraphModeCompact() throws Exception { - TinkerGraph graph = new TinkerGraph(); - - String json = "{ \"mode\":\"COMPACT\",\"vertices\": [ {\"_id\":1, \"test\": \"please work\", \"testlist\":[1, 2, 3, null], \"testmap\":{\"big\":10000000000, \"small\":0.4954959595959, \"nullKey\":null}}, {\"_id\":2, \"testagain\":\"please work again\"}], \"edges\":[{\"_id\":100, \"_outV\":1, \"_inV\":2, \"_label\":\"works\", \"teste\": \"please worke\", \"keyNull\":null}]}"; - - byte[] bytes = json.getBytes(); - InputStream inputStream = new ByteArrayInputStream(bytes); - - GraphSONReader.inputGraph(graph, inputStream); - - Assert.assertEquals(2, getIterableCount(graph.getVertices())); - Assert.assertEquals(1, getIterableCount(graph.getEdges())); - - Vertex v1 = graph.getVertex(1); - Assert.assertNotNull(v1); - Assert.assertEquals("please work", v1.getProperty("test")); - - Map map = (Map) v1.getProperty("testmap"); - Assert.assertNotNull(map); - Assert.assertEquals(10000000000l, Long.parseLong(map.get("big").toString())); - Assert.assertEquals(0.4954959595959, Double.parseDouble(map.get("small").toString()), 0); - Assert.assertNull(map.get("nullKey")); - - List list = (List) v1.getProperty("testlist"); - Assert.assertEquals(4, list.size()); - - boolean foundNull = false; - for (int ix = 0; ix < list.size(); ix++) { - if (list.get(ix) == null) { - foundNull = true; - break; - } - } - - Assert.assertTrue(foundNull); - - Vertex v2 = graph.getVertex(2); - Assert.assertNotNull(v2); - Assert.assertEquals("please work again", v2.getProperty("testagain")); - - Edge e = graph.getEdge(100); - Assert.assertNotNull(e); - Assert.assertEquals("works", e.getLabel()); - Assert.assertEquals(v1, e.getVertex(Direction.OUT)); - Assert.assertEquals(v2, e.getVertex(Direction.IN)); - Assert.assertEquals("please worke", e.getProperty("teste")); - Assert.assertNull(e.getProperty("keyNull")); - - } - - @Test - public void inputGraphExtendedFullCycle() throws Exception { - TinkerGraph graph = TinkerGraphFactory.createTinkerGraph(); - - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - - GraphSONWriter writer = new GraphSONWriter(graph); - writer.outputGraph(stream, null, null, GraphSONMode.EXTENDED); - - stream.flush(); - stream.close(); - - String jsonString = new String(stream.toByteArray()); - - byte[] bytes = jsonString.getBytes(); - InputStream inputStream = new ByteArrayInputStream(bytes); - - TinkerGraph emptyGraph = new TinkerGraph(); - GraphSONReader.inputGraph(emptyGraph, inputStream); - - Assert.assertEquals(6, getIterableCount(emptyGraph.getVertices())); - Assert.assertEquals(6, getIterableCount(emptyGraph.getEdges())); - - for (Vertex v : graph.getVertices()) { - Vertex found = emptyGraph.getVertex(v.getId()); - - Assert.assertNotNull(v); - - for (String key : found.getPropertyKeys()) { - Assert.assertEquals(v.getProperty(key), found.getProperty(key)); - } - } - - for (Edge e : graph.getEdges()) { - Edge found = emptyGraph.getEdge(e.getId()); - - Assert.assertNotNull(e); - - for (String key : found.getPropertyKeys()) { - Assert.assertEquals(e.getProperty(key), found.getProperty(key)); - } - } - - } - - @Test - public void inputGraphCompactFullCycle() throws Exception { - TinkerGraph graph = TinkerGraphFactory.createTinkerGraph(); - - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - - Set edgeKeys = new HashSet(); - edgeKeys.add(GraphSONTokens._ID); - edgeKeys.add(GraphSONTokens._IN_V); - edgeKeys.add(GraphSONTokens._OUT_V); - edgeKeys.add(GraphSONTokens._LABEL); - - Set vertexKeys = new HashSet(); - vertexKeys.add(GraphSONTokens._ID); - - GraphSONWriter writer = new GraphSONWriter(graph); - writer.outputGraph(stream, vertexKeys, edgeKeys, GraphSONMode.COMPACT); - - stream.flush(); - stream.close(); - - String jsonString = new String(stream.toByteArray()); - - byte[] bytes = jsonString.getBytes(); - InputStream inputStream = new ByteArrayInputStream(bytes); - - TinkerGraph emptyGraph = new TinkerGraph(); - GraphSONReader.inputGraph(emptyGraph, inputStream); - - Assert.assertEquals(6, getIterableCount(emptyGraph.getVertices())); - Assert.assertEquals(6, getIterableCount(emptyGraph.getEdges())); - - for (Vertex v : graph.getVertices()) { - Vertex found = emptyGraph.getVertex(v.getId()); - - Assert.assertNotNull(v); - - for (String key : found.getPropertyKeys()) { - Assert.assertEquals(v.getProperty(key), found.getProperty(key)); - } - - // no properties should be here - Assert.assertEquals(null, found.getProperty("name")); - } - - for (Edge e : graph.getEdges()) { - Edge found = emptyGraph.getEdge(e.getId()); - - Assert.assertNotNull(e); - - for (String key : found.getPropertyKeys()) { - Assert.assertEquals(e.getProperty(key), found.getProperty(key)); - } - - // no properties should be here - Assert.assertEquals(null, found.getProperty("weight")); - } - - } - - @Test(expected = IllegalArgumentException.class) - public void inputGraphCompactFullCycleBroken() throws Exception { - TinkerGraph graph = TinkerGraphFactory.createTinkerGraph(); - - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - - Set edgeKeys = new HashSet(); - edgeKeys.add(GraphSONTokens._IN_V); - edgeKeys.add(GraphSONTokens._OUT_V); - edgeKeys.add(GraphSONTokens._LABEL); - - Set vertexKeys = new HashSet(); - - GraphSONWriter writer = new GraphSONWriter(graph); - writer.outputGraph(stream, vertexKeys, edgeKeys, GraphSONMode.COMPACT); - - stream.flush(); - stream.close(); - - String jsonString = new String(stream.toByteArray()); - - byte[] bytes = jsonString.getBytes(); - InputStream inputStream = new ByteArrayInputStream(bytes); - - TinkerGraph emptyGraph = new TinkerGraph(); - GraphSONReader.inputGraph(emptyGraph, inputStream); - - } - - private int getIterableCount(Iterable elements) { - int counter = 0; - - Iterator iterator = elements.iterator(); - while (iterator.hasNext()) { - iterator.next(); - counter++; - } - - return counter; - } -} diff --git a/sonar-core/src/test/java/org/sonar/core/graph/GraphSONUtilityTest.java b/sonar-core/src/test/java/org/sonar/core/graph/GraphSONUtilityTest.java deleted file mode 100644 index 23b2653d07e..00000000000 --- a/sonar-core/src/test/java/org/sonar/core/graph/GraphSONUtilityTest.java +++ /dev/null @@ -1,1156 +0,0 @@ -/* - * Sonar, open source software quality management tool. - * Copyright (C) 2008-2012 SonarSource - * mailto:contact AT sonarsource DOT com - * - * Sonar is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * Sonar is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with Sonar; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ - -package org.sonar.core.graph; - -import com.tinkerpop.blueprints.Direction; -import com.tinkerpop.blueprints.Edge; -import com.tinkerpop.blueprints.Graph; -import com.tinkerpop.blueprints.Vertex; -import com.tinkerpop.blueprints.impls.tg.TinkerGraph; -import com.tinkerpop.blueprints.util.io.graphson.ElementFactory; -import com.tinkerpop.blueprints.util.io.graphson.ElementPropertyConfig; -import com.tinkerpop.blueprints.util.io.graphson.GraphElementFactory; -import com.tinkerpop.blueprints.util.io.graphson.GraphSONMode; -import com.tinkerpop.blueprints.util.io.graphson.GraphSONTokens; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.JSONValue; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import static org.fest.assertions.Assertions.assertThat; - -public class GraphSONUtilityTest { - private final String vertexJson1 = "{\"name\":\"marko\",\"age\":29,\"_id\":1,\"_type\":\"vertex\"}"; - private final String vertexJson2 = "{\"name\":\"vadas\",\"age\":27,\"_id\":2,\"_type\":\"vertex\"}"; - private final String edgeJsonLight = "{\"weight\":0.5,\"_outV\":1,\"_inV\":2}"; - private final String edgeJson = "{\"weight\":0.5,\"_id\":7,\"_type\":\"edge\",\"_outV\":1,\"_inV\":2,\"_label\":\"knows\"}"; - private TinkerGraph graph = new TinkerGraph(); - private InputStream inputStreamVertexJson1; - private InputStream inputStreamEdgeJsonLight; - - @Before - public void setUp() { - this.graph.clear(); - - this.inputStreamVertexJson1 = new ByteArrayInputStream(vertexJson1.getBytes()); - this.inputStreamEdgeJsonLight = new ByteArrayInputStream(edgeJsonLight.getBytes()); - } - - @Test - public void jsonFromElementEdgeNoPropertiesNoKeysNoTypes() { - Vertex v1 = this.graph.addVertex(1); - Vertex v2 = this.graph.addVertex(2); - - Edge e = this.graph.addEdge(3, v1, v2, "test"); - e.setProperty("weight", 0.5f); - - JSONObject json = GraphSONUtility.jsonFromElement(e, null, GraphSONMode.NORMAL); - - assertThat(json).isNotNull(); - assertThat(json.containsKey(GraphSONTokens._ID)).isTrue(); - assertThat(json.get(GraphSONTokens._ID)).isEqualTo("3"); - assertThat(json.containsKey(GraphSONTokens._LABEL)).isTrue(); - assertThat(json.get(GraphSONTokens._LABEL)).isEqualTo("test"); - assertThat(json.containsKey(GraphSONTokens._TYPE)).isTrue(); - assertThat(json.get(GraphSONTokens._TYPE)).isEqualTo("edge"); - assertThat(json.containsKey(GraphSONTokens._IN_V)).isTrue(); - assertThat(json.get(GraphSONTokens._IN_V)).isEqualTo("2"); - assertThat(json.containsKey(GraphSONTokens._OUT_V)).isTrue(); - assertThat(json.get(GraphSONTokens._OUT_V)).isEqualTo("1"); - assertThat(json.containsKey("weight")).isTrue(); - assertThat(json.get("weight")).isEqualTo(0.5f); - } - - @Test - public void jsonFromElementEdgeCompactIdOnlyAsInclude() { - Vertex v1 = this.graph.addVertex(1); - Vertex v2 = this.graph.addVertex(2); - - Edge e = this.graph.addEdge(3, v1, v2, "test"); - e.setProperty("weight", 0.5f); - - Set propertiesToInclude = new HashSet() {{ - add(GraphSONTokens._ID); - }}; - - JSONObject json = GraphSONUtility.jsonFromElement(e, propertiesToInclude, GraphSONMode.COMPACT); - - assertThat(json).isNotNull(); - assertThat(json.containsKey(GraphSONTokens._TYPE)).isFalse(); - assertThat(json.containsKey(GraphSONTokens._LABEL)).isFalse(); - assertThat(json.containsKey(GraphSONTokens._IN_V)).isFalse(); - assertThat(json.containsKey(GraphSONTokens._OUT_V)).isFalse(); - assertThat(json.containsKey(GraphSONTokens._ID)).isTrue(); - assertThat(json.containsKey("weight")).isFalse(); - } - - @Test - public void jsonFromElementEdgeCompactIdOnlyAsExclude() { - ElementFactory factory = new GraphElementFactory(this.graph); - Vertex v1 = this.graph.addVertex(1); - Vertex v2 = this.graph.addVertex(2); - - Edge e = this.graph.addEdge(3, v1, v2, "test"); - e.setProperty("weight", 0.5f); - e.setProperty("x", "y"); - - Set propertiesToExclude = new HashSet() {{ - add(GraphSONTokens._TYPE); - add(GraphSONTokens._LABEL); - add(GraphSONTokens._IN_V); - add(GraphSONTokens._OUT_V); - add("weight"); - }}; - - ElementPropertyConfig config = new ElementPropertyConfig(null, propertiesToExclude, - ElementPropertyConfig.ElementPropertiesRule.INCLUDE, - ElementPropertyConfig.ElementPropertiesRule.EXCLUDE); - GraphSONUtility utility = new GraphSONUtility(GraphSONMode.COMPACT, factory, config); - JSONObject json = utility.jsonFromElement(e); - - assertThat(json).isNotNull(); - assertThat(json.containsKey(GraphSONTokens._TYPE)).isFalse(); - assertThat(json.containsKey(GraphSONTokens._LABEL)).isFalse(); - assertThat(json.containsKey(GraphSONTokens._IN_V)).isFalse(); - assertThat(json.containsKey(GraphSONTokens._OUT_V)).isFalse(); - assertThat(json.containsKey(GraphSONTokens._ID)).isTrue(); - assertThat(json.containsKey("weight")).isFalse(); - assertThat(json.containsKey("x")).isTrue(); - assertThat(json.get("x")).isEqualTo("y"); - } - - @Test - public void jsonFromElementEdgeCompactAllKeys() { - Vertex v1 = this.graph.addVertex(1); - Vertex v2 = this.graph.addVertex(2); - - Edge e = this.graph.addEdge(3, v1, v2, "test"); - e.setProperty("weight", 0.5f); - - JSONObject json = GraphSONUtility.jsonFromElement(e, null, GraphSONMode.COMPACT); - - assertThat(json).isNotNull(); - assertThat(json.containsKey(GraphSONTokens._ID)).isTrue(); - assertThat(json.containsKey(GraphSONTokens._TYPE)).isTrue(); - assertThat(json.containsKey(GraphSONTokens._LABEL)).isTrue(); - assertThat(json.containsKey(GraphSONTokens._IN_V)).isTrue(); - assertThat(json.containsKey(GraphSONTokens._OUT_V)).isTrue(); - assertThat(json.get("weight")).isEqualTo(0.5f); - } - - @Test - public void jsonFromElementVertexNoPropertiesNoKeysNoTypes() { - Vertex v = this.graph.addVertex(1); - v.setProperty("name", "marko"); - - JSONObject json = GraphSONUtility.jsonFromElement(v, null, GraphSONMode.NORMAL); - - assertThat(json).isNotNull(); - assertThat(json.containsKey(GraphSONTokens._ID)).isTrue(); - assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); - assertThat(json.containsKey(GraphSONTokens._TYPE)).isTrue(); - assertThat(json.get(GraphSONTokens._TYPE)).isEqualTo("vertex"); - assertThat(json.get("name")).isEqualTo("marko"); - } - - @Test - public void jsonFromElementVertexCompactIdOnlyAsInclude() { - Vertex v = this.graph.addVertex(1); - v.setProperty("name", "marko"); - - Set propertiesToInclude = new HashSet() {{ - add(GraphSONTokens._ID); - }}; - - JSONObject json = GraphSONUtility.jsonFromElement(v, propertiesToInclude, GraphSONMode.COMPACT); - - assertThat(json).isNotNull(); - assertThat(json.containsKey(GraphSONTokens._TYPE)).isFalse(); - assertThat(json.containsKey(GraphSONTokens._ID)).isTrue(); - assertThat(json.containsKey("name")).isFalse(); - } - - @Test - public void jsonFromElementVertexCompactIdNameOnlyAsExclude() { - GraphElementFactory factory = new GraphElementFactory(this.graph); - Vertex v = this.graph.addVertex(1); - v.setProperty("name", "marko"); - - Set propertiesToExclude = new HashSet() {{ - add(GraphSONTokens._TYPE); - }}; - - ElementPropertyConfig config = new ElementPropertyConfig(propertiesToExclude, null, - ElementPropertyConfig.ElementPropertiesRule.EXCLUDE, - ElementPropertyConfig.ElementPropertiesRule.EXCLUDE); - - GraphSONUtility utility = new GraphSONUtility(GraphSONMode.COMPACT, factory, config); - JSONObject json = utility.jsonFromElement(v); - - assertThat(json).isNotNull(); - assertThat(json.containsKey(GraphSONTokens._TYPE)).isFalse(); - assertThat(json.containsKey(GraphSONTokens._ID)).isTrue(); - assertThat(json.containsKey("name")).isTrue(); - } - - @Test - public void jsonFromElementVertexCompactAllOnly() { - Vertex v = this.graph.addVertex(1); - v.setProperty("name", "marko"); - - JSONObject json = GraphSONUtility.jsonFromElement(v, null, GraphSONMode.COMPACT); - - assertThat(json).isNotNull(); - assertThat(json.containsKey(GraphSONTokens._TYPE)).isTrue(); - assertThat(json.containsKey(GraphSONTokens._ID)).isTrue(); - assertThat(json.containsKey("name")).isTrue(); - } - - @Test - public void jsonFromElementVertexPrimitivePropertiesNoKeysNoTypes() { - Vertex v = this.graph.addVertex(1); - v.setProperty("keyString", "string"); - v.setProperty("keyLong", 1L); - v.setProperty("keyInt", 2); - v.setProperty("keyFloat", 3.3f); - v.setProperty("keyExponentialDouble", 1312928167.626012); - v.setProperty("keyDouble", 4.4); - v.setProperty("keyBoolean", true); - - JSONObject json = GraphSONUtility.jsonFromElement(v, null, GraphSONMode.NORMAL); - - assertThat(json).isNotNull(); - assertThat(json.containsKey(GraphSONTokens._ID)).isTrue(); - assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); - assertThat(json.containsKey("keyString")).isTrue(); - assertThat(json.get("keyString")).isEqualTo("string"); - assertThat(json.containsKey("keyLong")).isTrue(); - assertThat(json.get("keyLong")).isEqualTo(1L); - assertThat(json.containsKey("keyInt")).isTrue(); - assertThat(json.get("keyInt")).isEqualTo(2); - assertThat(json.containsKey("keyFloat")).isTrue(); - assertThat(json.get("keyFloat")).isEqualTo(3.3f); - assertThat(json.containsKey("keyExponentialDouble")).isTrue(); - assertThat(json.get("keyExponentialDouble")).isEqualTo(1312928167.626012); - assertThat(json.containsKey("keyDouble")).isTrue(); - assertThat(json.get("keyDouble")).isEqualTo(4.4); - assertThat(json.containsKey("keyBoolean")).isTrue(); - assertThat(json.get("keyBoolean")).isEqualTo(true); - } - - @Test - public void jsonFromElementVertexMapPropertyNoKeysNoTypes() { - Vertex v = this.graph.addVertex(1); - Map map = new HashMap(); - map.put("this", "some"); - map.put("that", 1); - - v.setProperty("keyMap", map); - - JSONObject json = GraphSONUtility.jsonFromElement(v, null, GraphSONMode.NORMAL); - - assertThat(json).isNotNull(); - assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); - assertThat(json.containsKey("keyMap")).isTrue(); - - JSONObject mapAsJSON = (JSONObject) json.get("keyMap"); - assertThat(mapAsJSON).isNotNull(); - assertThat(mapAsJSON.containsKey("this")).isTrue(); - assertThat(mapAsJSON.get("this")).isEqualTo("some"); - assertThat(mapAsJSON.containsKey("that")).isTrue(); - assertThat(mapAsJSON.get("that")).isEqualTo(1); - } - - @Test - public void jsonFromElementVertexListPropertyNoKeysNoTypes() { - Vertex v = this.graph.addVertex(1); - List list = new ArrayList(); - list.add("this"); - list.add("that"); - list.add("other"); - list.add(true); - - v.setProperty("keyList", list); - - JSONObject json = GraphSONUtility.jsonFromElement(v, null, GraphSONMode.NORMAL); - - assertThat(json).isNotNull(); - assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); - assertThat(json.containsKey("keyList")).isTrue(); - - JSONArray listAsJSON = (JSONArray) json.get("keyList"); - assertThat(listAsJSON).isNotNull(); - assertThat(listAsJSON).hasSize(4); - } - - @Test - public void jsonFromElementVertexStringArrayPropertyNoKeysNoTypes() { - Vertex v = this.graph.addVertex(1); - String[] stringArray = new String[]{"this", "that", "other"}; - - v.setProperty("keyStringArray", stringArray); - - JSONObject json = GraphSONUtility.jsonFromElement(v, null, GraphSONMode.NORMAL); - - assertThat(json).isNotNull(); - assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); - assertThat(json.containsKey("keyStringArray")).isTrue(); - - JSONArray stringArrayAsJSON = (JSONArray) json.get("keyStringArray"); - assertThat(stringArrayAsJSON).isNotNull(); - assertThat(stringArrayAsJSON).hasSize(3); - } - - @Test - public void jsonFromElementVertexDoubleArrayPropertyNoKeysNoTypes() { - Vertex v = this.graph.addVertex(1); - double[] doubleArray = new double[]{1.0, 2.0, 3.0}; - - v.setProperty("keyDoubleArray", doubleArray); - - JSONObject json = GraphSONUtility.jsonFromElement(v, null, GraphSONMode.NORMAL); - - assertThat(json).isNotNull(); - assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); - assertThat(json.containsKey("keyDoubleArray")).isTrue(); - - JSONArray doubleArrayAsJSON = (JSONArray) json.get("keyDoubleArray"); - assertThat(doubleArrayAsJSON).isNotNull(); - assertThat(doubleArrayAsJSON).hasSize(3); - } - - @Test - public void jsonFromElementVertexIntArrayPropertyNoKeysNoTypes() { - Vertex v = this.graph.addVertex(1); - int[] intArray = new int[]{1, 2, 3}; - - v.setProperty("keyIntArray", intArray); - - JSONObject json = GraphSONUtility.jsonFromElement(v, null, GraphSONMode.NORMAL); - - assertThat(json).isNotNull(); - assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); - assertThat(json.containsKey("keyIntArray")).isTrue(); - - JSONArray intArrayAsJSON = (JSONArray) json.get("keyIntArray"); - assertThat(intArrayAsJSON).isNotNull(); - assertThat(intArrayAsJSON).hasSize(3); - } - - @Test - public void jsonFromElementVertexLongArrayPropertyNoKeysNoTypes() { - Vertex v = this.graph.addVertex(1); - long[] longArray = new long[]{1l, 2l, 3l}; - - v.setProperty("keyLongArray", longArray); - - JSONObject json = GraphSONUtility.jsonFromElement(v, null, GraphSONMode.NORMAL); - - assertThat(json).isNotNull(); - assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); - assertThat(json.containsKey("keyLongArray")).isTrue(); - - JSONArray longArrayAsJSON = (JSONArray) json.get("keyLongArray"); - assertThat(longArrayAsJSON).isNotNull(); - assertThat(longArrayAsJSON).hasSize(3); - } - - @Test - public void jsonFromElementFloatArrayPropertyNoKeysNoTypes() { - Vertex v = this.graph.addVertex(1); - float[] floatArray = new float[]{1.0f, 2.0f, 3.0f}; - - v.setProperty("keyFloatArray", floatArray); - - JSONObject json = GraphSONUtility.jsonFromElement(v, null, GraphSONMode.NORMAL); - - assertThat(json).isNotNull(); - assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); - assertThat(json.containsKey("keyFloatArray")).isTrue(); - - JSONArray floatArrayAsJSON = (JSONArray) json.get("keyFloatArray"); - assertThat(floatArrayAsJSON).isNotNull(); - assertThat(floatArrayAsJSON).hasSize(3); - } - - @Test - public void jsonFromElementBooleanArrayPropertyNoKeysNoTypes() { - Vertex v = this.graph.addVertex(1); - boolean[] booleanArray = new boolean[]{true, false, true}; - - v.setProperty("keyBooleanArray", booleanArray); - - JSONObject json = GraphSONUtility.jsonFromElement(v, null, GraphSONMode.NORMAL); - - assertThat(json).isNotNull(); - assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); - assertThat(json.containsKey("keyBooleanArray")).isTrue(); - - JSONArray booleanArrayAsJSON = (JSONArray) json.get("keyBooleanArray"); - assertThat(booleanArrayAsJSON).isNotNull(); - assertThat(booleanArrayAsJSON).hasSize(3); - } - - @Test - public void jsonFromElementVertexCatPropertyNoKeysNoTypes() { - Vertex v = this.graph.addVertex(1); - v.setProperty("mycat", new Cat("smithers")); - - JSONObject json = GraphSONUtility.jsonFromElement(v, null, GraphSONMode.NORMAL); - - assertThat(json).isNotNull(); - assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); - assertThat(json.containsKey("mycat")).isTrue(); - assertThat(json.get("mycat")).isEqualTo("smithers"); - } - - @Test - public void jsonFromElementVertexCatPropertyNoKeysWithTypes() { - Vertex v = this.graph.addVertex(1); - v.setProperty("mycat", new Cat("smithers")); - - JSONObject json = GraphSONUtility.jsonFromElement(v, null, GraphSONMode.EXTENDED); - - assertThat(json).isNotNull(); - assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); - assertThat(json.containsKey("mycat")).isTrue(); - - JSONObject jsonObjectCat = (JSONObject) json.get("mycat"); - assertThat(jsonObjectCat.containsKey("value")).isTrue(); - assertThat(jsonObjectCat.get("value")).isEqualTo("smithers"); - } - - @Test - public void jsonFromElementVertexCatArrayPropertyNoKeysNoTypes() { - Vertex v = this.graph.addVertex(1); - List cats = new ArrayList(); - cats.add(new Cat("smithers")); - cats.add(new Cat("mcallister")); - - v.setProperty("cats", cats); - - JSONObject json = GraphSONUtility.jsonFromElement(v, null, GraphSONMode.NORMAL); - - assertThat(json).isNotNull(); - assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); - assertThat(json.containsKey("cats")).isTrue(); - - JSONArray catListAsJson = (JSONArray) json.get("cats"); - assertThat(catListAsJson).hasSize(2); - } - - @Test - public void jsonFromElementCrazyPropertyNoKeysNoTypes() { - Vertex v = this.graph.addVertex(1); - List mix = new ArrayList(); - mix.add(new Cat("smithers")); - mix.add(true); - - List deepCats = new ArrayList(); - deepCats.add(new Cat("mcallister")); - mix.add(deepCats); - - Map map = new HashMap(); - map.put("crazy", mix); - - int[] someInts = new int[]{1, 2, 3}; - map.put("ints", someInts); - - map.put("regular", "stuff"); - - Map innerMap = new HashMap(); - innerMap.put("me", "you"); - - map.put("inner", innerMap); - - v.setProperty("crazy-map", map); - - JSONObject json = GraphSONUtility.jsonFromElement(v, null, GraphSONMode.NORMAL); - - assertThat(json).isNotNull(); - assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); - assertThat(json.containsKey("crazy-map")).isTrue(); - - JSONObject mapAsJson = (JSONObject) json.get("crazy-map"); - assertThat(mapAsJson.containsKey("regular")).isTrue(); - assertThat(mapAsJson.get("regular")).isEqualTo("stuff"); - - assertThat(mapAsJson.containsKey("ints")).isTrue(); - JSONArray intArrayAsJson = (JSONArray) mapAsJson.get("ints"); - assertThat(intArrayAsJson).hasSize(3); - - assertThat(mapAsJson.containsKey("crazy")).isTrue(); - JSONArray deepListAsJSON = (JSONArray) mapAsJson.get("crazy"); - assertThat(deepListAsJSON).hasSize(3); - - assertThat(mapAsJson.containsKey("inner")).isTrue(); - JSONObject mapInMapAsJSON = (JSONObject) mapAsJson.get("inner"); - assertThat(mapInMapAsJSON.containsKey("me")).isTrue(); - assertThat(mapInMapAsJSON.get("me")).isEqualTo("you"); - - } - - @Test - public void jsonFromElementVertexNoPropertiesWithKeysNoTypes() { - Vertex v = this.graph.addVertex(1); - v.setProperty("x", "X"); - v.setProperty("y", "Y"); - v.setProperty("z", "Z"); - - Set propertiesToInclude = new HashSet(); - propertiesToInclude.add("y"); - JSONObject json = GraphSONUtility.jsonFromElement(v, propertiesToInclude, GraphSONMode.NORMAL); - - assertThat(json).isNotNull(); - assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); - assertThat(json.get(GraphSONTokens._TYPE)).isEqualTo("vertex"); - assertThat(json.containsKey("x")).isFalse(); - assertThat(json.containsKey("z")).isFalse(); - assertThat(json.containsKey("y")).isTrue(); - } - - @Test - public void jsonFromElementVertexVertexPropertiesWithKeysNoTypes() { - Vertex v = this.graph.addVertex(1); - v.setProperty("x", "X"); - v.setProperty("y", "Y"); - v.setProperty("z", "Z"); - - Vertex innerV = this.graph.addVertex(2); - innerV.setProperty("x", "X"); - innerV.setProperty("y", "Y"); - innerV.setProperty("z", "Z"); - - v.setProperty("v", innerV); - - Set propertiesToInclude = new HashSet(); - propertiesToInclude.add("y"); - propertiesToInclude.add("v"); - - JSONObject json = GraphSONUtility.jsonFromElement(v, propertiesToInclude, GraphSONMode.NORMAL); - - assertThat(json).isNotNull(); - assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); - assertThat(json.get(GraphSONTokens._TYPE)).isEqualTo("vertex"); - assertThat(json.containsKey("x")).isFalse(); - assertThat(json.containsKey("z")).isFalse(); - assertThat(json.containsKey("y")).isTrue(); - assertThat(json.containsKey("v")).isTrue(); - - JSONObject innerJson = (JSONObject) json.get("v"); - assertThat(innerJson.containsKey("x")).isFalse(); - assertThat(innerJson.containsKey("z")).isFalse(); - assertThat(innerJson.containsKey("y")).isTrue(); - assertThat(innerJson.containsKey("v")).isFalse(); - } - - @Test - public void jsonFromElementVertexPrimitivePropertiesNoKeysWithTypes() { - Vertex v = this.graph.addVertex(1); - v.setProperty("keyString", "string"); - v.setProperty("keyLong", 1L); - v.setProperty("keyInt", 2); - v.setProperty("keyFloat", 3.3f); - v.setProperty("keyDouble", 4.4); - v.setProperty("keyBoolean", true); - - JSONObject json = GraphSONUtility.jsonFromElement(v, null, GraphSONMode.EXTENDED); - - assertThat(json).isNotNull(); - assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); - assertThat(json.containsKey("keyString")).isTrue(); - - JSONObject valueAsJson = (JSONObject) json.get("keyString"); - assertThat(valueAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); - assertThat(valueAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_STRING); - assertThat(valueAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); - assertThat(valueAsJson.get(GraphSONTokens.VALUE)).isEqualTo("string"); - - valueAsJson = (JSONObject) json.get("keyLong"); - assertThat(valueAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); - assertThat(valueAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_LONG); - assertThat(valueAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); - assertThat(valueAsJson.get(GraphSONTokens.VALUE)).isEqualTo(1L); - - valueAsJson = (JSONObject) json.get("keyInt"); - assertThat(valueAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); - assertThat(valueAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_INTEGER); - assertThat(valueAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); - assertThat(valueAsJson.get(GraphSONTokens.VALUE)).isEqualTo(2); - - valueAsJson = (JSONObject) json.get("keyFloat"); - assertThat(valueAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); - assertThat(valueAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_FLOAT); - assertThat(valueAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); - assertThat(valueAsJson.get(GraphSONTokens.VALUE)).isEqualTo(3.3f); - - valueAsJson = (JSONObject) json.get("keyDouble"); - assertThat(valueAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); - assertThat(valueAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_DOUBLE); - assertThat(valueAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); - assertThat(valueAsJson.get(GraphSONTokens.VALUE)).isEqualTo(4.4); - - valueAsJson = (JSONObject) json.get("keyBoolean"); - assertThat(valueAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); - assertThat(valueAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_BOOLEAN); - assertThat(valueAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); - assertThat(valueAsJson.get(GraphSONTokens.VALUE)).isEqualTo(true); - } - - @Test - public void jsonFromElementVertexListPropertiesNoKeysWithTypes() { - Vertex v = this.graph.addVertex(1); - List list = new ArrayList(); - list.add("this"); - list.add("this"); - list.add("this"); - - v.setProperty("keyList", list); - - JSONObject json = GraphSONUtility.jsonFromElement(v, null, GraphSONMode.EXTENDED); - - assertThat(json).isNotNull(); - assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); - assertThat(json.containsKey("keyList")).isTrue(); - - JSONObject listWithTypeAsJson = (JSONObject) json.get("keyList"); - assertThat(listWithTypeAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); - assertThat(listWithTypeAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_LIST); - assertThat(listWithTypeAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); - - JSONArray listAsJSON = (JSONArray) listWithTypeAsJson.get(GraphSONTokens.VALUE); - assertThat(listAsJSON).isNotNull(); - assertThat(listAsJSON).hasSize(3); - - for (int ix = 0; ix < listAsJSON.size(); ix++) { - JSONObject valueAsJson = (JSONObject) listAsJSON.get(ix); - assertThat(valueAsJson).isNotNull(); - assertThat(valueAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); - assertThat(valueAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_STRING); - assertThat(valueAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); - assertThat(valueAsJson.get(GraphSONTokens.VALUE)).isEqualTo("this"); - } - } - - @Test - public void jsonFromElementVertexBooleanListPropertiesNoKeysWithTypes() { - Vertex v = this.graph.addVertex(1); - List list = new ArrayList(); - list.add(true); - list.add(true); - list.add(true); - - v.setProperty("keyList", list); - - JSONObject json = GraphSONUtility.jsonFromElement(v, null, GraphSONMode.EXTENDED); - - assertThat(json).isNotNull(); - assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); - assertThat(json.containsKey("keyList")).isTrue(); - - JSONObject listWithTypeAsJson = (JSONObject) json.get("keyList"); - assertThat(listWithTypeAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); - assertThat(listWithTypeAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_LIST); - assertThat(listWithTypeAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); - - JSONArray listAsJSON = (JSONArray) listWithTypeAsJson.get(GraphSONTokens.VALUE); - assertThat(listAsJSON).isNotNull(); - assertThat(listAsJSON).hasSize(3); - - for (int ix = 0; ix < listAsJSON.size(); ix++) { - JSONObject valueAsJson = (JSONObject) listAsJSON.get(ix); - assertThat(valueAsJson).isNotNull(); - assertThat(valueAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); - assertThat(valueAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_BOOLEAN); - assertThat(valueAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); - assertThat(valueAsJson.get(GraphSONTokens.VALUE)).isEqualTo(true); - } - } - - @Test - public void jsonFromElementVertexLongListPropertiesNoKeysWithTypes() { - Vertex v = this.graph.addVertex(1); - List list = new ArrayList(); - list.add(1000L); - list.add(1000L); - list.add(1000L); - - v.setProperty("keyList", list); - - JSONObject json = GraphSONUtility.jsonFromElement(v, null, GraphSONMode.EXTENDED); - - assertThat(json).isNotNull(); - assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); - assertThat(json.containsKey("keyList")).isTrue(); - - JSONObject listWithTypeAsJson = (JSONObject) json.get("keyList"); - assertThat(listWithTypeAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); - assertThat(listWithTypeAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_LIST); - assertThat(listWithTypeAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); - - JSONArray listAsJSON = (JSONArray) listWithTypeAsJson.get(GraphSONTokens.VALUE); - assertThat(listAsJSON).isNotNull(); - assertThat(listAsJSON).hasSize(3); - - for (int ix = 0; ix < listAsJSON.size(); ix++) { - JSONObject valueAsJson = (JSONObject) listAsJSON.get(ix); - assertThat(valueAsJson).isNotNull(); - assertThat(valueAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); - assertThat(valueAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_LONG); - assertThat(valueAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); - assertThat(valueAsJson.get(GraphSONTokens.VALUE)).isEqualTo(1000L); - } - } - - @Test - public void jsonFromElementVertexIntListPropertiesNoKeysWithTypes() { - Vertex v = this.graph.addVertex(1); - List list = new ArrayList(); - list.add(1); - list.add(1); - list.add(1); - - v.setProperty("keyList", list); - - JSONObject json = GraphSONUtility.jsonFromElement(v, null, GraphSONMode.EXTENDED); - - assertThat(json).isNotNull(); - assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); - assertThat(json.containsKey("keyList")).isTrue(); - - JSONObject listWithTypeAsJson = (JSONObject) json.get("keyList"); - assertThat(listWithTypeAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); - assertThat(listWithTypeAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_LIST); - assertThat(listWithTypeAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); - - JSONArray listAsJSON = (JSONArray) listWithTypeAsJson.get(GraphSONTokens.VALUE); - assertThat(listAsJSON).isNotNull(); - assertThat(listAsJSON).hasSize(3); - - for (int ix = 0; ix < listAsJSON.size(); ix++) { - JSONObject valueAsJson = (JSONObject) listAsJSON.get(ix); - assertThat(valueAsJson).isNotNull(); - assertThat(valueAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); - assertThat(valueAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_INTEGER); - assertThat(valueAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); - assertThat(valueAsJson.get(GraphSONTokens.VALUE)).isEqualTo(1); - } - } - - @Test - public void jsonFromElementVertexListOfListPropertiesNoKeysWithTypes() { - Vertex v = this.graph.addVertex(1); - List list = new ArrayList(); - list.add(1); - list.add(1); - list.add(1); - - List> listList = new ArrayList>(); - listList.add(list); - - v.setProperty("keyList", listList); - - JSONObject json = GraphSONUtility.jsonFromElement(v, null, GraphSONMode.EXTENDED); - - assertThat(json).isNotNull(); - assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); - assertThat(json.containsKey("keyList")).isTrue(); - - JSONObject listWithTypeAsJson = (JSONObject) json.get("keyList"); - assertThat(listWithTypeAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); - assertThat(listWithTypeAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_LIST); - assertThat(listWithTypeAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); - - JSONArray array = (JSONArray) listWithTypeAsJson.get(GraphSONTokens.VALUE); - JSONObject obj = (JSONObject) array.get(0); - JSONArray listAsJSON = (JSONArray) obj.get(GraphSONTokens.VALUE); - assertThat(listAsJSON).isNotNull(); - assertThat(listAsJSON).hasSize(3); - - for (int ix = 0; ix < listAsJSON.size(); ix++) { - JSONObject valueAsJson = (JSONObject) listAsJSON.get(ix); - assertThat(valueAsJson).isNotNull(); - assertThat(valueAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); - assertThat(valueAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_INTEGER); - assertThat(valueAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); - assertThat(valueAsJson.get(GraphSONTokens.VALUE)).isEqualTo(1); - } - } - - @Test - public void jsonFromElementVertexMapPropertiesNoKeysWithTypes() { - Vertex v = this.graph.addVertex(1); - - Map map = new HashMap(); - map.put("this", "some"); - map.put("that", 1); - - v.setProperty("keyMap", map); - - JSONObject json = GraphSONUtility.jsonFromElement(v, null, GraphSONMode.EXTENDED); - - assertThat(json).isNotNull(); - assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); - assertThat(json.containsKey("keyMap")).isTrue(); - - JSONObject mapWithTypeAsJSON = (JSONObject) json.get("keyMap"); - assertThat(mapWithTypeAsJSON).isNotNull(); - assertThat(mapWithTypeAsJSON.containsKey(GraphSONTokens.TYPE)).isTrue(); - assertThat(mapWithTypeAsJSON.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_MAP); - - assertThat(mapWithTypeAsJSON.containsKey(GraphSONTokens.VALUE)).isTrue(); - JSONObject mapAsJSON = (JSONObject) mapWithTypeAsJSON.get(GraphSONTokens.VALUE); - - assertThat(mapAsJSON.containsKey("this")).isTrue(); - JSONObject thisAsJson = (JSONObject) mapAsJSON.get("this"); - assertThat(thisAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); - assertThat(thisAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_STRING); - assertThat(thisAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); - assertThat(thisAsJson.get(GraphSONTokens.VALUE)).isEqualTo("some"); - - assertThat(mapAsJSON.containsKey("that")).isTrue(); - JSONObject thatAsJson = (JSONObject) mapAsJSON.get("that"); - assertThat(thatAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); - assertThat(thatAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_INTEGER); - assertThat(thatAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); - assertThat(thatAsJson.get(GraphSONTokens.VALUE)).isEqualTo(1); - } - - @Test - public void jsonFromElementNullsNoKeysNoTypes() { - Graph g = new TinkerGraph(); - Vertex v = g.addVertex(1); - v.setProperty("key", null); - - Map map = new HashMap(); - map.put("innerkey", null); - - List innerList = new ArrayList(); - innerList.add(null); - innerList.add("innerstring"); - map.put("list", innerList); - - v.setProperty("keyMap", map); - - List list = new ArrayList(); - list.add(null); - list.add("string"); - v.setProperty("keyList", list); - - JSONObject json = GraphSONUtility.jsonFromElement(v, null, GraphSONMode.NORMAL); - - assertThat(json).isNotNull(); - assertThat(json.get("key")).isNull(); - ; - - JSONObject jsonMap = (JSONObject) json.get("keyMap"); - assertThat(jsonMap).isNotNull(); - assertThat(jsonMap.get("innerkey")).isNull(); - - JSONArray jsonInnerArray = (JSONArray) jsonMap.get("list"); - assertThat(jsonInnerArray).isNotNull(); - assertThat(jsonInnerArray.get(0)).isNull(); - assertThat(jsonInnerArray.get(1)).isEqualTo("innerstring"); - - JSONArray jsonArray = (JSONArray) json.get("keyList"); - assertThat(jsonArray).isNotNull(); - assertThat(jsonArray.get(0)).isNull(); - assertThat(jsonArray.get(1)).isEqualTo("string"); - } - - @Test - public void jsonFromElementNullsNoKeysWithTypes() { - Graph g = new TinkerGraph(); - Vertex v = g.addVertex(1); - v.setProperty("key", null); - - Map map = new HashMap(); - map.put("innerkey", null); - - List innerList = new ArrayList(); - innerList.add(null); - innerList.add("innerstring"); - map.put("list", innerList); - - v.setProperty("keyMap", map); - - List list = new ArrayList(); - list.add(null); - list.add("string"); - v.setProperty("keyList", list); - - JSONObject json = GraphSONUtility.jsonFromElement(v, null, GraphSONMode.EXTENDED); - - - assertThat(json).isNotNull(); - JSONObject jsonObjectKey = (JSONObject) json.get("key"); - assertThat(jsonObjectKey.get(GraphSONTokens.VALUE)).isNull(); - assertThat(jsonObjectKey.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_UNKNOWN); - - JSONObject keyMap = (JSONObject) json.get("keyMap"); - JSONObject jsonMap = (JSONObject) keyMap.get(GraphSONTokens.VALUE); - assertThat(jsonMap).isNotNull(); - JSONObject jsonObjectMap = (JSONObject) jsonMap.get("innerkey"); - assertThat(jsonObjectMap.get(GraphSONTokens.VALUE)).isNull(); - assertThat(jsonObjectMap.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_UNKNOWN); - - JSONObject listJson = (JSONObject) jsonMap.get("list"); - JSONArray jsonInnerArray = (JSONArray) listJson.get(GraphSONTokens.VALUE); - assertThat(jsonInnerArray).isNotNull(); - JSONObject jsonObjectInnerListFirst = (JSONObject) jsonInnerArray.get(0); - assertThat(jsonObjectInnerListFirst.get(GraphSONTokens.VALUE)).isNull(); - assertThat(jsonObjectInnerListFirst.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_UNKNOWN); - - JSONObject keyList = (JSONObject) json.get("keyList"); - JSONArray jsonArray = (JSONArray) keyList.get(GraphSONTokens.VALUE); - assertThat(jsonArray).isNotNull(); - JSONObject jsonObjectListFirst = (JSONObject) jsonArray.get(0); - assertThat(jsonObjectListFirst.get(GraphSONTokens.VALUE)).isNull(); - assertThat(jsonObjectListFirst.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_UNKNOWN); - } - - @Test - public void vertexFromJsonValid() throws Exception { - Graph g = new TinkerGraph(); - ElementFactory factory = new GraphElementFactory(g); - - Vertex v = GraphSONUtility.vertexFromJson((JSONObject) JSONValue.parse(vertexJson1), factory, GraphSONMode.NORMAL, null); - - assertThat(v).isSameAs(g.getVertex(1)); - - // tinkergraph converts id to string - assertThat(v.getId()).isEqualTo("1"); - assertThat(v.getProperty("name")).isEqualTo("marko"); - assertThat(v.getProperty("age")).isEqualTo(29L); - } - - @Test - public void vertexFromJsonStringValid() throws Exception { - Graph g = new TinkerGraph(); - ElementFactory factory = new GraphElementFactory(g); - - Vertex v = GraphSONUtility.vertexFromJson(vertexJson1, factory, GraphSONMode.NORMAL, null); - - assertThat(v).isSameAs(g.getVertex(1)); - - // tinkergraph converts id to string - assertThat(v.getId()).isEqualTo("1"); - assertThat(v.getProperty("name")).isEqualTo("marko"); - assertThat(v.getProperty("age")).isEqualTo(29L); - } - - @Test - public void vertexFromJsonStringValidExtended() throws Exception { - Graph g = new TinkerGraph(); - ElementFactory factory = new GraphElementFactory(g); - - String vertexJson = "{\"person\":{\"value\":\"marko\",\"type\":\"string\"},\"_id\":1,\"_type\":\"vertex\"}"; - Vertex v = GraphSONUtility.vertexFromJson(vertexJson, factory, GraphSONMode.EXTENDED, null); - - Assert.assertSame(v, g.getVertex(1)); - - // tinkergraph converts id to string - Assert.assertEquals("1", v.getId()); - Assert.assertEquals("marko", v.getProperty("person")); - } - - @Test - public void vertexFromJsonInputStreamValid() throws Exception { - Graph g = new TinkerGraph(); - ElementFactory factory = new GraphElementFactory(g); - - Vertex v = GraphSONUtility.vertexFromJson(inputStreamVertexJson1, factory, GraphSONMode.NORMAL, null); - - Assert.assertSame(v, g.getVertex(1)); - - // tinkergraph converts id to string - Assert.assertEquals("1", v.getId()); - Assert.assertEquals("marko", v.getProperty("name")); - Assert.assertEquals(29L, v.getProperty("age")); - } - - @Test - public void vertexFromJsonIgnoreKeyValid() throws Exception { - Graph g = new TinkerGraph(); - ElementFactory factory = new GraphElementFactory(g); - - Set ignoreAge = new HashSet(); - ignoreAge.add("age"); - ElementPropertyConfig config = ElementPropertyConfig.ExcludeProperties(ignoreAge, null); - GraphSONUtility utility = new GraphSONUtility(GraphSONMode.NORMAL, factory, config); - Vertex v = utility.vertexFromJson((JSONObject) JSONValue.parse(vertexJson1)); - - Assert.assertSame(v, g.getVertex(1)); - - // tinkergraph converts id to string - Assert.assertEquals("1", v.getId()); - Assert.assertEquals("marko", v.getProperty("name")); - Assert.assertNull(v.getProperty("age")); - } - - @Test - public void edgeFromJsonValid() throws Exception { - Graph g = new TinkerGraph(); - ElementFactory factory = new GraphElementFactory(g); - - Vertex v1 = GraphSONUtility.vertexFromJson((JSONObject) JSONValue.parse(vertexJson1), factory, GraphSONMode.NORMAL, null); - Vertex v2 = GraphSONUtility.vertexFromJson((JSONObject) JSONValue.parse(vertexJson2), factory, GraphSONMode.NORMAL, null); - Edge e = GraphSONUtility.edgeFromJson((JSONObject) JSONValue.parse(edgeJson), v1, v2, factory, GraphSONMode.NORMAL, null); - - Assert.assertSame(v1, g.getVertex(1)); - Assert.assertSame(v2, g.getVertex(2)); - Assert.assertSame(e, g.getEdge(7)); - - // tinkergraph converts id to string - Assert.assertEquals("7", e.getId()); - Assert.assertEquals(0.5d, e.getProperty("weight")); - Assert.assertEquals("knows", e.getLabel()); - Assert.assertEquals(v1, e.getVertex(Direction.OUT)); - Assert.assertEquals(v2, e.getVertex(Direction.IN)); - } - - @Test - public void edgeFromJsonStringValid() throws Exception { - Graph g = new TinkerGraph(); - ElementFactory factory = new GraphElementFactory(g); - - Vertex v1 = GraphSONUtility.vertexFromJson(vertexJson1, factory, GraphSONMode.NORMAL, null); - Vertex v2 = GraphSONUtility.vertexFromJson(vertexJson2, factory, GraphSONMode.NORMAL, null); - Edge e = GraphSONUtility.edgeFromJson(edgeJson, v1, v2, factory, GraphSONMode.NORMAL, null); - - Assert.assertSame(v1, g.getVertex(1)); - Assert.assertSame(v2, g.getVertex(2)); - Assert.assertSame(e, g.getEdge(7)); - - // tinkergraph converts id to string - Assert.assertEquals("7", e.getId()); - Assert.assertEquals(0.5d, e.getProperty("weight")); - Assert.assertEquals("knows", e.getLabel()); - Assert.assertEquals(v1, e.getVertex(Direction.OUT)); - Assert.assertEquals(v2, e.getVertex(Direction.IN)); - } - - @Test - public void edgeFromJsonIgnoreWeightValid() throws Exception { - Graph g = new TinkerGraph(); - ElementFactory factory = new GraphElementFactory(g); - - Vertex v1 = GraphSONUtility.vertexFromJson((JSONObject) JSONValue.parse(vertexJson1), factory, GraphSONMode.NORMAL, null); - Vertex v2 = GraphSONUtility.vertexFromJson((JSONObject) JSONValue.parse(vertexJson2), factory, GraphSONMode.NORMAL, null); - - Set ignoreWeight = new HashSet(); - ignoreWeight.add("weight"); - ElementPropertyConfig config = ElementPropertyConfig.ExcludeProperties(null, ignoreWeight); - GraphSONUtility utility = new GraphSONUtility(GraphSONMode.NORMAL, factory, config); - Edge e = utility.edgeFromJson((JSONObject) JSONValue.parse(edgeJson), v1, v2); - - Assert.assertSame(v1, g.getVertex(1)); - Assert.assertSame(v2, g.getVertex(2)); - Assert.assertSame(e, g.getEdge(7)); - - // tinkergraph converts id to string - Assert.assertEquals("7", e.getId()); - Assert.assertNull(e.getProperty("weight")); - Assert.assertEquals("knows", e.getLabel()); - Assert.assertEquals(v1, e.getVertex(Direction.OUT)); - Assert.assertEquals(v2, e.getVertex(Direction.IN)); - } - - @Test - public void edgeFromJsonNormalLabelOrIdOnEdge() throws Exception { - Graph g = new TinkerGraph(); - ElementFactory factory = new GraphElementFactory(g); - - Vertex v1 = GraphSONUtility.vertexFromJson((JSONObject) JSONValue.parse(vertexJson1), factory, GraphSONMode.NORMAL, null); - Vertex v2 = GraphSONUtility.vertexFromJson((JSONObject) JSONValue.parse(vertexJson2), factory, GraphSONMode.NORMAL, null); - Edge e = GraphSONUtility.edgeFromJson((JSONObject) JSONValue.parse(edgeJsonLight), v1, v2, factory, GraphSONMode.NORMAL, null); - - Assert.assertSame(v1, g.getVertex(1)); - Assert.assertSame(v2, g.getVertex(2)); - Assert.assertSame(e, g.getEdge(0)); - } - - @Test - public void edgeFromJsonInputStreamCompactLabelOrIdOnEdge() throws Exception { - Graph g = new TinkerGraph(); - ElementFactory factory = new GraphElementFactory(g); - - Vertex v1 = GraphSONUtility.vertexFromJson((JSONObject) JSONValue.parse(vertexJson1), factory, GraphSONMode.COMPACT, null); - Vertex v2 = GraphSONUtility.vertexFromJson((JSONObject) JSONValue.parse(vertexJson2), factory, GraphSONMode.COMPACT, null); - Edge e = GraphSONUtility.edgeFromJson(inputStreamEdgeJsonLight, v1, v2, factory, GraphSONMode.COMPACT, null); - - Assert.assertSame(v1, g.getVertex(1)); - Assert.assertSame(v2, g.getVertex(2)); - Assert.assertSame(e, g.getEdge(0)); - } - - @Test - public void edgeFromJsonInputStreamCompactNoIdOnEdge() throws Exception { - Graph g = new TinkerGraph(); - ElementFactory factory = new GraphElementFactory(g); - - Set vertexKeys = new HashSet() {{ - add(GraphSONTokens._ID); - }}; - - Set edgeKeys = new HashSet() {{ - add(GraphSONTokens._IN_V); - }}; - - GraphSONUtility graphson = new GraphSONUtility(GraphSONMode.COMPACT, factory, vertexKeys, edgeKeys); - - Vertex v1 = graphson.vertexFromJson((JSONObject) JSONValue.parse(vertexJson1)); - Vertex v2 = graphson.vertexFromJson((JSONObject) JSONValue.parse(vertexJson2)); - Edge e = graphson.edgeFromJson(inputStreamEdgeJsonLight, v1, v2); - - Assert.assertSame(v1, g.getVertex(1)); - Assert.assertSame(v2, g.getVertex(2)); - Assert.assertSame(e, g.getEdge(0)); - } - - private class Cat { - private String name; - - public Cat(String name) { - this.name = name; - } - - public String getName() { - return this.name; - } - - @Override - public String toString() { - return this.name; - } - } -} diff --git a/sonar-core/src/test/java/org/sonar/core/graph/GraphSONWriterTest.java b/sonar-core/src/test/java/org/sonar/core/graph/GraphSONWriterTest.java deleted file mode 100644 index f62122a843d..00000000000 --- a/sonar-core/src/test/java/org/sonar/core/graph/GraphSONWriterTest.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Sonar, open source software quality management tool. - * Copyright (C) 2008-2012 SonarSource - * mailto:contact AT sonarsource DOT com - * - * Sonar is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * Sonar is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with Sonar; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ - -package org.sonar.core.graph; - -import com.tinkerpop.blueprints.Graph; -import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; -import com.tinkerpop.blueprints.util.io.graphson.GraphSONMode; -import com.tinkerpop.blueprints.util.io.graphson.GraphSONTokens; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.JSONValue; -import org.junit.Test; - -import java.io.ByteArrayOutputStream; - -import static org.fest.assertions.Assertions.assertThat; - -public class GraphSONWriterTest { - - @Test - public void outputGraphNoEmbeddedTypes() throws Exception { - Graph g = TinkerGraphFactory.createTinkerGraph(); - - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - - GraphSONWriter writer = new GraphSONWriter(g); - writer.outputGraph(stream, null, null, GraphSONMode.NORMAL); - - stream.flush(); - stream.close(); - - String jsonString = new String(stream.toByteArray()); - - JSONObject rootNode = (JSONObject) JSONValue.parse(jsonString); - - // ensure that the JSON conforms to basic structure and that the right - // number of graph elements are present. other tests already cover element formatting - assertThat(rootNode).isNotNull(); - assertThat(rootNode.containsKey(GraphSONTokens.MODE)).isTrue(); - assertThat(rootNode.get(GraphSONTokens.MODE)).isEqualTo("NORMAL"); - - assertThat(rootNode.containsKey(GraphSONTokens.VERTICES)).isTrue(); - - JSONArray vertices = (JSONArray) rootNode.get(GraphSONTokens.VERTICES); - assertThat(vertices).hasSize(6); - - assertThat(rootNode.containsKey(GraphSONTokens.EDGES)).isTrue(); - - JSONArray edges = (JSONArray) rootNode.get(GraphSONTokens.EDGES); - assertThat(edges).hasSize(6); - } - - @Test - public void outputGraphWithEmbeddedTypes() throws Exception { - Graph g = TinkerGraphFactory.createTinkerGraph(); - - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - - GraphSONWriter writer = new GraphSONWriter(g); - writer.outputGraph(stream, null, null, GraphSONMode.EXTENDED); - - stream.flush(); - stream.close(); - - String jsonString = new String(stream.toByteArray()); - - JSONObject rootNode = (JSONObject) JSONValue.parse(jsonString); - - // ensure that the JSON conforms to basic structure and that the right - // number of graph elements are present. other tests already cover element formatting - assertThat(rootNode).isNotNull(); - assertThat(rootNode.containsKey(GraphSONTokens.MODE)).isTrue(); - assertThat(rootNode.get(GraphSONTokens.MODE)).isEqualTo("EXTENDED"); - - assertThat(rootNode.containsKey(GraphSONTokens.VERTICES)).isTrue(); - - JSONArray vertices = (JSONArray) rootNode.get(GraphSONTokens.VERTICES); - assertThat(vertices).hasSize(6); - - assertThat(rootNode.containsKey(GraphSONTokens.EDGES)).isTrue(); - - JSONArray edges = (JSONArray) rootNode.get(GraphSONTokens.EDGES); - assertThat(edges).hasSize(6); - } - - @Test - public void outputGraphWithCompact() throws Exception { - Graph g = TinkerGraphFactory.createTinkerGraph(); - - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - - GraphSONWriter writer = new GraphSONWriter(g); - writer.outputGraph(stream, null, null, GraphSONMode.COMPACT); - - stream.flush(); - stream.close(); - - String jsonString = new String(stream.toByteArray()); - - JSONObject rootNode = (JSONObject) JSONValue.parse(jsonString); - - // ensure that the JSON conforms to basic structure and that the right - // number of graph elements are present. other tests already cover element formatting - assertThat(rootNode).isNotNull(); - assertThat(rootNode.containsKey(GraphSONTokens.MODE)).isTrue(); - assertThat(rootNode.get(GraphSONTokens.MODE)).isEqualTo("COMPACT"); - - assertThat(rootNode.containsKey(GraphSONTokens.VERTICES)).isTrue(); - - JSONArray vertices = (JSONArray) rootNode.get(GraphSONTokens.VERTICES); - assertThat(vertices).hasSize(6); - - assertThat(rootNode.containsKey(GraphSONTokens.EDGES)).isTrue(); - - JSONArray edges = (JSONArray) rootNode.get(GraphSONTokens.EDGES); - assertThat(edges).hasSize(6); - } -} diff --git a/sonar-core/src/test/java/org/sonar/core/graph/graphson/GraphsonReaderTest.java b/sonar-core/src/test/java/org/sonar/core/graph/graphson/GraphsonReaderTest.java new file mode 100644 index 00000000000..9c0cb908c8a --- /dev/null +++ b/sonar-core/src/test/java/org/sonar/core/graph/graphson/GraphsonReaderTest.java @@ -0,0 +1,339 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2008-2012 SonarSource + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.core.graph.graphson; + +import com.tinkerpop.blueprints.Direction; +import com.tinkerpop.blueprints.Edge; +import com.tinkerpop.blueprints.Vertex; +import com.tinkerpop.blueprints.impls.tg.TinkerGraph; +import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; +import org.junit.Assert; +import org.junit.Test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class GraphsonReaderTest { + + @Test + public void inputGraphModeExtended() throws Exception { + TinkerGraph graph = new TinkerGraph(); + + String json = "{ \"mode\":\"EXTENDED\", \"vertices\": [ {\"_id\":1, \"_type\":\"vertex\", \"test\": { \"type\":\"string\", \"value\":\"please work\"}, \"testlist\":{\"type\":\"list\", \"value\":[{\"type\":\"int\", \"value\":1}, {\"type\":\"int\",\"value\":2}, {\"type\":\"int\",\"value\":3}, {\"type\":\"unknown\",\"value\":null}]}, \"testmap\":{\"type\":\"map\", \"value\":{\"big\":{\"type\":\"long\", \"value\":10000000000}, \"small\":{\"type\":\"double\", \"value\":0.4954959595959}, \"nullKey\":{\"type\":\"unknown\", \"value\":null}}}}, {\"_id\":2, \"_type\":\"vertex\", \"testagain\":{\"type\":\"string\", \"value\":\"please work again\"}}], \"edges\":[{\"_id\":100, \"_type\":\"edge\", \"_outV\":1, \"_inV\":2, \"_label\":\"works\", \"teste\": {\"type\":\"string\", \"value\":\"please worke\"}, \"keyNull\":{\"type\":\"unknown\", \"value\":null}}]}"; + + byte[] bytes = json.getBytes(); + InputStream inputStream = new ByteArrayInputStream(bytes); + + new GraphSONReader().read(inputStream, graph); + + Assert.assertEquals(2, getIterableCount(graph.getVertices())); + Assert.assertEquals(1, getIterableCount(graph.getEdges())); + + Vertex v1 = graph.getVertex(1); + Assert.assertNotNull(v1); + Assert.assertEquals("please work", v1.getProperty("test")); + + Map map = (Map) v1.getProperty("testmap"); + Assert.assertNotNull(map); + Assert.assertEquals(10000000000l, Long.parseLong(map.get("big").toString())); + Assert.assertEquals(0.4954959595959, Double.parseDouble(map.get("small").toString()), 0); + Assert.assertNull(map.get("nullKey")); + + List list = (List) v1.getProperty("testlist"); + Assert.assertEquals(4, list.size()); + + boolean foundNull = false; + for (int ix = 0; ix < list.size(); ix++) { + if (list.get(ix) == null) { + foundNull = true; + break; + } + } + + Assert.assertTrue(foundNull); + + Vertex v2 = graph.getVertex(2); + Assert.assertNotNull(v2); + Assert.assertEquals("please work again", v2.getProperty("testagain")); + + Edge e = graph.getEdge(100); + Assert.assertNotNull(e); + Assert.assertEquals("works", e.getLabel()); + Assert.assertEquals(v1, e.getVertex(Direction.OUT)); + Assert.assertEquals(v2, e.getVertex(Direction.IN)); + Assert.assertEquals("please worke", e.getProperty("teste")); + Assert.assertNull(e.getProperty("keyNull")); + + } + + @Test + public void inputGraphModeNormal() throws Exception { + TinkerGraph graph = new TinkerGraph(); + + String json = "{ \"mode\":\"NORMAL\",\"vertices\": [ {\"_id\":1, \"_type\":\"vertex\", \"test\": \"please work\", \"testlist\":[1, 2, 3, null], \"testmap\":{\"big\":10000000000, \"small\":0.4954959595959, \"nullKey\":null}}, {\"_id\":2, \"_type\":\"vertex\", \"testagain\":\"please work again\"}], \"edges\":[{\"_id\":100, \"_type\":\"edge\", \"_outV\":1, \"_inV\":2, \"_label\":\"works\", \"teste\": \"please worke\", \"keyNull\":null}]}"; + + byte[] bytes = json.getBytes(); + InputStream inputStream = new ByteArrayInputStream(bytes); + + new GraphSONReader().read(inputStream, graph); + + Assert.assertEquals(2, getIterableCount(graph.getVertices())); + Assert.assertEquals(1, getIterableCount(graph.getEdges())); + + Vertex v1 = graph.getVertex(1); + Assert.assertNotNull(v1); + Assert.assertEquals("please work", v1.getProperty("test")); + + Map map = (Map) v1.getProperty("testmap"); + Assert.assertNotNull(map); + Assert.assertEquals(10000000000l, Long.parseLong(map.get("big").toString())); + Assert.assertEquals(0.4954959595959, Double.parseDouble(map.get("small").toString()), 0); + Assert.assertNull(map.get("nullKey")); + + List list = (List) v1.getProperty("testlist"); + Assert.assertEquals(4, list.size()); + + boolean foundNull = false; + for (int ix = 0; ix < list.size(); ix++) { + if (list.get(ix) == null) { + foundNull = true; + break; + } + } + + Assert.assertTrue(foundNull); + + Vertex v2 = graph.getVertex(2); + Assert.assertNotNull(v2); + Assert.assertEquals("please work again", v2.getProperty("testagain")); + + Edge e = graph.getEdge(100); + Assert.assertNotNull(e); + Assert.assertEquals("works", e.getLabel()); + Assert.assertEquals(v1, e.getVertex(Direction.OUT)); + Assert.assertEquals(v2, e.getVertex(Direction.IN)); + Assert.assertEquals("please worke", e.getProperty("teste")); + Assert.assertNull(e.getProperty("keyNull")); + + } + + @Test + public void inputGraphModeCompact() throws Exception { + TinkerGraph graph = new TinkerGraph(); + + String json = "{ \"mode\":\"COMPACT\",\"vertices\": [ {\"_id\":1, \"test\": \"please work\", \"testlist\":[1, 2, 3, null], \"testmap\":{\"big\":10000000000, \"small\":0.4954959595959, \"nullKey\":null}}, {\"_id\":2, \"testagain\":\"please work again\"}], \"edges\":[{\"_id\":100, \"_outV\":1, \"_inV\":2, \"_label\":\"works\", \"teste\": \"please worke\", \"keyNull\":null}]}"; + + byte[] bytes = json.getBytes(); + InputStream inputStream = new ByteArrayInputStream(bytes); + + new GraphSONReader().read(inputStream, graph); + + Assert.assertEquals(2, getIterableCount(graph.getVertices())); + Assert.assertEquals(1, getIterableCount(graph.getEdges())); + + Vertex v1 = graph.getVertex(1); + Assert.assertNotNull(v1); + Assert.assertEquals("please work", v1.getProperty("test")); + + Map map = (Map) v1.getProperty("testmap"); + Assert.assertNotNull(map); + Assert.assertEquals(10000000000l, Long.parseLong(map.get("big").toString())); + Assert.assertEquals(0.4954959595959, Double.parseDouble(map.get("small").toString()), 0); + Assert.assertNull(map.get("nullKey")); + + List list = (List) v1.getProperty("testlist"); + Assert.assertEquals(4, list.size()); + + boolean foundNull = false; + for (Object aList : list) { + if (aList == null) { + foundNull = true; + break; + } + } + + Assert.assertTrue(foundNull); + + Vertex v2 = graph.getVertex(2); + Assert.assertNotNull(v2); + Assert.assertEquals("please work again", v2.getProperty("testagain")); + + Edge e = graph.getEdge(100); + Assert.assertNotNull(e); + Assert.assertEquals("works", e.getLabel()); + Assert.assertEquals(v1, e.getVertex(Direction.OUT)); + Assert.assertEquals(v2, e.getVertex(Direction.IN)); + Assert.assertEquals("please worke", e.getProperty("teste")); + Assert.assertNull(e.getProperty("keyNull")); + + } + + @Test + public void inputGraphExtendedFullCycle() throws Exception { + TinkerGraph graph = TinkerGraphFactory.createTinkerGraph(); + + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + + GraphSONWriter writer = new GraphSONWriter(); + writer.write(graph, stream, GraphSONMode.EXTENDED); + + stream.flush(); + stream.close(); + + String jsonString = new String(stream.toByteArray()); + + byte[] bytes = jsonString.getBytes(); + InputStream inputStream = new ByteArrayInputStream(bytes); + + TinkerGraph emptyGraph = new TinkerGraph(); + new GraphSONReader().read(inputStream, emptyGraph); + + Assert.assertEquals(6, getIterableCount(emptyGraph.getVertices())); + Assert.assertEquals(6, getIterableCount(emptyGraph.getEdges())); + + for (Vertex v : graph.getVertices()) { + Vertex found = emptyGraph.getVertex(v.getId()); + + Assert.assertNotNull(v); + + for (String key : found.getPropertyKeys()) { + Assert.assertEquals(v.getProperty(key), found.getProperty(key)); + } + } + + for (Edge e : graph.getEdges()) { + Edge found = emptyGraph.getEdge(e.getId()); + + Assert.assertNotNull(e); + + for (String key : found.getPropertyKeys()) { + Assert.assertEquals(e.getProperty(key), found.getProperty(key)); + } + } + + } + + @Test + public void inputGraphCompactFullCycle() throws Exception { + TinkerGraph graph = TinkerGraphFactory.createTinkerGraph(); + + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + + Set edgeKeys = new HashSet(); + edgeKeys.add(GraphSONTokens._ID); + edgeKeys.add(GraphSONTokens._IN_V); + edgeKeys.add(GraphSONTokens._OUT_V); + edgeKeys.add(GraphSONTokens._LABEL); + + Set vertexKeys = new HashSet(); + vertexKeys.add(GraphSONTokens._ID); + + GraphSONWriter writer = new GraphSONWriter(); + writer.write(graph, stream, GraphSONMode.EXTENDED, vertexKeys, edgeKeys); + + stream.flush(); + stream.close(); + + String jsonString = new String(stream.toByteArray()); + + byte[] bytes = jsonString.getBytes(); + InputStream inputStream = new ByteArrayInputStream(bytes); + + TinkerGraph emptyGraph = new TinkerGraph(); + new GraphSONReader().read(inputStream, emptyGraph); + + Assert.assertEquals(6, getIterableCount(emptyGraph.getVertices())); + Assert.assertEquals(6, getIterableCount(emptyGraph.getEdges())); + + for (Vertex v : graph.getVertices()) { + Vertex found = emptyGraph.getVertex(v.getId()); + + Assert.assertNotNull(v); + + for (String key : found.getPropertyKeys()) { + Assert.assertEquals(v.getProperty(key), found.getProperty(key)); + } + + // no properties should be here + Assert.assertEquals(null, found.getProperty("name")); + } + + for (Edge e : graph.getEdges()) { + Edge found = emptyGraph.getEdge(e.getId()); + + Assert.assertNotNull(e); + + for (String key : found.getPropertyKeys()) { + Assert.assertEquals(e.getProperty(key), found.getProperty(key)); + } + + // no properties should be here + Assert.assertEquals(null, found.getProperty("weight")); + } + + } + + @Test(expected = GraphSonException.class) + public void inputGraphCompactFullCycleBroken() throws Exception { + TinkerGraph graph = TinkerGraphFactory.createTinkerGraph(); + + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + + Set edgeKeys = new HashSet(); + edgeKeys.add(GraphSONTokens._IN_V); + edgeKeys.add(GraphSONTokens._OUT_V); + edgeKeys.add(GraphSONTokens._LABEL); + + Set vertexKeys = new HashSet(); + + GraphSONWriter writer = new GraphSONWriter(); + writer.write(graph, stream, GraphSONMode.COMPACT, vertexKeys, edgeKeys); + + stream.flush(); + stream.close(); + + String jsonString = new String(stream.toByteArray()); + + byte[] bytes = jsonString.getBytes(); + InputStream inputStream = new ByteArrayInputStream(bytes); + + TinkerGraph emptyGraph = new TinkerGraph(); + new GraphSONReader().read(inputStream, emptyGraph); + + } + + private int getIterableCount(Iterable elements) { + int counter = 0; + + Iterator iterator = elements.iterator(); + while (iterator.hasNext()) { + iterator.next(); + counter++; + } + + return counter; + } +} diff --git a/sonar-core/src/test/java/org/sonar/core/graph/graphson/GraphsonUtilTest.java b/sonar-core/src/test/java/org/sonar/core/graph/graphson/GraphsonUtilTest.java new file mode 100644 index 00000000000..ad24c277774 --- /dev/null +++ b/sonar-core/src/test/java/org/sonar/core/graph/graphson/GraphsonUtilTest.java @@ -0,0 +1,1151 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2008-2012 SonarSource + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.core.graph.graphson; + +import com.tinkerpop.blueprints.Direction; +import com.tinkerpop.blueprints.Edge; +import com.tinkerpop.blueprints.Graph; +import com.tinkerpop.blueprints.Vertex; +import com.tinkerpop.blueprints.impls.tg.TinkerGraph; +import com.tinkerpop.blueprints.util.io.graphson.GraphSONTokens; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.fest.assertions.Assertions.assertThat; + +public class GraphsonUtilTest { + private final String vertexJson1 = "{\"name\":\"marko\",\"age\":29,\"_id\":1,\"_type\":\"vertex\"}"; + private final String vertexJson2 = "{\"name\":\"vadas\",\"age\":27,\"_id\":2,\"_type\":\"vertex\"}"; + private final String edgeJsonLight = "{\"weight\":0.5,\"_outV\":1,\"_inV\":2}"; + private final String edgeJson = "{\"weight\":0.5,\"_id\":7,\"_type\":\"edge\",\"_outV\":1,\"_inV\":2,\"_label\":\"knows\"}"; + private TinkerGraph graph = new TinkerGraph(); + private InputStream inputStreamVertexJson1; + private InputStream inputStreamEdgeJsonLight; + + @Before + public void setUp() { + this.graph.clear(); + + this.inputStreamVertexJson1 = new ByteArrayInputStream(vertexJson1.getBytes()); + this.inputStreamEdgeJsonLight = new ByteArrayInputStream(edgeJsonLight.getBytes()); + } + + @Test + public void jsonFromElementEdgeNoPropertiesNoKeysNoTypes() { + Vertex v1 = this.graph.addVertex(1); + Vertex v2 = this.graph.addVertex(2); + + Edge e = this.graph.addEdge(3, v1, v2, "test"); + e.setProperty("weight", 0.5f); + + JSONObject json = GraphsonUtil.jsonFromElement(e, null, GraphSONMode.NORMAL); + + assertThat(json).isNotNull(); + assertThat(json.containsKey(GraphSONTokens._ID)).isTrue(); + assertThat(json.get(GraphSONTokens._ID)).isEqualTo("3"); + assertThat(json.containsKey(GraphSONTokens._LABEL)).isTrue(); + assertThat(json.get(GraphSONTokens._LABEL)).isEqualTo("test"); + assertThat(json.containsKey(GraphSONTokens._TYPE)).isTrue(); + assertThat(json.get(GraphSONTokens._TYPE)).isEqualTo("edge"); + assertThat(json.containsKey(GraphSONTokens._IN_V)).isTrue(); + assertThat(json.get(GraphSONTokens._IN_V)).isEqualTo("2"); + assertThat(json.containsKey(GraphSONTokens._OUT_V)).isTrue(); + assertThat(json.get(GraphSONTokens._OUT_V)).isEqualTo("1"); + assertThat(json.containsKey("weight")).isTrue(); + assertThat(json.get("weight")).isEqualTo(0.5f); + } + + @Test + public void jsonFromElementEdgeCompactIdOnlyAsInclude() { + Vertex v1 = this.graph.addVertex(1); + Vertex v2 = this.graph.addVertex(2); + + Edge e = this.graph.addEdge(3, v1, v2, "test"); + e.setProperty("weight", 0.5f); + + Set propertiesToInclude = new HashSet() {{ + add(GraphSONTokens._ID); + }}; + + JSONObject json = GraphsonUtil.jsonFromElement(e, propertiesToInclude, GraphSONMode.COMPACT); + + assertThat(json).isNotNull(); + assertThat(json.containsKey(GraphSONTokens._TYPE)).isFalse(); + assertThat(json.containsKey(GraphSONTokens._LABEL)).isFalse(); + assertThat(json.containsKey(GraphSONTokens._IN_V)).isFalse(); + assertThat(json.containsKey(GraphSONTokens._OUT_V)).isFalse(); + assertThat(json.containsKey(GraphSONTokens._ID)).isTrue(); + assertThat(json.containsKey("weight")).isFalse(); + } + + @Test + public void jsonFromElementEdgeCompactIdOnlyAsExclude() { + ElementFactory factory = new ElementFactory(this.graph); + Vertex v1 = this.graph.addVertex(1); + Vertex v2 = this.graph.addVertex(2); + + Edge e = this.graph.addEdge(3, v1, v2, "test"); + e.setProperty("weight", 0.5f); + e.setProperty("x", "y"); + + Set propertiesToExclude = new HashSet() {{ + add(GraphSONTokens._TYPE); + add(GraphSONTokens._LABEL); + add(GraphSONTokens._IN_V); + add(GraphSONTokens._OUT_V); + add("weight"); + }}; + + ElementPropertyConfig config = new ElementPropertyConfig(null, propertiesToExclude, + ElementPropertyConfig.ElementPropertiesRule.INCLUDE, + ElementPropertyConfig.ElementPropertiesRule.EXCLUDE); + GraphsonUtil utility = new GraphsonUtil(GraphSONMode.COMPACT, factory, config); + JSONObject json = utility.jsonFromElement(e); + + assertThat(json).isNotNull(); + assertThat(json.containsKey(GraphSONTokens._TYPE)).isFalse(); + assertThat(json.containsKey(GraphSONTokens._LABEL)).isFalse(); + assertThat(json.containsKey(GraphSONTokens._IN_V)).isFalse(); + assertThat(json.containsKey(GraphSONTokens._OUT_V)).isFalse(); + assertThat(json.containsKey(GraphSONTokens._ID)).isTrue(); + assertThat(json.containsKey("weight")).isFalse(); + assertThat(json.containsKey("x")).isTrue(); + assertThat(json.get("x")).isEqualTo("y"); + } + + @Test + public void jsonFromElementEdgeCompactAllKeys() { + Vertex v1 = this.graph.addVertex(1); + Vertex v2 = this.graph.addVertex(2); + + Edge e = this.graph.addEdge(3, v1, v2, "test"); + e.setProperty("weight", 0.5f); + + JSONObject json = GraphsonUtil.jsonFromElement(e, null, GraphSONMode.COMPACT); + + assertThat(json).isNotNull(); + assertThat(json.containsKey(GraphSONTokens._ID)).isTrue(); + assertThat(json.containsKey(GraphSONTokens._TYPE)).isTrue(); + assertThat(json.containsKey(GraphSONTokens._LABEL)).isTrue(); + assertThat(json.containsKey(GraphSONTokens._IN_V)).isTrue(); + assertThat(json.containsKey(GraphSONTokens._OUT_V)).isTrue(); + assertThat(json.get("weight")).isEqualTo(0.5f); + } + + @Test + public void jsonFromElementVertexNoPropertiesNoKeysNoTypes() { + Vertex v = this.graph.addVertex(1); + v.setProperty("name", "marko"); + + JSONObject json = GraphsonUtil.jsonFromElement(v, null, GraphSONMode.NORMAL); + + assertThat(json).isNotNull(); + assertThat(json.containsKey(GraphSONTokens._ID)).isTrue(); + assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); + assertThat(json.containsKey(GraphSONTokens._TYPE)).isTrue(); + assertThat(json.get(GraphSONTokens._TYPE)).isEqualTo("vertex"); + assertThat(json.get("name")).isEqualTo("marko"); + } + + @Test + public void jsonFromElementVertexCompactIdOnlyAsInclude() { + Vertex v = this.graph.addVertex(1); + v.setProperty("name", "marko"); + + Set propertiesToInclude = new HashSet() {{ + add(GraphSONTokens._ID); + }}; + + JSONObject json = GraphsonUtil.jsonFromElement(v, propertiesToInclude, GraphSONMode.COMPACT); + + assertThat(json).isNotNull(); + assertThat(json.containsKey(GraphSONTokens._TYPE)).isFalse(); + assertThat(json.containsKey(GraphSONTokens._ID)).isTrue(); + assertThat(json.containsKey("name")).isFalse(); + } + + @Test + public void jsonFromElementVertexCompactIdNameOnlyAsExclude() { + ElementFactory factory = new ElementFactory(this.graph); + Vertex v = this.graph.addVertex(1); + v.setProperty("name", "marko"); + + Set propertiesToExclude = new HashSet() {{ + add(GraphSONTokens._TYPE); + }}; + + ElementPropertyConfig config = new ElementPropertyConfig(propertiesToExclude, null, + ElementPropertyConfig.ElementPropertiesRule.EXCLUDE, + ElementPropertyConfig.ElementPropertiesRule.EXCLUDE); + + GraphsonUtil utility = new GraphsonUtil(GraphSONMode.COMPACT, factory, config); + JSONObject json = utility.jsonFromElement(v); + + assertThat(json).isNotNull(); + assertThat(json.containsKey(GraphSONTokens._TYPE)).isFalse(); + assertThat(json.containsKey(GraphSONTokens._ID)).isTrue(); + assertThat(json.containsKey("name")).isTrue(); + } + + @Test + public void jsonFromElementVertexCompactAllOnly() { + Vertex v = this.graph.addVertex(1); + v.setProperty("name", "marko"); + + JSONObject json = GraphsonUtil.jsonFromElement(v, null, GraphSONMode.COMPACT); + + assertThat(json).isNotNull(); + assertThat(json.containsKey(GraphSONTokens._TYPE)).isTrue(); + assertThat(json.containsKey(GraphSONTokens._ID)).isTrue(); + assertThat(json.containsKey("name")).isTrue(); + } + + @Test + public void jsonFromElementVertexPrimitivePropertiesNoKeysNoTypes() { + Vertex v = this.graph.addVertex(1); + v.setProperty("keyString", "string"); + v.setProperty("keyLong", 1L); + v.setProperty("keyInt", 2); + v.setProperty("keyFloat", 3.3f); + v.setProperty("keyExponentialDouble", 1312928167.626012); + v.setProperty("keyDouble", 4.4); + v.setProperty("keyBoolean", true); + + JSONObject json = GraphsonUtil.jsonFromElement(v, null, GraphSONMode.NORMAL); + + assertThat(json).isNotNull(); + assertThat(json.containsKey(GraphSONTokens._ID)).isTrue(); + assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); + assertThat(json.containsKey("keyString")).isTrue(); + assertThat(json.get("keyString")).isEqualTo("string"); + assertThat(json.containsKey("keyLong")).isTrue(); + assertThat(json.get("keyLong")).isEqualTo(1L); + assertThat(json.containsKey("keyInt")).isTrue(); + assertThat(json.get("keyInt")).isEqualTo(2); + assertThat(json.containsKey("keyFloat")).isTrue(); + assertThat(json.get("keyFloat")).isEqualTo(3.3f); + assertThat(json.containsKey("keyExponentialDouble")).isTrue(); + assertThat(json.get("keyExponentialDouble")).isEqualTo(1312928167.626012); + assertThat(json.containsKey("keyDouble")).isTrue(); + assertThat(json.get("keyDouble")).isEqualTo(4.4); + assertThat(json.containsKey("keyBoolean")).isTrue(); + assertThat(json.get("keyBoolean")).isEqualTo(true); + } + + @Test + public void jsonFromElementVertexMapPropertyNoKeysNoTypes() { + Vertex v = this.graph.addVertex(1); + Map map = new HashMap(); + map.put("this", "some"); + map.put("that", 1); + + v.setProperty("keyMap", map); + + JSONObject json = GraphsonUtil.jsonFromElement(v, null, GraphSONMode.NORMAL); + + assertThat(json).isNotNull(); + assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); + assertThat(json.containsKey("keyMap")).isTrue(); + + JSONObject mapAsJSON = (JSONObject) json.get("keyMap"); + assertThat(mapAsJSON).isNotNull(); + assertThat(mapAsJSON.containsKey("this")).isTrue(); + assertThat(mapAsJSON.get("this")).isEqualTo("some"); + assertThat(mapAsJSON.containsKey("that")).isTrue(); + assertThat(mapAsJSON.get("that")).isEqualTo(1); + } + + @Test + public void jsonFromElementVertexListPropertyNoKeysNoTypes() { + Vertex v = this.graph.addVertex(1); + List list = new ArrayList(); + list.add("this"); + list.add("that"); + list.add("other"); + list.add(true); + + v.setProperty("keyList", list); + + JSONObject json = GraphsonUtil.jsonFromElement(v, null, GraphSONMode.NORMAL); + + assertThat(json).isNotNull(); + assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); + assertThat(json.containsKey("keyList")).isTrue(); + + JSONArray listAsJSON = (JSONArray) json.get("keyList"); + assertThat(listAsJSON).isNotNull(); + assertThat(listAsJSON).hasSize(4); + } + + @Test + public void jsonFromElementVertexStringArrayPropertyNoKeysNoTypes() { + Vertex v = this.graph.addVertex(1); + String[] stringArray = new String[]{"this", "that", "other"}; + + v.setProperty("keyStringArray", stringArray); + + JSONObject json = GraphsonUtil.jsonFromElement(v, null, GraphSONMode.NORMAL); + + assertThat(json).isNotNull(); + assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); + assertThat(json.containsKey("keyStringArray")).isTrue(); + + JSONArray stringArrayAsJSON = (JSONArray) json.get("keyStringArray"); + assertThat(stringArrayAsJSON).isNotNull(); + assertThat(stringArrayAsJSON).hasSize(3); + } + + @Test + public void jsonFromElementVertexDoubleArrayPropertyNoKeysNoTypes() { + Vertex v = this.graph.addVertex(1); + double[] doubleArray = new double[]{1.0, 2.0, 3.0}; + + v.setProperty("keyDoubleArray", doubleArray); + + JSONObject json = GraphsonUtil.jsonFromElement(v, null, GraphSONMode.NORMAL); + + assertThat(json).isNotNull(); + assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); + assertThat(json.containsKey("keyDoubleArray")).isTrue(); + + JSONArray doubleArrayAsJSON = (JSONArray) json.get("keyDoubleArray"); + assertThat(doubleArrayAsJSON).isNotNull(); + assertThat(doubleArrayAsJSON).hasSize(3); + } + + @Test + public void jsonFromElementVertexIntArrayPropertyNoKeysNoTypes() { + Vertex v = this.graph.addVertex(1); + int[] intArray = new int[]{1, 2, 3}; + + v.setProperty("keyIntArray", intArray); + + JSONObject json = GraphsonUtil.jsonFromElement(v, null, GraphSONMode.NORMAL); + + assertThat(json).isNotNull(); + assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); + assertThat(json.containsKey("keyIntArray")).isTrue(); + + JSONArray intArrayAsJSON = (JSONArray) json.get("keyIntArray"); + assertThat(intArrayAsJSON).isNotNull(); + assertThat(intArrayAsJSON).hasSize(3); + } + + @Test + public void jsonFromElementVertexLongArrayPropertyNoKeysNoTypes() { + Vertex v = this.graph.addVertex(1); + long[] longArray = new long[]{1l, 2l, 3l}; + + v.setProperty("keyLongArray", longArray); + + JSONObject json = GraphsonUtil.jsonFromElement(v, null, GraphSONMode.NORMAL); + + assertThat(json).isNotNull(); + assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); + assertThat(json.containsKey("keyLongArray")).isTrue(); + + JSONArray longArrayAsJSON = (JSONArray) json.get("keyLongArray"); + assertThat(longArrayAsJSON).isNotNull(); + assertThat(longArrayAsJSON).hasSize(3); + } + + @Test + public void jsonFromElementFloatArrayPropertyNoKeysNoTypes() { + Vertex v = this.graph.addVertex(1); + float[] floatArray = new float[]{1.0f, 2.0f, 3.0f}; + + v.setProperty("keyFloatArray", floatArray); + + JSONObject json = GraphsonUtil.jsonFromElement(v, null, GraphSONMode.NORMAL); + + assertThat(json).isNotNull(); + assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); + assertThat(json.containsKey("keyFloatArray")).isTrue(); + + JSONArray floatArrayAsJSON = (JSONArray) json.get("keyFloatArray"); + assertThat(floatArrayAsJSON).isNotNull(); + assertThat(floatArrayAsJSON).hasSize(3); + } + + @Test + public void jsonFromElementBooleanArrayPropertyNoKeysNoTypes() { + Vertex v = this.graph.addVertex(1); + boolean[] booleanArray = new boolean[]{true, false, true}; + + v.setProperty("keyBooleanArray", booleanArray); + + JSONObject json = GraphsonUtil.jsonFromElement(v, null, GraphSONMode.NORMAL); + + assertThat(json).isNotNull(); + assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); + assertThat(json.containsKey("keyBooleanArray")).isTrue(); + + JSONArray booleanArrayAsJSON = (JSONArray) json.get("keyBooleanArray"); + assertThat(booleanArrayAsJSON).isNotNull(); + assertThat(booleanArrayAsJSON).hasSize(3); + } + + @Test + public void jsonFromElementVertexCatPropertyNoKeysNoTypes() { + Vertex v = this.graph.addVertex(1); + v.setProperty("mycat", new Cat("smithers")); + + JSONObject json = GraphsonUtil.jsonFromElement(v, null, GraphSONMode.NORMAL); + + assertThat(json).isNotNull(); + assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); + assertThat(json.containsKey("mycat")).isTrue(); + assertThat(json.get("mycat")).isEqualTo("smithers"); + } + + @Test + public void jsonFromElementVertexCatPropertyNoKeysWithTypes() { + Vertex v = this.graph.addVertex(1); + v.setProperty("mycat", new Cat("smithers")); + + JSONObject json = GraphsonUtil.jsonFromElement(v, null, GraphSONMode.EXTENDED); + + assertThat(json).isNotNull(); + assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); + assertThat(json.containsKey("mycat")).isTrue(); + + JSONObject jsonObjectCat = (JSONObject) json.get("mycat"); + assertThat(jsonObjectCat.containsKey("value")).isTrue(); + assertThat(jsonObjectCat.get("value")).isEqualTo("smithers"); + } + + @Test + public void jsonFromElementVertexCatArrayPropertyNoKeysNoTypes() { + Vertex v = this.graph.addVertex(1); + List cats = new ArrayList(); + cats.add(new Cat("smithers")); + cats.add(new Cat("mcallister")); + + v.setProperty("cats", cats); + + JSONObject json = GraphsonUtil.jsonFromElement(v, null, GraphSONMode.NORMAL); + + assertThat(json).isNotNull(); + assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); + assertThat(json.containsKey("cats")).isTrue(); + + JSONArray catListAsJson = (JSONArray) json.get("cats"); + assertThat(catListAsJson).hasSize(2); + } + + @Test + public void jsonFromElementCrazyPropertyNoKeysNoTypes() { + Vertex v = this.graph.addVertex(1); + List mix = new ArrayList(); + mix.add(new Cat("smithers")); + mix.add(true); + + List deepCats = new ArrayList(); + deepCats.add(new Cat("mcallister")); + mix.add(deepCats); + + Map map = new HashMap(); + map.put("crazy", mix); + + int[] someInts = new int[]{1, 2, 3}; + map.put("ints", someInts); + + map.put("regular", "stuff"); + + Map innerMap = new HashMap(); + innerMap.put("me", "you"); + + map.put("inner", innerMap); + + v.setProperty("crazy-map", map); + + JSONObject json = GraphsonUtil.jsonFromElement(v, null, GraphSONMode.NORMAL); + + assertThat(json).isNotNull(); + assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); + assertThat(json.containsKey("crazy-map")).isTrue(); + + JSONObject mapAsJson = (JSONObject) json.get("crazy-map"); + assertThat(mapAsJson.containsKey("regular")).isTrue(); + assertThat(mapAsJson.get("regular")).isEqualTo("stuff"); + + assertThat(mapAsJson.containsKey("ints")).isTrue(); + JSONArray intArrayAsJson = (JSONArray) mapAsJson.get("ints"); + assertThat(intArrayAsJson).hasSize(3); + + assertThat(mapAsJson.containsKey("crazy")).isTrue(); + JSONArray deepListAsJSON = (JSONArray) mapAsJson.get("crazy"); + assertThat(deepListAsJSON).hasSize(3); + + assertThat(mapAsJson.containsKey("inner")).isTrue(); + JSONObject mapInMapAsJSON = (JSONObject) mapAsJson.get("inner"); + assertThat(mapInMapAsJSON.containsKey("me")).isTrue(); + assertThat(mapInMapAsJSON.get("me")).isEqualTo("you"); + + } + + @Test + public void jsonFromElementVertexNoPropertiesWithKeysNoTypes() { + Vertex v = this.graph.addVertex(1); + v.setProperty("x", "X"); + v.setProperty("y", "Y"); + v.setProperty("z", "Z"); + + Set propertiesToInclude = new HashSet(); + propertiesToInclude.add("y"); + JSONObject json = GraphsonUtil.jsonFromElement(v, propertiesToInclude, GraphSONMode.NORMAL); + + assertThat(json).isNotNull(); + assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); + assertThat(json.get(GraphSONTokens._TYPE)).isEqualTo("vertex"); + assertThat(json.containsKey("x")).isFalse(); + assertThat(json.containsKey("z")).isFalse(); + assertThat(json.containsKey("y")).isTrue(); + } + + @Test + public void jsonFromElementVertexVertexPropertiesWithKeysNoTypes() { + Vertex v = this.graph.addVertex(1); + v.setProperty("x", "X"); + v.setProperty("y", "Y"); + v.setProperty("z", "Z"); + + Vertex innerV = this.graph.addVertex(2); + innerV.setProperty("x", "X"); + innerV.setProperty("y", "Y"); + innerV.setProperty("z", "Z"); + + v.setProperty("v", innerV); + + Set propertiesToInclude = new HashSet(); + propertiesToInclude.add("y"); + propertiesToInclude.add("v"); + + JSONObject json = GraphsonUtil.jsonFromElement(v, propertiesToInclude, GraphSONMode.NORMAL); + + assertThat(json).isNotNull(); + assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); + assertThat(json.get(GraphSONTokens._TYPE)).isEqualTo("vertex"); + assertThat(json.containsKey("x")).isFalse(); + assertThat(json.containsKey("z")).isFalse(); + assertThat(json.containsKey("y")).isTrue(); + assertThat(json.containsKey("v")).isTrue(); + + JSONObject innerJson = (JSONObject) json.get("v"); + assertThat(innerJson.containsKey("x")).isFalse(); + assertThat(innerJson.containsKey("z")).isFalse(); + assertThat(innerJson.containsKey("y")).isTrue(); + assertThat(innerJson.containsKey("v")).isFalse(); + } + + @Test + public void jsonFromElementVertexPrimitivePropertiesNoKeysWithTypes() { + Vertex v = this.graph.addVertex(1); + v.setProperty("keyString", "string"); + v.setProperty("keyLong", 1L); + v.setProperty("keyInt", 2); + v.setProperty("keyFloat", 3.3f); + v.setProperty("keyDouble", 4.4); + v.setProperty("keyBoolean", true); + + JSONObject json = GraphsonUtil.jsonFromElement(v, null, GraphSONMode.EXTENDED); + + assertThat(json).isNotNull(); + assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); + assertThat(json.containsKey("keyString")).isTrue(); + + JSONObject valueAsJson = (JSONObject) json.get("keyString"); + assertThat(valueAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); + assertThat(valueAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_STRING); + assertThat(valueAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); + assertThat(valueAsJson.get(GraphSONTokens.VALUE)).isEqualTo("string"); + + valueAsJson = (JSONObject) json.get("keyLong"); + assertThat(valueAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); + assertThat(valueAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_LONG); + assertThat(valueAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); + assertThat(valueAsJson.get(GraphSONTokens.VALUE)).isEqualTo(1L); + + valueAsJson = (JSONObject) json.get("keyInt"); + assertThat(valueAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); + assertThat(valueAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_INTEGER); + assertThat(valueAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); + assertThat(valueAsJson.get(GraphSONTokens.VALUE)).isEqualTo(2); + + valueAsJson = (JSONObject) json.get("keyFloat"); + assertThat(valueAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); + assertThat(valueAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_FLOAT); + assertThat(valueAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); + assertThat(valueAsJson.get(GraphSONTokens.VALUE)).isEqualTo(3.3f); + + valueAsJson = (JSONObject) json.get("keyDouble"); + assertThat(valueAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); + assertThat(valueAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_DOUBLE); + assertThat(valueAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); + assertThat(valueAsJson.get(GraphSONTokens.VALUE)).isEqualTo(4.4); + + valueAsJson = (JSONObject) json.get("keyBoolean"); + assertThat(valueAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); + assertThat(valueAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_BOOLEAN); + assertThat(valueAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); + assertThat(valueAsJson.get(GraphSONTokens.VALUE)).isEqualTo(true); + } + + @Test + public void jsonFromElementVertexListPropertiesNoKeysWithTypes() { + Vertex v = this.graph.addVertex(1); + List list = new ArrayList(); + list.add("this"); + list.add("this"); + list.add("this"); + + v.setProperty("keyList", list); + + JSONObject json = GraphsonUtil.jsonFromElement(v, null, GraphSONMode.EXTENDED); + + assertThat(json).isNotNull(); + assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); + assertThat(json.containsKey("keyList")).isTrue(); + + JSONObject listWithTypeAsJson = (JSONObject) json.get("keyList"); + assertThat(listWithTypeAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); + assertThat(listWithTypeAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_LIST); + assertThat(listWithTypeAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); + + JSONArray listAsJSON = (JSONArray) listWithTypeAsJson.get(GraphSONTokens.VALUE); + assertThat(listAsJSON).isNotNull(); + assertThat(listAsJSON).hasSize(3); + + for (int ix = 0; ix < listAsJSON.size(); ix++) { + JSONObject valueAsJson = (JSONObject) listAsJSON.get(ix); + assertThat(valueAsJson).isNotNull(); + assertThat(valueAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); + assertThat(valueAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_STRING); + assertThat(valueAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); + assertThat(valueAsJson.get(GraphSONTokens.VALUE)).isEqualTo("this"); + } + } + + @Test + public void jsonFromElementVertexBooleanListPropertiesNoKeysWithTypes() { + Vertex v = this.graph.addVertex(1); + List list = new ArrayList(); + list.add(true); + list.add(true); + list.add(true); + + v.setProperty("keyList", list); + + JSONObject json = GraphsonUtil.jsonFromElement(v, null, GraphSONMode.EXTENDED); + + assertThat(json).isNotNull(); + assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); + assertThat(json.containsKey("keyList")).isTrue(); + + JSONObject listWithTypeAsJson = (JSONObject) json.get("keyList"); + assertThat(listWithTypeAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); + assertThat(listWithTypeAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_LIST); + assertThat(listWithTypeAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); + + JSONArray listAsJSON = (JSONArray) listWithTypeAsJson.get(GraphSONTokens.VALUE); + assertThat(listAsJSON).isNotNull(); + assertThat(listAsJSON).hasSize(3); + + for (int ix = 0; ix < listAsJSON.size(); ix++) { + JSONObject valueAsJson = (JSONObject) listAsJSON.get(ix); + assertThat(valueAsJson).isNotNull(); + assertThat(valueAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); + assertThat(valueAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_BOOLEAN); + assertThat(valueAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); + assertThat(valueAsJson.get(GraphSONTokens.VALUE)).isEqualTo(true); + } + } + + @Test + public void jsonFromElementVertexLongListPropertiesNoKeysWithTypes() { + Vertex v = this.graph.addVertex(1); + List list = new ArrayList(); + list.add(1000L); + list.add(1000L); + list.add(1000L); + + v.setProperty("keyList", list); + + JSONObject json = GraphsonUtil.jsonFromElement(v, null, GraphSONMode.EXTENDED); + + assertThat(json).isNotNull(); + assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); + assertThat(json.containsKey("keyList")).isTrue(); + + JSONObject listWithTypeAsJson = (JSONObject) json.get("keyList"); + assertThat(listWithTypeAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); + assertThat(listWithTypeAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_LIST); + assertThat(listWithTypeAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); + + JSONArray listAsJSON = (JSONArray) listWithTypeAsJson.get(GraphSONTokens.VALUE); + assertThat(listAsJSON).isNotNull(); + assertThat(listAsJSON).hasSize(3); + + for (int ix = 0; ix < listAsJSON.size(); ix++) { + JSONObject valueAsJson = (JSONObject) listAsJSON.get(ix); + assertThat(valueAsJson).isNotNull(); + assertThat(valueAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); + assertThat(valueAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_LONG); + assertThat(valueAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); + assertThat(valueAsJson.get(GraphSONTokens.VALUE)).isEqualTo(1000L); + } + } + + @Test + public void jsonFromElementVertexIntListPropertiesNoKeysWithTypes() { + Vertex v = this.graph.addVertex(1); + List list = new ArrayList(); + list.add(1); + list.add(1); + list.add(1); + + v.setProperty("keyList", list); + + JSONObject json = GraphsonUtil.jsonFromElement(v, null, GraphSONMode.EXTENDED); + + assertThat(json).isNotNull(); + assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); + assertThat(json.containsKey("keyList")).isTrue(); + + JSONObject listWithTypeAsJson = (JSONObject) json.get("keyList"); + assertThat(listWithTypeAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); + assertThat(listWithTypeAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_LIST); + assertThat(listWithTypeAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); + + JSONArray listAsJSON = (JSONArray) listWithTypeAsJson.get(GraphSONTokens.VALUE); + assertThat(listAsJSON).isNotNull(); + assertThat(listAsJSON).hasSize(3); + + for (int ix = 0; ix < listAsJSON.size(); ix++) { + JSONObject valueAsJson = (JSONObject) listAsJSON.get(ix); + assertThat(valueAsJson).isNotNull(); + assertThat(valueAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); + assertThat(valueAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_INTEGER); + assertThat(valueAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); + assertThat(valueAsJson.get(GraphSONTokens.VALUE)).isEqualTo(1); + } + } + + @Test + public void jsonFromElementVertexListOfListPropertiesNoKeysWithTypes() { + Vertex v = this.graph.addVertex(1); + List list = new ArrayList(); + list.add(1); + list.add(1); + list.add(1); + + List> listList = new ArrayList>(); + listList.add(list); + + v.setProperty("keyList", listList); + + JSONObject json = GraphsonUtil.jsonFromElement(v, null, GraphSONMode.EXTENDED); + + assertThat(json).isNotNull(); + assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); + assertThat(json.containsKey("keyList")).isTrue(); + + JSONObject listWithTypeAsJson = (JSONObject) json.get("keyList"); + assertThat(listWithTypeAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); + assertThat(listWithTypeAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_LIST); + assertThat(listWithTypeAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); + + JSONArray array = (JSONArray) listWithTypeAsJson.get(GraphSONTokens.VALUE); + JSONObject obj = (JSONObject) array.get(0); + JSONArray listAsJSON = (JSONArray) obj.get(GraphSONTokens.VALUE); + assertThat(listAsJSON).isNotNull(); + assertThat(listAsJSON).hasSize(3); + + for (int ix = 0; ix < listAsJSON.size(); ix++) { + JSONObject valueAsJson = (JSONObject) listAsJSON.get(ix); + assertThat(valueAsJson).isNotNull(); + assertThat(valueAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); + assertThat(valueAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_INTEGER); + assertThat(valueAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); + assertThat(valueAsJson.get(GraphSONTokens.VALUE)).isEqualTo(1); + } + } + + @Test + public void jsonFromElementVertexMapPropertiesNoKeysWithTypes() { + Vertex v = this.graph.addVertex(1); + + Map map = new HashMap(); + map.put("this", "some"); + map.put("that", 1); + + v.setProperty("keyMap", map); + + JSONObject json = GraphsonUtil.jsonFromElement(v, null, GraphSONMode.EXTENDED); + + assertThat(json).isNotNull(); + assertThat(json.get(GraphSONTokens._ID)).isEqualTo("1"); + assertThat(json.containsKey("keyMap")).isTrue(); + + JSONObject mapWithTypeAsJSON = (JSONObject) json.get("keyMap"); + assertThat(mapWithTypeAsJSON).isNotNull(); + assertThat(mapWithTypeAsJSON.containsKey(GraphSONTokens.TYPE)).isTrue(); + assertThat(mapWithTypeAsJSON.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_MAP); + + assertThat(mapWithTypeAsJSON.containsKey(GraphSONTokens.VALUE)).isTrue(); + JSONObject mapAsJSON = (JSONObject) mapWithTypeAsJSON.get(GraphSONTokens.VALUE); + + assertThat(mapAsJSON.containsKey("this")).isTrue(); + JSONObject thisAsJson = (JSONObject) mapAsJSON.get("this"); + assertThat(thisAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); + assertThat(thisAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_STRING); + assertThat(thisAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); + assertThat(thisAsJson.get(GraphSONTokens.VALUE)).isEqualTo("some"); + + assertThat(mapAsJSON.containsKey("that")).isTrue(); + JSONObject thatAsJson = (JSONObject) mapAsJSON.get("that"); + assertThat(thatAsJson.containsKey(GraphSONTokens.TYPE)).isTrue(); + assertThat(thatAsJson.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_INTEGER); + assertThat(thatAsJson.containsKey(GraphSONTokens.VALUE)).isTrue(); + assertThat(thatAsJson.get(GraphSONTokens.VALUE)).isEqualTo(1); + } + + @Test + public void jsonFromElementNullsNoKeysNoTypes() { + Graph g = new TinkerGraph(); + Vertex v = g.addVertex(1); + v.setProperty("key", null); + + Map map = new HashMap(); + map.put("innerkey", null); + + List innerList = new ArrayList(); + innerList.add(null); + innerList.add("innerstring"); + map.put("list", innerList); + + v.setProperty("keyMap", map); + + List list = new ArrayList(); + list.add(null); + list.add("string"); + v.setProperty("keyList", list); + + JSONObject json = GraphsonUtil.jsonFromElement(v, null, GraphSONMode.NORMAL); + + assertThat(json).isNotNull(); + assertThat(json.get("key")).isNull(); + ; + + JSONObject jsonMap = (JSONObject) json.get("keyMap"); + assertThat(jsonMap).isNotNull(); + assertThat(jsonMap.get("innerkey")).isNull(); + + JSONArray jsonInnerArray = (JSONArray) jsonMap.get("list"); + assertThat(jsonInnerArray).isNotNull(); + assertThat(jsonInnerArray.get(0)).isNull(); + assertThat(jsonInnerArray.get(1)).isEqualTo("innerstring"); + + JSONArray jsonArray = (JSONArray) json.get("keyList"); + assertThat(jsonArray).isNotNull(); + assertThat(jsonArray.get(0)).isNull(); + assertThat(jsonArray.get(1)).isEqualTo("string"); + } + + @Test + public void jsonFromElementNullsNoKeysWithTypes() { + Graph g = new TinkerGraph(); + Vertex v = g.addVertex(1); + v.setProperty("key", null); + + Map map = new HashMap(); + map.put("innerkey", null); + + List innerList = new ArrayList(); + innerList.add(null); + innerList.add("innerstring"); + map.put("list", innerList); + + v.setProperty("keyMap", map); + + List list = new ArrayList(); + list.add(null); + list.add("string"); + v.setProperty("keyList", list); + + JSONObject json = GraphsonUtil.jsonFromElement(v, null, GraphSONMode.EXTENDED); + + + assertThat(json).isNotNull(); + JSONObject jsonObjectKey = (JSONObject) json.get("key"); + assertThat(jsonObjectKey.get(GraphSONTokens.VALUE)).isNull(); + assertThat(jsonObjectKey.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_UNKNOWN); + + JSONObject keyMap = (JSONObject) json.get("keyMap"); + JSONObject jsonMap = (JSONObject) keyMap.get(GraphSONTokens.VALUE); + assertThat(jsonMap).isNotNull(); + JSONObject jsonObjectMap = (JSONObject) jsonMap.get("innerkey"); + assertThat(jsonObjectMap.get(GraphSONTokens.VALUE)).isNull(); + assertThat(jsonObjectMap.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_UNKNOWN); + + JSONObject listJson = (JSONObject) jsonMap.get("list"); + JSONArray jsonInnerArray = (JSONArray) listJson.get(GraphSONTokens.VALUE); + assertThat(jsonInnerArray).isNotNull(); + JSONObject jsonObjectInnerListFirst = (JSONObject) jsonInnerArray.get(0); + assertThat(jsonObjectInnerListFirst.get(GraphSONTokens.VALUE)).isNull(); + assertThat(jsonObjectInnerListFirst.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_UNKNOWN); + + JSONObject keyList = (JSONObject) json.get("keyList"); + JSONArray jsonArray = (JSONArray) keyList.get(GraphSONTokens.VALUE); + assertThat(jsonArray).isNotNull(); + JSONObject jsonObjectListFirst = (JSONObject) jsonArray.get(0); + assertThat(jsonObjectListFirst.get(GraphSONTokens.VALUE)).isNull(); + assertThat(jsonObjectListFirst.get(GraphSONTokens.TYPE)).isEqualTo(GraphSONTokens.TYPE_UNKNOWN); + } + + @Test + public void vertexFromJsonValid() throws Exception { + Graph g = new TinkerGraph(); + ElementFactory factory = new ElementFactory(g); + + Vertex v = GraphsonUtil.vertexFromJson((JSONObject) JSONValue.parse(vertexJson1), factory, GraphSONMode.NORMAL, null); + + assertThat(v).isSameAs(g.getVertex(1)); + + // tinkergraph converts id to string + assertThat(v.getId()).isEqualTo("1"); + assertThat(v.getProperty("name")).isEqualTo("marko"); + assertThat(v.getProperty("age")).isEqualTo(29L); + } + + @Test + public void vertexFromJsonStringValid() throws Exception { + Graph g = new TinkerGraph(); + ElementFactory factory = new ElementFactory(g); + + Vertex v = GraphsonUtil.vertexFromJson(vertexJson1, factory, GraphSONMode.NORMAL, null); + + assertThat(v).isSameAs(g.getVertex(1)); + + // tinkergraph converts id to string + assertThat(v.getId()).isEqualTo("1"); + assertThat(v.getProperty("name")).isEqualTo("marko"); + assertThat(v.getProperty("age")).isEqualTo(29L); + } + + @Test + public void vertexFromJsonStringValidExtended() throws Exception { + Graph g = new TinkerGraph(); + ElementFactory factory = new ElementFactory(g); + + String vertexJson = "{\"person\":{\"value\":\"marko\",\"type\":\"string\"},\"_id\":1,\"_type\":\"vertex\"}"; + Vertex v = GraphsonUtil.vertexFromJson(vertexJson, factory, GraphSONMode.EXTENDED, null); + + Assert.assertSame(v, g.getVertex(1)); + + // tinkergraph converts id to string + Assert.assertEquals("1", v.getId()); + Assert.assertEquals("marko", v.getProperty("person")); + } + + @Test + public void vertexFromJsonInputStreamValid() throws Exception { + Graph g = new TinkerGraph(); + ElementFactory factory = new ElementFactory(g); + + Vertex v = GraphsonUtil.vertexFromJson(inputStreamVertexJson1, factory, GraphSONMode.NORMAL, null); + + Assert.assertSame(v, g.getVertex(1)); + + // tinkergraph converts id to string + Assert.assertEquals("1", v.getId()); + Assert.assertEquals("marko", v.getProperty("name")); + Assert.assertEquals(29L, v.getProperty("age")); + } + + @Test + public void vertexFromJsonIgnoreKeyValid() throws Exception { + Graph g = new TinkerGraph(); + ElementFactory factory = new ElementFactory(g); + + Set ignoreAge = new HashSet(); + ignoreAge.add("age"); + ElementPropertyConfig config = ElementPropertyConfig.excludeProperties(ignoreAge, null); + GraphsonUtil utility = new GraphsonUtil(GraphSONMode.NORMAL, factory, config); + Vertex v = utility.vertexFromJson((JSONObject) JSONValue.parse(vertexJson1)); + + Assert.assertSame(v, g.getVertex(1)); + + // tinkergraph converts id to string + Assert.assertEquals("1", v.getId()); + Assert.assertEquals("marko", v.getProperty("name")); + Assert.assertNull(v.getProperty("age")); + } + + @Test + public void edgeFromJsonValid() throws Exception { + Graph g = new TinkerGraph(); + ElementFactory factory = new ElementFactory(g); + + Vertex v1 = GraphsonUtil.vertexFromJson((JSONObject) JSONValue.parse(vertexJson1), factory, GraphSONMode.NORMAL, null); + Vertex v2 = GraphsonUtil.vertexFromJson((JSONObject) JSONValue.parse(vertexJson2), factory, GraphSONMode.NORMAL, null); + Edge e = GraphsonUtil.edgeFromJson((JSONObject) JSONValue.parse(edgeJson), v1, v2, factory, GraphSONMode.NORMAL, null); + + Assert.assertSame(v1, g.getVertex(1)); + Assert.assertSame(v2, g.getVertex(2)); + Assert.assertSame(e, g.getEdge(7)); + + // tinkergraph converts id to string + Assert.assertEquals("7", e.getId()); + Assert.assertEquals(0.5d, e.getProperty("weight")); + Assert.assertEquals("knows", e.getLabel()); + Assert.assertEquals(v1, e.getVertex(Direction.OUT)); + Assert.assertEquals(v2, e.getVertex(Direction.IN)); + } + + @Test + public void edgeFromJsonStringValid() throws Exception { + Graph g = new TinkerGraph(); + ElementFactory factory = new ElementFactory(g); + + Vertex v1 = GraphsonUtil.vertexFromJson(vertexJson1, factory, GraphSONMode.NORMAL, null); + Vertex v2 = GraphsonUtil.vertexFromJson(vertexJson2, factory, GraphSONMode.NORMAL, null); + Edge e = GraphsonUtil.edgeFromJson(edgeJson, v1, v2, factory, GraphSONMode.NORMAL, null); + + Assert.assertSame(v1, g.getVertex(1)); + Assert.assertSame(v2, g.getVertex(2)); + Assert.assertSame(e, g.getEdge(7)); + + // tinkergraph converts id to string + Assert.assertEquals("7", e.getId()); + Assert.assertEquals(0.5d, e.getProperty("weight")); + Assert.assertEquals("knows", e.getLabel()); + Assert.assertEquals(v1, e.getVertex(Direction.OUT)); + Assert.assertEquals(v2, e.getVertex(Direction.IN)); + } + + @Test + public void edgeFromJsonIgnoreWeightValid() throws Exception { + Graph g = new TinkerGraph(); + ElementFactory factory = new ElementFactory(g); + + Vertex v1 = GraphsonUtil.vertexFromJson((JSONObject) JSONValue.parse(vertexJson1), factory, GraphSONMode.NORMAL, null); + Vertex v2 = GraphsonUtil.vertexFromJson((JSONObject) JSONValue.parse(vertexJson2), factory, GraphSONMode.NORMAL, null); + + Set ignoreWeight = new HashSet(); + ignoreWeight.add("weight"); + ElementPropertyConfig config = ElementPropertyConfig.excludeProperties(null, ignoreWeight); + GraphsonUtil utility = new GraphsonUtil(GraphSONMode.NORMAL, factory, config); + Edge e = utility.edgeFromJson((JSONObject) JSONValue.parse(edgeJson), v1, v2); + + Assert.assertSame(v1, g.getVertex(1)); + Assert.assertSame(v2, g.getVertex(2)); + Assert.assertSame(e, g.getEdge(7)); + + // tinkergraph converts id to string + Assert.assertEquals("7", e.getId()); + Assert.assertNull(e.getProperty("weight")); + Assert.assertEquals("knows", e.getLabel()); + Assert.assertEquals(v1, e.getVertex(Direction.OUT)); + Assert.assertEquals(v2, e.getVertex(Direction.IN)); + } + + @Test + public void edgeFromJsonNormalLabelOrIdOnEdge() throws Exception { + Graph g = new TinkerGraph(); + ElementFactory factory = new ElementFactory(g); + + Vertex v1 = GraphsonUtil.vertexFromJson((JSONObject) JSONValue.parse(vertexJson1), factory, GraphSONMode.NORMAL, null); + Vertex v2 = GraphsonUtil.vertexFromJson((JSONObject) JSONValue.parse(vertexJson2), factory, GraphSONMode.NORMAL, null); + Edge e = GraphsonUtil.edgeFromJson((JSONObject) JSONValue.parse(edgeJsonLight), v1, v2, factory, GraphSONMode.NORMAL, null); + + Assert.assertSame(v1, g.getVertex(1)); + Assert.assertSame(v2, g.getVertex(2)); + Assert.assertSame(e, g.getEdge(0)); + } + + @Test + public void edgeFromJsonInputStreamCompactLabelOrIdOnEdge() throws Exception { + Graph g = new TinkerGraph(); + ElementFactory factory = new ElementFactory(g); + + Vertex v1 = GraphsonUtil.vertexFromJson((JSONObject) JSONValue.parse(vertexJson1), factory, GraphSONMode.COMPACT, null); + Vertex v2 = GraphsonUtil.vertexFromJson((JSONObject) JSONValue.parse(vertexJson2), factory, GraphSONMode.COMPACT, null); + Edge e = GraphsonUtil.edgeFromJson(inputStreamEdgeJsonLight, v1, v2, factory, GraphSONMode.COMPACT, null); + + Assert.assertSame(v1, g.getVertex(1)); + Assert.assertSame(v2, g.getVertex(2)); + Assert.assertSame(e, g.getEdge(0)); + } + + @Test + public void edgeFromJsonInputStreamCompactNoIdOnEdge() throws Exception { + Graph g = new TinkerGraph(); + ElementFactory factory = new ElementFactory(g); + + Set vertexKeys = new HashSet() {{ + add(GraphSONTokens._ID); + }}; + + Set edgeKeys = new HashSet() {{ + add(GraphSONTokens._IN_V); + }}; + + GraphsonUtil graphson = new GraphsonUtil(GraphSONMode.COMPACT, factory, vertexKeys, edgeKeys); + + Vertex v1 = graphson.vertexFromJson((JSONObject) JSONValue.parse(vertexJson1)); + Vertex v2 = graphson.vertexFromJson((JSONObject) JSONValue.parse(vertexJson2)); + Edge e = graphson.edgeFromJson(inputStreamEdgeJsonLight, v1, v2); + + Assert.assertSame(v1, g.getVertex(1)); + Assert.assertSame(v2, g.getVertex(2)); + Assert.assertSame(e, g.getEdge(0)); + } + + private class Cat { + private String name; + + public Cat(String name) { + this.name = name; + } + + public String getName() { + return this.name; + } + + @Override + public String toString() { + return this.name; + } + } +} diff --git a/sonar-core/src/test/java/org/sonar/core/graph/graphson/GraphsonWriterTest.java b/sonar-core/src/test/java/org/sonar/core/graph/graphson/GraphsonWriterTest.java new file mode 100644 index 00000000000..54551df7f1d --- /dev/null +++ b/sonar-core/src/test/java/org/sonar/core/graph/graphson/GraphsonWriterTest.java @@ -0,0 +1,133 @@ +/* + * Sonar, open source software quality management tool. + * Copyright (C) 2008-2012 SonarSource + * mailto:contact AT sonarsource DOT com + * + * Sonar is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * Sonar is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with Sonar; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.core.graph.graphson; + +import com.tinkerpop.blueprints.Graph; +import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; +import org.junit.Test; + +import java.io.ByteArrayOutputStream; + +import static org.fest.assertions.Assertions.assertThat; + +public class GraphsonWriterTest { + + @Test + public void outputGraphNoEmbeddedTypes() throws Exception { + Graph g = TinkerGraphFactory.createTinkerGraph(); + + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + + GraphSONWriter writer = new GraphSONWriter(); + writer.write(g, stream, GraphSONMode.NORMAL); + + stream.flush(); + stream.close(); + + String jsonString = new String(stream.toByteArray()); + + JSONObject rootNode = (JSONObject) JSONValue.parse(jsonString); + + // ensure that the JSON conforms to basic structure and that the right + // number of graph elements are present. other tests already cover element formatting + assertThat(rootNode).isNotNull(); + assertThat(rootNode.containsKey(GraphSONTokens.MODE)).isTrue(); + assertThat(rootNode.get(GraphSONTokens.MODE)).isEqualTo("NORMAL"); + + assertThat(rootNode.containsKey(GraphSONTokens.VERTICES)).isTrue(); + + JSONArray vertices = (JSONArray) rootNode.get(GraphSONTokens.VERTICES); + assertThat(vertices).hasSize(6); + + assertThat(rootNode.containsKey(GraphSONTokens.EDGES)).isTrue(); + + JSONArray edges = (JSONArray) rootNode.get(GraphSONTokens.EDGES); + assertThat(edges).hasSize(6); + } + + @Test + public void outputGraphWithEmbeddedTypes() throws Exception { + Graph g = TinkerGraphFactory.createTinkerGraph(); + + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + + GraphSONWriter writer = new GraphSONWriter(); + writer.write(g, stream, GraphSONMode.EXTENDED); + + stream.flush(); + stream.close(); + + String jsonString = new String(stream.toByteArray()); + + JSONObject rootNode = (JSONObject) JSONValue.parse(jsonString); + + // ensure that the JSON conforms to basic structure and that the right + // number of graph elements are present. other tests already cover element formatting + assertThat(rootNode).isNotNull(); + assertThat(rootNode.containsKey(GraphSONTokens.MODE)).isTrue(); + assertThat(rootNode.get(GraphSONTokens.MODE)).isEqualTo("EXTENDED"); + + assertThat(rootNode.containsKey(GraphSONTokens.VERTICES)).isTrue(); + + JSONArray vertices = (JSONArray) rootNode.get(GraphSONTokens.VERTICES); + assertThat(vertices).hasSize(6); + + assertThat(rootNode.containsKey(GraphSONTokens.EDGES)).isTrue(); + + JSONArray edges = (JSONArray) rootNode.get(GraphSONTokens.EDGES); + assertThat(edges).hasSize(6); + } + + @Test + public void outputGraphWithCompact() throws Exception { + Graph g = TinkerGraphFactory.createTinkerGraph(); + + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + + GraphSONWriter writer = new GraphSONWriter(); + writer.write(g, stream, GraphSONMode.COMPACT); + + stream.flush(); + stream.close(); + + String jsonString = new String(stream.toByteArray()); + + JSONObject rootNode = (JSONObject) JSONValue.parse(jsonString); + + // ensure that the JSON conforms to basic structure and that the right + // number of graph elements are present. other tests already cover element formatting + assertThat(rootNode).isNotNull(); + assertThat(rootNode.containsKey(GraphSONTokens.MODE)).isTrue(); + assertThat(rootNode.get(GraphSONTokens.MODE)).isEqualTo("COMPACT"); + + assertThat(rootNode.containsKey(GraphSONTokens.VERTICES)).isTrue(); + + JSONArray vertices = (JSONArray) rootNode.get(GraphSONTokens.VERTICES); + assertThat(vertices).hasSize(6); + + assertThat(rootNode.containsKey(GraphSONTokens.EDGES)).isTrue(); + + JSONArray edges = (JSONArray) rootNode.get(GraphSONTokens.EDGES); + assertThat(edges).hasSize(6); + } +} -- cgit v1.2.3