org.apache.tinkerpop.gremlin.driver.Result Java Examples

The following examples show how to use org.apache.tinkerpop.gremlin.driver.Result. 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 Project: tinkerpop   Author: apache   File: GremlinDriverIntegrateTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldProcessRequestsOutOfOrder() throws Exception {
    final Cluster cluster = TestClientFactory.open();
    final Client client = cluster.connect();

    final ResultSet rsFive = client.submit("Thread.sleep(5000);'five'");
    final ResultSet rsZero = client.submit("'zero'");

    final CompletableFuture<List<Result>> futureFive = rsFive.all();
    final CompletableFuture<List<Result>> futureZero = rsZero.all();

    final long start = System.nanoTime();
    assertFalse(futureFive.isDone());
    assertEquals("zero", futureZero.get().get(0).getString());

    logger.info("Eval of 'zero' complete: " + TimeUtil.millisSince(start));

    assertFalse(futureFive.isDone());
    assertEquals("five", futureFive.get(10, TimeUnit.SECONDS).get(0).getString());

    logger.info("Eval of 'five' complete: " + TimeUtil.millisSince(start));
}
 
Example #2
Source Project: tinkerpop   Author: apache   File: GremlinDriverIntegrateTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldIterate() throws Exception {
    final Cluster cluster = TestClientFactory.open();
    final Client client = cluster.connect();

    final ResultSet results = client.submit("[1,2,3,4,5,6,7,8,9]");
    final Iterator<Result> itty = results.iterator();
    final AtomicInteger counter = new AtomicInteger(0);
    while (itty.hasNext()) {
        counter.incrementAndGet();
        assertEquals(counter.get(), itty.next().getInt());
    }

    assertEquals(9, counter.get());
    assertThat(results.allItemsAvailable(), is(true));

    // can't stream it again
    assertThat(results.iterator().hasNext(), is(false));

    cluster.close();
}
 
Example #3
Source Project: tinkerpop   Author: apache   File: GremlinDriverIntegrateTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSerializeToStringWhenRequestedGryoV1() throws Exception {
    final Map<String, Object> m = new HashMap<>();
    m.put("serializeResultToString", true);
    final GryoMessageSerializerV1d0 serializer = new GryoMessageSerializerV1d0();
    serializer.configure(m, null);

    final Cluster cluster = TestClientFactory.build().serializer(serializer).create();
    final Client client = cluster.connect();

    final ResultSet resultSet = client.submit("TinkerFactory.createClassic()");
    final List<Result> results = resultSet.all().join();
    assertEquals(1, results.size());
    assertEquals("tinkergraph[vertices:6 edges:6]", results.get(0).getString());

    cluster.close();
}
 
Example #4
Source Project: tinkerpop   Author: apache   File: GremlinDriverIntegrateTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSerializeToStringWhenRequestedGryoV3() throws Exception {
    final Map<String, Object> m = new HashMap<>();
    m.put("serializeResultToString", true);
    final GryoMessageSerializerV3d0 serializer = new GryoMessageSerializerV3d0();
    serializer.configure(m, null);

    final Cluster cluster = TestClientFactory.build().serializer(serializer).create();
    final Client client = cluster.connect();

    final ResultSet resultSet = client.submit("TinkerFactory.createClassic()");
    final List<Result> results = resultSet.all().join();
    assertEquals(1, results.size());
    assertEquals("tinkergraph[vertices:6 edges:6]", results.get(0).getString());

    cluster.close();
}
 
Example #5
Source Project: tinkerpop   Author: apache   File: GremlinDriverIntegrateTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldWorkWithGraphSONV2Serialization() throws Exception {
    final Cluster cluster = TestClientFactory.build().serializer(Serializers.GRAPHSON_V2D0).create();
    final Client client = cluster.connect();

    final List<Result> r = client.submit("TinkerFactory.createModern().traversal().V(1)").all().join();
    assertEquals(1, r.size());

    final Vertex v = r.get(0).get(DetachedVertex.class);
    assertEquals(1, v.id());
    assertEquals("person", v.label());

    assertEquals(2, IteratorUtils.count(v.properties()));
    assertEquals("marko", v.value("name"));
    assertEquals(29, Integer.parseInt(v.value("age").toString()));

    cluster.close();
}
 
Example #6
Source Project: tinkerpop   Author: apache   File: GremlinDriverIntegrateTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldWorkWithGraphSONV3Serialization() throws Exception {
    final Cluster cluster = TestClientFactory.build().serializer(Serializers.GRAPHSON_V3D0).create();
    final Client client = cluster.connect();

    final List<Result> r = client.submit("TinkerFactory.createModern().traversal().V(1)").all().join();
    assertEquals(1, r.size());

    final Vertex v = r.get(0).get(DetachedVertex.class);
    assertEquals(1, v.id());
    assertEquals("person", v.label());

    assertEquals(2, IteratorUtils.count(v.properties()));
    assertEquals("marko", v.value("name"));
    assertEquals(29, Integer.parseInt(v.value("age").toString()));

    cluster.close();
}
 
Example #7
@Override
@SuppressWarnings("unchecked")
public GraphMetadata metadata() {
    Client gremlinClient = cluster.connect();
    try {
        List<Result> labels = gremlinClient.submit("g.V().label().groupCount()").all().get();
        Map<String, Number> labelResult = labels.stream()
                .map(r -> r.get(Map.class))
                .map(r -> (Map<String, Number>) r)
                .flatMap(m -> m.entrySet().stream())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

        List<Result> rels = gremlinClient.submit("g.E().label().groupCount()").all().get();
        Map<String, Number> relResult = rels.stream()
                .map(r -> r.get(Map.class))
                .map(r -> (Map<String, Number>) r)
                .flatMap(m -> m.entrySet().stream())
                .collect((Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));

        List<Result> vertexProp = gremlinClient.submit("g.V().properties().key().dedup()").all().get();

        List<String> vertexPropResult = vertexProp.stream()
                .map(Result::getString)
                .collect(toList());

        List<Result> edgeProp = gremlinClient.submit("g.E().properties().key().dedup()").all().get();

        List<String> edgePropResult = edgeProp.stream()
                .map(Result::getString)
                .collect(toList());

        return new OpenCypherGremlinGraphMetadata(labelResult, relResult, vertexPropResult, edgePropResult);
    } catch (InterruptedException | ExecutionException e) {
        String exceptionMessage = wrapExceptionInMeaningMessage(e);
        throw new OpenCypherGremlinException(exceptionMessage, e);
    } finally {
        gremlinClient.close();
    }
}
 
Example #8
Source Project: tinkerpop   Author: apache   File: DriverRemoteAcceptor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object submit(final List<String> args) throws RemoteException {
    final String line = getScript(String.join(" ", args), this.shellEnvironment);

    try {
        final List<Result> resultSet = send(line);
        this.shellEnvironment.setVariable(RESULT, resultSet);
        return resultSet.stream().map(result -> result.getObject()).iterator();
    } catch (SaslException sasl) {
        throw new RemoteException("Security error - check username/password and related settings", sasl);
    } catch (Exception ex) {
        final Optional<ResponseException> inner = findResponseException(ex);
        if (inner.isPresent()) {
            final ResponseException responseException = inner.get();
            if (responseException.getResponseStatusCode() == ResponseStatusCode.SERVER_ERROR_TIMEOUT) {
                throw new RemoteException(String.format("%s - try increasing the timeout with the :remote command", responseException.getMessage()));
            } else if (responseException.getResponseStatusCode() == ResponseStatusCode.SERVER_ERROR_SERIALIZATION)
                throw new RemoteException(String.format(
                        "Server could not serialize the result requested. Server error - %s. Note that the class must be serializable by the client and server for proper operation.", responseException.getMessage()),
                        responseException.getRemoteStackTrace().orElse(null));
            else
                throw new RemoteException(responseException.getMessage(), responseException.getRemoteStackTrace().orElse(null));
        } else if (ex.getCause() != null) {
            final Throwable rootCause = ExceptionUtils.getRootCause(ex);
            if (rootCause instanceof TimeoutException)
                throw new RemoteException("Host did not respond in a timely fashion - check the server status and submit again.");
            else
                throw new RemoteException(rootCause.getMessage());
        } else {
            throw new RemoteException(ex.getMessage());
        }
    }
}
 
Example #9
Source Project: tinkerpop   Author: apache   File: DriverRemoteAcceptor.java    License: Apache License 2.0 5 votes vote down vote up
private List<Result> send(final String gremlin) throws SaslException {
    try {
        final RequestOptions.Builder options = RequestOptions.build();
        aliases.forEach(options::addAlias);
        if (timeout > NO_TIMEOUT)
            options.timeout(timeout);

        options.userAgent(USER_AGENT);

        final ResultSet rs = this.currentClient.submit(gremlin, options.create());
        final List<Result> results = rs.all().get();
        final Map<String, Object> statusAttributes = rs.statusAttributes().getNow(null);

        // Check for and print warnings
        if (null != statusAttributes && statusAttributes.containsKey(Tokens.STATUS_ATTRIBUTE_WARNINGS)) {
            final Object warningAttributeObject = statusAttributes.get(Tokens.STATUS_ATTRIBUTE_WARNINGS);
            if (warningAttributeObject instanceof List) {
                for (Object warningListItem : (List<?>)warningAttributeObject)
                    shellEnvironment.errPrintln(String.valueOf(warningListItem));
            } else {
                shellEnvironment.errPrintln(String.valueOf(warningAttributeObject));
            }
        }

        return results;
    } catch (Exception e) {
        // handle security error as-is and unwrapped
        final Optional<Throwable> throwable  = Stream.of(ExceptionUtils.getThrowables(e)).filter(t -> t instanceof SaslException).findFirst();
        if (throwable.isPresent())
            throw (SaslException) throwable.get();

        throw new IllegalStateException(e.getMessage(), e);
    }
}
 
Example #10
Source Project: tinkerpop   Author: apache   File: DriverRemoteAcceptorIntegrateTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldConnectAndSubmitSession() throws Exception {
    assertThat(acceptor.connect(Arrays.asList(Storage.toPath(TestHelper.generateTempFileFromResource(this.getClass(), "remote.yaml", ".tmp")), "session")).toString(), startsWith("Configured "));
    assertEquals("1", ((Iterator) acceptor.submit(Collections.singletonList("x = 1"))).next());
    assertEquals("0", ((Iterator) acceptor.submit(Collections.singletonList("x - 1"))).next());
    assertEquals("0", ((List<Result>) groovysh.getInterp().getContext().getProperty(DriverRemoteAcceptor.RESULT)).iterator().next().getString());
}
 
Example #11
Source Project: tinkerpop   Author: apache   File: DriverRemoteAcceptorIntegrateTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldConnectAndSubmitManagedSession() throws Exception {
    assertThat(acceptor.connect(Arrays.asList(Storage.toPath(TestHelper.generateTempFileFromResource(this.getClass(), "remote.yaml", ".tmp")), "session-managed")).toString(), startsWith("Configured "));
    assertEquals("1", ((Iterator) acceptor.submit(Collections.singletonList("x = 1"))).next());
    assertEquals("0", ((Iterator) acceptor.submit(Collections.singletonList("x - 1"))).next());
    assertEquals("0", ((List<Result>) groovysh.getInterp().getContext().getProperty(DriverRemoteAcceptor.RESULT)).iterator().next().getString());
}
 
Example #12
Source Project: tinkerpop   Author: apache   File: DriverRemoteAcceptorIntegrateTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldConnectAndReturnVerticesWithAnAlias() throws Exception {
    assertThat(acceptor.connect(Collections.singletonList(Storage.toPath(TestHelper.generateTempFileFromResource(this.getClass(), "remote.yaml", ".tmp")))).toString(), startsWith("Configured "));
    acceptor.configure(Arrays.asList("alias", "x", "g"));
    assertThat(IteratorUtils.list(((Iterator<String>) acceptor.submit(Collections.singletonList("x.addVertex('name','stephen');x.addVertex('name','marko');x.traversal().V()")))), hasSize(2));
    assertThat(((List<Result>) groovysh.getInterp().getContext().getProperty(DriverRemoteAcceptor.RESULT)).stream().map(Result::getString).collect(Collectors.toList()), hasSize(2));
}
 
Example #13
Source Project: tinkerpop   Author: apache   File: DriverRemoteAcceptorIntegrateTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldConnectAndSubmitInSession() throws Exception {
    assertThat(acceptor.connect(Arrays.asList(Storage.toPath(TestHelper.generateTempFileFromResource(this.getClass(), "remote.yaml", ".tmp")), "session")).toString(), startsWith("Configured "));
    assertEquals("2", ((Iterator) acceptor.submit(Collections.singletonList("x=1+1"))).next());
    assertEquals("2", ((List<Result>) groovysh.getInterp().getContext().getProperty(DriverRemoteAcceptor.RESULT)).iterator().next().getString());
    assertEquals("4", ((Iterator) acceptor.submit(Collections.singletonList("x+2"))).next());
    assertEquals("4", ((List<Result>) groovysh.getInterp().getContext().getProperty(DriverRemoteAcceptor.RESULT)).iterator().next().getString());
}
 
Example #14
Source Project: tinkerpop   Author: apache   File: DriverRemoteAcceptorIntegrateTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldConnectAndSubmitInNamedSession() throws Exception {
    assertThat(acceptor.connect(Arrays.asList(Storage.toPath(TestHelper.generateTempFileFromResource(this.getClass(), "remote.yaml", ".tmp")), "session", "AAA")).toString(), startsWith("Configured "));
    assertEquals("2", ((Iterator) acceptor.submit(Collections.singletonList("x=1+1"))).next());
    assertEquals("2", ((List<Result>) groovysh.getInterp().getContext().getProperty(DriverRemoteAcceptor.RESULT)).iterator().next().getString());
    assertEquals("4", ((Iterator) acceptor.submit(Collections.singletonList("x+2"))).next());
    assertEquals("4", ((List<Result>) groovysh.getInterp().getContext().getProperty(DriverRemoteAcceptor.RESULT)).iterator().next().getString());
}
 
Example #15
Source Project: tinkerpop   Author: apache   File: GremlinDriverIntegrateTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldProcessSessionRequestsInOrder() throws Exception {
    final Cluster cluster = TestClientFactory.open();
    final Client client = cluster.connect(name.getMethodName());

    final ResultSet rsFive = client.submit("Thread.sleep(5000);'five'");
    final ResultSet rsZero = client.submit("'zero'");

    final CompletableFuture<List<Result>> futureFive = rsFive.all();
    final CompletableFuture<List<Result>> futureZero = rsZero.all();

    final CountDownLatch latch = new CountDownLatch(2);
    final List<String> order = new ArrayList<>();
    final ExecutorService executor = Executors.newSingleThreadExecutor();

    futureFive.thenAcceptAsync(r -> {
        order.add(r.get(0).getString());
        latch.countDown();
    }, executor);

    futureZero.thenAcceptAsync(r -> {
        order.add(r.get(0).getString());
        latch.countDown();
    }, executor);

    // wait for both results
    latch.await(30000, TimeUnit.MILLISECONDS);

    // should be two results
    assertEquals(2, order.size());

    // ensure that "five" is first then "zero"
    assertThat(order, contains("five", "zero"));
}
 
Example #16
Source Project: tinkerpop   Author: apache   File: GremlinDriverIntegrateTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldGetSomeThenSomeMore() throws Exception {
    final Cluster cluster = TestClientFactory.open();
    final Client client = cluster.connect();

    final ResultSet results = client.submit("[1,2,3,4,5,6,7,8,9]");
    final CompletableFuture<List<Result>> batch1 = results.some(5);
    final CompletableFuture<List<Result>> batch2 = results.some(5);
    final CompletableFuture<List<Result>> batchNothingLeft = results.some(5);

    assertEquals(5, batch1.get().size());
    assertEquals(1, batch1.get().get(0).getInt());
    assertEquals(2, batch1.get().get(1).getInt());
    assertEquals(3, batch1.get().get(2).getInt());
    assertEquals(4, batch1.get().get(3).getInt());
    assertEquals(5, batch1.get().get(4).getInt());

    assertEquals(4, batch2.get().size());
    assertEquals(6, batch2.get().get(0).getInt());
    assertEquals(7, batch2.get().get(1).getInt());
    assertEquals(8, batch2.get().get(2).getInt());
    assertEquals(9, batch2.get().get(3).getInt());

    assertEquals(0, batchNothingLeft.get().size());

    cluster.close();
}
 
Example #17
Source Project: tinkerpop   Author: apache   File: GremlinDriverIntegrateTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldGetOneThenSomeThenSomeMore() throws Exception {
    final Cluster cluster = TestClientFactory.open();
    final Client client = cluster.connect();

    final ResultSet results = client.submit("[1,2,3,4,5,6,7,8,9]");
    final Result one = results.one();
    final CompletableFuture<List<Result>> batch1 = results.some(4);
    final CompletableFuture<List<Result>> batch2 = results.some(5);
    final CompletableFuture<List<Result>> batchNothingLeft = results.some(5);

    assertEquals(1, one.getInt());

    assertEquals(4, batch1.get().size());
    assertEquals(2, batch1.get().get(0).getInt());
    assertEquals(3, batch1.get().get(1).getInt());
    assertEquals(4, batch1.get().get(2).getInt());
    assertEquals(5, batch1.get().get(3).getInt());

    assertEquals(4, batch2.get().size());
    assertEquals(6, batch2.get().get(0).getInt());
    assertEquals(7, batch2.get().get(1).getInt());
    assertEquals(8, batch2.get().get(2).getInt());
    assertEquals(9, batch2.get().get(3).getInt());

    assertEquals(0, batchNothingLeft.get().size());

    cluster.close();
}
 
Example #18
Source Project: tinkerpop   Author: apache   File: GremlinDriverIntegrateTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSerializeToStringWhenRequestedGraphBinaryV1() throws Exception {
    final Map<String, Object> m = new HashMap<>();
    m.put("serializeResultToString", true);
    final GraphBinaryMessageSerializerV1 serializer = new GraphBinaryMessageSerializerV1();
    serializer.configure(m, null);

    final Cluster cluster = TestClientFactory.build().serializer(serializer).create();
    final Client client = cluster.connect();

    final ResultSet resultSet = client.submit("TinkerFactory.createClassic()");
    final List<Result> results = resultSet.all().join();
    assertEquals(1, results.size());
    assertEquals("tinkergraph[vertices:6 edges:6]", results.get(0).getString());

    cluster.close();
}
 
Example #19
Source Project: tinkerpop   Author: apache   File: GremlinDriverIntegrateTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDeserializeWithCustomClassesV1() throws Exception {
    final Map<String, Object> m = new HashMap<>();
    m.put("custom", Collections.singletonList(String.format("%s;%s", JsonBuilder.class.getCanonicalName(), JsonBuilderGryoSerializer.class.getCanonicalName())));
    final GryoMessageSerializerV1d0 serializer = new GryoMessageSerializerV1d0();
    serializer.configure(m, null);

    final Cluster cluster = TestClientFactory.build().serializer(serializer).create();
    final Client client = cluster.connect();

    final List<Result> json = client.submit("b = new groovy.json.JsonBuilder();b.people{person {fname 'stephen'\nlname 'mallette'}};b").all().join();
    assertEquals("{\"people\":{\"person\":{\"fname\":\"stephen\",\"lname\":\"mallette\"}}}", json.get(0).getString());
    cluster.close();
}
 
Example #20
Source Project: tinkerpop   Author: apache   File: GremlinDriverIntegrateTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDeserializeWithCustomClassesV3() throws Exception {
    final Map<String, Object> m = new HashMap<>();
    m.put("custom", Collections.singletonList(String.format("%s;%s", JsonBuilder.class.getCanonicalName(), JsonBuilderGryoSerializer.class.getCanonicalName())));
    final GryoMessageSerializerV3d0 serializer = new GryoMessageSerializerV3d0();
    serializer.configure(m, null);

    final Cluster cluster = TestClientFactory.build().serializer(serializer).create();
    final Client client = cluster.connect();

    final List<Result> json = client.submit("b = new groovy.json.JsonBuilder();b.people{person {fname 'stephen'\nlname 'mallette'}};b").all().join();
    assertEquals("{\"people\":{\"person\":{\"fname\":\"stephen\",\"lname\":\"mallette\"}}}", json.get(0).getString());
    cluster.close();
}
 
Example #21
Source Project: tinkerpop   Author: apache   File: GremlinDriverIntegrateTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldWorkWithGraphSONV1Serialization() throws Exception {
    final Cluster cluster = TestClientFactory.build().serializer(Serializers.GRAPHSON_V1D0).create();
    final Client client = cluster.connect();

    final List<Result> r = client.submit("TinkerFactory.createModern().traversal().V(1)").all().join();
    assertEquals(1, r.size());

    final Map<String,Object> m = r.get(0).get(Map.class);
    assertEquals(4, m.size());
    assertEquals(1, m.get("id"));
    assertEquals("person", m.get("label"));
    assertEquals("vertex", m.get("type"));

    final Map<String,Object> properties = (Map<String,Object>) m.get("properties");
    assertEquals(2, properties.size());

    final List<Object> names = (List<Object>) properties.get("name");
    assertEquals(1, names.size());

    final Map<String,Object> nameProperties = (Map<String,Object>) names.get(0);
    assertEquals(2, nameProperties.size());
    assertEquals(0l, nameProperties.get("id"));
    assertEquals("marko", nameProperties.get("value"));

    final List<Object> ages = (List<Object>) properties.get("age");
    assertEquals(1, ages.size());

    final Map<String,Object> ageProperties = (Map<String,Object>) ages.get(0);
    assertEquals(2, ageProperties.size());
    assertEquals(1l, ageProperties.get("id"));
    assertEquals(29, ageProperties.get("value"));

    cluster.close();
}
 
Example #22
Source Project: tinkerpop   Author: apache   File: GremlinDriverIntegrateTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldWorkWithGraphSONExtendedV2Serialization() throws Exception {
    final Cluster cluster = TestClientFactory.build().serializer(Serializers.GRAPHSON_V2D0).create();
    final Client client = cluster.connect();

    final Instant now = Instant.now();
    final List<Result> r = client.submit("java.time.Instant.ofEpochMilli(" + now.toEpochMilli() + ")").all().join();
    assertEquals(1, r.size());

    final Instant then = r.get(0).get(Instant.class);
    assertEquals(now, then);

    cluster.close();
}
 
Example #23
Source Project: tinkerpop   Author: apache   File: GremlinDriverIntegrateTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldWorkWithGraphSONExtendedV3Serialization() throws Exception {
    final Cluster cluster = TestClientFactory.build().serializer(Serializers.GRAPHSON_V3D0).create();
    final Client client = cluster.connect();

    final Instant now = Instant.now();
    final List<Result> r = client.submit("java.time.Instant.ofEpochMilli(" + now.toEpochMilli() + ")").all().join();
    assertEquals(1, r.size());

    final Instant then = r.get(0).get(Instant.class);
    assertEquals(now, then);

    cluster.close();
}
 
Example #24
Source Project: tinkerpop   Author: apache   File: GremlinDriverIntegrateTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldWorkWithGraphBinaryV1Serialization() throws Exception {
    final Cluster cluster = TestClientFactory.build().serializer(Serializers.GRAPHBINARY_V1D0).create();
    final Client client = cluster.connect();

    final List<Result> r = client.submit("TinkerFactory.createModern().traversal().V(1)").all().join();
    assertEquals(1, r.size());

    final Vertex v = r.get(0).get(ReferenceVertex.class);
    assertEquals(1, v.id());
    assertEquals("person", v.label());

    cluster.close();
}
 
Example #25
Source Project: tinkerpop   Author: apache   File: GremlinDriverIntegrateTest.java    License: Apache License 2.0 5 votes vote down vote up
private void assertFutureTimeout(final CompletableFuture<List<Result>> futureFirst) {
    try
    {
        futureFirst.get();
        fail("Should have timed out");
    }
    catch (Exception ex)
    {
        final Throwable root = ExceptionUtils.getRootCause(ex);
        assertThat(root, instanceOf(ResponseException.class));
        assertThat(root.getMessage(), startsWith("Evaluation exceeded the configured 'evaluationTimeout' threshold of 250 ms"));
    }
}
 
Example #26
Source Project: tinkerpop   Author: apache   File: GremlinResultSetIntegrateTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandleVertexResultFromTraversalBulked() throws Exception {
    final Graph graph = TinkerGraph.open();
    final GraphTraversalSource g = graph.traversal();
    final Client aliased = client.alias("gmodern");
    final ResultSet resultSetUnrolled = aliased.submit(g.V().both().barrier().both().barrier());
    final List<Result> results = resultSetUnrolled.all().get();

    assertThat(results.get(0).getObject(), CoreMatchers.instanceOf(Traverser.class));
    assertEquals(6, results.size());
}
 
Example #27
Source Project: tinkerpop   Author: apache   File: GremlinResultSetIntegrateTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandleMapIteratedResult() throws Exception {
    final ResultSet results = client.submit("gmodern.V().groupCount().by(bothE().count())");
    final List<Result> resultList = results.all().get();
    final Map m = resultList.get(0).get(HashMap.class);
    assertEquals(2, m.size());
    assertEquals(3L, m.get(1L));
    assertEquals(3L, m.get(3L));
}
 
Example #28
Source Project: nifi   Author: apache   File: GremlinClientService.java    License: Apache License 2.0 5 votes vote down vote up
public Map<String, String> doQuery(String query, Map<String, Object> parameters, GraphQueryResultCallback handler) {
    try {
        Iterator<Result> iterator = client.submit(query, parameters).iterator();
        long count = 0;
        while (iterator.hasNext()) {
            Result result = iterator.next();
            Object obj = result.getObject();
            if (obj instanceof Map) {
                handler.process((Map)obj, iterator.hasNext());
            } else {
                handler.process(new HashMap<String, Object>(){{
                    put("result", obj);
                }}, iterator.hasNext());
            }
            count++;
        }

        Map<String, String> resultAttributes = new HashMap<>();
        resultAttributes.put(NODES_CREATED, NOT_SUPPORTED);
        resultAttributes.put(RELATIONS_CREATED, NOT_SUPPORTED);
        resultAttributes.put(LABELS_ADDED, NOT_SUPPORTED);
        resultAttributes.put(NODES_DELETED, NOT_SUPPORTED);
        resultAttributes.put(RELATIONS_DELETED, NOT_SUPPORTED);
        resultAttributes.put(PROPERTIES_SET, NOT_SUPPORTED);
        resultAttributes.put(ROWS_RETURNED, String.valueOf(count));

        return resultAttributes;

    } catch (Exception ex) {
        throw new ProcessException(ex);
    }
}
 
Example #29
Source Project: tinkerpop   Author: apache   File: DriverRemoteAcceptorIntegrateTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void shouldConnectAndSubmitSimple() throws Exception {
    assertThat(acceptor.connect(Collections.singletonList(Storage.toPath(TestHelper.generateTempFileFromResource(this.getClass(), "remote.yaml", ".tmp")))).toString(), startsWith("Configured "));
    assertEquals("2", ((Iterator) acceptor.submit(Collections.singletonList("1+1"))).next());
    assertEquals("2", ((List<Result>) groovysh.getInterp().getContext().getProperty(DriverRemoteAcceptor.RESULT)).iterator().next().getString());
}
 
Example #30
Source Project: tinkerpop   Author: apache   File: DriverRemoteAcceptorIntegrateTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void shouldConnectAndSubmitSimpleList() throws Exception {
    assertThat(acceptor.connect(Collections.singletonList(Storage.toPath(TestHelper.generateTempFileFromResource(this.getClass(), "remote.yaml", ".tmp")))).toString(), startsWith("Configured "));
    assertThat(IteratorUtils.list(((Iterator<String>) acceptor.submit(Collections.singletonList("[1,2,3,4,5]")))), contains("1", "2", "3", "4", "5"));
    assertThat(((List<Result>) groovysh.getInterp().getContext().getProperty(DriverRemoteAcceptor.RESULT)).stream().map(Result::getString).collect(Collectors.toList()), contains("1", "2", "3", "4", "5"));
}