Java Code Examples for org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerFactory#createClassic()

The following examples show how to use org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerFactory#createClassic() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GraphSONMessageSerializerV1d0Test.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSerializeToJsonMapWithElementForKey() throws Exception {
    final TinkerGraph graph = TinkerFactory.createClassic();
    final GraphTraversalSource g = graph.traversal();
    final Map<Vertex, Integer> map = new HashMap<>();
    map.put(g.V().has("name", "marko").next(), 1000);

    final String results = SERIALIZER.serializeResponseAsString(ResponseMessage.build(msg).result(map).create());
    final JsonNode json = mapper.readTree(results);

    assertNotNull(json);
    assertEquals(msg.getRequestId().toString(), json.get(SerTokens.TOKEN_REQUEST).asText());
    final JsonNode converted = json.get(SerTokens.TOKEN_RESULT).get(SerTokens.TOKEN_DATA);

    assertNotNull(converted);

    // with no embedded types the key (which is a vertex) simply serializes out to an id
    // {"result":{"1":1000},"code":200,"requestId":"2d62161b-9544-4f39-af44-62ec49f9a595","type":0}
    assertEquals(1000, converted.get("1").asInt());
}
 
Example 2
Source File: GraphSONMessageSerializerGremlinV1d0Test.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSerializeToJsonMapWithElementForKey() throws Exception {
    final TinkerGraph graph = TinkerFactory.createClassic();
    final GraphTraversalSource g = graph.traversal();
    final Map<Vertex, Integer> map = new HashMap<>();
    map.put(g.V().has("name", "marko").next(), 1000);

    final ResponseMessage response = convert(map);
    assertCommon(response);

    final Map<String, Integer> deserializedMap = (Map<String, Integer>) response.getResult().getData();
    assertEquals(1, deserializedMap.size());

    // with no embedded types the key (which is a vertex) simply serializes out to an id
    // {"result":{"1":1000},"code":200,"requestId":"2d62161b-9544-4f39-af44-62ec49f9a595","type":0}
    assertEquals(new Integer(1000), deserializedMap.get("1"));
}
 
Example 3
Source File: GraphSONMessageSerializerV2d0Test.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSerializeToJsonMapWithElementForKey() throws Exception {
    final TinkerGraph graph = TinkerFactory.createClassic();
    final GraphTraversalSource g = graph.traversal();
    final Map<Vertex, Integer> map = new HashMap<>();
    map.put(g.V().has("name", "marko").next(), 1000);

    final String results = SERIALIZER.serializeResponseAsString(ResponseMessage.build(msg).result(map).create());
    final JsonNode json = mapper.readTree(results);

    assertNotNull(json);
    assertEquals(msg.getRequestId().toString(), json.get(SerTokens.TOKEN_REQUEST).asText());
    final JsonNode converted = json.get(SerTokens.TOKEN_RESULT).get(SerTokens.TOKEN_DATA);

    assertNotNull(converted);

    // with no embedded types the key (which is a vertex) simply serializes out to an id
    // {"result":{"1":1000},"code":200,"requestId":"2d62161b-9544-4f39-af44-62ec49f9a595","type":0}
    assertEquals(1000, converted.get("1").get(GraphSONTokens.VALUEPROP).asInt());
}
 
Example 4
Source File: GryoLiteMessageSerializerV1d0Test.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSerializeToMapWithElementForKey() throws Exception {
    final TinkerGraph graph = TinkerFactory.createClassic();
    final GraphTraversalSource g = graph.traversal();
    final Map<Vertex, Integer> map = new HashMap<>();
    map.put(g.V().has("name", "marko").next(), 1000);

    final ResponseMessage response = convertBinary(map);
    assertCommon(response);

    final Map<Vertex, Integer> deserializedMap = (Map<Vertex, Integer>) response.getResult().getData();
    assertEquals(1, deserializedMap.size());

    final Vertex deserializedMarko = deserializedMap.keySet().iterator().next();
    assertEquals(0, IteratorUtils.count(deserializedMarko.properties()));
    assertEquals(1, deserializedMarko.id());
    assertEquals(Vertex.DEFAULT_LABEL, deserializedMarko.label());

    assertEquals(new Integer(1000), deserializedMap.values().iterator().next());
}
 
Example 5
Source File: GraphSONMessageSerializerGremlinV2d0Test.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSerializeToJsonMapWithElementForKey() throws Exception {
    final TinkerGraph graph = TinkerFactory.createClassic();
    final GraphTraversalSource g = graph.traversal();
    final Map<Vertex, Integer> map = new HashMap<>();
    map.put(g.V().has("name", "marko").next(), 1000);

    final ResponseMessage response = convert(map);
    assertCommon(response);

    final Map<String, Integer> deserializedMap = (Map<String, Integer>) response.getResult().getData();
    assertEquals(1, deserializedMap.size());

    // with no embedded types the key (which is a vertex) simply serializes out to an id
    // {"result":{"1":1000},"code":200,"requestId":"2d62161b-9544-4f39-af44-62ec49f9a595","type":0}
    assertEquals(new Integer(1000), deserializedMap.get("1"));
}
 
Example 6
Source File: GremlinGroovyScriptEngineOverGraphTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldProperlyHandleBindings() throws Exception {
    final Graph graph = TinkerFactory.createClassic();
    final GraphTraversalSource g = graph.traversal();
    final ScriptEngine engine = new GremlinGroovyScriptEngine();
    engine.put("g", g);
    engine.put("marko", convertToVertexId(graph, "marko"));
    Assert.assertEquals(g.V(convertToVertexId(graph, "marko")).next(), engine.eval("g.V(marko).next()"));

    final Bindings bindings = engine.createBindings();
    bindings.put("g", g);
    bindings.put("s", "marko");
    bindings.put("f", 0.5f);
    bindings.put("i", 1);
    bindings.put("b", true);
    bindings.put("l", 100l);
    bindings.put("d", 1.55555d);

    assertEquals(engine.eval("g.E().has('weight',f).next()", bindings), g.E(convertToEdgeId(graph, "marko", "knows", "vadas")).next());
    assertEquals(engine.eval("g.V().has('name',s).next()", bindings), g.V(convertToVertexId(graph, "marko")).next());
    assertEquals(engine.eval("g.V().sideEffect{it.get().property('bbb',it.get().value('name')=='marko')}.iterate();g.V().has('bbb',b).next()", bindings), g.V(convertToVertexId(graph, "marko")).next());
    assertEquals(engine.eval("g.V().sideEffect{it.get().property('iii',it.get().value('name')=='marko'?1:0)}.iterate();g.V().has('iii',i).next()", bindings), g.V(convertToVertexId(graph, "marko")).next());
    assertEquals(engine.eval("g.V().sideEffect{it.get().property('lll',it.get().value('name')=='marko'?100l:0l)}.iterate();g.V().has('lll',l).next()", bindings), g.V(convertToVertexId(graph, "marko")).next());
    assertEquals(engine.eval("g.V().sideEffect{it.get().property('ddd',it.get().value('name')=='marko'?1.55555d:0)}.iterate();g.V().has('ddd',d).next()", bindings), g.V(convertToVertexId(graph, "marko")).next());
}
 
Example 7
Source File: BaseSqlGremlinTest.java    From sql-gremlin with Apache License 2.0 5 votes vote down vote up
public void setUpBefore(Data data) {
    switch(data) {
        case MODERN:
            graph = TinkerFactory.createModern();
            break;
        case CLASSIC:
            graph = TinkerFactory.createClassic();
            break;
        case CREW:
            graph = TinkerFactory.createTheCrew();
            break;
        case SPACE:
            graph = SqlFactory.createSpaceGraph();
            break;
        default:
            throw new UnsupportedOperationException("Unsupported graph " + data);
    }
    g = graph.traversal();

    ObjectMapper mapper = new ObjectMapper();
    try {
        schemaConfig = mapper.readValue(new File("schema.json"), SchemaConfig.class);
    } catch (Exception e) {
        throw new SchemaException("Error reading the schema file.", e);
    }

    compiler = new GremlinCompiler(graph, schemaConfig);

}
 
Example 8
Source File: ShowcaseClassicTest.java    From peapod with Apache License 2.0 5 votes vote down vote up
@Before
public void init() {
    TinkerGraph classic = TinkerFactory.createClassic();
    graph = new FramedGraph(classic, Person.class.getPackage());

    marko = graph.v(1, Person.class);
    vadas = graph.v(2, Person.class);
    lop = graph.v(3, Software.class);
    josh = graph.v(4, Person.class);
    ripple = graph.v(5, Software.class);
    peter = graph.v(6, Person.class);
}
 
Example 9
Source File: GraphSONMessageSerializerV3d0Test.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSerializeToJsonMapWithElementForKey() throws Exception {
    final TinkerGraph graph = TinkerFactory.createClassic();
    final GraphTraversalSource g = graph.traversal();
    final Map<Vertex, Integer> map = new HashMap<>();
    final Vertex v1 = g.V().has("name", "marko").next();
    map.put(v1, 1000);

    final ResponseMessage response = convert(map);
    assertCommon(response);

    final Map<Vertex, Integer> deserializedMap = (Map<Vertex, Integer>) response.getResult().getData();
    assertEquals(1, deserializedMap.size());
    assertEquals(new Integer(1000), deserializedMap.get(v1));
}
 
Example 10
Source File: GraphSONMessageSerializerV1d0Test.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSerializeToJsonTree() throws Exception {
    final TinkerGraph graph = TinkerFactory.createClassic();
    final GraphTraversalSource g = graph.traversal();
    final Tree t = g.V(1).out().properties("name").tree().next();

    
    final String results = SERIALIZER.serializeResponseAsString(ResponseMessage.build(msg).result(t).create());

    final JsonNode json = mapper.readTree(results);

    assertNotNull(json);
    assertEquals(msg.getRequestId().toString(), json.get(SerTokens.TOKEN_REQUEST).asText());
    final JsonNode converted = json.get(SerTokens.TOKEN_RESULT).get(SerTokens.TOKEN_DATA);
    assertNotNull(converted);
    
    //check the first object and it's properties
    assertEquals(1, converted.get("1").get("key").get("id").asInt());
    assertEquals("marko", converted.get("1").get("key").get("properties").get("name").get(0).get("value").asText());
    
    //check objects tree structure
    //check Vertex property
    assertEquals("vadas", converted.get("1")
                             .get("value")
                             .get("2")
                             .get("value")
                             .get("3").get("key").get("value").asText());
    assertEquals("name", converted.get("1")
                             .get("value")
                             .get("2")
                             .get("value")
                             .get("3").get("key").get("label").asText());
    
    // check subitem
    assertEquals("lop", converted.get("1")
                             .get("value")
                             .get("3")
                             .get("key")
                             .get("properties").get("name").get(0).get("value").asText());
}
 
Example 11
Source File: GraphSONMessageSerializerGremlinV1d0Test.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSerializeToTreeJson() throws Exception {
    final TinkerGraph graph = TinkerFactory.createClassic();
    final GraphTraversalSource g = graph.traversal();
    final Map t = g.V(1).out().properties("name").tree().next();

    final ResponseMessage response = convert(t);
    assertCommon(response);

    final Map<String, Map<String, Map>> deserializedMap = (Map<String, Map<String, Map>>) response.getResult().getData();

    assertEquals(1, deserializedMap.size());

    //check the first object and it's properties
    final Map<String,Object> vertex = deserializedMap.get("1").get("key");
    final Map<String,List<Map>> vertexProperties = (Map<String, List<Map>>)vertex.get("properties");
    assertEquals(1, (int)vertex.get("id"));
    assertEquals("marko", vertexProperties.get("name").get(0).get("value"));

    //check objects tree structure
    //check Vertex property
    final Map<String, Map<String, Map>> subTreeMap =  deserializedMap.get("1").get("value");
    final Map<String, Map<String, Map>> subTreeMap2 = subTreeMap.get("2").get("value");
    final Map<String, String> vertexPropertiesDeep = subTreeMap2.get("3").get("key");
    assertEquals("vadas", vertexPropertiesDeep.get("value"));
    assertEquals("name", vertexPropertiesDeep.get("label"));

    // check subitem
    final Map<String,Object> vertex2 = subTreeMap.get("3").get("key");
    final Map<String,List<Map>> vertexProperties2 = (Map<String, List<Map>>)vertex2.get("properties");

    assertEquals("lop", vertexProperties2.get("name").get(0).get("value"));
}
 
Example 12
Source File: GremlinGroovyScriptEngineOverGraphTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@org.junit.Ignore
public void shouldAllowUseOfClasses() throws ScriptException {
    final Graph graph = TinkerFactory.createClassic();
    final GraphTraversalSource g = graph.traversal();
    GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine();

    final Bindings bindings = engine.createBindings();
    bindings.put("g", g);
    bindings.put("vadas", convertToVertexId(graph, "vadas"));

    // works when it's all defined together
    assertEquals(true, engine.eval("class c { static def isVadas(v){v.value('name')=='vadas'}};c.isVadas(g.V(vadas).next())", bindings));

    // let's reset this piece and make sure isVadas is not hanging around.
    engine.reset();

    // validate that isVadas throws an exception since it is not defined
    try {
        engine.eval("c.isVadas(g.V(vadas).next())", bindings);

        // fail the test if the above doesn't throw an exception
        fail("Function should be gone");
    } catch (Exception ex) {
        // this is good...we want this. it means isVadas isn't hanging about
    }

    // now...define the class separately on its own in one script...
    // HERE'S an AWKWARD BIT.........
    // YOU HAVE TO END WITH: null;
    // ....OR ELSE YOU GET:
    // javax.script.ScriptException: javax.script.ScriptException:
    // org.codehaus.groovy.runtime.metaclass.MissingMethodExceptionNoStack: No signature of method: c.main()
    // is applicable for argument types: ([Ljava.lang.String;) values: [[]]
    // WOULD BE NICE IF WE DIDN'T HAVE TO DO THAT
    engine.eval("class c { static def isVadas(v){v.name=='vadas'}};null;", bindings);

    // make sure the class works on its own...this generates: groovy.lang.MissingPropertyException: No such property: c for class: Script2
    assertEquals(true, engine.eval("c.isVadas(g.V(vadas).next())", bindings));
}
 
Example 13
Source File: SampleCode.java    From tinkerpop3 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Demonstration of the Sparql/PG API.
 * 
 */
@Test 
public void demonstrateSparqlAPI() throws Exception {
    
    /*
     * Bulk load the classic graph.
     */
    final TinkerGraph classic = TinkerFactory.createClassic();
    graph.bulkLoad(classic);
    graph.tx().commit();

    /*
     * "Who created a project named 'lop' that was also created by someone 
     * who is 29 years old? Return the two creators."
     * 
     * gremlin> g.V().match(
     *        __.as('a').out('created').as('b'),
     *        __.as('b').has('name', 'lop'),
     *        __.as('b').in('created').as('c'),
     *        __.as('c').has('age', 29)).
     *      select('a','c').by('name')
     * ==>[a:marko, c:marko]
     * ==>[a:josh, c:marko]
     * ==>[a:peter, c:marko]
     */
    final String sparql = 
            "select ?a ?c { " +
                 // vertex named "lop"
            "    ?lop <blaze:name> \"lop\" . " +
                 // created by ?c
            "    <<?c_id ?x ?lop>> rdf:type <blaze:created> . " +
                 // whose age is 29
            "    ?c_id <blaze:age> \"29\"^^xsd:int . " +
                 // created by ?a
            "    <<?a_id ?y ?lop>> rdf:type <blaze:created> . " +
                 // gather names
            "    ?a_id <blaze:name> ?a . " +
            "    ?c_id <blaze:name> ?c . " +
            "}";

    /*
     * Run the query, auto-translate RDF values to PG values.
     */
    final List<BlazeBindingSet> results = graph.select(sparql).collect();
    
    log.info(() -> results.stream());
    assertEquals(3, results.size());
    assertEquals(1, results.stream().map(bs -> bs.get("c")).distinct().count());
    assertEquals(3, results.stream().map(bs -> bs.get("a")).distinct().count());
    
}
 
Example 14
Source File: ConsoleCompiler.java    From sparql-gremlin with Apache License 2.0 4 votes vote down vote up
public static void main(final String[] args) throws IOException {

        final Options options = new Options();
        options.addOption("f", "file", true, "a file that contains a SPARQL query");
        options.addOption("g", "graph", true, "the graph that's used to execute the query [classic|modern|crew|kryo file]");
        // TODO: add an OLAP option (perhaps: "--olap spark"?)

        final CommandLineParser parser = new DefaultParser();
        final CommandLine commandLine;

        try {
            commandLine = parser.parse(options, args);
        } catch (ParseException e) {
            System.out.println(e.getMessage());
            printHelp(1);
            return;
        }

        final InputStream inputStream = commandLine.hasOption("file")
                ? new FileInputStream(commandLine.getOptionValue("file"))
                : System.in;
        final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        final StringBuilder queryBuilder = new StringBuilder();

        if (!reader.ready()) {
            printHelp(1);
        }

        String line;
        while (null != (line = reader.readLine())) {
            queryBuilder.append(System.lineSeparator()).append(line);
        }

        final String queryString = queryBuilder.toString();
        final Graph graph;

        if (commandLine.hasOption("graph")) {
            switch (commandLine.getOptionValue("graph").toLowerCase()) {
                case "classic":
                    graph = TinkerFactory.createClassic();
                    break;
                case "modern":
                    graph = TinkerFactory.createModern();
                    break;
                case "crew":
                    graph = TinkerFactory.createTheCrew();
                    break;
                default:
                    graph = TinkerGraph.open();
                    graph.io(IoCore.gryo()).readGraph(commandLine.getOptionValue("graph"));
                    break;
            }
        } else {
            graph = TinkerFactory.createModern();
        }

        final Traversal<Vertex, ?> traversal = SparqlToGremlinCompiler.convertToGremlinTraversal(graph, queryString);

        printWithHeadline("SPARQL Query", queryString);
        printWithHeadline("Traversal (prior execution)", traversal);
        printWithHeadline("Result", String.join(System.lineSeparator(),
                traversal.toStream().map(Object::toString).collect(Collectors.toList())));
        printWithHeadline("Traversal (after execution)", traversal);
    }
 
Example 15
Source File: GraphSONMessageSerializerV2d0Test.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldSerializeToTreeJson() throws Exception {
    final TinkerGraph graph = TinkerFactory.createClassic();
    final GraphTraversalSource g = graph.traversal();
    final Tree t = g.V(1).out().properties("name").tree().next();

    final String results = SERIALIZER.serializeResponseAsString(ResponseMessage.build(msg).result(t).create());

    final JsonNode json = mapper.readTree(results);

    assertNotNull(json);
    assertEquals(msg.getRequestId().toString(), json.get(SerTokens.TOKEN_REQUEST).asText());
    final JsonNode converted = json.get(SerTokens.TOKEN_RESULT).get(SerTokens.TOKEN_DATA);
    assertNotNull(converted);

    //result is: tree{v1=>tree{vp['name'->'vadas']=>null, vp['name'->'lop']=>null, vp['name'->'josh']=>null}}
    
    //check the first object and it's properties
    assertEquals(1, converted.get(GraphSONTokens.VALUEPROP)
            .get(0)
            .get(GraphSONTokens.KEY).get(GraphSONTokens.VALUEPROP)
            .get(GraphSONTokens.ID).get(GraphSONTokens.VALUEPROP).asInt());

    assertEquals("marko", converted.get(GraphSONTokens.VALUEPROP)
            .get(0)
            .get(GraphSONTokens.KEY).get(GraphSONTokens.VALUEPROP)
            .get(GraphSONTokens.PROPERTIES)
            .get("name")
            .get(0)
            .get(GraphSONTokens.VALUEPROP).get(GraphSONTokens.VALUE).asText());

    //check the leafs
    assertEquals("vadas", converted.get(GraphSONTokens.VALUEPROP)
            .get(0)
            .get(GraphSONTokens.VALUE).get(GraphSONTokens.VALUEPROP)
            .get(0)
            .get(GraphSONTokens.KEY).get(GraphSONTokens.VALUEPROP)
            .get(GraphSONTokens.PROPERTIES)
            .get("name")
            .get(0)
            .get(GraphSONTokens.VALUEPROP).get(GraphSONTokens.VALUE).asText());

    assertEquals("lop", converted.get(GraphSONTokens.VALUEPROP)
            .get(0)
            .get(GraphSONTokens.VALUE).get(GraphSONTokens.VALUEPROP)
            .get(1)
            .get(GraphSONTokens.KEY).get(GraphSONTokens.VALUEPROP)
            .get(GraphSONTokens.PROPERTIES)
            .get("name")
            .get(0)
            .get(GraphSONTokens.VALUEPROP).get(GraphSONTokens.VALUE).asText());

    assertEquals("josh", converted.get(GraphSONTokens.VALUEPROP)
            .get(0)
            .get(GraphSONTokens.VALUE).get(GraphSONTokens.VALUEPROP)
            .get(2)
            .get(GraphSONTokens.KEY).get(GraphSONTokens.VALUEPROP)
            .get(GraphSONTokens.PROPERTIES)
            .get("name")
            .get(0)
            .get(GraphSONTokens.VALUEPROP).get(GraphSONTokens.VALUE).asText());
}