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

The following examples show how to use org.apache.tinkerpop.gremlin.structure.VertexProperty. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PageRankVertexProgram.java    From titan1withtp3.1 with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(Vertex vertex, Messenger<Double> messenger, Memory memory) {
    if (memory.isInitialIteration()) {
        messenger.sendMessage(inE, 1D);
    } else if (1 == memory.getIteration()) {
        double initialPageRank = 1D / vertexCount;
        double edgeCount = IteratorUtils.stream(messenger.receiveMessages()).reduce(0D, (a, b) -> a + b);
        vertex.property(VertexProperty.Cardinality.single, PAGE_RANK, initialPageRank);
        vertex.property(VertexProperty.Cardinality.single, OUTGOING_EDGE_COUNT, edgeCount);
        messenger.sendMessage(outE, initialPageRank / edgeCount);
    } else {
        double newPageRank = IteratorUtils.stream(messenger.receiveMessages()).reduce(0D, (a, b) -> a + b);
        newPageRank =  (dampingFactor * newPageRank) + ((1D - dampingFactor) / vertexCount);
        vertex.property(VertexProperty.Cardinality.single, PAGE_RANK, newPageRank);
        messenger.sendMessage(outE, newPageRank / vertex.<Double>value(OUTGOING_EDGE_COUNT));
    }
}
 
Example #2
Source File: TinkerGraph.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
/**
 * An empty private constructor that initializes {@link TinkerGraph}.
 */
private TinkerGraph(final Configuration configuration) {
    this.configuration = configuration;
    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()));
    allowNullPropertyValues = configuration.getBoolean(GREMLIN_TINKERGRAPH_ALLOW_NULL_PROPERTY_VALUES, false);

    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 #3
Source File: TinkerGraphProvider.java    From tinkergraph-gremlin with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Object> getBaseConfiguration(final String graphName, final Class<?> test, final String testMethodName,
                                                final LoadGraphWith.GraphData loadGraphWith) {
    final TinkerGraph.DefaultIdManager idManager = selectIdMakerFromGraphData(loadGraphWith);
    final String idMaker = (idManager.equals(TinkerGraph.DefaultIdManager.ANY) ? selectIdMakerFromTest(test, testMethodName) : idManager).name();
    return new HashMap<String, Object>() {{
        put(Graph.GRAPH, TinkerGraph.class.getName());
        put(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_ID_MANAGER, idMaker);
        put(TinkerGraph.GREMLIN_TINKERGRAPH_EDGE_ID_MANAGER, idMaker);
        put(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_PROPERTY_ID_MANAGER, idMaker);
        if (requiresListCardinalityAsDefault(loadGraphWith, test, testMethodName))
            put(TinkerGraph.GREMLIN_TINKERGRAPH_DEFAULT_VERTEX_PROPERTY_CARDINALITY, VertexProperty.Cardinality.list.name());
        if (requiresPersistence(test, testMethodName)) {
            put(TinkerGraph.GREMLIN_TINKERGRAPH_GRAPH_FORMAT, "gryo");
            final File tempDir = TestHelper.makeTestDataPath(test, "temp");
            put(TinkerGraph.GREMLIN_TINKERGRAPH_GRAPH_LOCATION,
                    tempDir.getAbsolutePath() + File.separator + testMethodName + ".kryo");
        }
    }};
}
 
Example #4
Source File: SerializerTestVertex.java    From tinkergraph-gremlin with Apache License 2.0 6 votes vote down vote up
@Override
protected <V> VertexProperty<V> updateSpecificProperty(
  VertexProperty.Cardinality cardinality, String key, V value) {
    if (STRING_PROPERTY.equals(key)) {
        this.stringProperty = (String) value;
    } else if (STRING_LIST_PROPERTY.equals(key)) {
        if (value instanceof List) {
            this.stringListProperty = (List) value;
        } else {
            if (this.stringListProperty == null) this.stringListProperty = new ArrayList<>();
            this.stringListProperty.add((String) value);
        }
    } else if (INT_PROPERTY.equals(key)) {
        this.intProperty = (Integer) value;
    } else if (INT_LIST_PROPERTY.equals(key)) {
        if (value instanceof List) {
            this.intListProperty = (List) value;
        } else {
            if (this.intListProperty == null) this.intListProperty = new ArrayList<>();
            this.intListProperty.add((Integer) value);
        }
    } else {
        throw new RuntimeException("property with key=" + key + " not (yet) supported by " + this.getClass().getName());
    }
    return property(key);
}
 
Example #5
Source File: DatabaseFixer.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
private void addMissingVertexVersions(Vertex vertex) {
  int rev = vertex.value("rev");
  if (rev > 1) {
    Iterator<Vertex> previousVersions = vertex.vertices(Direction.IN, "VERSION_OF");
    if (previousVersions.hasNext()) {
      addMissingVertexVersions(previousVersions.next());
    } else {
      Vertex duplicate = vertex.graph().addVertex();
      duplicate.addEdge("VERSION_OF", vertex);
      for (Iterator<VertexProperty<Object>> properties = vertex.properties(); properties.hasNext(); ) {
        VertexProperty<Object> property = properties.next();
        if (Objects.equals(property.key(), "isLatest")) {
          duplicate.property(property.key(), false);
        } else if (Objects.equals(property.key(), "rev")) {
          duplicate.property(property.key(), rev - 1);
        } else if (Objects.equals(property.key(), "modified")) {
          duplicate.property("modified", vertex.value("created"));
        } else {
          duplicate.property(property.key(), property.value());
        }
      }
      addMissingVertexVersions(duplicate);
    }
  }
}
 
Example #6
Source File: TinkerGraphProvider.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Object> getBaseConfiguration(final String graphName, final Class<?> test, final String testMethodName,
                                                final LoadGraphWith.GraphData loadGraphWith) {
    final TinkerGraph.DefaultIdManager idManager = selectIdMakerFromGraphData(loadGraphWith);
    final String idMaker = (idManager.equals(TinkerGraph.DefaultIdManager.ANY) ? selectIdMakerFromTest(test, testMethodName) : idManager).name();
    return new HashMap<String, Object>() {{
        put(Graph.GRAPH, TinkerGraph.class.getName());
        put(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_ID_MANAGER, idMaker);
        put(TinkerGraph.GREMLIN_TINKERGRAPH_EDGE_ID_MANAGER, idMaker);
        put(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_PROPERTY_ID_MANAGER, idMaker);
        if (requiresListCardinalityAsDefault(loadGraphWith, test, testMethodName))
            put(TinkerGraph.GREMLIN_TINKERGRAPH_DEFAULT_VERTEX_PROPERTY_CARDINALITY, VertexProperty.Cardinality.list.name());
        if (requiresPersistence(test, testMethodName)) {
            put(TinkerGraph.GREMLIN_TINKERGRAPH_GRAPH_FORMAT, "gryo");
            put(TinkerGraph.GREMLIN_TINKERGRAPH_GRAPH_LOCATION,TestHelper.makeTestDataFile(test, "temp", testMethodName + ".kryo"));
        }
    }};
}
 
Example #7
Source File: Song.java    From tinkergraph-gremlin with Apache License 2.0 6 votes vote down vote up
@Override
protected <V> VertexProperty<V> updateSpecificProperty(
  VertexProperty.Cardinality cardinality, String key, V value) {
    if (NAME.equals(key)) {
        this.name = (String) value;
    } else if (SONG_TYPE.equals(key)) {
        this.songType = (String) value;
    } else if (PERFORMANCES.equals(key)) {
        this.performances = ((Integer) value);
    } else if (TEST_PROP.equals(key)) {
        this.testProp = (int[]) value;
    } else {
        throw new RuntimeException("property with key=" + key + " not (yet) supported by " + this.getClass().getName());
    }
    return property(key);
}
 
Example #8
Source File: PartitionStrategy.java    From tinkerpop with Apache License 2.0 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 #9
Source File: ShortestPathVertexProgram.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
private void updateHaltedTraversers(final Vertex vertex, final Memory memory) {
    if (isStartVertex(vertex)) {
        final List<Path> paths = memory.get(SHORTEST_PATHS);
        if (vertex.property(TraversalVertexProgram.HALTED_TRAVERSERS).isPresent()) {
            // replace the current set of halted traversers with new new traversers that hold the shortest paths
            // found for this vertex
            final TraverserSet<Vertex> haltedTraversers = vertex.value(TraversalVertexProgram.HALTED_TRAVERSERS);
            final TraverserSet<Path> newHaltedTraversers = new TraverserSet<>();
            for (final Traverser.Admin<Vertex> traverser : haltedTraversers) {
                final Vertex v = traverser.get();
                for (final Path path : paths) {
                    if (path.get(0).equals(v)) {
                        newHaltedTraversers.add(traverser.split(path, this.programStep));
                    }
                }
            }
            vertex.property(VertexProperty.Cardinality.single, TraversalVertexProgram.HALTED_TRAVERSERS, newHaltedTraversers);
        }
    }
}
 
Example #10
Source File: TinkerGraphGraphSONSerializerV2d0Test.java    From tinkerpop with Apache License 2.0 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 #11
Source File: NodeTest.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Before
public void setUp() {
  mockDocumentVertex = mock(Vertex.class);

  VertexProperty timIdProperty = mock(VertexProperty.class);
  VertexProperty typesProperty = mock(VertexProperty.class);

  given(timIdProperty.value()).willReturn(TIM_ID);
  given(typesProperty.value()).willReturn("[\"" + TYPE +  "\"]");

  given(mockDocumentVertex.property("tim_id")).willReturn(timIdProperty);
  given(mockDocumentVertex.property("types")).willReturn(typesProperty);
  given(mockDocumentVertex.value("document_title")).willReturn(DOCUMENT_LABEL);
  given(mockDocumentVertex.keys()).willReturn(Sets.newHashSet("document_title"));
}
 
Example #12
Source File: SchemaDefine.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
public static <T extends Entity> T fromVertex(Vertex vertex, T entity) {
    E.checkArgument(vertex.label().equals(entity.label()),
                    "Illegal vertex label '%s' for entity '%s'",
                    vertex.label(), entity.label());
    entity.id((Id) vertex.id());
    for (Iterator<VertexProperty<Object>> iter = vertex.properties();
         iter.hasNext();) {
        VertexProperty<Object> prop = iter.next();
        entity.property(prop.key(), prop.value());
    }
    return entity;
}
 
Example #13
Source File: D3GraphTest.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
private Vertex mockVertex(String timId, String type, String labelPropertyKey, String label) {
  Vertex mockDocumentVertex = mock(Vertex.class);

  VertexProperty timIdProperty = mock(VertexProperty.class);
  VertexProperty typesProperty = mock(VertexProperty.class);

  given(timIdProperty.value()).willReturn(timId);
  given(typesProperty.value()).willReturn("[\"" + type +  "\"]");

  given(mockDocumentVertex.property("tim_id")).willReturn(timIdProperty);
  given(mockDocumentVertex.property("types")).willReturn(typesProperty);
  given(mockDocumentVertex.value(labelPropertyKey)).willReturn(label);
  given(mockDocumentVertex.keys()).willReturn(Sets.newHashSet(labelPropertyKey));
  return mockDocumentVertex;
}
 
Example #14
Source File: ReferenceVertexPropertyTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.SIMPLE)
public void shouldAttachToVertex() {
    final Vertex v = graph.addVertex();
    final VertexProperty toReference = v.property(VertexProperty.Cardinality.single, "test", "this");
    final ReferenceVertexProperty<?> rvp = ReferenceFactory.detach(toReference);
    final VertexProperty referenced = rvp.attach(Attachable.Method.get(v));

    assertEquals(toReference, referenced);
    assertEquals(toReference.getClass(), referenced.getClass());
    assertFalse(referenced instanceof ReferenceVertexProperty);
}
 
Example #15
Source File: BlazeGraph.java    From tinkerpop3 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Iterate properties on a BlazeVertex. Return type 
 * strengthened from normal iterator. You MUST close this iterator when 
 * finished.
 * 
 * @see Vertex#properties(String...)
 */
<V> CloseableIterator<VertexProperty<V>> properties(
        final BlazeVertex vertex, final String... keys) {
    final List<URI> uris = 
            Stream.of(keys).map(vf::propertyURI).collect(toList());
    final String queryStr = sparql.vertexProperties(vertex, uris);
    
    final Stream<VertexProperty<V>> stream = _select(queryStr, nextQueryId())
            .map(transforms.<V>vertexProperty(vertex)); 
    return CloseableIterator.of(stream);
}
 
Example #16
Source File: ElementHelperTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test(expected = ClassCastException.class)
public void shouldFailTryingToAttachPropertiesWithCardinalityNonStringKey() {
    final Element mockElement = mock(Vertex.class);
    final Graph mockGraph = mock(Graph.class);
    final Graph.Features mockGraphFeatures = mock(Graph.Features.class);
    final Graph.Features.VertexFeatures mockVertexFeatures = mock(Graph.Features.VertexFeatures.class);
    final Graph.Features.VertexPropertyFeatures mockVertexPropertyFeatures = mock(Graph.Features.VertexPropertyFeatures.class);
    when(mockElement.graph()).thenReturn(mockGraph);
    when(mockGraph.features()).thenReturn(mockGraphFeatures);
    when(mockGraphFeatures.vertex()).thenReturn(mockVertexFeatures);
    when(mockVertexFeatures.properties()).thenReturn(mockVertexPropertyFeatures);
    when(mockVertexPropertyFeatures.supportsNullPropertyValues()).thenReturn(true);
    ElementHelper.attachProperties(mockElement, VertexProperty.Cardinality.single, "test", 123, 321, "test");
}
 
Example #17
Source File: DocumentGraphConsumerTest.java    From baleen with Apache License 2.0 5 votes vote down vote up
@Test
public void testDocumentGraphConsumerCanCopeWithSameRelationExternalId()
    throws AnalysisEngineProcessException, ResourceInitializationException, IOException,
        URISyntaxException {

  properties.setProperty(
      TinkerGraph.GREMLIN_TINKERGRAPH_DEFAULT_VERTEX_PROPERTY_CARDINALITY,
      VertexProperty.Cardinality.list.name());
  writeProperties();

  Person p1 = Annotations.createPerson(jCas, 0, 10, "source");
  Person p2 = Annotations.createPerson(jCas, 10, 20, "target");

  Relation r1 = new Relation(jCas);
  r1.setBegin(0);
  r1.setEnd(4);
  r1.setValue("test");
  r1.setSource(p1);
  r1.setTarget(p2);
  r1.addToIndexes(jCas);

  Relation r2 = new Relation(jCas);
  r2.setBegin(0);
  r2.setEnd(4);
  r2.setValue("test");
  r2.setSource(p1);
  r2.setTarget(p2);
  r2.addToIndexes(jCas);

  assertEquals(r1.getExternalId(), r2.getExternalId());

  processJCas(
      DocumentGraphConsumer.PARAM_GRAPH_CONFIG,
      propertiesFile.getAbsolutePath(),
      DocumentGraphConsumer.PARAM_OUTPUT_RELATIONS_AS_LINKS,
      true);
  Graph graph = GraphFactory.open(propertiesFile.getAbsolutePath());

  assertTrue(graph.traversal().E(r1.getExternalId()).hasNext());
}
 
Example #18
Source File: PostProcessManager.java    From atlas with Apache License 2.0 5 votes vote down vote up
@Override
public void processItem(Object vertexId) {
    batchCounter++;
    counter++;

    try {
        Vertex         vertex           = bulkLoadGraph.traversal().V(vertexId).next();
        boolean        isTypeVertex     = vertex.property(TYPENAME_PROPERTY_KEY).isPresent();
        VertexProperty typeNameProperty = vertex.property(ENTITY_TYPE_PROPERTY_KEY);

        if (!isTypeVertex && typeNameProperty.isPresent()) {
            String typeName = (String) typeNameProperty.value();
            if (!typePropertiesMap.containsKey(typeName)) {
                return;
            }

            Map<String, List<String>> collectionTypeProperties = typePropertiesMap.get(typeName);
            for (String key : nonPrimitiveCategoryKeys) {
                if (!collectionTypeProperties.containsKey(key)) {
                    continue;
                }

                for(String propertyName : collectionTypeProperties.get(key)) {
                    processor.process(vertex, typeName, propertyName);
                }
            }
        }

        commitBatch();
    } catch (Exception ex) {
        LOG.error("processItem: v[{}] error!", vertexId, ex);
    }
}
 
Example #19
Source File: AbstractRdfEntityGraphConsumer.java    From baleen with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private Object addNodeToModel(OntModel model, Vertex v) {
  try {
    String label = v.label();
    if (EVENT.equals(label)) {
      return addIndividual(model, v, EVENT);
    }
    if (ENTITY.equals(label)) {
      Iterator<VertexProperty<Object>> properties = v.properties("type");
      List<?> types =
          Lists.newArrayList(properties).stream()
              .filter(VertexProperty::isPresent)
              .map(VertexProperty::value)
              .collect(Collectors.toList());
      Optional<String> aggregate = mode.aggregate((List<String>) types);
      if (aggregate.isPresent()) {
        return addIndividual(model, v, aggregate.get());
      }

      getMonitor().warn("Not type information for {} using entity", v);
      return addIndividual(model, v, ENTITY);
    }
    getMonitor().warn("Unrecognized Label {}", label);
  } catch (BaleenException e) {
    getMonitor().warn("Error adding node {} - {} ", v, e.getMessage());
  }
  return null;
}
 
Example #20
Source File: TestBasicOperations.java    From tinkerpop3 with GNU General Public License v2.0 5 votes vote down vote up
public void testCardinalityList() throws Exception {
    
    final BlazeVertex a = graph.addVertex(T.id, "a");
    a.property(Cardinality.list, "foo", "bar", "acl", "public");
    a.property(Cardinality.list, "foo", "baz", "acl", "public");
    a.property(Cardinality.list, "foo", "bar", "acl", "private");
    graph.tx().commit();

    log.debug(() -> "\n"+graph.dumpStore());

    final List<VertexProperty<Object>> vps = a.properties("foo").collect();
    log.debug(() -> vps.stream());
    assertEquals(3, vps.size());
    
    vps.get(0).remove();
    graph.tx().commit();
    log.debug(() -> "\n"+graph.dumpStore());
    assertEquals(2, a.properties().count());
    
    vps.get(1).remove();
    graph.tx().commit();
    log.debug(() -> "\n"+graph.dumpStore());
    assertEquals(1, a.properties().count());
    
    a.remove();
    graph.tx().commit();
    log.debug(() -> "\n"+graph.dumpStore());
    assertEquals(0, a.properties().count());
    
}
 
Example #21
Source File: PreloadedVertex.java    From titan1withtp3.1 with Apache License 2.0 5 votes vote down vote up
@Override
public <V> Iterator<VertexProperty<V>> properties(String... keys) {
    accessCheck.accessProperties();
    if (mixin == NO_MIXIN) return super.properties(keys);
    if (keys != null && keys.length > 0) {
        int count = 0;
        for (int i = 0; i < keys.length; i++) if (mixin.supports(keys[i])) count++;
        if (count == 0) return super.properties(keys);
        else if (count == keys.length) return mixin.properties(keys);
    }
    return (Iterator) com.google.common.collect.Iterators.concat(super.properties(keys), mixin.properties(keys));
}
 
Example #22
Source File: TinkerGraphComputerView.java    From tinkergraph-gremlin with Apache License 2.0 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 #23
Source File: StarGraph.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
public Vertex addVertex(final Object... keyValues) {
    if (null == this.starVertex) {
        ElementHelper.legalPropertyKeyValueArray(keyValues);
        this.starVertex = new StarVertex(ElementHelper.getIdValue(keyValues).orElse(this.nextId()), ElementHelper.getLabelValue(keyValues).orElse(Vertex.DEFAULT_LABEL));
        ElementHelper.attachProperties(this.starVertex, VertexProperty.Cardinality.list, keyValues); // TODO: is this smart? I say no... cause vertex property ids are not preserved.
        return this.starVertex;
    } else
        return new StarAdjacentVertex(ElementHelper.getIdValue(keyValues).orElse(this.nextId()));
}
 
Example #24
Source File: GraphSONSerializersV3d0.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(final VertexProperty property, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider)
        throws IOException {
    jsonGenerator.writeStartObject();

    jsonGenerator.writeObjectField(GraphSONTokens.ID, property.id());
    jsonGenerator.writeObjectField(GraphSONTokens.VALUE, property.value());
    if (includeLabel)
        jsonGenerator.writeStringField(GraphSONTokens.LABEL, property.label());
    tryWriteMetaProperties(property, jsonGenerator, normalize);

    jsonGenerator.writeEndObject();
}
 
Example #25
Source File: EventStrategyProcessTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.VERTICES_ONLY)
public void shouldReferenceVertexPropertyWhenChanged() {
    final AtomicBoolean triggered = new AtomicBoolean(false);
    final Vertex v = graph.addVertex();
    final String label = v.label();
    final Object id = v.id();
    v.property("to-change", "blah");

    final MutationListener listener = new AbstractMutationListener() {


        @Override
        public void vertexPropertyChanged(final Vertex element, final VertexProperty oldValue, final Object setValue, final Object... vertexPropertyKeyValues) {
            assertThat(element, instanceOf(ReferenceVertex.class));
            assertEquals(label, element.label());
            assertEquals(id, element.id());
            assertEquals("to-change", oldValue.key());
            assertEquals("blah", oldValue.value());
            assertEquals("dah", setValue);
            triggered.set(true);
        }
    };
    final EventStrategy.Builder builder = EventStrategy.build().addListener(listener).detach(EventStrategy.Detachment.REFERENCE);

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

    final EventStrategy eventStrategy = builder.create();
    final GraphTraversalSource gts = create(eventStrategy);

    gts.V(v).property(VertexProperty.Cardinality.single, "to-change", "dah").iterate();
    tryCommit(graph);

    assertEquals(1, IteratorUtils.count(g.V(v).properties()));
    assertThat(triggered.get(), is(true));
}
 
Example #26
Source File: Artist.java    From tinkergraph-gremlin with Apache License 2.0 5 votes vote down vote up
@Override
protected <V> VertexProperty<V> updateSpecificProperty(
  VertexProperty.Cardinality cardinality, String key, V value) {
    if (NAME.equals(key)) {
        this.name = (String) value;
    } else {
        throw new RuntimeException("property with key=" + key + " not (yet) supported by " + this.getClass().getName());
    }
    return property(key);
}
 
Example #27
Source File: EventStrategyProcessTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.VERTICES_ONLY)
public void shouldUseActualVertexPropertyWhenRemoved() {
    final AtomicBoolean triggered = new AtomicBoolean(false);
    final Vertex v = graph.addVertex();
    final VertexProperty vp = v.property("to-remove","blah");
    final String label = vp.label();
    final Object value = vp.value();
    final VertexProperty vpToKeep = v.property("to-keep","dah");

    final MutationListener listener = new AbstractMutationListener() {
        @Override
        public void vertexPropertyRemoved(final VertexProperty element) {
            assertEquals(vp, element);
            assertEquals(label, element.label());
            assertEquals(value, element.value());
            triggered.set(true);
        }
    };
    final EventStrategy.Builder builder = EventStrategy.build().addListener(listener).detach(EventStrategy.Detachment.REFERENCE);

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

    final EventStrategy eventStrategy = builder.create();
    final GraphTraversalSource gts = create(eventStrategy);

    gts.V(v).properties("to-remove").drop().iterate();
    tryCommit(graph);

    assertEquals(1, IteratorUtils.count(g.V(v).properties()));
    assertEquals(vpToKeep.value(), g.V(v).values("to-keep").next());
    assertThat(triggered.get(), is(true));
}
 
Example #28
Source File: DetachedVertex.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
public DetachedVertex(final Object id, final String label, final Map<String, Object> properties) {
    super(id, label);
    if (properties != null && !properties.isEmpty()) {
        this.properties = new HashMap<>();
        properties.entrySet().iterator().forEachRemaining(entry ->
            this.properties.put(entry.getKey(), IteratorUtils.<Property>list(IteratorUtils.map(((List<Object>) entry.getValue()).iterator(),
                    m -> VertexProperty.class.isAssignableFrom(m.getClass())
                            ? (VertexProperty) m
                            : new DetachedVertexProperty<>(((Map) m).get(ID), entry.getKey(), ((Map) m).get(VALUE), (Map<String, Object>) ((Map) m).getOrDefault(PROPERTIES, new HashMap<>()), this)))));
    }
}
 
Example #29
Source File: ValueTraversalTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldWorkOnVertexWithMissingKey() {
    final ValueTraversal<Vertex, Integer> t = new ValueTraversal<>("age");
    final Vertex v = mock(Vertex.class);
    when(v.property("age")).thenReturn(VertexProperty.empty());
    t.addStart(new B_O_Traverser<>(v, 1).asAdmin());
    assertNull(t.next());
}
 
Example #30
Source File: SerializerTestVertex.java    From tinkergraph-gremlin with Apache License 2.0 5 votes vote down vote up
@Override
protected <V> Iterator<VertexProperty<V>> specificProperties(String key) {
    final VertexProperty<V> ret;
    if (STRING_PROPERTY.equals(key) && stringProperty != null) {
        return IteratorUtils.of(new SpecializedVertexProperty(this, key, stringProperty));
    } else if (key == STRING_LIST_PROPERTY && stringListProperty != null) {
        return IteratorUtils.of(new SpecializedVertexProperty(this, key, stringListProperty));
    } else if (key == INT_PROPERTY && intProperty != null) {
        return IteratorUtils.of(new SpecializedVertexProperty(this, key, intProperty));
    } else if (key == INT_LIST_PROPERTY && intListProperty != null) {
        return IteratorUtils.of(new SpecializedVertexProperty(this, key, intListProperty));
    } else {
        return Collections.emptyIterator();
    }
}