Java Code Examples for org.apache.tinkerpop.gremlin.structure.Graph#traversal()

The following examples show how to use org.apache.tinkerpop.gremlin.structure.Graph#traversal() . 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: 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 2
Source File: TinkerGraphIoStepTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldWriteReadWithCustomIoRegistryGryo() throws Exception {
    final UUID uuid = UUID.randomUUID();
    g.addV("person").property("name","stephen").property("custom", new CustomId("a", uuid)).iterate();

    final File file = TestHelper.generateTempFile(TinkerGraphIoStepTest.class, "shouldWriteReadWithCustomIoRegistryGryo", ".kryo");
    g.io(file.getAbsolutePath()).with(IO.registry, CustomId.CustomIdIoRegistry.class.getName()).write().iterate();

    final Graph emptyGraph = TinkerGraph.open();
    final GraphTraversalSource emptyG = emptyGraph.traversal();

    try {
        emptyG.io(file.getAbsolutePath()).read().iterate();
        fail("Can't read without a registry");
    } catch (Exception ignored) {
        // do nothing
    }

    emptyG.io(file.getAbsolutePath()).with(IO.registry, CustomId.CustomIdIoRegistry.instance()).read().iterate();

    assertEquals(1, emptyG.V().has("custom", new CustomId("a", uuid)).count().next().intValue());
}
 
Example 3
Source File: GremlinEnabledScriptEngineTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void shouldNotAllowBytecodeEvalWithAliasInBindings() throws Exception {
    final GremlinScriptEngine scriptEngine = manager.getEngineByName(ENGINE_TO_TEST);
    final Graph graph = EmptyGraph.instance();
    final GraphTraversalSource g = graph.traversal();

    // purposefully use "x" to match the name of the traversal source binding for "x" below and
    // thus tests the alias added for "x"
    final GraphTraversal t = getTraversalWithLambda(g);

    final Bindings bindings = new SimpleBindings();
    bindings.put("x", g);
    bindings.put(GremlinScriptEngine.HIDDEN_G, g);

    scriptEngine.eval(t.asAdmin().getBytecode(), bindings, "x");
}
 
Example 4
Source File: TestRepeatStepGraphOut.java    From sqlg with MIT License 6 votes vote down vote up
@Test
public void g_V_repeatXoutX_timesX2X_emit_path() {
    loadModern();
    Graph graph = this.sqlgGraph;
    assertModernGraph(graph, true, false);
    GraphTraversalSource g = graph.traversal();
    final List<DefaultGraphTraversal<Vertex, Path>> traversals = new ArrayList<>();
    DefaultGraphTraversal<Vertex, Path> t = (DefaultGraphTraversal<Vertex, Path>) g.V().repeat(__.out()).emit().times(2).path();
    Assert.assertEquals(3, t.getSteps().size());
    traversals.add(t);
    traversals.forEach(traversal -> {
        printTraversalForm(traversal);
        Assert.assertEquals(2, traversal.getSteps().size());
        final Map<Integer, Long> pathLengths = new HashMap<>();
        int counter = 0;
        while (traversal.hasNext()) {
            counter++;
            MapHelper.incr(pathLengths, traversal.next().size(), 1L);
        }
        Assert.assertEquals(2, pathLengths.size());
        Assert.assertEquals(8, counter);
        Assert.assertEquals(new Long(6), pathLengths.get(2));
        Assert.assertEquals(new Long(2), pathLengths.get(3));
    });
}
 
Example 5
Source File: GremlinEnabledScriptEngineTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldEvalBytecode() throws Exception {
    final GremlinScriptEngine scriptEngine = manager.getEngineByName(ENGINE_TO_TEST);
    final Graph graph = EmptyGraph.instance();
    final GraphTraversalSource g = graph.traversal();

    // purposefully use "x" to match the name of the traversal source binding for "x" below and
    // thus tests the alias added for "x"
    final GraphTraversal t = getTraversalWithLambda(g);

    final Bindings bindings = new SimpleBindings();
    bindings.put("x", g);

    final Traversal evald = scriptEngine.eval(t.asAdmin().getBytecode(), bindings, "x");

    assertTraversals(t, evald);

    assertThat(manager.getBindings().containsKey(GremlinScriptEngine.HIDDEN_G), is(false));
}
 
Example 6
Source File: GremlinEnabledScriptEngineTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void shouldNotAllowBytecodeEvalWithAliasAsTraversalSource() throws Exception {
    final GremlinScriptEngine scriptEngine = manager.getEngineByName(ENGINE_TO_TEST);
    final Graph graph = EmptyGraph.instance();
    final GraphTraversalSource g = graph.traversal();

    // purposefully use "x" to match the name of the traversal source binding for "x" below and
    // thus tests the alias added for "x"
    final GraphTraversal t = getTraversalWithLambda(g);

    final Bindings bindings = new SimpleBindings();
    bindings.put("x", g);

    scriptEngine.eval(t.asAdmin().getBytecode(), bindings, GremlinScriptEngine.HIDDEN_G);
}
 
Example 7
Source File: CredentialTraversalDslTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotRemoveUser() {
    final Graph graph = TinkerGraph.open();
    final CredentialTraversalSource g = graph.traversal(CredentialTraversalSource.class);
    assertThat(graph.vertices().hasNext(), is(false));
    g.user("stephen", "secret").iterate();
    assertThat(graph.vertices().hasNext(), is(true));

    g.users("stephanie").drop().iterate();
    assertThat(graph.vertices().hasNext(), is(true));
}
 
Example 8
Source File: GremlinGroovyScriptEngineSandboxedStandardTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldEvalGraphTraversalSource() throws Exception {
    final Graph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal();
    GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine();
    Bindings bindings = engine.createBindings();
    bindings.put("g", g);
    bindings.put("marko", convertToVertexId(graph, "marko"));
    assertEquals(g.V(convertToVertexId(graph, "marko")).next(), engine.eval("g.V(marko).next()", bindings));

    engine = new GremlinGroovyScriptEngine(notSandboxed);
    try {
        bindings = engine.createBindings();
        bindings.put("g", g);
        bindings.put("marko", convertToVertexId(graph, "marko"));
        engine.eval("g.V(marko).next()", bindings);
        fail("Type checking should have forced an error as 'g' is not defined");
    } catch (Exception ex) {
        assertEquals(MultipleCompilationErrorsException.class, ex.getCause().getClass());
        assertThat(ex.getMessage(), containsString("The variable [g] is undeclared."));
    }

    engine = new GremlinGroovyScriptEngine(sandboxed);
    bindings = engine.createBindings();
    bindings.put("g", g);
    bindings.put("marko", convertToVertexId(graph, "marko"));
    assertEquals(g.V(convertToVertexId(graph, "marko")).next(), engine.eval("g.V(marko).next()", bindings));
    assertEquals(g.V(convertToVertexId(graph, "marko")).out("created").count().next(), engine.eval("g.V(marko).out(\"created\").count().next()", bindings));
}
 
Example 9
Source File: CassandraInputFormatIT.java    From titan1withtp3.1 with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadGraphOfTheGods() {
    GraphOfTheGodsFactory.load(graph, null, true);
    assertEquals(12L, (long) graph.traversal().V().count().next());
    Graph g = GraphFactory.open("target/test-classes/cassandra-read.properties");
    GraphTraversalSource t = g.traversal(GraphTraversalSource.computer(SparkGraphComputer.class));
    assertEquals(12L, (long) t.V().count().next());
}
 
Example 10
Source File: GremlinGroovyScriptEngineOverGraphTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldLoadImports() throws Exception {
    final Graph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal();
    final ScriptEngine engineWithImports = new GremlinGroovyScriptEngine();
    engineWithImports.put("g", g);
    assertEquals(Vertex.class.getName(), engineWithImports.eval("Vertex.class.getName()"));
    assertEquals(2l, engineWithImports.eval("g.V().has('age',gt(30)).count().next()"));
    assertEquals(Direction.IN, engineWithImports.eval("Direction.IN"));
    assertEquals(Direction.OUT, engineWithImports.eval("Direction.OUT"));
    assertEquals(Direction.BOTH, engineWithImports.eval("Direction.BOTH"));
}
 
Example 11
Source File: AbstractTinkerGraphGraphSONTranslatorProvider.java    From tinkergraph-gremlin with Apache License 2.0 5 votes vote down vote up
@Override
public GraphTraversalSource traversal(final Graph graph) {
    if ((Boolean) graph.configuration().getProperty("skipTest"))
        return graph.traversal();
    else {
        final GraphTraversalSource g = graph.traversal();
        return g.withStrategies(new TranslationStrategy(g, new GraphSONTranslator<>(JavaTranslator.of(g), version)));
    }
}
 
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: TinkerGraphPlayTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore
public void testPlay8() throws Exception {
    Graph graph = TinkerFactory.createModern();
    GraphTraversalSource g = graph.traversal();
    System.out.println(g.withSack(1).inject(1).repeat(sack((BiFunction)sum).by(constant(1))).times(10).emit().math("sin _").by(sack()).toList());
}
 
Example 14
Source File: TinkerpopTest.java    From sqlg with MIT License 5 votes vote down vote up
public void g_V_chooseXlabel_eq_person__unionX__out_lang__out_nameX__in_labelX() throws IOException {
    Graph graph = this.sqlgGraph;
    final GraphReader reader = GryoReader.build()
            .mapper(graph.io(GryoIo.build()).mapper().create())
            .create();
    try (final InputStream stream = AbstractGremlinTest.class.getResourceAsStream("/tinkerpop-modern.kryo")) {
        reader.readGraph(stream, graph);
    }
    assertModernGraph(graph, true, false);
    GraphTraversalSource g = graph.traversal();
    List<Vertex> traversala2 =  g.V().hasId(convertToVertexId("marko")).toList();
    Assert.assertEquals(1, traversala2.size());
    Assert.assertEquals(convertToVertex(graph, "marko"), traversala2.get(0));

}
 
Example 15
Source File: GremlinGroovyScriptEngineOverGraphTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldAllowFunctionsUsedInClosure() throws ScriptException {
    final Graph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal();
    final GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine();

    final Bindings bindings = engine.createBindings();
    bindings.put("g", g);
    bindings.put("#jsr223.groovy.engine.keep.globals", "phantom");
    bindings.put("vadas", convertToVertexId(graph, "vadas"));

    // this works on its own when the function and the line that uses it is in one "script".  this is the
    // current workaround
    assertEquals(g.V(convertToVertexId(graph, "vadas")).next(), engine.eval("def isVadas(v){v.value('name')=='vadas'};g.V().filter{isVadas(it.get())}.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("isVadas(g.V(vadas).next())", bindings);

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

    // now...define the function separately on its own in one script
    bindings.remove("#jsr223.groovy.engine.keep.globals");
    engine.eval("def isVadas(v){v.value('name')=='vadas'}", bindings);

    // make sure the function works on its own...no problem
    assertEquals(true, engine.eval("isVadas(g.V(vadas).next())", bindings));

    // make sure the function works in a closure...this generates a StackOverflowError
    assertEquals(g.V(convertToVertexId(graph, "vadas")).next(), engine.eval("g.V().filter{isVadas(it.get())}.next()", bindings));
}
 
Example 16
Source File: GremlinGroovyScriptEngineIntegrateTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotBlowTheHeapParameterized() throws ScriptException {
    final Graph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal();
    final GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine();

    final String[] gremlins = new String[]{
            "g.V(xxx).out().toList()",
            "g.V(xxx).in().toList()",
            "g.V(xxx).out().out().out().toList()",
            "g.V(xxx).out().groupCount()"
    };

    long parameterizedStartTime = System.currentTimeMillis();
    logger.info("Try to blow the heap with parameterized Gremlin.");
    try {
        for (int ix = 0; ix < 50001; ix++) {
            final Bindings bindings = engine.createBindings();
            bindings.put("g", g);
            bindings.put("xxx", (ix % 4) + 1);
            engine.eval(gremlins[ix % 4], bindings);

            if (ix > 0 && ix % 5000 == 0) {
                logger.info(String.format("%s scripts processed in %s (ms) - rate %s (ms/q).", ix, System.currentTimeMillis() - parameterizedStartTime, Double.valueOf(System.currentTimeMillis() - parameterizedStartTime) / Double.valueOf(ix)));
            }
        }
    } catch (OutOfMemoryError oome) {
        fail("Blew the heap - the cache should prevent this from happening.");
    }
}
 
Example 17
Source File: GremlinGroovyScriptEngineTinkerPopSandboxTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldEvalOnGAsTheMethodIsWhiteListed() throws Exception {
    final Graph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal();
    final CompileStaticGroovyCustomizer standardSandbox = new CompileStaticGroovyCustomizer(TinkerPopSandboxExtension.class.getName());
    final GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine(standardSandbox);

    final Bindings bindings = engine.createBindings();
    bindings.put("g", g);
    bindings.put("marko", convertToVertexId(graph, "marko"));
    assertEquals(g.V(convertToVertexId(graph, "marko")).next(), engine.eval("g.V(marko).next()", bindings));
    assertEquals(g.V(convertToVertexId(graph, "marko")).out("created").count().next(), engine.eval("g.V(marko).out(\"created\").count().next()", bindings));
}
 
Example 18
Source File: CommunityGeneratorTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.SIMPLE)
@FeatureRequirement(featureClass = Graph.Features.VertexPropertyFeatures.class, feature = Graph.Features.VertexPropertyFeatures.FEATURE_INTEGER_VALUES)
public void shouldGenerateSameGraph() throws Exception {
    final Configuration configuration = graphProvider.newGraphConfiguration("g1", this.getClass(), name.getMethodName(), null);
    final Graph graph1 = graphProvider.openTestGraph(configuration);

    try {
        communityGeneratorTest(graph, () -> 123456789l);

        afterLoadGraphWith(graph1);
        communityGeneratorTest(graph1, () -> 123456789l);

        final GraphTraversalSource g = graph.traversal();
        final GraphTraversalSource g1 = graph1.traversal();

        assertTrue(g.E().count().next() > 0);
        assertTrue(g.V().count().next() > 0);
        assertTrue(g1.E().count().next() > 0);
        assertTrue(g1.V().count().next() > 0);
        assertEquals(g.E().count().next(), g.E().count().next());

        // ensure that every vertex has the same number of edges between graphs.
        assertTrue(same(graph, graph1));
    } catch (Exception ex) {
        throw ex;
    } finally {
        graphProvider.clear(graph1, configuration);
    }

    assertFalse(failures.get() >= ultimateFailureThreshold);
}
 
Example 19
Source File: DatabaseMigrator.java    From timbuctoo with GNU General Public License v3.0 4 votes vote down vote up
public void execute() {
  Graph graph = graphWrapper.getGraph();
  if (graph.tx().isOpen()) {
    LOG.error("Transaction wasn't closed before calling migrator");
  }
  boolean verticesAvailable;
  List<String> executedMigrations;
  try (Transaction transaction = graph.tx()) {
    transaction.open();
    GraphTraversalSource traversalSource = graph.traversal();
    executedMigrations = traversalSource.V()
      .has("type", EXECUTED_MIGRATIONS_TYPE)
      .map(vertexTraverser -> (String) vertexTraverser.get()
        .property("name")
        .value())
      .toList();

    verticesAvailable = traversalSource.V().hasNext();
  }
  migrations.forEach((name, migration) -> {
    try (Transaction transaction = graph.tx()) {
      transaction.open();
      if (!verticesAvailable) {
        LOG.info("Skipping migration with name '{}' because this is a clean database. ", name);
        this.saveExecution(graph, name);
        transaction.commit();
      } else if (!executedMigrations.contains(name)) {
        LOG.info("Executing migration with name '{}'", name);
        try {
          migration.execute(graphWrapper);
          this.saveExecution(graph, name);
          transaction.commit();
        } catch (IOException e) {
          LOG.error("Could not complete migration with name '{}'", name);
        }
      } else {
        LOG.info("Skipping migration with name '{}', because it has already been executed.", name);
      }
    }
  });
}
 
Example 20
Source File: Util.java    From jaeger-analytics-java with Apache License 2.0 4 votes vote down vote up
public static TraceTraversalSource traceTraversal(Graph graph) {
  return graph.traversal(TraceTraversalSource.class);
}