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

The following examples show how to use org.apache.tinkerpop.gremlin.structure.Vertex#vertices() . 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: TinkerGraphQuerySwitchMonitored.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Collection<TinkerGraphSwitchMonitoredMatch> evaluate() {
	final Collection<TinkerGraphSwitchMonitoredMatch> matches = new ArrayList<>();

	final Collection<Vertex> switches = driver.getVertices(SWITCH);

	// (sw:Switch)
	for (final Vertex sw : switches) {
		final Iterable<Vertex> monitoredByVertices = () -> sw.vertices(Direction.OUT, MONITORED_BY);

		boolean hasSensor = false;
		for (final Vertex monitoredByVertex : monitoredByVertices) {
			if (monitoredByVertex.label().equals(SENSOR)) {
				hasSensor = true;
				break;
			}
		}

		if (!hasSensor) {
			matches.add(new TinkerGraphSwitchMonitoredMatch(sw));
		}
	}

	return matches;
}
 
Example 2
Source File: TinkerpopSaverTest.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void addPropertyDescriptionsStoresTheOrderOfThePropertyDescriptions() {
  final TinkerpopSaver instance = new TinkerpopSaver(vres, graphWrapper, VRE_NAME, VRE_NAME,
    MAX_VERTICES_PER_TRANSACTION, VRE_NAME);
  ImportPropertyDescriptions importPropertyDescriptions = new ImportPropertyDescriptions();
  importPropertyDescriptions.getOrCreate(6).setPropertyName("first");
  importPropertyDescriptions.getOrCreate(5).setPropertyName("second");
  importPropertyDescriptions.getOrCreate(7).setPropertyName("third");

  instance.addPropertyDescriptions(rawCollection, importPropertyDescriptions);

  Iterator<Vertex> hasFirstProperty = rawCollection.vertices(Direction.OUT, "hasFirstProperty");
  assertThat(hasFirstProperty.hasNext(), is(true));
  Vertex first = hasFirstProperty.next();
  assertThat(first, likeVertex().withProperty("id", 6).withProperty("name", "first"));
  Iterator<Vertex> hasNextProperty = first.vertices(Direction.OUT, "hasNextProperty");
  assertThat(hasNextProperty.hasNext(), is(true));
  Vertex second = hasNextProperty.next();
  assertThat(second, is(likeVertex().withProperty("id", 5).withProperty("name", "second")));
  Iterator<Vertex> hasNextProperty2 = second.vertices(Direction.OUT, "hasNextProperty");
  assertThat(hasNextProperty2.hasNext(), is(true));
  assertThat(hasNextProperty2.next(), is(likeVertex().withProperty("id", 7).withProperty("name", "third")));

}
 
Example 3
Source File: TestLoadingAdjacent.java    From sqlg with MIT License 6 votes vote down vote up
@Test
public void testLoadAdjacentVertices() {
    Vertex v1 = this.sqlgGraph.addVertex(T.label, "Person", "name", "john1");
    Vertex v2 = this.sqlgGraph.addVertex(T.label, "Person", "name", "john2");
    v1.addEdge("friend", v2, "weight", 1);
    this.sqlgGraph.tx().commit();

    Iterator<Vertex> adjacents = v1.vertices(Direction.OUT);

    Assert.assertTrue(adjacents.hasNext());

    Vertex adjacent = adjacents.next();

    Assert.assertFalse(adjacents.hasNext());

    Assert.assertEquals(v2.id(), adjacent.id());
    Assert.assertEquals(toList(v2.properties()), toList(adjacent.properties()));
}
 
Example 4
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 5
Source File: Collection.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
private static ReadableProperty loadDisplayName(Vertex collectionVertex, Vre vre) {
  final Iterator<Vertex> initialV = collectionVertex.vertices(Direction.OUT, HAS_DISPLAY_NAME_RELATION_NAME);
  if (!initialV.hasNext()) {
    return null;
  }

  try {
    return ReadableProperty.load(initialV.next(), vre.getVreName());
  } catch (IOException | NoSuchMethodException | InstantiationException | InvocationTargetException |
    IllegalAccessException e) {

    LOG.error(databaseInvariant, "Failed to load configuration for  display name for collection {} ",
      collectionVertex.value(COLLECTION_NAME_PROPERTY_NAME), e);
  }
  return null;
}
 
Example 6
Source File: MapInAdjacentPropertiesHandler.java    From windup with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Getter
 */
private static Map<String, Serializable> handleGetter(Vertex vertex, Method method, Object[] args,
            MapInAdjacentProperties ann)
{
    if (args != null && args.length != 0)
        throw new WindupException("Method must take no arguments: " + method.getName());

    // Find the map vertex.
    Map<String, Serializable> map = new HashMap<>();
    Iterator<Vertex> it = vertex.vertices(Direction.OUT, ann.label());
    Vertex mapVertex = null;
    if (!it.hasNext())
    {
        // No map yet.
        return map;
    }
    else
    {
        mapVertex = it.next();
        if (it.hasNext())
        {
            // Multiple vertices behind edges with given label.
            log.warning("Found multiple vertices for a map, using only first one; for: " + method.getName());
        }
    }

    Set<String> keys = mapVertex.keys();
    for (String key : keys)
    {
        final Property<Object> val = mapVertex.property(key);
        if (!val.isPresent() || !(val.value() instanceof String))
            log.warning("@InProperties is meant for Map<String,Serializable>, but the value was: " + val.getClass());
        map.put(key, "" + val.value());
    }
    return map;
}
 
Example 7
Source File: VertexDeserializer.java    From grakn with GNU Affero General Public License v3.0 5 votes vote down vote up
private static Boolean isLoopAdded(Vertex vertex, String label) {
    Iterator<Vertex> adjacentVertices = vertex.vertices(Direction.BOTH, label);

    while (adjacentVertices.hasNext()) {
        Vertex adjacentVertex = adjacentVertices.next();

        if (adjacentVertex.equals(vertex)) {
            return true;
        }
    }

    return false;
}
 
Example 8
Source File: Collection.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
private boolean collectionNameIsUniqueToThisVre(Vertex collectionVertex, String vreName) {
  final Iterator<Vertex> vreV = collectionVertex.vertices(Direction.IN, Vre.HAS_COLLECTION_RELATION_NAME);
  if (vreV.hasNext() && !vreV.next().value(Vre.VRE_NAME_PROPERTY_NAME).equals(vreName)) {
    return false;
  }

  return true;
}
 
Example 9
Source File: Collection.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
public Vertex save(Graph graph, String vreName) {
  Vertex collectionVertex = findOrCreateCollectionVertex(graph);

  if (!collectionNameIsUniqueToThisVre(collectionVertex, vreName)) {
    final String message =
      String.format("Collection '%s' already exists for another VRE than '%s'", collectionName, vreName);
    LOG.error(message);
    throw new IllegalArgumentException(message);
  }

  collectionVertex.property(COLLECTION_NAME_PROPERTY_NAME, collectionName);
  collectionVertex.property(ENTITY_TYPE_NAME_PROPERTY_NAME, entityTypeName);
  collectionVertex.property(IS_RELATION_COLLECTION_PROPERTY_NAME, isRelationCollection);
  collectionVertex.property(COLLECTION_LABEL_PROPERTY_NAME, collectionLabel);
  collectionVertex.property(COLLECTION_IS_UNKNOWN_PROPERTY_NAME, unknown);
  if (description != null) {
    collectionVertex.property(COLLECTION_DESCRIPTION_PROPERTY_NAME, description);
  }
  saveArchetypeRelation(graph, collectionVertex);

  savePropertyConfigurations(graph, collectionVertex);

  // Create a container node to hold the entities in this collection.
  Iterator<Vertex> entityNodeIt = collectionVertex.vertices(Direction.OUT, HAS_ENTITY_NODE_RELATION_NAME);
  if (!entityNodeIt.hasNext()) {
    collectionVertex.addEdge(HAS_ENTITY_NODE_RELATION_NAME, graph.addVertex(COLLECTION_ENTITIES_LABEL));
  }

  return collectionVertex;
}
 
Example 10
Source File: Collection.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
private static LinkedHashMap<String, ReadableProperty> loadProperties(Vertex collectionVertex, Vre vre) {
  final Iterator<Vertex> initialV = collectionVertex.vertices(Direction.OUT, HAS_INITIAL_PROPERTY_RELATION_NAME);
  final LinkedHashMap<String, ReadableProperty> properties = Maps.newLinkedHashMap();
  if (!initialV.hasNext()) {
    return properties;
  }

  Vertex current = initialV.next();
  try {
    properties.put(current.value(ReadableProperty.CLIENT_PROPERTY_NAME),
      ReadableProperty.load(current, vre.getVreName()));
    while (current.vertices(Direction.OUT, ReadableProperty.HAS_NEXT_PROPERTY_RELATION_NAME).hasNext()) {
      current = current.vertices(Direction.OUT, ReadableProperty.HAS_NEXT_PROPERTY_RELATION_NAME).next();
      properties.put(current.value(ReadableProperty.CLIENT_PROPERTY_NAME),
        ReadableProperty.load(current, vre.getVreName()));
    }

  } catch (IOException | NoSuchMethodException | InstantiationException | InvocationTargetException |
    IllegalAccessException e) {

    LOG.error(databaseInvariant, "Failed to load configuration for property {} for collection {} ",
      current.property(ReadableProperty.CLIENT_PROPERTY_NAME).isPresent() ?
        current.value(ReadableProperty.CLIENT_PROPERTY_NAME) : "",
      collectionVertex.value(COLLECTION_NAME_PROPERTY_NAME), e);
  }

  return properties;
}
 
Example 11
Source File: LogEntryFactory.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
public LogEntry createForVertex(Vertex vertex) {
  Iterator<Vertex> previous = vertex.vertices(Direction.IN, "VERSION_OF");
  if (previous.hasNext()) {
    return new UpdateVertexLogEntry(vertex, previous.next());
  }
  return new CreateVertexLogEntry(vertex);
}
 
Example 12
Source File: MyBenchmark.java    From peapod with Apache License 2.0 5 votes vote down vote up
@Benchmark
public void testGetFramedVerticesTypedTinkerpop(Blackhole bh) {
    Vertex next = godGraph.traversal().V().hasLabel("god").has("name", "saturn").next();
    bh.consume(next.property("name").value());
    Iterator<Vertex> children = next.vertices(Direction.IN, "father");
    while (children.hasNext()) {
        Vertex child = children.next();
        Vertex father = child.vertices(Direction.OUT, "father").next();
        bh.consume(father);
    }
}
 
Example 13
Source File: TinkerGraphUtil.java    From trainbenchmark with Eclipse Public License 1.0 5 votes vote down vote up
public static Iterable<Vertex> getAdjacentNodes(final Vertex source, final String edgeLabel,
		final Direction direction, final String[] targetVertexLabels) {
	final Collection<Vertex> vertices = new LinkedList<>();
	final Iterable<Vertex> candidateVertices = () -> source.vertices(direction, edgeLabel);
	for (final Vertex candidateVertex : candidateVertices) {
		if (!Arrays.asList(targetVertexLabels).contains(candidateVertex.label())) {
			continue;
		}
		vertices.add(candidateVertex);
	}
	return vertices;
}
 
Example 14
Source File: TitanVertexDeserializer.java    From titan1withtp3.1 with Apache License 2.0 5 votes vote down vote up
private static Boolean isLoopAdded(Vertex vertex, String label) {
    Iterator<Vertex> adjacentVertices = vertex.vertices(Direction.BOTH, label);

    while (adjacentVertices.hasNext()) {
        Vertex adjacentVertex = adjacentVertices.next();

        if(adjacentVertex.equals(vertex)){
            return true;
        }
    }

    return false;
}
 
Example 15
Source File: ClassificationService.java    From windup with Eclipse Public License 1.0 4 votes vote down vote up
private void getMigrationEffortDetails(ProjectModelTraversal traversal, Set<String> includeTags, Set<String> excludeTags,
                                       Set<String> issueCategoryIDs, boolean recursive, boolean includeZero,
                                       EffortAccumulatorFunction accumulatorFunction)
{
    LOG.log(Level.INFO, String.format(System.lineSeparator()+"\t\t\tEFFORT C: getMigrationEffortDetails() with: %s, %srecur, %sincludeZero, %s, tags: %s, excl: %s",
            traversal, recursive ? "" : "!", includeZero ? "" : "!", accumulatorFunction, includeTags, excludeTags));

    final Set<Vertex> initialVertices = traversal.getAllProjectsAsVertices(recursive);

    GraphTraversal<Vertex, Vertex> pipeline = this.getGraphContext().getGraph().traversal().V();
    // If the multivalue index is not 1st, then it doesn't work - https://github.com/thinkaurelius/titan/issues/403
    if (!includeZero)
    {
        pipeline.has(EffortReportModel.EFFORT, P.gt(0));
        pipeline.has(WindupVertexFrame.TYPE_PROP, P.eq(ClassificationModel.TYPE));
    }
    else
    {
        pipeline.has(WindupVertexFrame.TYPE_PROP, ClassificationModel.TYPE);
    }
    pipeline.as("classification");
    // For each classification, count it repeatedly for each file that is within given set of Projects (from the traversal).
    pipeline.out(ClassificationModel.FILE_MODEL);
    pipeline.in(ProjectModel.PROJECT_MODEL_TO_FILE);
    pipeline.filter(new SetMembersFilter(initialVertices));
    pipeline.select("classification");

    boolean checkTags = !includeTags.isEmpty() || !excludeTags.isEmpty();
    FileService fileService = new FileService(getGraphContext());
    for (Vertex v : pipeline.toSet())
    {
        if (checkTags || !issueCategoryIDs.isEmpty())
        {
            ClassificationModel classificationModel = frame(v);

            // only check tags if we have some passed in
            if (checkTags && !classificationModel.matchesTags(includeTags, excludeTags))
                continue;

            if (!issueCategoryIDs.isEmpty() && !issueCategoryIDs.contains(classificationModel.getIssueCategory().getCategoryID()))
                continue;
        }

        // For each classification, count it repeatedly for each file.
        // TODO: .accumulate(v, count);
        // TODO: This could be all done just within the query (provided that the tags would be taken care of).
        //       Accumulate could be a PipeFunction.
        Iterator<Vertex> fileVertexIterator = v.vertices(Direction.OUT, ClassificationModel.FILE_MODEL);
        while (fileVertexIterator.hasNext())
        {
            Vertex fileVertex = fileVertexIterator.next();

            // Make sure that this file is actually in an accepted project. The pipeline condition will return
            // classifications that aren't necessarily in the same project.
            FileModel fileModel = fileService.frame(fileVertex);
            if (initialVertices.contains(fileModel.getProjectModel().getElement()))
                accumulatorFunction.accumulate(v);
        }
    }
}
 
Example 16
Source File: FindFilesNotClassifiedOrHinted.java    From windup with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException
{
    ExecutionStatistics.get().begin(NAME);
    if (arguments.size() != 1)
    {
        throw new TemplateModelException("Error, method expects one argument (Iterable<FileModel>)");
    }
    @SuppressWarnings("unchecked")
    Iterable<FileModel> fileModels = FreeMarkerUtil.freemarkerWrapperToIterable(arguments.get(0));

    FindFilesNotClassifiedOrHintedGremlinCriterion criterion = new FindFilesNotClassifiedOrHintedGremlinCriterion();
    List<Vertex> initialFileModelsAsVertices = new ArrayList<>();
    for (FileModel fm : fileModels)
    {
        initialFileModelsAsVertices.add(fm.getElement());
    }
    Iterable<Vertex> result = criterion.query(context, initialFileModelsAsVertices);

    List<FileModel> resultModels = new ArrayList<>();
    for (Vertex v : result)
    {
        FileModel f = context.getFramed().frameElement(v, FileModel.class);

        //we don't want to show our decompiled classes in the report
        boolean wasNotGenerated = f.isWindupGenerated() == null || !f.isWindupGenerated();
        boolean isOfInterestingType = f instanceof JavaSourceFileModel || f instanceof XmlFileModel || f instanceof JavaClassFileModel;
        //we don't want to list .class files that have their decompiled .java file with hints/classifications
        boolean withoutHiddenHints = true;

        if (f instanceof JavaClassFileModel)
        {
            Iterator<Vertex> decompiled = v.vertices(Direction.OUT, JavaClassFileModel.DECOMPILED_FILE);
            if (decompiled.hasNext())
            {
                withoutHiddenHints = !decompiled.next().vertices(Direction.IN, FileReferenceModel.FILE_MODEL).hasNext();
            }
        }

        if (wasNotGenerated && withoutHiddenHints && isOfInterestingType)
        {
            //if it passed all the checks, add it
            resultModels.add(f);
        }
    }

    ExecutionStatistics.get().end(NAME);
    return resultModels;
}
 
Example 17
Source File: TinkerGraphUtil.java    From trainbenchmark with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * The trick used in the
 * hu.bme.mit.trainbenchmark.benchmark.neo4j.util.Neo4jUtil#isConnected()
 * method will not work here as TinkerPop's Vertex class does not provide an
 * interface for efficiently accessing the degree (w.r.t. a certain
 * relationship type/direction) of the node.
 * 
 * @param source
 * @param target
 * @param edgeLabel
 * @return
 */
public static boolean isConnected(final Vertex source, final Vertex target, final String edgeLabel) {
	final Iterable<Vertex> vertices = () -> source.vertices(Direction.OUT, edgeLabel);
	for (final Vertex vertex : vertices) {
		if (vertex.equals(target)) {
			return true;
		}
	}
	return false;
}