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());
    }
}