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

The following examples show how to use org.apache.tinkerpop.gremlin.structure.Vertex#value() . 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: 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 2
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 3
Source File: SimpleAuthenticator.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
public AuthenticatedUser authenticate(final Map<String, String> credentials) throws AuthenticationException {
    final Vertex user;
    if (!credentials.containsKey(PROPERTY_USERNAME)) throw new IllegalArgumentException(String.format("Credentials must contain a %s", PROPERTY_USERNAME));
    if (!credentials.containsKey(PROPERTY_PASSWORD)) throw new IllegalArgumentException(String.format("Credentials must contain a %s", PROPERTY_PASSWORD));

    final String username = credentials.get(PROPERTY_USERNAME);
    final String password = credentials.get(PROPERTY_PASSWORD);
    final CredentialTraversal<Vertex,Vertex> t = credentialStore.users(username);
    if (!t.hasNext())
        throw new AuthenticationException("Username and/or password are incorrect");

    user = t.next();
    if (t.hasNext()) {
        logger.warn("There is more than one user with the username [{}] - usernames must be unique", username);
        throw new AuthenticationException("Username and/or password are incorrect");
    }

    final String hash = user.value(PROPERTY_PASSWORD);
    if (!BCrypt.checkpw(password, hash))
        throw new AuthenticationException("Username and/or password are incorrect");

    return new AuthenticatedUser(username);
}
 
Example 4
Source File: HugeVariables.java    From hugegraph with Apache License 2.0 6 votes vote down vote up
@Override
public <R> Optional<R> get(String key) {
    if (key == null) {
        throw Graph.Variables.Exceptions.variableKeyCanNotBeNull();
    }
    if (key.isEmpty()) {
        throw Graph.Variables.Exceptions.variableKeyCanNotBeEmpty();
    }

    Vertex vertex = this.queryVariableVertex(key);
    if (vertex == null) {
        return Optional.empty();
    }

    String type = vertex.value(Hidden.hide(VARIABLE_TYPE));
    if (!Arrays.asList(TYPES).contains(Hidden.hide(type))) {
        throw Graph.Variables.Exceptions
                   .dataTypeOfVariableValueNotSupported(type);
    }
    // The value of key VARIABLE_TYPE is the name of variable value
    return Optional.of(vertex.value(Hidden.hide(type)));
}
 
Example 5
Source File: FileLogOutput.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void updateVertex(Vertex vertex) {
  String modifiedString = vertex.value("modified");

  try {
    Change modified = objectMapper.readValue(modifiedString, Change.class);
    writeAndFlush(
      String.format("%d - Vertex with tim_id '%s' updated.%n", modified.getTimeStamp(), vertex.value("tim_id")));
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 6
Source File: FileLogOutput.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void newVertex(Vertex vertex) {
  String modifiedString = vertex.value("modified");

  try {
    Change modified = objectMapper.readValue(modifiedString, Change.class);
    writeAndFlush(
      String.format("%d - Vertex with tim_id '%s' created.%n", modified.getTimeStamp(), vertex.value("tim_id")));
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 7
Source File: VertexTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@LoadGraphWith(MODERN)
public void g_VX1X_to_XOUT_knowsX() {
    final Traversal<Vertex, Vertex> traversal = get_g_VX1X_to_XOUT_knowsX(convertToVertexId("marko"));
    printTraversalForm(traversal);
    int counter = 0;
    while (traversal.hasNext()) {
        counter++;
        final Vertex vertex = traversal.next();
        final String name = vertex.value("name");
        assertTrue(name.equals("vadas") || name.equals("josh"));
    }
    assertEquals(2, counter);
    assertFalse(traversal.hasNext());
}
 
Example 8
Source File: Vre.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
public static Vre load(Vertex vreVertex) {
  final Vre vre = new Vre(
    vreVertex.value(VRE_NAME_PROPERTY_NAME),
    loadKeywordTypes(vreVertex),
    loadPublishState(vreVertex),
    loadMetadata(vreVertex)
  );

  vreVertex.vertices(Direction.OUT, HAS_COLLECTION_RELATION_NAME).forEachRemaining(collectionV -> {
    Collection collection = Collection.load(collectionV, vre);
    vre.addCollection(collection);
  });

  return vre;
}
 
Example 9
Source File: AbstractLabel.java    From sqlg with MIT License 5 votes vote down vote up
Partition addPartition(Vertex partitionVertex) {
    Preconditions.checkState(this.getSchema().getTopology().isSqlWriteLockHeldByCurrentThread());
    VertexProperty<String> from = partitionVertex.property(SQLG_SCHEMA_PARTITION_FROM);
    VertexProperty<String> to = partitionVertex.property(SQLG_SCHEMA_PARTITION_TO);
    VertexProperty<String> in = partitionVertex.property(SQLG_SCHEMA_PARTITION_IN);
    VertexProperty<String> partitionType = partitionVertex.property(SQLG_SCHEMA_PARTITION_PARTITION_TYPE);
    VertexProperty<String> partitionExpression = partitionVertex.property(SQLG_SCHEMA_PARTITION_PARTITION_EXPRESSION);
    Partition partition;
    if (from.isPresent()) {
        Preconditions.checkState(to.isPresent());
        Preconditions.checkState(!in.isPresent());
        partition = new Partition(
                this.sqlgGraph,
                this,
                partitionVertex.value(SQLG_SCHEMA_PARTITION_NAME),
                from.value(),
                to.value(),
                PartitionType.from(partitionType.<String>value()),
                partitionExpression.isPresent() ? partitionExpression.<String>value() : null);
    } else {
        Preconditions.checkState(in.isPresent());
        Preconditions.checkState(!to.isPresent());
        partition = new Partition(
                this.sqlgGraph,
                this,
                partitionVertex.value(SQLG_SCHEMA_PARTITION_NAME),
                in.value(),
                PartitionType.from(partitionType.<String>value()),
                partitionExpression.isPresent() ? partitionExpression.<String>value() : null);
    }
    this.partitions.put(partitionVertex.value(SQLG_SCHEMA_PARTITION_NAME), partition);
    return partition;
}
 
Example 10
Source File: TinkerGraphTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void shouldNotReadValueOfPropertyOnVertexThatWasRemoved() {
    final TinkerGraph graph = TinkerGraph.open();
    final Vertex v = graph.addVertex();
    v.property("name", "stephen");

    assertEquals("stephen", v.value("name"));
    v.remove();
    v.value("name");
}
 
Example 11
Source File: Neo4jLuceneEntityFetcher.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
private Optional<Vertex> getVertexByIndex(GraphTraversalSource source, UUID id, String collectionName) {
  // Look up the vertex for this neo4j Node
  Optional<Vertex> vertexOpt = indexHandler.findById(id);

  // Return if the neo4j Node ID matches no vertex (extreme edge case)
  if (!vertexOpt.isPresent()) {
    LOG.error(Logmarkers.databaseInvariant,
      "Vertex with tim_id {} is found in index with id {}L but not in graph database", id);
    return Optional.empty();
  }

  // Get the latest version of the found Vertex
  Vertex foundVertex = vertexOpt.get();
  int infinityGuard = 0;
  while (foundVertex.vertices(Direction.OUT, "VERSION_OF").hasNext()) {
    // The neo4j index Node is one version_of behind the actual node
    foundVertex = foundVertex.vertices(Direction.OUT, "VERSION_OF").next();
    if (++infinityGuard >= MAX_VERSION_OF_DEPTH) {
      LOG.error(Logmarkers.databaseInvariant, "Vertices with tim_id {} might have circular VERSION_OF", id);
      return Optional.empty();
    }
  }

  // Only if this latest version is truly registered as latest return this as a successful hit
  if (foundVertex.value("isLatest")) {
    return Optional.of(foundVertex);
  } else {
    LOG.error(Logmarkers.databaseInvariant,
      "Last version of vertex with tim_id {} is not marked as isLatest=true", id);
  }

  // Failed to find vertex in lucene index, so return
  return Optional.empty();
}
 
Example 12
Source File: InvariantsCheck.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public ValidationResult check(Vertex vertex) {
  List<ValidationResult> validationResults = Lists.newArrayList();
  String[] vertexTypes = getEntityTypesOrDefault(vertex);
  String id = vertex.value("tim_id");

  vertex.edges(Direction.BOTH).forEachRemaining(edge -> {
    if (!Objects.equals(edge.label(), "VERSION_OF")) { // ignore the VERSION_OF relations
      String[] edgeTypes = getEntityTypesOrDefault(edge);
      for (String edgeType : edgeTypes) {
        Optional<Collection> collectionOptional = vres.getCollectionForType(edgeType);
        String edgeId = edge.value("tim_id");

        if (!collectionOptional.isPresent()) {
          validationResults.add(
            new ElementValidationResult(false,
              String.format("Edge with tim_id '%s' has contains unknown variant '%s'", edgeId, edgeType)));
          continue;
        }

        Collection edgeCollection = collectionOptional.get();
        // Only check accepted edges / relations, Timbuctoo sees not accepted relations as deleted.
        if (isAccepted(edge, edgeType) && vreContainsAVariationOfTheVertex(vertexTypes, edgeCollection)) {
          addInvalidVertex(validationResults, id, vertexTypes, edgeType, edgeId);
        }
      }
    }
  });
  return new CompositeValidationResult(validationResults);
}
 
Example 13
Source File: PropertyCoreTest.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
@Override
protected <V> V propertyList(String key, Object... values) {
    HugeGraph graph = graph();
    key = "list_" + key;
    Vertex vertex = graph.addVertex(T.label, "person", "id", 2,
                                    key, Arrays.asList(values));
    graph.tx().commit();

    vertex = graph.vertices(vertex.id()).next();
    Assert.assertTrue(TraversalUtil.testProperty(vertex.property(key),
                                                 Arrays.asList(values)));
    return vertex.value(key);
}
 
Example 14
Source File: TestBatchNormalUpdatePrimitiveArrays.java    From sqlg with MIT License 4 votes vote down vote up
private void testBatchUpdateArraybyte_assert(SqlgGraph sqlgGraph, Vertex god) {
    god = sqlgGraph.traversal().V(god.id()).next();
    byte[] array = god.value("array");
    Assert.assertArrayEquals(new byte[]{5, 6}, array);
}
 
Example 15
Source File: TestBatchNormalUpdatePrimitiveArrays.java    From sqlg with MIT License 4 votes vote down vote up
private void testBatchUpdateArrayfloat_assert(SqlgGraph sqlgGraph, Vertex god) {
    god = sqlgGraph.traversal().V(god.id()).next();
    float[] array = god.value("array");
    Assert.assertArrayEquals(new float[]{5.5f, 6.6f}, array, 0f);
}
 
Example 16
Source File: AbstractLabel.java    From sqlg with MIT License 4 votes vote down vote up
void addDistributionProperty(Vertex distributionProperty) {
    Preconditions.checkState(this.getSchema().getTopology().isSqlWriteLockHeldByCurrentThread());
    this.distributionPropertyColumn = new PropertyColumn(this, distributionProperty.value(SQLG_SCHEMA_PROPERTY_NAME), PropertyType.valueOf(distributionProperty.value(SQLG_SCHEMA_PROPERTY_TYPE)));
}
 
Example 17
Source File: TestBatchNormalUpdatePrimitiveArrays.java    From sqlg with MIT License 4 votes vote down vote up
private void testBatchUpdateArraylong_assert(SqlgGraph sqlgGraph, Vertex god) {
    god = sqlgGraph.traversal().V(god.id()).next();
    long[] array = god.value("array");
    Assert.assertArrayEquals(new long[]{5L, 6L}, array);
}
 
Example 18
Source File: TestBatchNormalUpdatePrimitiveArrays.java    From sqlg with MIT License 4 votes vote down vote up
private void testBatchUpdateArrayInteger_assert(SqlgGraph sqlgGraph, Vertex god) {
    god = sqlgGraph.traversal().V(god.id()).next();
    Integer[] array = god.value("array");
    Assert.assertArrayEquals(new Integer[]{1, 2}, array);
}
 
Example 19
Source File: TitanIndexTest.java    From titan1withtp3.1 with Apache License 2.0 4 votes vote down vote up
@Test
public void testDualMapping() {
    if (!indexFeatures.supportsStringMapping(Mapping.TEXTSTRING)) return;

    PropertyKey name = makeKey("name", String.class);
    TitanGraphIndex mixed = mgmt.buildIndex("mixed", Vertex.class).addKey(name, Mapping.TEXTSTRING.asParameter()).buildMixedIndex(INDEX);
    mixed.name();
    finishSchema();


    tx.addVertex("name", "Long John Don");
    tx.addVertex("name", "Long Little Lewis");
    tx.addVertex("name", "Middle Sister Mabel");

    clopen();
    evaluateQuery(tx.query().has("name", Cmp.EQUAL, "Long John Don"), ElementCategory.VERTEX,
            1, new boolean[]{true, true}, "mixed");
    evaluateQuery(tx.query().has("name", Text.CONTAINS, "Long"), ElementCategory.VERTEX,
            2, new boolean[]{true, true}, "mixed");
    evaluateQuery(tx.query().has("name", Text.CONTAINS, "Long Don"), ElementCategory.VERTEX,
            1, new boolean[]{true, true}, "mixed");
    evaluateQuery(tx.query().has("name", Text.CONTAINS_PREFIX, "Lon"), ElementCategory.VERTEX,
            2, new boolean[]{true, true}, "mixed");
    evaluateQuery(tx.query().has("name", Text.CONTAINS_REGEX, "Lit*le"), ElementCategory.VERTEX,
            1, new boolean[]{true, true}, "mixed");
    evaluateQuery(tx.query().has("name", Text.REGEX, "Long.*"), ElementCategory.VERTEX,
            2, new boolean[]{true, true}, "mixed");
    evaluateQuery(tx.query().has("name", Text.PREFIX, "Middle"), ElementCategory.VERTEX,
            1, new boolean[]{true, true}, "mixed");

    for (Vertex u : tx.getVertices()) {
        String n = u.<String>value("name");
        if (n.endsWith("Don")) {
            u.remove();
        } else if (n.endsWith("Lewis")) {
            u.property(VertexProperty.Cardinality.single, "name", "Big Brother Bob");
        } else if (n.endsWith("Mabel")) {
            u.property("name").remove();
        }
    }

    clopen();

    evaluateQuery(tx.query().has("name", Text.CONTAINS, "Long"), ElementCategory.VERTEX,
            0, new boolean[]{true, true}, "mixed");
    evaluateQuery(tx.query().has("name", Text.CONTAINS, "Big"), ElementCategory.VERTEX,
            1, new boolean[]{true, true}, "mixed");
    evaluateQuery(tx.query().has("name", Text.PREFIX, "Big"), ElementCategory.VERTEX,
            1, new boolean[]{true, true}, "mixed");
    evaluateQuery(tx.query().has("name", Text.PREFIX, "Middle"), ElementCategory.VERTEX,
            0, new boolean[]{true, true}, "mixed");

}
 
Example 20
Source File: TestBatchNormalUpdatePrimitiveArrays.java    From sqlg with MIT License 4 votes vote down vote up
private void testBatchUpdateArrayLong_assert(SqlgGraph sqlgGraph, Vertex god) {
    god = sqlgGraph.traversal().V(god.id()).next();
    Long[] array = god.value("array");
    Assert.assertArrayEquals(new Long[]{6L, 7L}, array);
}