Java Code Examples for org.apache.tinkerpop.gremlin.structure.Graph

The following examples show how to use org.apache.tinkerpop.gremlin.structure.Graph. These examples are extracted from open source projects. 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   Source File: GremlinEnabledScriptEngineTest.java    License: 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 2
@Override
protected void processGraph(String documentSourceName, Graph graph) {
  WriterBuilder<? extends GraphWriter> writer;
  switch (format) {
    case GRYO:
      writer = graph.io(IoCore.gryo()).writer();
      break;
    case GRAPHSON:
      writer = graph.io(IoCore.graphson()).writer();
      break;
    case GRAPHML:
      // FALL THROUGH
    default:
      writer = graph.io(IoCore.graphml()).writer().normalize(true);
      break;
  }

  try (final OutputStream os = createOutputStream(documentSourceName)) {
    writer.create().writeGraph(os, graph);
  } catch (IOException e) {
    getMonitor().error("Error writing graph", e);
  }
}
 
Example 3
@Test
public void shouldSerializeEdgeProperty() throws Exception {
    final Graph g = TinkerGraph.open();
    final Vertex v1 = g.addVertex();
    final Vertex v2 = g.addVertex();
    final Edge e = v1.addEdge("test", v2);
    e.property("abc", 123);

    final Iterable<Property<Object>> iterable = IteratorUtils.list(e.properties("abc"));
    final String results = SERIALIZER.serializeResponseAsString(ResponseMessage.build(msg).result(iterable).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);
    assertEquals(1, converted.size());

    final JsonNode propertyAsJson = converted.get(0);
    assertNotNull(propertyAsJson);

    assertEquals(123, propertyAsJson.get("value").asInt());
}
 
Example 4
Source Project: tinkerpop   Source File: IoTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES)
public void shouldReadWriteModernWrappedInJsonObject() throws Exception {
    final GraphSONMapper mapper = graph.io(graphson).mapper().version(GraphSONVersion.V1_0).create();
    try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) {
        final GraphWriter writer = graph.io(graphson()).writer().wrapAdjacencyList(true).mapper(mapper).create();
        writer.writeGraph(os, graph);

        final Configuration configuration = graphProvider.newGraphConfiguration("readGraph", this.getClass(), name.getMethodName(), LoadGraphWith.GraphData.MODERN);
        graphProvider.clear(configuration);
        final Graph g1 = graphProvider.openTestGraph(configuration);
        final GraphReader reader = graph.io(graphson()).reader().mapper(mapper).unwrapAdjacencyList(true).create();
        try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) {
            reader.readGraph(bais, g1);
        }

        // modern uses double natively so always assert as such
        IoTest.assertModernGraph(g1, true, true);

        graphProvider.clear(g1, configuration);
    }
}
 
Example 5
Source Project: tinkerpop   Source File: OutputRDDTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldWriteToArbitraryRDD() throws Exception {
    final Configuration configuration = new BaseConfiguration();
    configuration.setProperty("spark.master", "local[4]");
    configuration.setProperty("spark.serializer", GryoSerializer.class.getCanonicalName());
    configuration.setProperty(Graph.GRAPH, HadoopGraph.class.getName());
    configuration.setProperty(Constants.GREMLIN_HADOOP_INPUT_LOCATION, SparkHadoopGraphProvider.PATHS.get("tinkerpop-modern-v3d0.kryo"));
    configuration.setProperty(Constants.GREMLIN_HADOOP_GRAPH_READER, GryoInputFormat.class.getCanonicalName());
    configuration.setProperty(Constants.GREMLIN_HADOOP_GRAPH_WRITER, ExampleOutputRDD.class.getCanonicalName());
    configuration.setProperty(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION, TestHelper.makeTestDataDirectory(this.getClass(), "shouldWriteToArbitraryRDD"));
    configuration.setProperty(Constants.GREMLIN_HADOOP_JARS_IN_DISTRIBUTED_CACHE, false);
    ////////
    Graph graph = GraphFactory.open(configuration);
    graph.compute(SparkGraphComputer.class)
            .result(GraphComputer.ResultGraph.NEW)
            .persist(GraphComputer.Persist.EDGES)
            .program(TraversalVertexProgram.build()
                    .traversal(graph.traversal().withComputer(Computer.compute(SparkGraphComputer.class)),
                            "gremlin-groovy",
                            "g.V()").create(graph)).submit().get();
}
 
Example 6
Source Project: tinkerpop   Source File: EventStrategyProcessTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.VERTICES_ONLY)
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_REMOVE_EDGES)
public void shouldTriggerRemoveEdge() {
    final StubMutationListener listener1 = new StubMutationListener();
    final StubMutationListener listener2 = new StubMutationListener();
    final EventStrategy.Builder builder = EventStrategy.build()
            .addListener(listener1)
            .addListener(listener2);

    if (graph.features().graph().supportsTransactions())
        builder.eventQueue(new EventStrategy.TransactionalEventQueue(graph));

    final EventStrategy eventStrategy = builder.create();

    final Vertex v = graph.addVertex("some", "thing");
    v.addEdge("self", v);
    final GraphTraversalSource gts = create(eventStrategy);
    gts.E().drop().iterate();

    tryCommit(graph);

    assertEquals(1, listener1.edgeRemovedEventRecorded());
    assertEquals(1, listener2.edgeRemovedEventRecorded());
}
 
Example 7
Source Project: tinkerpop   Source File: IoEdgeTest.java    License: Apache License 2.0 6 votes vote down vote up
@Parameterized.Parameters(name = "{0}")
public static Iterable<Object[]> data() {
    return Arrays.asList(new Object[][]{
            {"graphson-v1", false, false,
                    (Function<Graph,GraphReader>) g -> g.io(GraphSONIo.build(GraphSONVersion.V1_0)).reader().create(),
                    (Function<Graph, GraphWriter>) g -> g.io(GraphSONIo.build(GraphSONVersion.V1_0)).writer().create()},
            {"graphson-v1-embedded", true, true,
                    (Function<Graph,GraphReader>) g -> g.io(GraphSONIo.build(GraphSONVersion.V1_0)).reader().mapper(g.io(GraphSONIo.build(GraphSONVersion.V2_0)).mapper().typeInfo(TypeInfo.PARTIAL_TYPES).create()).create(),
                    (Function<Graph, GraphWriter>) g -> g.io(GraphSONIo.build(GraphSONVersion.V1_0)).writer().mapper(g.io(GraphSONIo.build(GraphSONVersion.V2_0)).mapper().typeInfo(TypeInfo.PARTIAL_TYPES).create()).create()},
            {"graphson-v2", false, false,
                    (Function<Graph, GraphReader>) g -> g.io(GraphSONIo.build(GraphSONVersion.V2_0)).reader().mapper(g.io(GraphSONIo.build(GraphSONVersion.V2_0)).mapper().typeInfo(TypeInfo.NO_TYPES).create()).create(),
                    (Function<Graph, GraphWriter>) g -> g.io(GraphSONIo.build(GraphSONVersion.V2_0)).writer().mapper(g.io(GraphSONIo.build(GraphSONVersion.V2_0)).mapper().typeInfo(TypeInfo.NO_TYPES).create()).create()},
            {"graphson-v2-embedded", true, true,
                    (Function<Graph, GraphReader>) g -> g.io(GraphSONIo.build(GraphSONVersion.V2_0)).reader().mapper(g.io(GraphSONIo.build(GraphSONVersion.V2_0)).mapper().typeInfo(TypeInfo.PARTIAL_TYPES).create()).create(),
                    (Function<Graph, GraphWriter>) g -> g.io(GraphSONIo.build(GraphSONVersion.V2_0)).writer().mapper(g.io(GraphSONIo.build(GraphSONVersion.V2_0)).mapper().typeInfo(TypeInfo.PARTIAL_TYPES).create()).create()},
            {"graphson-v3", true, true,
                    (Function<Graph, GraphReader>) g -> g.io(GraphSONIo.build(GraphSONVersion.V3_0)).reader().mapper(g.io(GraphSONIo.build(GraphSONVersion.V3_0)).mapper().create()).create(),
                    (Function<Graph, GraphWriter>) g -> g.io(GraphSONIo.build(GraphSONVersion.V3_0)).writer().mapper(g.io(GraphSONIo.build(GraphSONVersion.V3_0)).mapper().create()).create()},
            {"gryo-v1", true, true,
                    (Function<Graph,GraphReader>) g -> g.io(GryoIo.build(GryoVersion.V1_0)).reader().create(),
                    (Function<Graph, GraphWriter>) g -> g.io(GryoIo.build(GryoVersion.V1_0)).writer().create()},
            {"gryo-v3", true, true,
                    (Function<Graph,GraphReader>) g -> g.io(GryoIo.build(GryoVersion.V3_0)).reader().create(),
                    (Function<Graph, GraphWriter>) g -> g.io(GryoIo.build(GryoVersion.V3_0)).writer().create()}
    });
}
 
Example 8
Source Project: tinkerpop   Source File: AbstractGremlinSuite.java    License: Apache License 2.0 6 votes vote down vote up
static void validateOptInAndOutAnnotations(final Class<?> klass) throws InitializationError {
    // sometimes test names change and since they are String representations they can easily break if a test
    // is renamed. this test will validate such things.  it is not possible to @OptOut of this test.
    final Graph.OptOut[] optOuts = klass.getAnnotationsByType(Graph.OptOut.class);
    for (Graph.OptOut optOut : optOuts) {
        final Class testClass;
        try {
            testClass = Class.forName(optOut.test());
        } catch (Exception ex) {
            throw new InitializationError(String.format("Invalid @OptOut on Graph instance.  Could not instantiate test class (it may have been renamed): %s", optOut.test()));
        }

        if (!optOut.method().equals("*") && !Arrays.stream(testClass.getMethods()).anyMatch(m -> m.getName().equals(optOut.method())))
            throw new InitializationError(String.format("Invalid @OptOut on Graph instance.  Could not match @OptOut test name %s on test class %s (it may have been renamed)", optOut.method(), optOut.test()));
    }
}
 
Example 9
Source Project: tinkerpop   Source File: TinkerGraphProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Object> getBaseConfiguration(final String graphName, final Class<?> test, final String testMethodName,
                                                final LoadGraphWith.GraphData loadGraphWith) {
    final TinkerGraph.DefaultIdManager idManager = selectIdMakerFromGraphData(loadGraphWith);
    final String idMaker = (idManager.equals(TinkerGraph.DefaultIdManager.ANY) ? selectIdMakerFromTest(test, testMethodName) : idManager).name();
    return new HashMap<String, Object>() {{
        put(Graph.GRAPH, TinkerGraph.class.getName());
        put(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_ID_MANAGER, idMaker);
        put(TinkerGraph.GREMLIN_TINKERGRAPH_EDGE_ID_MANAGER, idMaker);
        put(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_PROPERTY_ID_MANAGER, idMaker);
        if (requiresListCardinalityAsDefault(loadGraphWith, test, testMethodName))
            put(TinkerGraph.GREMLIN_TINKERGRAPH_DEFAULT_VERTEX_PROPERTY_CARDINALITY, VertexProperty.Cardinality.list.name());
        if (requiresPersistence(test, testMethodName)) {
            put(TinkerGraph.GREMLIN_TINKERGRAPH_GRAPH_FORMAT, "gryo");
            put(TinkerGraph.GREMLIN_TINKERGRAPH_GRAPH_LOCATION, TestHelper.makeTestDataFile(test, "temp", testMethodName + ".kryo"));
        }
    }};
}
 
Example 10
Source Project: tinkerpop   Source File: TraversalHelper.java    License: Apache License 2.0 6 votes vote down vote up
public static boolean hasLabels(final Traversal.Admin<?, ?> traversal) {
    for (final Step<?, ?> step : traversal.getSteps()) {
        for (final String label : step.getLabels()) {
            if (!Graph.Hidden.isHidden(label))
                return true;
        }
        if (step instanceof TraversalParent) {
            for (final Traversal.Admin<?, ?> local : ((TraversalParent) step).getLocalChildren()) {
                if (TraversalHelper.hasLabels(local))
                    return true;
            }
            for (final Traversal.Admin<?, ?> global : ((TraversalParent) step).getGlobalChildren()) {
                if (TraversalHelper.hasLabels(global))
                    return true;
            }
        }
    }
    return false;
}
 
Example 11
Source Project: hugegraph   Source File: TestGraphProvider.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean customizedId(Class<?> test, String testMethod) {
    Method method;
    try {
        method = test.getDeclaredMethod(testMethod);
    } catch (NoSuchMethodException ignored) {
        return false;
    }
    FeatureRequirements features =
                        method.getAnnotation(FeatureRequirements.class);
    if (features == null) {
        return false;
    }
    for (FeatureRequirement feature : features.value()) {
        if (feature.featureClass() == Graph.Features.VertexFeatures.class &&
            ID_TYPES.contains(feature.feature())) {
            // Expect CUSTOMIZED_ID if want to pass id to create vertex
            return true;
        }
    }
    return false;
}
 
Example 12
Source Project: hgraphdb   Source File: LabelMetadataModel.java    License: Apache License 2.0 6 votes vote down vote up
public LabelMetadata deserialize(Result result) {
    byte[] bytes = result.getRow();
    PositionedByteRange buffer = new SimplePositionedByteRange(bytes);
    String label = OrderedBytes.decodeString(buffer);
    ElementType type = OrderedBytes.decodeInt8(buffer) == 1 ? ElementType.VERTEX : ElementType.EDGE;

    ValueType idType = null;
    Long createdAt = null;
    Long updatedAt = null;
    Map<String, ValueType> props = new HashMap<>();
    for (Cell cell : result.listCells()) {
        String key = Bytes.toString(CellUtil.cloneQualifier(cell));
        if (!Graph.Hidden.isHidden(key)) {
            ValueType propType = ValueType.valueOf(((Byte) ValueUtils.deserialize(CellUtil.cloneValue(cell))).intValue());
            props.put(key, propType);
        } else if (key.equals(Constants.ELEMENT_ID)) {
            idType = ValueType.valueOf(((Byte) ValueUtils.deserialize(CellUtil.cloneValue(cell))).intValue());
        } else if (key.equals(Constants.CREATED_AT)) {
            createdAt = ValueUtils.deserialize(CellUtil.cloneValue(cell));
        } else if (key.equals(Constants.UPDATED_AT)) {
            updatedAt = ValueUtils.deserialize(CellUtil.cloneValue(cell));
        }
    }
    return new LabelMetadata(type, label, idType, createdAt, updatedAt, props);
}
 
Example 13
Source Project: tinkerpop   Source File: AddEdgeTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@LoadGraphWith(MODERN)
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES)
public void g_V_asXaX_outXcreatedX_inXcreatedX_whereXneqXaXX_asXbX_addEXcodeveloperX_fromXaX_toXbX_propertyXyear_2009X() {
    final Traversal<Vertex, Edge> traversal = get_g_V_asXaX_outXcreatedX_inXcreatedX_whereXneqXaXX_asXbX_addEXcodeveloperX_fromXaX_toXbX_propertyXyear_2009X();
    printTraversalForm(traversal);
    int count = 0;
    while (traversal.hasNext()) {
        final Edge edge = traversal.next();
        assertEquals("codeveloper", edge.label());
        assertEquals(2009, g.E(edge).values("year").next());
        assertEquals(1, g.E(edge).properties().count().next().intValue());
        assertEquals("person", g.E(edge).inV().label().next());
        assertEquals("person", g.E(edge).outV().label().next());
        assertFalse(g.E(edge).inV().values("name").next().equals("vadas"));
        assertFalse(g.E(edge).outV().values("name").next().equals("vadas"));
        assertFalse(g.E(edge).inV().next().equals(g.E(edge).outV().next()));
        count++;

    }
    assertEquals(6, count);
    assertEquals(12, IteratorUtils.count(g.E()));
    assertEquals(6, IteratorUtils.count(g.V()));
}
 
Example 14
Source Project: Ferma   Source File: PropertyMethodHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetName() {
    final Graph godGraph = TinkerGraph.open();
    GodGraphLoader.load(godGraph);

    final FramedGraph framedGraph = new DelegatingFramedGraph(godGraph, TEST_TYPES);

    final List<? extends God> gods = framedGraph.traverse(
        input -> input.V().has("name", "jupiter")).toList(God.class);

    final God father = gods.iterator().next();
    Assert.assertTrue(father != null);
    final VertexFrame fatherVertex = father;
    Assert.assertEquals(fatherVertex.getProperty("name"), "jupiter");
    Assert.assertEquals("jupiter", father.getName());
}
 
Example 15
Source Project: tinkerpop   Source File: HadoopIoStep.java    License: Apache License 2.0 6 votes vote down vote up
private void configureForRead(final Graph graph) {
    final String inputFormatClassNameOrKeyword = parameters.get(IO.reader, this::detectReader).get(0);
    String inputFormatClassName;
    if (inputFormatClassNameOrKeyword.equals(IO.graphson))
        inputFormatClassName = GraphSONInputFormat.class.getName();
    else if (inputFormatClassNameOrKeyword.equals(IO.gryo))
        inputFormatClassName = GryoInputFormat.class.getName();
    else if (inputFormatClassNameOrKeyword.equals(IO.graphml))
        throw new IllegalStateException("GraphML is not a supported file format for OLAP");
    else
        inputFormatClassName = inputFormatClassNameOrKeyword;

    graph.configuration().setProperty(Constants.GREMLIN_HADOOP_GRAPH_READER, inputFormatClassName);
    graph.configuration().setProperty(Constants.GREMLIN_HADOOP_INPUT_LOCATION, file);

    addParametersToConfiguration(graph);
}
 
Example 16
Source Project: tinkerpop   Source File: IoGraphTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@LoadGraphWith(LoadGraphWith.GraphData.CREW)
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES)
public void shouldReadWriteCrew() throws Exception {
    assumeThat("GraphML does not support multi/metaproperties", ioType, not("graphml"));
    try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) {

        final GraphWriter writer = graph.io(ioBuilderToTest).writer().create();
        writer.writeGraph(os, graph);

        final Configuration configuration = graphProvider.newGraphConfiguration("readGraph", this.getClass(), name.getMethodName(), LoadGraphWith.GraphData.CREW);
        graphProvider.clear(configuration);
        final Graph g1 = graphProvider.openTestGraph(configuration);

        final GraphReader reader = graph.io(ioBuilderToTest).reader().create();
        try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) {
            reader.readGraph(bais, g1);
        }

        IoTest.assertCrewGraph(g1, lossyForId);

        graphProvider.clear(g1, configuration);
    }
}
 
Example 17
Source Project: tinkerpop   Source File: CoreTraversalTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@LoadGraphWith(MODERN)
@FeatureRequirement(featureClass = Graph.Features.GraphFeatures.class, feature = FEATURE_TRANSACTIONS)
public void shouldTraverseIfManualTxEnabledAndOriginalTxIsClosed() {
    // auto should be the default, so force manual
    g.tx().onReadWrite(Transaction.READ_WRITE_BEHAVIOR.MANUAL);

    // close down the current transaction and fire up a fresh one
    g.tx().open();
    final Traversal t = g.V().has("name", "marko");
    g.tx().rollback();

    // the traversal should still work since there are auto transactions
    g.tx().open();
    assertEquals(1, IteratorUtils.count(t));
    g.tx().rollback();
}
 
Example 18
Source Project: tinkerpop   Source File: ConnectedComponentVertexProgram.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void loadState(final Graph graph, final Configuration config) {
    configuration = new BaseConfiguration();
    if (config != null) {
        ConfigurationUtils.copy(config, configuration);
    }

    if (configuration.containsKey(EDGE_TRAVERSAL)) {
        this.edgeTraversal = PureTraversal.loadState(configuration, EDGE_TRAVERSAL, graph);
        this.scope = MessageScope.Local.of(() -> this.edgeTraversal.get().clone());
    }

    scopes = new HashSet<>(Collections.singletonList(scope));

    this.property = configuration.getString(PROPERTY, COMPONENT);

    this.haltedTraversers = TraversalVertexProgram.loadHaltedTraversers(configuration);
    this.haltedTraversersIndex = new IndexedTraverserSet<>(v -> v);
    for (final Traverser.Admin<Vertex> traverser : this.haltedTraversers) {
        this.haltedTraversersIndex.add(traverser.split());
    }
}
 
Example 19
Source Project: tinkerpop   Source File: GraphSerializer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void writeValue(final Graph value, final Buffer buffer, final GraphBinaryWriter context) throws IOException {
    // this kinda looks scary memory-wise, but GraphBinary is about network derser so we are dealing with a
    // graph instance that should live in memory already - not expecting "big" stuff here.
    final List<Vertex> vertexList = IteratorUtils.list(value.vertices());
    final List<Edge> edgeList = IteratorUtils.list(value.edges());

    context.writeValue(vertexList.size(), buffer, false);

    for (Vertex v : vertexList) {
        writeVertex(buffer, context, v);
    }

    context.writeValue(edgeList.size(), buffer, false);

    for (Edge e : edgeList) {
        writeEdge(buffer, context, e);
    }
}
 
Example 20
@Override
public void apply(Traversal.Admin<?, ?> traversal) {
    if (TraversalHelper.onGraphComputer(traversal)) {
        return;
    }

    TraversalHelper.getStepsOfClass(GraphStep.class, traversal).forEach(originalGraphStep -> {
        if (originalGraphStep.getIds() == null || originalGraphStep.getIds().length == 0) {
            //Try to optimize for index calls
            JanusGraphStep<?, ?> janusGraphStep = new JanusGraphStep<>(originalGraphStep);
            TraversalHelper.replaceStep(originalGraphStep, janusGraphStep, traversal);
            HasStepFolder.foldInIds(janusGraphStep, traversal);
            HasStepFolder.foldInHasContainer(janusGraphStep, traversal, traversal);
            HasStepFolder.foldInOrder(janusGraphStep, janusGraphStep.getNextStep(), traversal, traversal, janusGraphStep.returnsVertex(), null);
            HasStepFolder.foldInRange(janusGraphStep, JanusGraphTraversalUtil.getNextNonIdentityStep(janusGraphStep), traversal, null);
        } else {
            //Make sure that any provided "start" elements are instantiated in the current transaction
            Object[] ids = originalGraphStep.getIds();
            ElementUtils.verifyArgsMustBeEitherIdOrElement(ids);
            if (ids[0] instanceof Element) {
                //GraphStep constructor ensures that the entire array is elements
                final Object[] elementIds = new Object[ids.length];
                for (int i = 0; i < ids.length; i++) {
                    elementIds[i] = ((Element) ids[i]).id();
                }
                originalGraphStep.setIteratorSupplier(() -> originalGraphStep.returnsVertex() ?
                        ((Graph) originalGraphStep.getTraversal().getGraph().get()).vertices(elementIds) :
                        ((Graph) originalGraphStep.getTraversal().getGraph().get()).edges(elementIds));
            }
        }

    });
}
 
Example 21
Source Project: tinkerpop   Source File: AddEdgeTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@LoadGraphWith(MODERN)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_NULL_PROPERTY_VALUES, supported = false)
public void g_V_outE_propertyXweight_nullX() {
    final Traversal<Vertex, Edge> traversal = get_g_V_outE_propertyXweight_nullX();
    printTraversalForm(traversal);
    traversal.forEachRemaining(e -> assertThat(e.properties("weight").hasNext(), is(false)));
}
 
Example 22
Source Project: Ferma   Source File: DelegatingTransactionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    gremlinTx = Mockito.mock(Transaction.class);
    framedGraph = Mockito.mock(WrappedFramedGraph.class, Mockito.RETURNS_MOCKS);
    baseGraph = Mockito.mock(Graph.class, Mockito.RETURNS_MOCKS);

    when(gremlinTx.createThreadedTx()).thenReturn(baseGraph);

    delegatingTx = new DelegatingTransaction(gremlinTx, framedGraph);
}
 
Example 23
@Test
public void shouldSerializeEdge() throws Exception {
    final Graph g = TinkerGraph.open();
    final Vertex v1 = g.addVertex();
    final Vertex v2 = g.addVertex();
    final Edge e = v1.addEdge("test", v2);
    e.property("abc", 123);

    final Iterable<Edge> iterable = IteratorUtils.list(g.edges());
    final String results = SERIALIZER.serializeResponseAsString(ResponseMessage.build(msg).result(iterable).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);
    assertEquals(1, converted.size());

    final JsonNode edgeAsJson = converted.get(0).get(GraphSONTokens.VALUEPROP);
    assertNotNull(edgeAsJson);

    assertEquals(((Long) e.id()).longValue(), edgeAsJson.get(GraphSONTokens.ID).get(GraphSONTokens.VALUEPROP).asLong());
    assertEquals(((Long) v1.id()).longValue(), edgeAsJson.get(GraphSONTokens.OUT).get(GraphSONTokens.VALUEPROP).asLong());
    assertEquals(((Long) v2.id()).longValue(), edgeAsJson.get(GraphSONTokens.IN).get(GraphSONTokens.VALUEPROP).asLong());
    assertEquals(e.label(), edgeAsJson.get(GraphSONTokens.LABEL).asText());

    final JsonNode properties = edgeAsJson.get(GraphSONTokens.PROPERTIES);
    assertNotNull(properties);
    assertEquals(123, properties.get("abc").get(GraphSONTokens.VALUEPROP).get("value").get(GraphSONTokens.VALUEPROP).asInt());
}
 
Example 24
Source Project: jaeger-analytics-java   Source File: UniqueSpanId.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void runWithMetrics(Graph graph) {
  Map<String, List<Span>> result = computeScore(graph);
  for (Map.Entry<String, List<Span>> entry: result.entrySet()) {
    List<Span> spans = entry.getValue();
    boolean uniqueId = spans.size() == 1;
    for (Span span: entry.getValue()) {
      counter.labels(String.valueOf(uniqueId), span.serviceName).inc();
    }
  }
}
 
Example 25
Source Project: tinkerpop   Source File: DropTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@LoadGraphWith(CREW)
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_REMOVE_PROPERTY)
public void g_V_properties_propertiesXstartTimeX_drop() {
    final Traversal<Vertex, ? extends Property<Object>> traversal = get_g_V_properties_propertiesXstartTimeX_drop();
    printTraversalForm(traversal);
    assertFalse(traversal.hasNext());
    g.V().forEachRemaining(vertex -> assertEquals(0, IteratorUtils.count(IteratorUtils.flatMap(vertex.properties("location"), vp -> vp.properties("startTime")))));
}
 
Example 26
Source Project: timbuctoo   Source File: EdgeRetrieverTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Test
public void getPreviousVersionReturnsThePreviousVersion() {
  UUID edgeId = UUID.randomUUID();
  Graph graph = newGraph().withVertex("v1", v -> v.withTimId("id1"))
                          .withVertex("v2",
                            v -> v.withOutgoingRelation("edge", "v1", e -> e.withRev(1).withTim_id(edgeId))
                                  .withOutgoingRelation("edge", "v1", e -> e.withRev(2).withTim_id(edgeId)))
                          .build();
  Edge edge = graph.traversal().E().has("tim_id", edgeId.toString()).has("rev", 2).next();
  EdgeRetriever instance = new EdgeRetriever();

  Edge previousVersion = instance.getPreviousVersion(edge);

  assertThat(previousVersion, is(likeEdge().withId(edgeId.toString()).withProperty("rev", 1)));
}
 
Example 27
Source Project: tinkerpop   Source File: DefaultGraphManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a new instance using the {@link Settings} from Gremlin Server.
 */
public DefaultGraphManager(final Settings settings) {
    settings.graphs.entrySet().forEach(e -> {
        try {
            final Graph newGraph = GraphFactory.open(e.getValue());
            graphs.put(e.getKey(), newGraph);
            logger.info("Graph [{}] was successfully configured via [{}].", e.getKey(), e.getValue());
        } catch (RuntimeException re) {
            logger.warn(String.format("Graph [%s] configured at [%s] could not be instantiated and will not be available in Gremlin Server.  GraphFactory message: %s",
                    e.getKey(), e.getValue(), re.getMessage()), re);
            if (re.getCause() != null) logger.debug("GraphFactory exception", re.getCause());
        }
    });
}
 
Example 28
Source Project: tinkerpop   Source File: DistributionGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private Builder(final Graph g) {
    super(Builder.class);
    this.g = g;
    final List<Vertex> allVertices = IteratorUtils.list(g.vertices());
    this.out = allVertices;
    this.in = allVertices;
    this.expectedNumEdges = allVertices.size() * 2;
}
 
Example 29
Source Project: tinkerpop   Source File: PartitionStrategyProcessTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.VERTICES_ONLY)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_META_PROPERTIES)
public void shouldHidePartitionKeyForValueMapWithEmptyKeys() {
    final GraphTraversalSource gOverA = g.withStrategies(PartitionStrategy.build()
            .includeMetaProperties(true)
            .partitionKey(partition).writePartition("A").readPartitions("A").create());
    final Vertex v = gOverA.addV().property("any", "thing").next();

    assertEquals(1L, (long) gOverA.V(v).valueMap().count().next());
    assertEquals("thing", ((List) gOverA.V(v).valueMap().next().get("any")).get(0));
}
 
Example 30
@Test
public void shouldReturnReferenceElements() {
    final Graph graph = TinkerFactory.createModern();
    GraphTraversalSource g = graph.traversal().withComputer().withStrategies(HaltedTraverserStrategy.reference());
    g.V().out().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
    g.V().out().properties("name").forEachRemaining(vertexProperty -> assertEquals(ReferenceVertexProperty.class, vertexProperty.getClass()));
    g.V().out().values("name").forEachRemaining(value -> assertEquals(String.class, value.getClass()));
    g.V().out().outE().forEachRemaining(edge -> assertEquals(ReferenceEdge.class, edge.getClass()));
    g.V().out().outE().properties("weight").forEachRemaining(property -> assertEquals(ReferenceProperty.class, property.getClass()));
    g.V().out().outE().values("weight").forEachRemaining(value -> assertEquals(Double.class, value.getClass()));
    g.V().out().out().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
    g.V().out().out().path().forEachRemaining(path -> assertEquals(ReferencePath.class, path.getClass()));
    g.V().out().pageRank().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
    g.V().out().pageRank().out().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
    // the default should be reference elements
    g = graph.traversal().withComputer();
    g.V().out().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
    g.V().out().properties("name").forEachRemaining(vertexProperty -> assertEquals(ReferenceVertexProperty.class, vertexProperty.getClass()));
    g.V().out().values("name").forEachRemaining(value -> assertEquals(String.class, value.getClass()));
    g.V().out().outE().forEachRemaining(edge -> assertEquals(ReferenceEdge.class, edge.getClass()));
    g.V().out().outE().properties("weight").forEachRemaining(property -> assertEquals(ReferenceProperty.class, property.getClass()));
    g.V().out().outE().values("weight").forEachRemaining(value -> assertEquals(Double.class, value.getClass()));
    g.V().out().out().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
    g.V().out().out().path().forEachRemaining(path -> assertEquals(ReferencePath.class, path.getClass()));
    g.V().out().pageRank().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
    g.V().out().pageRank().out().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
    // should handle nested collections
    g.V().out().fold().next().forEach(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
}