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

The following examples show how to use org.apache.tinkerpop.gremlin.structure.Graph. 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: AbstractGremlinSuite.java    From tinkerpop with 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 #2
Source File: TraversalHelper.java    From tinkerpop with 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 #3
Source File: GraphSONMessageSerializerV1d0Test.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@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 File: TestGraphProvider.java    From hugegraph with 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 #5
Source File: LabelMetadataModel.java    From hgraphdb with 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 #6
Source File: TinkerGraphProvider.java    From tinkerpop with 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 #7
Source File: AddEdgeTest.java    From tinkerpop with 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 #8
Source File: OutputRDDTest.java    From tinkerpop with 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 #9
Source File: PropertyMethodHandlerTest.java    From Ferma with 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 #10
Source File: IoTest.java    From tinkerpop with 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 #11
Source File: HadoopIoStep.java    From tinkerpop with 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 #12
Source File: IoEdgeTest.java    From tinkerpop with 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 #13
Source File: IoGraphTest.java    From tinkerpop with 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 #14
Source File: EventStrategyProcessTest.java    From tinkerpop with 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 #15
Source File: AbstractDocumentGraphFormatConsumer.java    From baleen with Apache License 2.0 6 votes vote down vote up
@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 #16
Source File: CoreTraversalTest.java    From tinkerpop with 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 #17
Source File: ConnectedComponentVertexProgram.java    From tinkerpop with 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 #18
Source File: GraphSerializer.java    From tinkerpop with 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 #19
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 #20
Source File: EventStrategy.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
public TransactionalEventQueue(final Graph graph) {
    if (!graph.features().graph().supportsTransactions())
        throw new IllegalStateException(String.format("%s requires the graph to support transactions", EventStrategy.class.getName()));

    // since this is a transactional graph events are enqueued so the events should be fired/reset only after
    // transaction is committed/rolled back as tied to a graph transaction
    graph.tx().addTransactionListener(status -> {
        if (status == Transaction.Status.COMMIT)
            fireEventQueue();
        else if (status == Transaction.Status.ROLLBACK)
            resetEventQueue();
        else
            throw new RuntimeException(String.format("The %s is not aware of this status: %s", EventQueue.class.getName(), status));
    });
}
 
Example #21
Source File: GraphSONReader.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
/**
 * Read data into a {@link Graph} from output generated by any of the {@link GraphSONWriter} {@code writeVertex} or
 * {@code writeVertices} methods or by {@link GryoWriter#writeGraph(OutputStream, Graph)}.
 *
 * @param inputStream a stream containing an entire graph of vertices and edges as defined by the accompanying
 *                    {@link GraphSONWriter#writeGraph(OutputStream, Graph)}.
 * @param graphToWriteTo the graph to write to when reading from the stream.
 */
@Override
public void readGraph(final InputStream inputStream, final Graph graphToWriteTo) throws IOException {
    // dual pass - create all vertices and store to cache the ids.  then create edges.  as long as we don't
    // have vertex labels in the output we can't do this single pass
    final Map<StarGraph.StarVertex,Vertex> cache = new HashMap<>();
    final AtomicLong counter = new AtomicLong(0);

    final boolean supportsTx = graphToWriteTo.features().graph().supportsTransactions();
    final Graph.Features.EdgeFeatures edgeFeatures = graphToWriteTo.features().edge();

    readVertexStrings(inputStream).<Vertex>map(FunctionUtils.wrapFunction(line -> readVertex(new ByteArrayInputStream(line.getBytes()), null, null, Direction.IN))).forEach(vertex -> {
        final Attachable<Vertex> attachable = (Attachable<Vertex>) vertex;
        cache.put((StarGraph.StarVertex) attachable.get(), attachable.attach(Attachable.Method.create(graphToWriteTo)));
        if (supportsTx && counter.incrementAndGet() % batchSize == 0)
            graphToWriteTo.tx().commit();
    });
    cache.entrySet().forEach(kv -> kv.getKey().edges(Direction.IN).forEachRemaining(e -> {
        // can't use a standard Attachable attach method here because we have to use the cache for those
        // graphs that don't support userSuppliedIds on edges.  note that outVertex/inVertex methods return
        // StarAdjacentVertex whose equality should match StarVertex.
        final Vertex cachedOutV = cache.get(e.outVertex());
        final Vertex cachedInV = cache.get(e.inVertex());

        if (null == cachedOutV) throw new IllegalStateException(String.format("Could not find outV with id [%s] to create edge with id [%s]", e.outVertex().id(), e.id()));
        if (null == cachedInV) throw new IllegalStateException(String.format("Could not find inV with id [%s] to create edge with id [%s]", e.inVertex().id(), e.id()));

        final Edge newEdge = edgeFeatures.willAllowId(e.id()) ? cachedOutV.addEdge(e.label(), cachedInV, T.id, e.id()) : cachedOutV.addEdge(e.label(), cachedInV);
        e.properties().forEachRemaining(p -> newEdge.property(p.key(), p.value()));
        if (supportsTx && counter.incrementAndGet() % batchSize == 0)
            graphToWriteTo.tx().commit();
    }));

    if (supportsTx) graphToWriteTo.tx().commit();
}
 
Example #22
Source File: GryoReader.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
/**
 * Read data into a {@link Graph} from output generated by any of the {@link GryoWriter} {@code writeVertex} or
 * {@code writeVertices} methods or by {@link GryoWriter#writeGraph(OutputStream, Graph)}.
 *
 * @param inputStream    a stream containing an entire graph of vertices and edges as defined by the accompanying
 *                       {@link GraphWriter#writeGraph(OutputStream, Graph)}.
 * @param graphToWriteTo the graph to write to when reading from the stream.
 * @throws IOException
 */
@Override
public void readGraph(final InputStream inputStream, final Graph graphToWriteTo) throws IOException {
    // dual pass - create all vertices and store to cache the ids.  then create edges.  as long as we don't
    // have vertex labels in the output we can't do this single pass
    final Map<StarGraph.StarVertex, Vertex> cache = new HashMap<>();
    final AtomicLong counter = new AtomicLong(0);

    final Graph.Features.EdgeFeatures edgeFeatures = graphToWriteTo.features().edge();
    final boolean supportsTx = graphToWriteTo.features().graph().supportsTransactions();

    IteratorUtils.iterate(new VertexInputIterator(new Input(inputStream), attachable -> {
        final Vertex v = cache.put((StarGraph.StarVertex) attachable.get(), attachable.attach(Attachable.Method.create(graphToWriteTo)));
        if (supportsTx && counter.incrementAndGet() % batchSize == 0)
            graphToWriteTo.tx().commit();
        return v;
    }, null, null));
    cache.entrySet().forEach(kv -> kv.getKey().edges(Direction.IN).forEachRemaining(e -> {
        // can't use a standard Attachable attach method here because we have to use the cache for those
        // graphs that don't support userSuppliedIds on edges. note that outVertex/inVertex methods return
        // StarAdjacentVertex whose equality should match StarVertex.
        final Vertex cachedOutV = cache.get(e.outVertex());
        final Vertex cachedInV = cache.get(e.inVertex());

        if (null == cachedOutV) throw new IllegalStateException(String.format("Could not find outV with id [%s] to create edge with id [%s]", e.outVertex().id(), e.id()));
        if (null == cachedInV) throw new IllegalStateException(String.format("Could not find inV with id [%s] to create edge with id [%s]", e.inVertex().id(), e.id()));

        final Edge newEdge = edgeFeatures.willAllowId(e.id()) ? cachedOutV.addEdge(e.label(), cachedInV, T.id, e.id()) : cachedOutV.addEdge(e.label(), cachedInV);
        e.properties().forEachRemaining(p -> newEdge.property(p.key(), p.value()));
        if (supportsTx && counter.incrementAndGet() % batchSize == 0)
            graphToWriteTo.tx().commit();
    }));

    if (supportsTx) graphToWriteTo.tx().commit();
}
 
Example #23
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 #24
Source File: HugeVariables.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
@Override
public void remove(String key) {
    if (key == null) {
        throw Graph.Variables.Exceptions.variableKeyCanNotBeNull();
    }
    if (key.isEmpty()) {
        throw Graph.Variables.Exceptions.variableKeyCanNotBeEmpty();
    }
    HugeVertex vertex = this.queryVariableVertex(key);
    if (vertex != null) {
        this.removeVariableVertex(vertex);
    }
}
 
Example #25
Source File: AddVertexTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@LoadGraphWith(MODERN)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_PROPERTY)
public void g_VX1X_addVXanimalX_propertyXage_selectXaX_byXageXX_propertyXname_puppyX() {
    final Traversal<Vertex, Vertex> traversal = get_g_VX1X_addVXanimalX_propertyXage_selectXaX_byXageXX_propertyXname_puppyX(convertToVertexId(graph, "marko"));
    printTraversalForm(traversal);
    final Vertex vertex = traversal.next();
    assertEquals("animal", vertex.label());
    assertEquals(29, vertex.<Integer>value("age").intValue());
    assertEquals("puppy", vertex.<String>value("name"));
    assertFalse(traversal.hasNext());
    assertEquals(7, IteratorUtils.count(g.V()));
}
 
Example #26
Source File: GremlinResultSetIntegrateTest.java    From tinkerpop with 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 File: GraphManager.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
private void loadGraph(String name, String path) {
    final Graph graph = GraphFactory.open(path);
    this.graphs.put(name, graph);
    LOG.info("Graph '{}' was successfully configured via '{}'", name, path);

    if (this.requireAuthentication() &&
        !(graph instanceof HugeGraphAuthProxy)) {
        LOG.warn("You may need to support access control for '{}' with {}",
                 path, HugeFactoryAuthProxy.GRAPH_FACTORY);
    }
}
 
Example #28
Source File: HasTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@LoadGraphWith(MODERN)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_USER_SUPPLIED_IDS)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_NUMERIC_IDS)
public void g_VX1X_out_hasXid_lt_3X() {
    // can only execute this on graphs with user supplied ids so that we can be assured of the lt op. it
    // sort of assumes that ids increment, but there's no feature check for that.  graphs that don't work this
    // way with numeric ids may need to optout
    final Traversal<Vertex, Vertex> traversal = get_g_VX1X_out_hasXid_lt_3X(convertToVertexId("marko"), convertToVertexId("lop"));
    assertVadasAsOnlyValueReturned(traversal);
}
 
Example #29
Source File: JanusGraphStepStrategy.java    From grakn with GNU Affero General Public License v3.0 5 votes vote down vote up
@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 #30
Source File: TraverseGraphDelegate.java    From act-platform with ISC License 5 votes vote down vote up
private Graph createGraph() {
  return ActGraph.builder()
          .setObjectManager(objectManager)
          .setFactManager(factManager)
          .setHasFactAccess(securityContext::hasReadPermission)
          .build();
}