Java Code Examples for org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal#hasNext()

The following examples show how to use org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal#hasNext() . 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: QueryRunner.java    From janusgraph_tutorial with Apache License 2.0 6 votes vote down vote up
public void printTimeline(GraphTraversal<Vertex, Map<String, Map<String, Object>>> traversal) {
  int count = 0;
  resetTimer();
  while (traversal.hasNext()) {
    Map<String, Map<String, Object>> item = traversal.next();
    Vertex user = (Vertex) item.get(userVertex);
    Edge posts = (Edge) item.get(postsEdge);
    Vertex statusUpdate = (Vertex) item.get(statusUpdateVertex);
    LOGGER.info(
        " {}: @{} {}: {}",
        count++,
        user.value(USER_NAME),
        formatTimestamp(posts.value(CREATED_AT)),
        statusUpdate.value(CONTENT)
    );
  }

  LOGGER.info("Printed {} element(s) in {}ms", count, duration());
}
 
Example 2
Source File: CollectionHasEntityRelationChangeListener.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onAddToCollection(Collection collection, Optional<Vertex> oldVertex, Vertex newVertex) {
  String type = collection.getEntityTypeName();
  final GraphTraversal<Vertex, Vertex> hasEntityNode = findEntityNodeForEntityTypeName(type);

  if (hasEntityNode.hasNext()) {
    hasEntityNode.next().addEdge(Collection.HAS_ENTITY_RELATION_NAME, newVertex);
  } else {
    LOG.error(databaseInvariant, "No hasEntity node found for collection with entityTypeName {} ", type);
  }
}
 
Example 3
Source File: EjbRemoteServiceModelService.java    From windup with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Either creates a new {@link EjbRemoteServiceModel} or returns an existing one if one already exists.
 */
public EjbRemoteServiceModel getOrCreate(Iterable<ProjectModel> applications, JavaClassModel remoteInterface, JavaClassModel implementationClass)
{
    GraphTraversal<Vertex, Vertex> pipeline = new GraphTraversalSource(getGraphContext().getGraph()).V();
    pipeline.has(WindupVertexFrame.TYPE_PROP, EjbRemoteServiceModel.TYPE);
    if (remoteInterface != null)
        pipeline.as("remoteInterface").out(EjbRemoteServiceModel.EJB_INTERFACE)
                .filter(vertexTraverser -> vertexTraverser.get().equals(remoteInterface.getElement()))
                .select("remoteInterface");

    if (implementationClass != null)
        pipeline.as("implementationClass").out(EjbRemoteServiceModel.EJB_IMPLEMENTATION_CLASS)
                    .filter(vertexTraverser -> vertexTraverser.get().equals(implementationClass.getElement()))
                    .select("implementationClass");

    if (pipeline.hasNext())
    {
        EjbRemoteServiceModel result = frame(pipeline.next());
        for (ProjectModel application : applications)
        {
            if (!Iterables.contains(result.getApplications(), application))
                result.addApplication(application);
        }
        return result;
    }
    else
    {
        EjbRemoteServiceModel model = create();
        model.setApplications(applications);
        model.setInterface(remoteInterface);
        model.setImplementationClass(implementationClass);
        return model;
    }
}
 
Example 4
Source File: TestBatchNormalPrimitive.java    From sqlg with MIT License 5 votes vote down vote up
private void testDoublePrimitiveEdge_assert(SqlgGraph sqlgGraph, double[] edgeNameArray) {
    GraphTraversal<Edge, Edge> traversal = sqlgGraph.traversal().E();
    int count = 0;
    double[] edgeNameArrayToTest = new double[10];
    while (traversal.hasNext()) {
        Array.set(edgeNameArrayToTest, count++, traversal.next().value("name"));
    }
    assertArrayEquals(edgeNameArray, edgeNameArrayToTest, 0D);
}
 
Example 5
Source File: Gremlin.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
private String evaluateQuery(String query) throws ScriptException {
  GraphTraversal traversalResult = (GraphTraversal) engine.eval(query, bindings);
  StringBuilder result = new StringBuilder();
  while (traversalResult.hasNext()) {

    dumpItem(traversalResult.next(), result);
  }
  if (result.length() > 0) {
    return result.toString();
  } else {
    return "No results...";
  }
}
 
Example 6
Source File: TestBatchNormalPrimitive.java    From sqlg with MIT License 5 votes vote down vote up
private void testShortPrimitiveEdge_assert(SqlgGraph sqlgGraph, short[] edgeNameArray) {
    GraphTraversal<Edge, Edge> traversal = sqlgGraph.traversal().E();
    int count = 0;
    short[] edgeNameArrayToTest = new short[10];
    while (traversal.hasNext()) {
        Array.set(edgeNameArrayToTest, count++, traversal.next().value("name"));
    }
    assertArrayEquals(edgeNameArray, edgeNameArrayToTest);
}
 
Example 7
Source File: TestRepeatStepOnEdges.java    From sqlg with MIT License 5 votes vote down vote up
private void checkResult(GraphTraversal gp) {
    int count = 0;
    while (gp.hasNext()) {
        logger.info(gp.next().toString());
        count++;
    }
    Assert.assertEquals(8, count);
}
 
Example 8
Source File: Collection.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
private void saveArchetypeRelation(Graph graph, Vertex collectionVertex) {
  if (!abstractType.equals(entityTypeName)) {
    GraphTraversal<Vertex, Vertex> archetype = graph.traversal().V().hasLabel(DATABASE_LABEL)
                                                    .has(ENTITY_TYPE_NAME_PROPERTY_NAME, abstractType);

    if (!archetype.hasNext()) {
      LOG.error(databaseInvariant, "No archetype collection with entityTypeName {} present in the graph",
        abstractType);
    } else {
      collectionVertex.addEdge(HAS_ARCHETYPE_RELATION_NAME, archetype.next());
    }
  } else {
    LOG.warn("Assuming collection {} is archetype because entityTypeName is equal to abstractType", collectionName);
  }
}
 
Example 9
Source File: TestBatchNormalPrimitive.java    From sqlg with MIT License 5 votes vote down vote up
private void testLongPrimitive_assert(SqlgGraph sqlgGraph, long[] vertexNameArray) {
    GraphTraversal<Vertex, Vertex> traversal = sqlgGraph.traversal().V();
    int count = 0;
    long[] vertexNameArrayToTest = new long[10];
    while (traversal.hasNext()) {
        Array.set(vertexNameArrayToTest, count++, traversal.next().value("name"));
    }
    assertArrayEquals(vertexNameArray, vertexNameArrayToTest);
}
 
Example 10
Source File: SourceReportService.java    From windup with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Find the SourceReportModel instance for this fileModel (this is a 1:1 relationship).
 */
public SourceReportModel getSourceReportForFileModel(FileModel fileModel)
{
    GraphTraversal<Vertex, Vertex> pipeline = new GraphTraversalSource(getGraphContext().getGraph()).V(fileModel.getElement());
    pipeline.in(SourceReportModel.SOURCE_REPORT_TO_SOURCE_FILE_MODEL);

    SourceReportModel result = null;
    if (pipeline.hasNext())
    {
        result = frame(pipeline.next());
    }
    return result;
}
 
Example 11
Source File: JaxRSWebServiceModelService.java    From windup with Eclipse Public License 1.0 5 votes vote down vote up
public JaxRSWebServiceModel getOrCreate(ProjectModel application, String path, JavaClassModel implementationClass)
{
    GraphTraversal<Vertex, Vertex> pipeline;
    if (implementationClass == null)
    {
        pipeline = new GraphTraversalSource(getGraphContext().getGraph()).V();
        pipeline.has(WindupVertexFrame.TYPE_PROP, JaxRSWebServiceModel.TYPE);
    }
    else
    {
        pipeline = new GraphTraversalSource(getGraphContext().getGraph()).V(implementationClass.getElement());
        pipeline.out(JaxRSWebServiceModel.JAXRS_IMPLEMENTATION_CLASS);
        pipeline.has(WindupVertexFrame.TYPE_PROP, Text.textContains(JaxRSWebServiceModel.TYPE));
    }
    pipeline.has(JaxRSWebServiceModel.PATH, path);

    if (pipeline.hasNext())
    {
        JaxRSWebServiceModel result = frame(pipeline.next());
        if (!result.isAssociatedWithApplication(application))
            result.addApplication(application);
        return result;
    }
    else
    {
        JaxRSWebServiceModel jaxWebService = create();
        jaxWebService.addApplication(application);
        jaxWebService.setPath(path);

        jaxWebService.setImplementationClass(implementationClass);
        return jaxWebService;
    }
}
 
Example 12
Source File: AtlasJanusGraph.java    From atlas with Apache License 2.0 5 votes vote down vote up
private Edge getFirstActiveEdge(GraphTraversal gt) {
    while (gt.hasNext()) {
        Edge gremlinEdge = (Edge) gt.next();
        if (gremlinEdge != null && gremlinEdge.property(STATE_PROPERTY_KEY).isPresent() &&
                gremlinEdge.property(STATE_PROPERTY_KEY).value().equals(AtlasEntity.Status.ACTIVE.toString())
        ) {
            return gremlinEdge;
        }
    }

    return null;
}
 
Example 13
Source File: Vre.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
private Vertex findOrCreateVreVertex(Graph graph) {
  // Look for existing VRE vertex
  Vertex vreVertex;
  GraphTraversal<Vertex, Vertex> existing = graph.traversal().V().hasLabel(DATABASE_LABEL)
                                                 .has(VRE_NAME_PROPERTY_NAME, vreName);
  // Create new if does not exist
  if (existing.hasNext()) {
    vreVertex = existing.next();
    LOG.debug("Replacing existing vertex {}.", vreVertex);
  } else {
    vreVertex = graph.addVertex(DATABASE_LABEL);
    LOG.debug("Creating new vertex");
  }
  return vreVertex;
}
 
Example 14
Source File: ApplicationReportIndexService.java    From windup with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Return a global application index (not associated with a specific {@link ProjectModel}).
 */
public ApplicationReportIndexModel getOrCreateGlobalApplicationIndex()
{
    GraphTraversal<Vertex, Vertex> pipeline = getGraphContext().getGraph().traversal().V();
    pipeline.has(WindupVertexFrame.TYPE_PROP, ApplicationReportModel.TYPE);
    pipeline.filter(it -> !it.get().edges(Direction.OUT, ApplicationReportIndexModel.APPLICATION_REPORT_INDEX_TO_PROJECT_MODEL).hasNext());

    final ApplicationReportIndexModel result = pipeline.hasNext() ? frame(pipeline.next()) : create();
    return result;
}
 
Example 15
Source File: TestBatchNormalPrimitive.java    From sqlg with MIT License 5 votes vote down vote up
private void testFloatPrimitiveEdge_assert(SqlgGraph sqlgGraph, float[] edgeNameArray) {
    GraphTraversal<Edge, Edge> traversal = sqlgGraph.traversal().E();
    int count = 0;
    float[] edgeNameArrayToTest = new float[10];
    while (traversal.hasNext()) {
        Array.set(edgeNameArrayToTest, count++, traversal.next().value("name"));
    }
    assertArrayEquals(edgeNameArray, edgeNameArrayToTest, 0F);
}
 
Example 16
Source File: TinkerPopOperations.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public byte[] getVreImageBlob(String vreName) {
  final GraphTraversal<Vertex, Vertex> vreT = getVreTraversal(vreName);

  if (vreT.hasNext()) {
    final Vertex vreVertex = vreT.next();
    if (vreVertex.property(Vre.IMAGE_BLOB_PROPERTY_NAME).isPresent()) {
      return vreVertex.value(Vre.IMAGE_BLOB_PROPERTY_NAME);
    }
  }
  return null;
}
 
Example 17
Source File: TinkerPopOperations.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void addTypeToEntity(UUID id, Collection typeToAdd) throws NotFoundException {

  GraphTraversal<Vertex, Vertex> entityTraversal = this.traversal.V()
                                                                 .has("tim_id", id.toString())
                                                                 .has("isLatest", true);

  if (!entityTraversal.hasNext()) {
    throw new NotFoundException();
  }

  Vertex entityVertex = entityTraversal.next();
  String entityTypesStr = getProp(entityVertex, "types", String.class).orElse("[]");

  String entityTypeName = typeToAdd.getEntityTypeName();
  if (!entityTypesStr.contains("\"" + entityTypeName + "\"")) {
    try {
      ArrayNode entityTypes = arrayToEncodedArray.tinkerpopToJson(entityTypesStr);
      entityTypes.add(entityTypeName);

      entityVertex.property("types", entityTypes.toString());
      if (entityVertex instanceof Neo4jVertex) {
        ((Neo4jVertex) entityVertex).addLabel(entityTypeName);
      }
    } catch (IOException e) {
      // FIXME potential bug?
      LOG.error(Logmarkers.databaseInvariant, "property 'types' was not parseable: " + entityTypesStr);
    }
  }
  listener.onAddToCollection(typeToAdd, Optional.empty(), entityVertex);

}
 
Example 18
Source File: ReaderStatusManager.java    From atlas with Apache License 2.0 4 votes vote down vote up
private static Vertex fetchUsingTypeName(GraphTraversalSource g) {
    GraphTraversal src = g.V().has(Constants.ENTITY_TYPE_PROPERTY_KEY, MIGRATION_STATUS_TYPE_NAME);
    return src.hasNext() ? (Vertex) src.next() : null;
}
 
Example 19
Source File: TinkerPopOperations.java    From timbuctoo with GNU General Public License v3.0 4 votes vote down vote up
@Override
public int deleteEntity(Collection collection, UUID id, Change modified)
  throws NotFoundException {

  requireCommit = true;

  GraphTraversal<Vertex, Vertex> entityTraversal = entityFetcher.getEntity(traversal, id, null,
    collection.getCollectionName());

  if (!entityTraversal.hasNext()) {
    throw new NotFoundException();
  }

  Vertex entity = entityTraversal.next();
  String entityTypesStr = getProp(entity, "types", String.class).orElse("[]");
  boolean wasRemoved = false;
  if (entityTypesStr.contains("\"" + collection.getEntityTypeName() + "\"")) {
    try {
      ArrayNode entityTypes = arrayToEncodedArray.tinkerpopToJson(entityTypesStr);
      if (entityTypes.size() == 1) {
        entity.property("deleted", true);
        wasRemoved = true;
      } else {
        for (int i = entityTypes.size() - 1; i >= 0; i--) {
          JsonNode val = entityTypes.get(i);
          if (val != null && val.asText("").equals(collection.getEntityTypeName())) {
            entityTypes.remove(i);
            wasRemoved = true;
          }
        }
        entity.property("types", entityTypes.toString());
      }
    } catch (IOException e) {
      LOG.error(Logmarkers.databaseInvariant, "property 'types' was not parseable: " + entityTypesStr);
    }
  } else {
    throw new NotFoundException();
  }

  int newRev = getProp(entity, "rev", Integer.class).orElse(1) + 1;
  entity.property("rev", newRev);

  entity.edges(Direction.BOTH).forEachRemaining(edge -> {
    // Skip the hasEntity and the VERSION_OF edge, which are not real relations, but system edges
    if (edge.label().equals(HAS_ENTITY_RELATION_NAME) || edge.label().equals(VERSION_OF)) {
      return;
    }
    Optional<Collection> ownEdgeCol = getOwnCollectionOfElement(collection.getVre(), edge);
    if (ownEdgeCol.isPresent()) {
      edge.property(ownEdgeCol.get().getEntityTypeName() + "_accepted", false);
    }
  });

  setModified(entity, modified);
  entity.property("pid").remove();

  Vertex duplicate = duplicateVertex(traversal, entity, indexHandler);

  if (wasRemoved) {
    listener.onRemoveFromCollection(collection, Optional.of(entity), duplicate);
  }

  return newRev;
}
 
Example 20
Source File: GraphOMRSMetadataStore.java    From egeria with Apache License 2.0 4 votes vote down vote up
synchronized EntitySummary getEntitySummaryFromStore(String guid)
        throws
        EntityNotKnownException,
        RepositoryErrorException
{

    String methodName = "getEntitySummaryFromStore";


    EntitySummary entity = null;

    // Look in the graph
    GraphTraversalSource g = instanceGraph.traversal();

    GraphTraversal<Vertex, Vertex> gt = g.V().hasLabel("Entity").has(PROPERTY_KEY_ENTITY_GUID, guid);

    if (gt.hasNext()) {
        Vertex vertex = gt.next();
        log.debug("{} found vertex {}", methodName, vertex);

        try {
            if (vertex != null) {
                log.debug("{} found entity vertex {}", methodName, vertex);
                entity = new EntitySummary();
                entityMapper.mapVertexToEntitySummary(vertex, entity);
            }

        }
        catch (RepositoryErrorException e) {

            log.error("{} Caught exception {}", methodName, e.getMessage());
            g.tx().rollback();

            throw new RepositoryErrorException(GraphOMRSErrorCode.ENTITY_NOT_FOUND.getMessageDefinition(guid, methodName,
                                                                                                        this.getClass().getName(),
                                                                                                        repositoryName),
                    this.getClass().getName(),
                    methodName, e);
        }

    } else {

        // Entity was not found by GUID
        log.error("{} entity with GUID {} not found", methodName, guid);
        g.tx().rollback();

        throw new EntityNotKnownException(GraphOMRSErrorCode.ENTITY_NOT_FOUND.getMessageDefinition(guid, methodName,
                                                                                                   this.getClass().getName(),
                                                                                                   repositoryName),
                this.getClass().getName(),
                methodName);
    }


    g.tx().commit();

    return entity;
}