Java Code Examples for org.apache.tinkerpop.gremlin.structure.Vertex#properties()

The following examples show how to use org.apache.tinkerpop.gremlin.structure.Vertex#properties() . 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: Attachable.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
public static Property createProperty(final Attachable<Property> attachableProperty, final Graph hostGraph) {
    final Property baseProperty = attachableProperty.get();
    final Element baseElement = baseProperty.element();
    if (baseElement instanceof Vertex) {
        return Method.createVertexProperty((Attachable) attachableProperty, hostGraph);
    } else if (baseElement instanceof Edge) {
        final Iterator<Edge> edgeIterator = hostGraph.edges(baseElement.id());
        if (edgeIterator.hasNext())
            return edgeIterator.next().property(baseProperty.key(), baseProperty.value());
        throw new IllegalStateException("Could not find edge to create the attachable property on");
    } else { // vertex property
        final Iterator<Vertex> vertexIterator = hostGraph.vertices(((VertexProperty) baseElement).element().id());
        if (vertexIterator.hasNext()) {
            final Vertex vertex = vertexIterator.next();
            final Iterator<VertexProperty<Object>> vertexPropertyIterator = vertex.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 2
Source File: VertexDuplicator.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
public static Vertex duplicateVertex(GraphTraversalSource traversal, Vertex vertex, IndexHandler indexHandler) {
  Vertex duplicate = traversal.addV().next();

  for (Iterator<VertexProperty<Object>> properties = vertex.properties(); properties.hasNext(); ) {
    VertexProperty<Object> property = properties.next();
    duplicate.property(property.key(), property.value());
  }

  for (String label : ((Neo4jVertex) vertex).labels()) {
    ((Neo4jVertex) duplicate).addLabel(label);
  }

  moveIncomingEdges(vertex, duplicate, indexHandler);
  moveOutgoingEdges(vertex, duplicate, indexHandler);

  vertex.property(IS_LATEST, false);
  duplicate.property(IS_LATEST, true);
  vertex.addEdge(VERSION_OF, duplicate);
  return duplicate;
}
 
Example 3
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 4
Source File: AbstractCompatibilityTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
protected void assertVertex(final Vertex expected, final Vertex actual) {
    assertEquals(expected.id(), actual.id());
    assertEquals(expected.label(), actual.label());

    if (!(getCompatibility() instanceof GraphBinaryCompatibility)) {
        assertEquals(IteratorUtils.count(expected.properties()), IteratorUtils.count(actual.properties()));
        for (String k : expected.keys()) {
            final Iterator<VertexProperty<Object>> expectedVps = expected.properties(k);
            final List<VertexProperty<Object>> actualVps = IteratorUtils.list(actual.properties(k));
            while (expectedVps.hasNext()) {
                final VertexProperty expectedVp = expectedVps.next();
                final VertexProperty<Object> found = actualVps.stream()
                        .filter(vp -> vp.id().equals(expectedVp.id()))
                        .findFirst()
                        .orElseThrow(() -> new RuntimeException("Could not find VertexProperty for " + expectedVp.id()));
                assertVertexProperty(expectedVp, found);
            }
        }
    }
}
 
Example 5
Source File: GryoSerializersV3d0.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
public <O extends OutputShim> void write(final KryoShim<?, O> kryo, final O output, final Vertex vertex) {
    kryo.writeClassAndObject(output, vertex.id());
    output.writeString(vertex.label());

    final Iterator<? extends VertexProperty> properties = vertex.properties();
    output.writeBoolean(properties.hasNext());
    while (properties.hasNext()) {
        final VertexProperty vp = properties.next();
        kryo.writeClassAndObject(output, vp.id());
        output.writeString(vp.label());
        kryo.writeClassAndObject(output, vp.value());

        if (vp instanceof DetachedVertexProperty || (vertex.graph().features().vertex().supportsMetaProperties())) {
            writeElementProperties(kryo, output, vp);
        } else {
            output.writeBoolean(false);
        }

        output.writeBoolean(properties.hasNext());
    }
}
 
Example 6
Source File: Attachable.java    From tinkerpop with Apache License 2.0 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 7
Source File: DetachedVertex.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
protected DetachedVertex(final Vertex vertex, final boolean withProperties) {
    super(vertex);

    // only serialize properties if requested, and there are meta properties present. this prevents unnecessary
    // object creation of a new HashMap of a new HashMap which will just be empty.  it will use
    // Collections.emptyMap() by default
    if (withProperties) {
        final Iterator<VertexProperty<Object>> propertyIterator = vertex.properties();
        if (propertyIterator.hasNext()) {
            this.properties = new HashMap<>();
            propertyIterator.forEachRemaining(property -> {
                final List<Property> list = this.properties.getOrDefault(property.key(), new ArrayList<>());
                list.add(DetachedFactory.detach(property, true));
                this.properties.put(property.key(), list);
            });
        }
    }
}
 
Example 8
Source File: ElementHelper.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
/**
 * This is a helper method for dealing with vertex property cardinality and typically used in {@link Vertex#property(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 9
Source File: MainGraphConnectorHelper.java    From egeria with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve all properties from the db and return the ones that match the whitelist. This will filter out irrelevant
 * properties that should not be returned to a UI.
 *
 * @param originalVertex
 * @return
 */
private Map<String, String> retrieveProperties(Vertex originalVertex) {
    Map<String, String> newNodeProperties = new HashMap<>();
    Iterator originalProperties = originalVertex.properties();
    while (originalProperties.hasNext()) {
        Property originalProperty = (Property) originalProperties.next();
        if (immutableReturnedPropertiesWhiteList.contains(originalProperty.key())) {
            String newPropertyKey = originalProperty.key().
                    replace(PROPERTY_KEY_PREFIX_VERTEX_INSTANCE_PROPERTY, "").
                    replace(PROPERTY_KEY_PREFIX_ELEMENT, "");

            String newPropertyValue = originalProperty.value().toString();
            newNodeProperties.put(newPropertyKey, newPropertyValue);
        }
    }
    return newNodeProperties;
}
 
Example 10
Source File: HugeTask.java    From hugegraph with Apache License 2.0 6 votes vote down vote up
public static <V> HugeTask<V> fromVertex(Vertex vertex) {
    String callableName = vertex.value(P.CALLABLE);
    TaskCallable<V> callable;
    try {
        callable = TaskCallable.fromClass(callableName);
    } catch (Exception e) {
        callable = TaskCallable.empty(e);
    }

    HugeTask<V> task = new HugeTask<>((Id) vertex.id(), null, callable);
    for (Iterator<VertexProperty<Object>> iter = vertex.properties();
         iter.hasNext();) {
        VertexProperty<Object> prop = iter.next();
        task.property(prop.key(), prop.value());
    }
    return task;
}
 
Example 11
Source File: Attachable.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
public static Optional<VertexProperty> getVertexProperty(final Attachable<VertexProperty> attachableVertexProperty, final Vertex hostVertex) {
    final VertexProperty baseVertexProperty = attachableVertexProperty.get();
    final Iterator<VertexProperty<Object>> vertexPropertyIterator = hostVertex.properties(baseVertexProperty.key());
    while (vertexPropertyIterator.hasNext()) {
        final VertexProperty vertexProperty = vertexPropertyIterator.next();
        if (ElementHelper.areEqual(vertexProperty, baseVertexProperty))
            return Optional.of(vertexProperty);
    }
    return Optional.empty();
}
 
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: 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 14
Source File: GraphSONSerializersV1d0.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
private void writeProperties(final Vertex vertex, final JsonGenerator jsonGenerator,
                                    final SerializerProvider serializerProvider, final TypeSerializer typeSerializer) throws IOException {
    jsonGenerator.writeObjectFieldStart(GraphSONTokens.PROPERTIES);
    if (typeSerializer != null) jsonGenerator.writeStringField(GraphSONTokens.CLASS, HashMap.class.getName());

    final List<String> keys = normalize ?
            IteratorUtils.list(vertex.keys().iterator(), Comparator.naturalOrder()) : new ArrayList<>(vertex.keys());
    for (String key : keys) {
        final Iterator<VertexProperty<Object>> vertexProperties = normalize ?
                IteratorUtils.list(vertex.properties(key), Comparators.PROPERTY_COMPARATOR).iterator() : vertex.properties(key);

        if (vertexProperties.hasNext()) {
            jsonGenerator.writeArrayFieldStart(key);
            if (typeSerializer != null) {
                jsonGenerator.writeString(ArrayList.class.getName());
                jsonGenerator.writeStartArray();
            }

            while (vertexProperties.hasNext()) {
                serializerVertexProperty(vertexProperties.next(), jsonGenerator, serializerProvider, typeSerializer, normalize, false);
            }

            jsonGenerator.writeEndArray();
            if (typeSerializer != null) jsonGenerator.writeEndArray();
        }
    }

    jsonGenerator.writeEndObject();
}
 
Example 15
Source File: GraphMLWriter.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
private static VertexProperty<Object> getCheckedVertexProperty(Vertex vertex, String key) {
    final Iterator<VertexProperty<Object>> properties = vertex.properties(key);
    final VertexProperty<Object> currentValue = properties.next();

    if (properties.hasNext())
        throw new IllegalStateException("Multiple properties exists for the provided key: [%s] and multi-properties are not directly supported by GraphML format");
    return currentValue;
}
 
Example 16
Source File: MainGraphMapper.java    From egeria with Apache License 2.0 5 votes vote down vote up
/**
 * Copies all the properties from an existing Vertex to a new one.
 *
 * @param originalVertex  - Vertex to copy
 * @param newVertex - Vertex to add the copied properties
 */
private void copyVertexProperties(Vertex originalVertex, Vertex newVertex) {
    final Iterator<VertexProperty<Object>> iterator = originalVertex.properties();
    while (iterator.hasNext()) {
        VertexProperty oldVertexProperty = iterator.next();
        newVertex.property(oldVertexProperty.key(), oldVertexProperty.value());
    }
}
 
Example 17
Source File: TinkerGraphGraphSONSerializerV2d0Test.java    From tinkergraph-gremlin with Apache License 2.0 4 votes vote down vote up
/**
 * Checks sequentially vertices and edges of both graphs. Will check sequentially Vertex IDs, Vertex Properties IDs
 * and values and classes. Then same for edges. To use when serializing a Graph and deserializing the supposedly
 * same Graph.
 */
private boolean approximateGraphsCheck(Graph g1, Graph g2) {
    final Iterator<Vertex> itV = g1.vertices();
    final Iterator<Vertex> itVRead = g2.vertices();

    while (itV.hasNext()) {
        final Vertex v = itV.next();
        final Vertex vRead = itVRead.next();

        // Will only check IDs but that's 'good' enough.
        if (!v.equals(vRead)) {
            return false;
        }

        final Iterator itVP = v.properties();
        final Iterator itVPRead = vRead.properties();
        while (itVP.hasNext()) {
            final VertexProperty vp = (VertexProperty) itVP.next();
            final VertexProperty vpRead = (VertexProperty) itVPRead.next();
            if (!vp.value().equals(vpRead.value())
                    || !vp.equals(vpRead)) {
                return false;
            }
        }
    }

    final Iterator<Edge> itE = g1.edges();
    final Iterator<Edge> itERead = g2.edges();

    while (itE.hasNext()) {
        final Edge e = itE.next();
        final Edge eRead = itERead.next();
        // Will only check IDs but that's good enough.
        if (!e.equals(eRead)) {
            return false;
        }

        final Iterator itEP = e.properties();
        final Iterator itEPRead = eRead.properties();
        while (itEP.hasNext()) {
            final Property ep = (Property) itEP.next();
            final Property epRead = (Property) itEPRead.next();
            if (!ep.value().equals(epRead.value())
                    || !ep.equals(epRead)) {
                return false;
            }
        }
    }
    return true;
}
 
Example 18
Source File: TinkerGraphGraphSONSerializerV2d0Test.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
/**
 * Checks sequentially vertices and edges of both graphs. Will check sequentially Vertex IDs, Vertex Properties IDs
 * and values and classes. Then same for edges. To use when serializing a Graph and deserializing the supposedly
 * same Graph.
 */
private boolean approximateGraphsCheck(Graph g1, Graph g2) {
    final Iterator<Vertex> itV = g1.vertices();
    final Iterator<Vertex> itVRead = g2.vertices();

    while (itV.hasNext()) {
        final Vertex v = itV.next();
        final Vertex vRead = itVRead.next();

        // Will only check IDs but that's 'good' enough.
        if (!v.equals(vRead)) {
            return false;
        }

        final Iterator itVP = v.properties();
        final Iterator itVPRead = vRead.properties();
        while (itVP.hasNext()) {
            final VertexProperty vp = (VertexProperty) itVP.next();
            final VertexProperty vpRead = (VertexProperty) itVPRead.next();
            if (!vp.value().equals(vpRead.value())
                    || !vp.equals(vpRead)) {
                return false;
            }
        }
    }

    final Iterator<Edge> itE = g1.edges();
    final Iterator<Edge> itERead = g2.edges();

    while (itE.hasNext()) {
        final Edge e = itE.next();
        final Edge eRead = itERead.next();
        // Will only check IDs but that's good enough.
        if (!e.equals(eRead)) {
            return false;
        }

        final Iterator itEP = e.properties();
        final Iterator itEPRead = eRead.properties();
        while (itEP.hasNext()) {
            final Property ep = (Property) itEP.next();
            final Property epRead = (Property) itEPRead.next();
            if (!ep.value().equals(epRead.value())
                    || !ep.equals(epRead)) {
                return false;
            }
        }
    }
    return true;
}