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

The following are top voted examples for showing how to use org.apache.tinkerpop.gremlin.structure.VertexProperty. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: tinkergraph-gremlin   File: TinkerGraphUUIDProvider.java   Source Code and License 7 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 = TinkerGraph.DefaultIdManager.UUID;
    final String idMaker = 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");
            final File tempDir = TestHelper.makeTestDataPath(test, "temp");
            put(TinkerGraph.GREMLIN_TINKERGRAPH_GRAPH_LOCATION,
                    tempDir.getAbsolutePath() + File.separator + testMethodName + ".kryo");
        }
    }};
}
 
Example 2
Project: tinkergraph-gremlin   File: TinkerGraphProvider.java   Source Code and License 7 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");
            final File tempDir = TestHelper.makeTestDataPath(test, "temp");
            put(TinkerGraph.GREMLIN_TINKERGRAPH_GRAPH_LOCATION,
                    tempDir.getAbsolutePath() + File.separator + testMethodName + ".kryo");
        }
    }};
}
 
Example 3
Project: act-platform   File: ObjectVertexTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testGetPropertyKeysOnVertex() {
  Vertex vertex = createVertex();
  // Test that the following properties exists on the vertex.
  Map<String, String> expected = MapUtils.map(
          T("value", "value")
  );

  Set<String> keys = vertex.keys();
  Set<VertexProperty<Object>> properties = SetUtils.set(vertex.properties());

  assertEquals(expected.size(), keys.size());
  assertEquals(expected.size(), properties.size());

  for (Map.Entry<String, String> entry : expected.entrySet()) {
    assertTrue(keys.contains(entry.getKey()));

    VertexProperty<Object> property = vertex.property(entry.getKey());
    assertNotNull(property.id());
    assertEquals(entry.getValue(), property.value());
    assertEquals(property.key(), property.label());
    assertEquals(StringFactory.propertyString(property), property.toString());
    assertSame(vertex, property.element());
  }
}
 
Example 4
Project: mongodb-gremlin   File: MongoDBStrategy.java   Source Code and License 6 votes vote down vote up
private static void insertList(final List list, final String listKey, final GraphTraversal traversal) {
    if (list.get(0) instanceof List)
        throw new IllegalArgumentException("Lists can not contain nested lists");
    char state = list.get(0) instanceof Map ? 'o' : 'p';
    for (int i = 1; i < list.size(); i++) {
        if (list.get(i) instanceof Map && 'p' == state)
            throw new IllegalArgumentException("Lists can only support all objects or all primitives");
        else if (list.get(i) instanceof List)
            throw new IllegalArgumentException("Lists can not contain nested lists");
        else if (!(list.get(i) instanceof Map) && 'o' == state)
            throw new IllegalArgumentException("Lists can only support all objects or all primitives");
    }
    for (final Object object : list) {
        if ('p' == state)
            traversal.property(VertexProperty.Cardinality.list, listKey, object);
        else {
            traversal.map(insertMap((Map) object, new DefaultGraphTraversal()));
            traversal.addE(listKey).from("a").select("a");
        }
    }
}
 
Example 5
Project: tinkergraph-gremlin   File: TinkerGraph.java   Source Code and License 6 votes vote down vote up
/**
 * An empty private constructor that initializes {@link TinkerGraph}.
 */
private TinkerGraph(final Configuration configuration, boolean usesSpecializedElements) {
    this.configuration = configuration;
    this.usesSpecializedElements = usesSpecializedElements;
    vertexIdManager = selectIdManager(configuration, GREMLIN_TINKERGRAPH_VERTEX_ID_MANAGER, Vertex.class);
    edgeIdManager = selectIdManager(configuration, GREMLIN_TINKERGRAPH_EDGE_ID_MANAGER, Edge.class);
    vertexPropertyIdManager = selectIdManager(configuration, GREMLIN_TINKERGRAPH_VERTEX_PROPERTY_ID_MANAGER, VertexProperty.class);
    defaultVertexPropertyCardinality = VertexProperty.Cardinality.valueOf(
            configuration.getString(GREMLIN_TINKERGRAPH_DEFAULT_VERTEX_PROPERTY_CARDINALITY, VertexProperty.Cardinality.single.name()));

    graphLocation = configuration.getString(GREMLIN_TINKERGRAPH_GRAPH_LOCATION, null);
    graphFormat = configuration.getString(GREMLIN_TINKERGRAPH_GRAPH_FORMAT, null);

    if ((graphLocation != null && null == graphFormat) || (null == graphLocation && graphFormat != null))
        throw new IllegalStateException(String.format("The %s and %s must both be specified if either is present",
                GREMLIN_TINKERGRAPH_GRAPH_LOCATION, GREMLIN_TINKERGRAPH_GRAPH_FORMAT));

    if (graphLocation != null) loadGraph();
}
 
Example 6
Project: tinkergraph-gremlin   File: TinkerGraphGraphSONSerializerV2d0Test.java   Source Code and License 6 votes vote down vote up
@Test
public void deserializersTestsVertexProperty() {
    final TinkerGraph tg = TinkerGraph.open();

    final Vertex v = tg.addVertex("vertexTest");

    final GraphWriter writer = getWriter(defaultMapperV2d0);
    final GraphReader reader = getReader(defaultMapperV2d0);

    final VertexProperty prop = v.property("born", LocalDateTime.of(1971, 1, 2, 20, 50));

    try (final ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        writer.writeObject(out, prop);
        final String json = out.toString();

        final VertexProperty vPropRead = (VertexProperty)reader.readObject(new ByteArrayInputStream(json.getBytes()), Object.class);
        //only classes and ids are checked, that's ok, full vertex property ser/de
        //is checked elsewhere.
        assertEquals(prop, vPropRead);
    } catch (IOException e) {
        e.printStackTrace();
        fail("Should not have thrown exception: " + e.getMessage());
    }
}
 
Example 7
Project: tinkergraph-gremlin   File: TinkerGraphTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldPersistToGryoAndHandleMultiProperties() {
    final String graphLocation = TestHelper.makeTestDataDirectory(TinkerGraphTest.class) + "shouldPersistToGryoMulti.kryo";
    final File f = new File(graphLocation);
    if (f.exists() && f.isFile()) f.delete();

    final Configuration conf = new BaseConfiguration();
    conf.setProperty(TinkerGraph.GREMLIN_TINKERGRAPH_GRAPH_FORMAT, "gryo");
    conf.setProperty(TinkerGraph.GREMLIN_TINKERGRAPH_GRAPH_LOCATION, graphLocation);
    final TinkerGraph graph = TinkerGraph.open(conf);
    TinkerFactory.generateTheCrew(graph);
    graph.close();

    conf.setProperty(TinkerGraph.GREMLIN_TINKERGRAPH_DEFAULT_VERTEX_PROPERTY_CARDINALITY, VertexProperty.Cardinality.list.toString());
    final TinkerGraph reloadedGraph = TinkerGraph.open(conf);
    IoTest.assertCrewGraph(reloadedGraph, false);
    reloadedGraph.close();
}
 
Example 8
Project: LiteGraph   File: PageRankVertexProgram.java   Source Code and License 6 votes vote down vote up
@Override
public void execute(final Vertex vertex, Messenger<Double> messenger, final Memory memory) {
    if (memory.isInitialIteration()) {
        messenger.sendMessage(this.countMessageScope, 1.0d);
    } else if (1 == memory.getIteration()) {
        double initialPageRank = (null == this.initialRankTraversal ?
                1.0d :
                TraversalUtil.apply(vertex, this.initialRankTraversal.get()).doubleValue()) / this.vertexCountAsDouble;
        double edgeCount = IteratorUtils.reduce(messenger.receiveMessages(), 0.0d, (a, b) -> a + b);
        vertex.property(VertexProperty.Cardinality.single, this.property, initialPageRank);
        vertex.property(VertexProperty.Cardinality.single, EDGE_COUNT, edgeCount);
        if (!this.terminate(memory)) // don't send messages if this is the last iteration
            messenger.sendMessage(this.incidentMessageScope, initialPageRank / edgeCount);
    } else {
        double newPageRank = IteratorUtils.reduce(messenger.receiveMessages(), 0.0d, (a, b) -> a + b);
        newPageRank = (this.alpha * newPageRank) + ((1.0d - this.alpha) / this.vertexCountAsDouble);
        vertex.property(VertexProperty.Cardinality.single, this.property, newPageRank);
        if (!this.terminate(memory)) // don't send messages if this is the last iteration
            messenger.sendMessage(this.incidentMessageScope, newPageRank / vertex.<Double>value(EDGE_COUNT));
    }
}
 
Example 9
Project: Purifinity   File: XOEntitiesIT.java   Source Code and License 6 votes vote down vote up
@Before
   public void createXOManager() throws SQLException, IOException, ServiceException {
AccountManagerTester.cleanupDatabase();
xoManager = xoManagerFactory.createXOManager();
GraphTraversal<Vertex, Vertex> vertices = ((Graph) ductileGraph).traversal().V();
int counter = 0;
while (vertices.hasNext()) {
    Vertex vertex = vertices.next();
    counter++;
    Iterator<VertexProperty<Object>> properties = vertex.properties();
    while (properties.hasNext()) {
	VertexProperty<Object> property = properties.next();
	System.out.println(property.key() + ": " + property.value());
    }
}
assertEquals(7, counter);
   }
 
Example 10
Project: LiteGraph   File: IoPropertyTest.java   Source Code and License 6 votes vote down vote up
@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldReadWriteVertexPropertyNoMetaProperties() throws Exception {
    try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) {
        final GraphWriter writer = writerMaker.apply(graph);
        final VertexProperty p = g.V(convertToVertexId("marko")).next().property("name");
        writer.writeVertexProperty(os, p);

        final AtomicBoolean called = new AtomicBoolean(false);
        final GraphReader reader = readerMaker.apply(graph);
        try (final ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) {
            reader.readVertexProperty(bais, propertyAttachable -> {
                assertEquals(p.value(), propertyAttachable.get().value());
                assertEquals(p.key(), propertyAttachable.get().key());
                assertEquals(0, IteratorUtils.count(propertyAttachable.get().properties()));
                called.set(true);
                return propertyAttachable.get();
            });
        }

        assertTrue(called.get());
    }
}
 
Example 11
Project: LiteGraph   File: TinkerGraph.java   Source Code and License 6 votes vote down vote up
@Override
public Vertex addVertex(final Object... keyValues) {
    ElementHelper.legalPropertyKeyValueArray(keyValues);
    Object idValue = vertexIdManager.convert(ElementHelper.getIdValue(keyValues).orElse(null));
    final String label = ElementHelper.getLabelValue(keyValues).orElse(Vertex.DEFAULT_LABEL);

    if (null != idValue) {
        if (this.vertices.containsKey(idValue))
            throw Exceptions.vertexWithIdAlreadyExists(idValue);
    } else {
        idValue = vertexIdManager.getNextId(this);
    }

    final Vertex vertex = new TinkerVertex(idValue, label, this);
    this.vertices.put(vertex.id(), vertex);

    ElementHelper.attachProperties(vertex, VertexProperty.Cardinality.list, keyValues);
    return vertex;
}
 
Example 12
Project: LiteGraph   File: MultiMetaNeo4jTrait.java   Source Code and License 6 votes vote down vote up
@Override
public <V> VertexProperty<V> getVertexProperty(final Neo4jVertex vertex, final String key) {
    final Neo4jNode node = vertex.getBaseVertex();
    if (node.hasProperty(key)) {
        if (node.getProperty(key).equals(VERTEX_PROPERTY_TOKEN)) {
            if (node.degree(Neo4jDirection.OUTGOING, Graph.Hidden.hide(key)) > 1)
                throw Vertex.Exceptions.multiplePropertiesExistForProvidedKey(key);
            else {
                return (VertexProperty<V>) new Neo4jVertexProperty<>(vertex, node.relationships(Neo4jDirection.OUTGOING, Graph.Hidden.hide(key)).iterator().next().end());
            }
        } else {
            return new Neo4jVertexProperty<>(vertex, key, (V) node.getProperty(key));
        }
    } else
        return VertexProperty.<V>empty();
}
 
Example 13
Project: LiteGraph   File: StarGraphGraphSONSerializer.java   Source Code and License 6 votes vote down vote up
/**
 * A helper function for reading a serialized {@link StarGraph} from a {@link Map} generated by
 * {@link StarGraphGraphSONSerializer}.
 */
public static StarGraph readStarGraphVertex(final Map<String, Object> vertexData) throws IOException {
    final StarGraph starGraph = StarGraph.open();
    starGraph.addVertex(T.id, vertexData.get(GraphSONTokens.ID), T.label, vertexData.get(GraphSONTokens.LABEL));
    if (vertexData.containsKey(GraphSONTokens.PROPERTIES)) {
        final Map<String, List<Map<String, Object>>> properties = (Map<String, List<Map<String, Object>>>) vertexData.get(GraphSONTokens.PROPERTIES);
        for (Map.Entry<String, List<Map<String, Object>>> property : properties.entrySet()) {
            for (Map<String, Object> p : property.getValue()) {
                final StarGraph.StarVertexProperty vp = (StarGraph.StarVertexProperty) starGraph.getStarVertex().property(VertexProperty.Cardinality.list, property.getKey(), p.get(GraphSONTokens.VALUE), T.id, p.get(GraphSONTokens.ID));
                if (p.containsKey(GraphSONTokens.PROPERTIES)) {
                    final Map<String, Object> edgePropertyData = (Map<String, Object>) p.get(GraphSONTokens.PROPERTIES);
                    for (Map.Entry<String, Object> epd : edgePropertyData.entrySet()) {
                        vp.property(epd.getKey(), epd.getValue());
                    }
                }
            }
        }
    }

    return starGraph;
}
 
Example 14
Project: LiteGraph   File: ElementHelper.java   Source Code and License 6 votes vote down vote up
/**
 * This is a helper method for dealing with vertex property cardinality and typically used in {@link Vertex#property(org.apache.tinkerpop.gremlin.structure.VertexProperty.Cardinality, String, Object, Object...)}.
 * If the cardinality is list, simply return {@link Optional#empty}.
 * If the cardinality is single, delete all existing properties of the provided key and return {@link Optional#empty}.
 * If the cardinality is set, find one that has the same key/value and attached the properties to it and return it. Else, if no equal value is found, return {@link Optional#empty}.
 *
 * @param vertex      the vertex to stage a vertex property for
 * @param cardinality the cardinality of the vertex property
 * @param key         the key of the vertex property
 * @param value       the value of the vertex property
 * @param keyValues   the properties of vertex property
 * @param <V>         the type of the vertex property value
 * @return a vertex property if it has been found in set with equal value
 */
public static <V> Optional<VertexProperty<V>> stageVertexProperty(final Vertex vertex, final VertexProperty.Cardinality cardinality, final String key, final V value, final Object... keyValues) {
    if (cardinality.equals(VertexProperty.Cardinality.single))
        vertex.properties(key).forEachRemaining(VertexProperty::remove);
    else if (cardinality.equals(VertexProperty.Cardinality.set)) {
        final Iterator<VertexProperty<V>> itty = vertex.properties(key);
        while (itty.hasNext()) {
            final VertexProperty<V> property = itty.next();
            if (property.value().equals(value)) {
                ElementHelper.attachProperties(property, keyValues);
                return Optional.of(property);
            }
        }
    } // do nothing on Cardinality.list
    return Optional.empty();
}
 
Example 15
Project: LiteGraph   File: DetachedVertexProperty.java   Source Code and License 6 votes vote down vote up
protected DetachedVertexProperty(final VertexProperty<V> vertexProperty, final boolean withProperties) {
    super(vertexProperty);
    this.value = vertexProperty.value();
    this.vertex = DetachedFactory.detach(vertexProperty.element(), false);

    // only serialize properties if requested, the graph supports it and there are meta properties present.
    // this prevents unnecessary object creation of a new HashMap which will just be empty.  it will use
    // Collections.emptyMap() by default
    if (withProperties && vertexProperty.graph().features().vertex().supportsMetaProperties()) {
        final Iterator<Property<Object>> propertyIterator = vertexProperty.properties();
        if (propertyIterator.hasNext()) {
            this.properties = new HashMap<>();
            propertyIterator.forEachRemaining(property -> this.properties.put(property.key(), Collections.singletonList(DetachedFactory.detach(property))));
        }
    }
}
 
Example 16
Project: LiteGraph   File: Attachable.java   Source Code and License 6 votes vote down vote up
public static <V> Function<Attachable<V>, V> create(final Host hostVertexOrGraph) {
    return (Attachable<V> attachable) -> {
        final Object base = attachable.get();
        if (base instanceof Vertex) {
            return hostVertexOrGraph instanceof Graph ?
                    (V) Method.createVertex((Attachable<Vertex>) attachable, (Graph) hostVertexOrGraph) :
                    (V) Method.createVertex((Attachable<Vertex>) attachable, (Vertex) hostVertexOrGraph);
        } else if (base instanceof Edge) {
            return hostVertexOrGraph instanceof Graph ?
                    (V) Method.createEdge((Attachable<Edge>) attachable, (Graph) hostVertexOrGraph) :
                    (V) Method.createEdge((Attachable<Edge>) attachable, (Vertex) hostVertexOrGraph);
        } else if (base instanceof VertexProperty) {
            return hostVertexOrGraph instanceof Graph ?
                    (V) Method.createVertexProperty((Attachable<VertexProperty>) attachable, (Graph) hostVertexOrGraph) :
                    (V) Method.createVertexProperty((Attachable<VertexProperty>) attachable, (Vertex) hostVertexOrGraph);
        } else if (base instanceof Property) {
            return hostVertexOrGraph instanceof Graph ?
                    (V) Method.createProperty((Attachable<Property>) attachable, (Graph) hostVertexOrGraph) :
                    (V) Method.createProperty((Attachable<Property>) attachable, (Vertex) hostVertexOrGraph);
        } else
            throw Attachable.Exceptions.providedAttachableMustContainAGraphObject(attachable);
    };
}
 
Example 17
Project: LiteGraph   File: Attachable.java   Source Code and License 6 votes vote down vote up
public static Property createProperty(final Attachable<Property> attachableProperty, final Vertex hostVertex) {
    final Property baseProperty = attachableProperty.get();
    final Element baseElement = baseProperty.element();
    if (baseElement instanceof Vertex) {
        return Method.createVertexProperty((Attachable) attachableProperty, hostVertex);
    } else if (baseElement instanceof Edge) {
        final Iterator<Edge> edgeIterator = hostVertex.edges(Direction.OUT);
        if (edgeIterator.hasNext())
            return edgeIterator.next().property(baseProperty.key(), baseProperty.value());
        throw new IllegalStateException("Could not find edge to create the property on");
    } else { // vertex property
        final Iterator<VertexProperty<Object>> vertexPropertyIterator = hostVertex.properties(((VertexProperty) baseElement).key());
        while (vertexPropertyIterator.hasNext()) {
            final VertexProperty<Object> vp = vertexPropertyIterator.next();
            if (ElementHelper.areEqual(vp, baseElement))
                return vp.property(baseProperty.key(), baseProperty.value());
        }
        throw new IllegalStateException("Could not find vertex property to create the attachable property on");
    }
}
 
Example 18
Project: LiteGraph   File: PartitionStrategy.java   Source Code and License 6 votes vote down vote up
@Override
public Map<String, List<Property>> apply(final Traverser<Map<String, List<Property>>> mapTraverser) {
    final Map<String,List<Property>> values = mapTraverser.get();
    final Map<String,List<Property>> filtered = new HashMap<>();

    // note the final filter that removes the partitionKey from the outgoing Map
    values.entrySet().forEach(p -> {
        final List l = p.getValue().stream().filter(property -> {
            if (property instanceof VertexProperty) {
                final Iterator<String> itty = ((VertexProperty) property).values(partitionKey);
                return itty.hasNext() && readPartitions.contains(itty.next());
            } else {
                return true;
            }
        }).filter(property -> !property.key().equals(partitionKey)).collect(Collectors.toList());
        if (l.size() > 0) filtered.put(p.getKey(), l);
    });

    return filtered;
}
 
Example 19
Project: LiteGraph   File: GraphSONSerializers.java   Source Code and License 6 votes vote down vote up
private static void tryWriteMetaProperties(final VertexProperty property, final JsonGenerator jsonGenerator,
                                           final SerializerProvider serializerProvider,
                                           final TypeSerializer typeSerializer, final boolean normalize) throws IOException {
    // when "detached" you can't check features of the graph it detached from so it has to be
    // treated differently from a regular VertexProperty implementation.
    if (property instanceof DetachedVertexProperty) {
        // only write meta properties key if they exist
        if (property.properties().hasNext()) {
            writeMetaProperties(property, jsonGenerator, serializerProvider, typeSerializer, normalize);
        }
    } else {
        // still attached - so we can check the features to see if it's worth even trying to write the
        // meta properties key
        if (property.graph().features().vertex().supportsMetaProperties() && property.properties().hasNext()) {
            writeMetaProperties(property, jsonGenerator, serializerProvider, typeSerializer, normalize);
        }
    }
}
 
Example 20
Project: tinkergraph-gremlin   File: TinkerFactory.java   Source Code and License 5 votes vote down vote up
public static TinkerGraph createTheCrew() {
    final Configuration conf = getNumberIdManagerConfiguration();
    conf.setProperty(TinkerGraph.GREMLIN_TINKERGRAPH_DEFAULT_VERTEX_PROPERTY_CARDINALITY, VertexProperty.Cardinality.list.name());
    final TinkerGraph g = TinkerGraph.open(conf);
    generateTheCrew(g);
    return g;
}
 
Example 21
Project: tinkergraph-gremlin   File: TinkerGraphComputerView.java   Source Code and License 5 votes vote down vote up
public void removeProperty(final TinkerVertex vertex, final String key, final VertexProperty property) {
    if (isComputeKey(key)) {
        this.removeValue(vertex, key, property);
    } else {
        throw GraphComputer.Exceptions.providedKeyIsNotAnElementComputeKey(key);
    }
}
 
Example 22
Project: tinkergraph-gremlin   File: TinkerGraphComputerView.java   Source Code and License 5 votes vote down vote up
protected void complete() {
    // remove all transient properties from the vertices
    for (final VertexComputeKey computeKey : this.computeKeys.values()) {
        if (computeKey.isTransient()) {
            for (final Map<String, List<VertexProperty<?>>> properties : this.computeProperties.values()) {
                properties.remove(computeKey.getKey());
            }
        }
    }
}
 
Example 23
Project: tinkergraph-gremlin   File: TinkerGraphComputerView.java   Source Code and License 5 votes vote down vote up
private void addPropertiesToOriginalGraph() {
    TinkerHelper.dropGraphComputerView(this.graph);
    this.computeProperties.forEach((element, properties) -> {
        properties.forEach((key, vertexProperties) -> {
            vertexProperties.forEach(vertexProperty -> {
                final VertexProperty<?> newVertexProperty = ((Vertex) element).property(VertexProperty.Cardinality.list, vertexProperty.key(), vertexProperty.value(), T.id, vertexProperty.id());
                vertexProperty.properties().forEachRemaining(property -> {
                    newVertexProperty.property(property.key(), property.value());
                });
            });
        });
    });
    this.computeProperties.clear();
}
 
Example 24
Project: tinkergraph-gremlin   File: TinkerGraphComputerView.java   Source Code and License 5 votes vote down vote up
private void addValue(final Vertex vertex, final String key, final VertexProperty property) {
    final Map<String, List<VertexProperty<?>>> elementProperties = this.computeProperties.computeIfAbsent(vertex, k -> new HashMap<>());
    elementProperties.compute(key, (k, v) -> {
        if (null == v) v = new ArrayList<>();
        v.add(property);
        return v;
    });
}
 
Example 25
Project: tinkergraph-gremlin   File: Song.java   Source Code and License 5 votes vote down vote up
@Override
protected <V> VertexProperty<V> specificProperty(String key) {
    if (key == NAME && name != null) {
        return new TinkerVertexProperty(this, key, name);
    } else if (key == SONG_TYPE && songType != null) {
        return new TinkerVertexProperty(this, key, songType);
    } else if (key == PERFORMANCES && performances != null) {
        return new TinkerVertexProperty(this, key, performances);
    } else {
        return VertexProperty.empty();
    }
}
 
Example 26
Project: tinkergraph-gremlin   File: Song.java   Source Code and License 5 votes vote down vote up
@Override
protected <V> VertexProperty<V> updateSpecificProperty(String key, V value) {
    if (key == NAME) {
        this.name = (String) value;
    } else if (key == SONG_TYPE) {
        this.songType = (String) value;
    } else if (key == PERFORMANCES) {
        this.performances = (Integer) value;
    } else {
        throw new RuntimeException("property with key=" + key + " not (yet) supported by " + this.getClass().getName());
    }
    return property(key);
}
 
Example 27
Project: tinkergraph-gremlin   File: Artist.java   Source Code and License 5 votes vote down vote up
@Override
protected <V> VertexProperty<V> specificProperty(String key) {
    if (key == NAME && name != null) {
        return new TinkerVertexProperty(this, key, name);
    } else {
        return VertexProperty.empty();
    }
}
 
Example 28
Project: tinkergraph-gremlin   File: Artist.java   Source Code and License 5 votes vote down vote up
@Override
protected <V> VertexProperty<V> updateSpecificProperty(String key, V value) {
    if (key == NAME) {
        this.name = (String) value;
    } else {
        throw new RuntimeException("property with key=" + key + " not (yet) supported by " + this.getClass().getName());
    }
    return property(key);
}
 
Example 29
Project: tinkergraph-gremlin   File: TinkerGraphIdManagerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldUseLongIdManagerToCoerceTypes() {
    final Graph graph = TinkerGraph.open(longIdManagerConfig);
    final Vertex v = graph.addVertex(T.id, vertexIdValue);
    final VertexProperty vp = v.property(VertexProperty.Cardinality.single, "test", "value", T.id, vertexPropertyIdValue);
    final Edge e = v.addEdge("self", v, T.id, edgeIdValue);

    assertEquals(100l, v.id());
    assertEquals(200l, e.id());
    assertEquals(300l, vp.id());
}
 
Example 30
Project: tinkergraph-gremlin   File: TinkerGraphIdManagerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldUseIntegerIdManagerToCoerceTypes() {
    final Graph graph = TinkerGraph.open(integerIdManagerConfig);
    final Vertex v = graph.addVertex(T.id, vertexIdValue);
    final VertexProperty vp = v.property(VertexProperty.Cardinality.single, "test", "value", T.id, vertexPropertyIdValue);
    final Edge e = v.addEdge("self", v, T.id, edgeIdValue);

    assertEquals(100, v.id());
    assertEquals(200, e.id());
    assertEquals(300, vp.id());
}
 
Example 31
Project: tinkergraph-gremlin   File: TinkerGraphIdManagerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldUseIdManagerToCoerceTypes() {
    final Graph graph = TinkerGraph.open(idManagerConfig);
    final Vertex v = graph.addVertex(T.id, vertexIdValue);
    final VertexProperty vp = v.property(VertexProperty.Cardinality.single, "test", "value", T.id, vertexPropertyIdValue);
    final Edge e = v.addEdge("self", v, T.id, edgeIdValue);

    assertEquals(vertexId, v.id());
    assertEquals(edgeId, e.id());
    assertEquals(vertexPropertyId, vp.id());
}
 
Example 32
Project: bitsy   File: BitsyVertex.java   Source Code and License 5 votes vote down vote up
@Override
public <T> VertexProperty<T> property(String key) {
    T value = value(key);
    if (value == null) {
        return VertexProperty.<T>empty();
    } else {
        return new BitsyVertexProperty<T>(this, key, value);
    }
}
 
Example 33
Project: bitsy   File: BitsyVertex.java   Source Code and License 5 votes vote down vote up
@Override
public <V> VertexProperty<V> property(final VertexProperty.Cardinality cardinality, final String key, final V value, final Object... keyValues) {
	if (cardinality != Cardinality.single) {
		// For some reason, TP3 tests fail with this exception
		//throw new BitsyException(BitsyErrorCodes.NO_MULTI_PROPERTY_SUPPORT, "Encountered cardinality: " + cardinality.toString());
	} else if (keyValues.length != 0) {
		throw new UnsupportedOperationException("Encountered key values: " + keyValues.toString(), new BitsyException(BitsyErrorCodes.NO_META_PROPERTY_SUPPORT));
	}

	return property(key, value);
}
 
Example 34
Project: bitsy   File: BitsyVertex.java   Source Code and License 5 votes vote down vote up
@Override
public <V> Iterator<VertexProperty<V>> properties(String... propertyKeys) {
       ArrayList<VertexProperty<V>> ans = new ArrayList<VertexProperty<V>>();

       if (propertyKeys.length == 0) {
       	if (this.properties == null) return Collections.emptyIterator();
       	propertyKeys = this.properties.getPropertyKeys();
       }

       for (String key : propertyKeys) {
       	VertexProperty<V> prop = property(key);
           if (prop.isPresent()) ans.add(prop);
       }
       return ans.iterator();
}
 
Example 35
Project: keti   File: GraphGenericRepository.java   Source Code and License 5 votes vote down vote up
public static String getPropertyOrEmptyString(final Vertex vertex, final String propertyKey) {
    VertexProperty<String> property = vertex.property(propertyKey);
    if (property.isPresent()) {
        return property.value();
    }
    return "";
}
 
Example 36
Project: keti   File: GraphGenericRepository.java   Source Code and License 5 votes vote down vote up
public static String getPropertyOrFail(final Vertex vertex, final String propertyKey) {
    VertexProperty<String> property = vertex.property(propertyKey);
    if (property.isPresent()) {
        return property.value();
    }
    throw new IllegalStateException(
            String.format("The vertex with id '%s' does not conatin the expected property '%s'.", vertex.id(),
                    propertyKey));
}
 
Example 37
Project: keti   File: GraphGenericRepository.java   Source Code and License 5 votes vote down vote up
public static String getPropertyOrNull(final Vertex vertex, final String propertyKey) {
    VertexProperty<String> property = vertex.property(propertyKey);
    if (property.isPresent()) {
        return property.value();
    }
    return null;
}
 
Example 38
Project: LiteGraph   File: ComputerGraph.java   Source Code and License 5 votes vote down vote up
@Override
public <V> VertexProperty<V> property(final VertexProperty.Cardinality cardinality, final String key, final V value, final Object... keyValues) {
    if (state.equals(State.MAP_REDUCE))
        throw GraphComputer.Exceptions.vertexPropertiesCanNotBeUpdatedInMapReduce();
    if (!computeKeys.contains(key))
        throw GraphComputer.Exceptions.providedKeyIsNotAnElementComputeKey(key);
    return new ComputerVertexProperty<>(this.getBaseVertex().property(cardinality, key, value, keyValues));
}
 
Example 39
Project: tinkerpop3   File: TestSearch.java   Source Code and License 5 votes vote down vote up
/**
 * Make sure we can find all five kinds of properties:
 * <p>
 * <pre>
 * Edge -> Property
 * Vertex -> VertexProperty(single/set)
 * Vertex -> VertexProperty(list)
 * VertexProperty(single/set) -> Property
 * VertexProperty(list) -> Property
 * </pre>
 * </p>
 */
public void testAllFiveKinds() {
    
    final BlazeVertex a = graph.addVertex(T.id, "a");
    final BlazeVertex b = graph.addVertex(T.id, "b");
    final BlazeEdge e = graph.addEdge(a, b, Edge.DEFAULT_LABEL, T.id, "e");
    
    final Property<String> ep = e.property("ep", "foo 1");
    final VertexProperty<String> vps = a.property(Cardinality.single, "vps", "foo 2");
    final VertexProperty<String> vpl = a.property(Cardinality.list, "vpl", "foo 3");
    final Property<String> vpsp = vps.property("vpsp", "foo 4");
    final Property<String> vplp = vpl.property("vplp", "foo 5");
    graph.commit();
    
    final Map<String,Property<String>> expected = 
            new HashMap<String,Property<String>>() {{
        put("foo 1", ep);
        put("foo 2", vps);
        put("foo 3", vpl);
        put("foo 4", vpsp);
        put("foo 5", vplp);
    }};
    
    log.debug(() -> "\n"+graph.dumpStore());
    
    final List<Property<String>> results = 
            graph.<String>search("foo", Match.ANY).collect();
    log.debug(() -> results.stream());
    assertEquals(5, results.size());
    results.stream().forEach(p -> {
        assertEquals(expected.get(p.value()), p);
    });
    
}
 
Example 40
Project: LiteGraph   File: ElementHelperTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldFailTryingToAttachPropertiesWithCardinalityToNullElement() {
    try {
        ElementHelper.attachProperties((Vertex) null, VertexProperty.Cardinality.single, "test", 123, 321, "test");
        fail("Should throw exception since the element argument is null");
    } catch (IllegalArgumentException iae) {
        assertEquals(Graph.Exceptions.argumentCanNotBeNull("vertex").getMessage(), iae.getMessage());
    }
}
 
Example 41
Project: LiteGraph   File: NativeNeo4jStructureCheck.java   Source Code and License 5 votes vote down vote up
@Test
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_MULTI_PROPERTIES)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_META_PROPERTIES)
public void shouldNotGenerateNodesAndRelationshipsForMultiPropertiesWithSingle() {
    graph.tx().readWrite();
    tryCommit(graph, graph -> validateCounts(0, 0, 0, 0));
    Vertex vertex = graph.addVertex(T.label, "person");
    tryCommit(graph, graph -> validateCounts(1, 0, 1, 0));
    vertex.property(VertexProperty.Cardinality.list, "name", "marko");
    assertEquals("marko", vertex.value("name"));
    tryCommit(graph, graph -> validateCounts(1, 0, 1, 0));
    vertex.property(VertexProperty.Cardinality.single, "name", "okram");
    tryCommit(graph, graph -> {
        validateCounts(1, 0, 1, 0);
        assertEquals("okram", vertex.value("name"));
    });
    VertexProperty vertexProperty = vertex.property("name");
    tryCommit(graph, graph -> {
        assertTrue(vertexProperty.isPresent());
        assertEquals("name", vertexProperty.key());
        assertEquals("okram", vertexProperty.value());
        validateCounts(1, 0, 1, 0);
    });

    // now make it a meta property (and thus, force node/relationship creation)
    vertexProperty.property("acl", "private");
    tryCommit(graph, graph -> {
        assertEquals("private", vertexProperty.value("acl"));
        validateCounts(1, 0, 2, 1);
    });

}
 
Example 42
Project: LiteGraph   File: DetachedVertexPropertyTest.java   Source Code and License 5 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.SIMPLE)
public void shouldAttachToGraph() {
    final Vertex v = graph.addVertex();
    final VertexProperty toDetach = v.property(VertexProperty.Cardinality.single, "test", "this");
    final DetachedVertexProperty<?> detached = DetachedFactory.detach(toDetach, true);
    final VertexProperty attached = detached.attach(Attachable.Method.get(graph));

    assertEquals(toDetach, attached);
    assertFalse(attached instanceof DetachedVertexProperty);
}
 
Example 43
Project: LiteGraph   File: DetachedVertexPropertyTest.java   Source Code and License 5 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.SIMPLE)
public void shouldAttachToVertex() {
    final Vertex v = graph.addVertex();
    final VertexProperty toDetach = v.property(VertexProperty.Cardinality.single, "test", "this");
    final DetachedVertexProperty<?> detached = DetachedFactory.detach(toDetach, true);
    final VertexProperty attached = detached.attach(Attachable.Method.get(v));

    assertEquals(toDetach, attached);
    assertEquals(toDetach.getClass(), attached.getClass());
    assertFalse(attached instanceof DetachedVertexProperty);
}
 
Example 44
Project: neo4j-gremlin-bolt   File: Neo4JVertex.java   Source Code and License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
@SuppressWarnings("unchecked")
public <V> Iterator<VertexProperty<V>> properties(String... propertyKeys) {
    Objects.requireNonNull(propertyKeys, "propertyKeys cannot be null");
    // check we have properties with key
    if (!properties.isEmpty()) {
        // no properties in filter
        if (propertyKeys.length == 0) {
            // all properties (return a copy since properties iterator can be modified by calling remove())
            return properties.entrySet().stream()
                .flatMap(entry -> entry.getValue().stream())
                .map(item -> (VertexProperty<V>)item)
                .collect(Collectors.toList())
                .iterator();
        }
        // one property in filter
        if (propertyKeys.length == 1) {
            // get list for key
            Collection<?> list = properties.get(propertyKeys[0]);
            if (list != null) {
                // all properties (return a copy since properties iterator can be modified by calling remove())
                return list.stream()
                    .map(item -> (VertexProperty<V>)item)
                    .collect(Collectors.toList())
                    .iterator();
            }
            // nothing on key
            return Collections.emptyIterator();
        }
        // loop property keys (return a copy since properties iterator can be modified by calling remove())
        return Arrays.stream(propertyKeys)
            .flatMap(key -> ((Collection<?>)properties.getOrDefault(key, Collections.EMPTY_LIST)).stream())
            .map(item -> (VertexProperty<V>)item)
            .collect(Collectors.toList())
            .iterator();
    }
    // nothing
    return Collections.emptyIterator();
}
 
Example 45
Project: bdio   File: ReadGraphContext.java   Source Code and License 5 votes vote down vote up
/**
 * Performs the reduction to a map.
 */
public final Map<StarVertex, Vertex> toMap(Map<StarVertex, Vertex> map, StarVertex baseVertex) {
    Vertex persisted = map.get(baseVertex);
    if (persisted != null) {
        // Update properties
        Iterator<VertexProperty<Object>> properties = baseVertex.properties();
        while (properties.hasNext()) {
            VertexProperty<Object> vp = properties.next();
            persisted.property(vertexFeatures.getCardinality(vp.key()), vp.key(), vp.value());
        }

        // Update edges
        Iterator<Edge> edges = baseVertex.edges(Direction.OUT);
        if (edges.hasNext()) {
            // Worst case scenario. We need to get the old key, which means a linear search...
            for (StarVertex existingUnpersistedVertex : map.keySet()) {
                if (existingUnpersistedVertex.equals(baseVertex)) {
                    edges.forEachRemaining(e -> {
                        existingUnpersistedVertex.addEdge(e.label(), e.inVertex());
                    });
                    break;
                }
            }
        }
    } else {
        // Create the new vertex
        boolean includeId = vertexFeatures.willAllowId(baseVertex.id());
        map.put(baseVertex, graph().addVertex(ElementHelper.getProperties(baseVertex, includeId, true, Collections.emptySet())));
    }

    // Batch commit update or insertion
    batchCommitTx();
    return map;
}
 
Example 46
Project: LiteGraph   File: ReferenceVertexPropertyTest.java   Source Code and License 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
@FeatureRequirementSet(FeatureRequirementSet.Package.SIMPLE)
public void shouldNotSupportRemove() {
    final Vertex v = graph.addVertex();
    final VertexProperty vp = v.property(VertexProperty.Cardinality.single, "test", "this");
    ReferenceFactory.detach(vp).remove();
}
 
Example 47
Project: bdio   File: BlackDuckIoReaderTest.java   Source Code and License 5 votes vote down vote up
@Test
public void readMetadataPartition() throws Exception {
    BdioMetadata metadata = BdioMetadata.createRandomUUID();
    graph.io(BlackDuckIo.build()
            .onGraphTopology(storeMetadataAndIds()
                    .andThen(b -> b.partitionStrategy("_partition", "abc"))))
            .readGraph(BdioTest.zipJsonBytes(metadata.asNamedGraph()));

    Vertex namedGraph = graph.traversal().V().hasLabel(TT.Metadata).next();
    VertexProperty<String> partition = namedGraph.property("_partition");
    assertThat(partition.isPresent()).isTrue();
    assertThat(partition.value()).isEqualTo("abc");
}
 
Example 48
Project: LiteGraph   File: AddPropertyStep.java   Source Code and License 5 votes vote down vote up
public AddPropertyStep(final Traversal.Admin traversal, final VertexProperty.Cardinality cardinality, final Object keyObject, final Object valueObject) {
    super(traversal);
    this.parameters.set(T.key, keyObject);
    this.parameters.set(T.value, valueObject);
    this.cardinality = cardinality;
    this.parameters.integrateTraversals(this);
}
 
Example 49
Project: LiteGraph   File: IoTest.java   Source Code and License 5 votes vote down vote up
/**
 * Note: this is only a very lightweight test of writer/reader encoding. It is known that there are characters
 * which, when written by GraphMLWriter, cause parse errors for GraphMLReader. However, this happens uncommonly
 * enough that is not yet known which characters those are. Only need to execute this test with TinkerGraph
 * or other graphs that support user supplied identifiers.
 */
@Test
@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)
@FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = FEATURE_STRING_VALUES)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = FEATURE_USER_SUPPLIED_IDS)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_STRING_IDS)
public void shouldProperlyEncodeWithGraphML() throws Exception {
    final Vertex v = graph.addVertex(T.id, "1");
    v.property(VertexProperty.Cardinality.single, "text", "\u00E9");

    final GraphMLWriter w = GraphMLWriter.build().create();

    final File f = TestHelper.generateTempFile(this.getClass(), "test", ".txt");
    try (final OutputStream out = new FileOutputStream(f)) {
        w.writeGraph(out, graph);
    }

    validateXmlAgainstGraphMLXsd(f);

    // reusing the same config used for creation of "g".
    final Configuration configuration = graphProvider.newGraphConfiguration("g2", this.getClass(), name.getMethodName(), null);
    graphProvider.clear(configuration);
    final Graph g2 = graphProvider.openTestGraph(configuration);
    final GraphMLReader r = GraphMLReader.build().create();

    try (final InputStream in = new FileInputStream(f)) {
        r.readGraph(in, g2);
    }

    final Vertex v2 = g2.vertices("1").next();
    assertEquals("\u00E9", v2.property("text").value());

    // need to manually close the "g2" instance
    graphProvider.clear(g2, configuration);
}
 
Example 50
Project: LiteGraph   File: DetachedVertexPropertyTest.java   Source Code and License 5 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.SIMPLE)
public void shouldNotConstructNewWithSomethingAlreadyDetached() {
    final Vertex v = graph.addVertex();
    final VertexProperty vp = v.property(VertexProperty.Cardinality.single, "test", "this");
    final DetachedVertexProperty dvp = DetachedFactory.detach(vp, true);
    assertSame(dvp, DetachedFactory.detach(dvp, true));
}
 
Example 51
Project: LiteGraph   File: DetachedVertexPropertyTest.java   Source Code and License 5 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.SIMPLE)
public void shouldConstructDetachedPropertyWithHiddenFromVertex() {
    final Vertex v = graph.addVertex();
    final VertexProperty vp = v.property(VertexProperty.Cardinality.single, "test", "this");
    final DetachedVertexProperty mp = DetachedFactory.detach(vp, true);
    assertEquals("test", mp.key());
    assertEquals("this", mp.value());
    assertEquals(DetachedVertex.class, mp.element().getClass());
}
 
Example 52
Project: LiteGraph   File: VertexWritableTest.java   Source Code and License 5 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.VERTICES_ONLY)
public void shouldConstructVertexWritableWithCorrectByteRepresentation() {
    final StarGraph graph = StarGraph.open();
    final Vertex v = graph.addVertex(T.id, 1, T.label, Vertex.DEFAULT_LABEL, "test", "123");
    v.property(VertexProperty.Cardinality.list, "name", "marko", "acl", "private");
    final VertexWritable vw = byteClone(new VertexWritable(v));

    assertEquals(v.id(), vw.get().id());
    assertEquals(v.label(), vw.get().label());
    assertEquals("123", vw.get().value("test"));
    assertEquals(2, IteratorUtils.count(vw.get().properties()));
    assertEquals("marko", vw.get().value("name"));
    assertEquals("private", vw.get().property("name").value("acl"));
}
 
Example 53
Project: LiteGraph   File: EventStrategyProcessTest.java   Source Code and License 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 shouldTriggerAddVertexPropertyPropertyRemoved() {
    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 vSome = graph.addVertex("some", "thing");
    vSome.property(VertexProperty.Cardinality.single, "that", "thing", "is", "good");
    final GraphTraversalSource gts = create(eventStrategy);
    final Vertex vAny = gts.V().addV().property("any", "thing").next();
    gts.V(vAny).properties("any").property("is", "bad").next();
    gts.V(vAny).properties("any").properties("is").drop().iterate();

    tryCommit(graph, g -> assertEquals(1, IteratorUtils.count(gts.V().has("any", "thing"))));

    assertEquals(1, listener1.addVertexEventRecorded());
    assertEquals(1, listener2.addVertexEventRecorded());
    assertEquals(1, listener2.vertexPropertyPropertyChangedEventRecorded());
    assertEquals(1, listener1.vertexPropertyPropertyChangedEventRecorded());
    assertEquals(1, listener2.vertexPropertyPropertyRemovedEventRecorded());
    assertEquals(1, listener1.vertexPropertyPropertyRemovedEventRecorded());
}
 
Example 54
Project: LiteGraph   File: GryoLiteMessageSerializerV1d0.java   Source Code and License 5 votes vote down vote up
private static GryoMapper.Builder overrideWithLite(final GryoMapper.Builder builder) {
    // override the core graph Elements so as to serialize with "reference" as opposed to "detached"
    builder.addCustom(Edge.class, new EdgeLiteSerializer());
    builder.addCustom(Vertex.class, new VertexLiteSerializer());
    builder.addCustom(VertexProperty.class, new VertexPropertyLiteSerializer());
    builder.addCustom(Property.class, new PropertyLiteSerializer());
    builder.addCustom(Path.class, new PathLiteSerializer());
    return builder;
}
 
Example 55
Project: LiteGraph   File: ComputerGraph.java   Source Code and License 5 votes vote down vote up
@Override
public <V> VertexProperty<V> property(final String key, final V value) {
    if (state.equals(State.MAP_REDUCE))
        throw GraphComputer.Exceptions.vertexPropertiesCanNotBeUpdatedInMapReduce();
    if (!computeKeys.contains(key))
        throw GraphComputer.Exceptions.providedKeyIsNotAnElementComputeKey(key);
    return new ComputerVertexProperty<>(this.getBaseVertex().property(key, value));
}
 
Example 56
Project: LiteGraph   File: ReferenceVertexPropertyTest.java   Source Code and License 5 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.SIMPLE)
public void shouldNotBeEqualsPropertiesAsIdIsDifferent() {
    final Vertex v = graph.addVertex();
    final VertexProperty vp1 = v.property(VertexProperty.Cardinality.single, "test", "this");
    final ReferenceVertexProperty mp1 = ReferenceFactory.detach(vp1);
    final VertexProperty vp2 = v.property(VertexProperty.Cardinality.single, "testing", "this");
    final ReferenceVertexProperty mp2 = ReferenceFactory.detach(vp2);
    assertFalse(mp1.equals(mp2));
}
 
Example 57
Project: LiteGraph   File: TinkerGraphComputerView.java   Source Code and License 5 votes vote down vote up
protected void complete() {
    // remove all transient properties from the vertices
    for (final VertexComputeKey computeKey : this.computeKeys.values()) {
        if (computeKey.isTransient()) {
            final List<VertexProperty<?>> toRemove = this.computeProperties.values().stream().flatMap(map -> map.getOrDefault(computeKey.getKey(), Collections.emptyList()).stream()).collect(Collectors.toList());
            toRemove.forEach(VertexProperty::remove);
        }
    }
}
 
Example 58
Project: LiteGraph   File: CommunityGeneratorTest.java   Source Code and License 5 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.SIMPLE)
public void shouldProcessVerticesEdges() {
    final Distribution dist = new NormalDistribution(2);
    final CommunityGenerator generator = CommunityGenerator.build(graph)
            .label("knows")
            .edgeProcessor(e -> e.<String>property("data", "test"))
            .vertexProcessor((v, m) -> {
                m.forEach(v::property);
                v.property(VertexProperty.Cardinality.single, "test", "data");
            })
            .communityDistribution(dist)
            .degreeDistribution(dist)
            .crossCommunityPercentage(0.0d)
            .expectedNumCommunities(2)
            .expectedNumEdges(1000).create();
    final long edgesGenerated = generator.generate();
    assertTrue(edgesGenerated > 0);
    tryCommit(graph, graph -> {
        assertEquals(new Long(edgesGenerated), new Long(IteratorUtils.count(graph.edges())));
        assertTrue(IteratorUtils.count(graph.vertices()) > 0);
        assertTrue(IteratorUtils.stream(graph.edges()).allMatch(e -> e.value("data").equals("test")));
        assertTrue(IteratorUtils.stream(graph.vertices()).allMatch(
                v -> v.value("test").equals("data") && v.property("communityIndex").isPresent()
        ));
    });
}
 
Example 59
Project: LiteGraph   File: TinkerGraphIdManagerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldUseIdManagerToCoerceTypes() {
    final Graph graph = TinkerGraph.open(idManagerConfig);
    final Vertex v = graph.addVertex(T.id, vertexIdValue);
    final VertexProperty vp = v.property(VertexProperty.Cardinality.single, "test", "value", T.id, vertexPropertyIdValue);
    final Edge e = v.addEdge("self", v, T.id, edgeIdValue);

    assertEquals(vertexId, v.id());
    assertEquals(edgeId, e.id());
    assertEquals(vertexPropertyId, vp.id());
}
 
Example 60
Project: LiteGraph   File: ElementHelper.java   Source Code and License 5 votes vote down vote up
/**
 * Assign key/value pairs as properties to a {@link org.apache.tinkerpop.gremlin.structure.Vertex}.
 * If the value of {@link T#id} or {@link T#label} is in the set of pairs, then they are ignored.
 *
 * @param vertex            the vertex to attach the properties to
 * @param cardinality       the cardinality of the key value pair settings
 * @param propertyKeyValues the key/value pairs to assign to the {@code element}
 * @throws ClassCastException       if the value of the key is not a {@link String}
 * @throws IllegalArgumentException if the value of {@code element} is null
 */
public static void attachProperties(final Vertex vertex, final VertexProperty.Cardinality cardinality, final Object... propertyKeyValues) {

    if (null == vertex) {
        throw Graph.Exceptions.argumentCanNotBeNull("vertex");
    }
    //System.out.println("property number="+propertyKeyValues.length);
    for (int i = 0; i < propertyKeyValues.length; i = i + 2) {
        if (!propertyKeyValues[i].equals(T.id) && !propertyKeyValues[i].equals(T.label)) {
            //System.out.println("cardinality="+cardinality+"\tkey="+propertyKeyValues[i]+"\tvalue="+propertyKeyValues[i+1]);
            vertex.property(cardinality, (String) propertyKeyValues[i], propertyKeyValues[i + 1]);
        }
    }
}