Example #1
0
  public Node _findSingleNode(Label label, String key, Object value) {
    try (ResourceIterator<Node> nodes = _findNodes(label, key, value)) {
      if (!nodes.hasNext()) return null;

      return nodes.next();
    }
  }
Example #2
0
  /** @return a {@link RequestContext} specifying at which point the store copy started. */
  public RequestContext flushStoresAndStreamStoreFiles(StoreWriter writer, boolean includeLogs) {
    try {
      long lastAppliedTransaction = transactionIdStore.getLastClosedTransactionId();
      monitor.startFlushingEverything();
      logRotationControl.forceEverything();
      monitor.finishFlushingEverything();
      ByteBuffer temporaryBuffer = ByteBuffer.allocateDirect(1024 * 1024);

      // Copy the store files
      monitor.startStreamingStoreFiles();
      try (ResourceIterator<File> files = dataSource.listStoreFiles(includeLogs)) {
        while (files.hasNext()) {
          File file = files.next();
          try (StoreChannel fileChannel = fileSystem.open(file, "r")) {
            monitor.startStreamingStoreFile(file);
            writer.write(
                relativePath(storeDirectory, file),
                fileChannel,
                temporaryBuffer,
                file.length() > 0);
            monitor.finishStreamingStoreFile(file);
          }
        }
      } finally {
        monitor.finishStreamingStoreFiles();
      }

      return anonymous(lastAppliedTransaction);
    } catch (IOException e) {
      throw new ServerFailureException(e);
    }
  }
  private Map<RowKey, Tuple> createAssociationMap(
      AssociationKey associationKey, AssociationContext associationContext, EntityKey entityKey) {
    String relationshipType = associationContext.getAssociationTypeContext().getRoleOnMainSide();
    ResourceIterator<Relationship> relationships =
        entityQueries
            .get(entityKey.getMetadata())
            .findAssociation(dataBase, entityKey.getColumnValues(), relationshipType);

    Map<RowKey, Tuple> tuples = new HashMap<RowKey, Tuple>();
    try {
      while (relationships.hasNext()) {
        Relationship relationship = relationships.next();
        AssociatedEntityKeyMetadata associatedEntityKeyMetadata =
            associationContext.getAssociationTypeContext().getAssociatedEntityKeyMetadata();
        EmbeddedNeo4jTupleAssociationSnapshot snapshot =
            new EmbeddedNeo4jTupleAssociationSnapshot(
                relationship, associationKey, associatedEntityKeyMetadata);
        RowKey rowKey = convert(associationKey, snapshot);
        tuples.put(rowKey, new Tuple(snapshot, SnapshotType.UPDATE));
      }
      return tuples;
    } finally {
      relationships.close();
    }
  }
Example #4
0
 public void printAllLabelNodes() {
   ResourceIterator<Node> allLabelNodes =
       GlobalGraphOperations.at(graphDb).getAllNodesWithLabel(getLabel()).iterator();
   while (allLabelNodes.hasNext()) {
     System.out.println(allLabelNodes.next().toString());
   }
 }
Example #5
0
  private List<Node> _findRelatedNodes(Label label, String key, Object value) {
    try (ResourceIterator<Node> hits = _findNodes(label, key, value)) {
      List<Node> nodes = new ArrayList<Node>();

      while (hits.hasNext()) {
        nodes.add(hits.next());
      }

      return nodes;
    }
  }
Example #6
0
  private String labelString(Node node) {
    try (ResourceIterator<Label> labels = node.getLabels().iterator()) {
      if (!labels.hasNext()) return "";

      StringBuilder result = new StringBuilder();
      while (labels.hasNext()) {
        Label next = labels.next();
        result.append(":").append(quote(next.name()));
      }
      return result.toString();
    }
  }
  public Long getTotalTokenCount() {
    Long frequency = (long) 0;

    try (Transaction ignored = database.beginTx(); ) {
      ResourceIterator<Node> it = database.findNodes(NodeLabel.NodeCounter);
      Node nodeCounter = it.next();
      Object count = nodeCounter.getProperty("word_token_count");
      if (count instanceof Integer) frequency = frequency + new Long((Integer) count);
      else if (count instanceof Long) frequency = frequency + (Long) count;
    }

    return frequency;
  }
Example #8
0
  public void enumrateAllNodesWithLabel(Label label, ProcessNode processNode) throws Exception {
    try (Transaction tx = graphDb.beginTx()) {
      //			GlobalGraphOperations global = Neo4jUtils.getGlobalOperations(graphDb);
      //			global.

      try (ResourceIterator<Node> nodes = graphDb.findNodes(label)) {
        while (nodes.hasNext()) {
          if (!processNode.processNode(nodes.next())) break;
        }
      }

      tx.success();
    }
  }
  private static Node findNodeByName(String nameToFind) {
    ArrayList<Node> userNodes = new ArrayList<>();
    Label label = DynamicLabel.label("Nome");
    try (Transaction tx = graphDb.beginTx()) {
      try (ResourceIterator<Node> users = graphDb.findNodes(label, "name", nameToFind)) {
        while (users.hasNext()) {
          userNodes.add(users.next());
        }

        for (Node node : userNodes) {
          System.out.println("trovato nodo: " + node.getProperty("name"));
        }
      }
    }
    return userNodes.get(0);
  }
  @Override
  public List<Tuple> getTuples(EntityKey[] keys, TupleContext tupleContext) {
    if (keys.length == 0) {
      return Collections.emptyList();
    }

    // We only supports one metadata for now
    EntityKeyMetadata metadata = keys[0].getMetadata();
    // The result returned by the query might not be in the same order as the keys.
    ResourceIterator<Node> nodes = entityQueries.get(metadata).findEntities(dataBase, keys);
    try {
      return tuplesResult(keys, tupleContext, nodes);
    } finally {
      nodes.close();
    }
  }
Example #11
0
  @Test
  public void shouldCloseTransactionsWhenIteratingOverSingleColumn() throws Exception {
    // Given an execution result that has been started but not exhausted
    createNode();
    createNode();
    ExecutionResult executionResult = engine.execute("MATCH (n) RETURN n");
    ResourceIterator<Node> resultIterator = executionResult.columnAs("n");
    resultIterator.next();
    assertThat(activeTransaction(), is(notNullValue()));

    // When
    resultIterator.close();

    // Then
    assertThat(activeTransaction(), is(nullValue()));
  }
Example #12
0
 @Override
 public void forEachTuple(ModelConsumer consumer, EntityKeyMetadata... entityKeyMetadatas) {
   for (EntityKeyMetadata entityKeyMetadata : entityKeyMetadatas) {
     ResourceIterator<Node> queryNodes =
         entityQueries.get(entityKeyMetadata).findEntities(dataBase);
     try {
       while (queryNodes.hasNext()) {
         Node next = queryNodes.next();
         Tuple tuple = new Tuple(new Neo4jTupleSnapshot(next, entityKeyMetadata));
         consumer.consume(tuple);
       }
     } finally {
       queryNodes.close();
     }
   }
 }
 @Override
 @WebMethod
 public ResponseDTO findAll(@WebParam NodeType nodeType, @WebParam SortOrder sortOrder) {
   Validator.checkRequiredArgument(nodeType);
   List<Domain> domainList = null;
   try (Transaction tx = graphDatabaseService.beginTx()) {
     ResourceIterator<Node> resourceIterator = indexRepository.getNodes(nodeType);
     if (resourceIterator != null && resourceIterator.hasNext()) {
       domainList = Lists.newArrayList();
       while (resourceIterator.hasNext()) {
         domainList.add(domainFactory.create(resourceIterator.next(), nodeType));
       }
     }
     tx.success();
     tx.close();
   }
   return new ResponseDTO(new Assembler().toDtos(domainList, nodeType));
 }
 @Override
 @WebMethod
 public ResponseDTO findDelayedFlights(Integer delayTime) {
   Map<String, List<DelayDTO>> delayDtoMap = Maps.newHashMap();
   try (Transaction tx = graphDatabaseService.beginTx()) {
     ResourceIterator<Node> resourceIterator = indexRepository.getNodes(NodeType.AIRPORT);
     if (resourceIterator != null) {
       while (resourceIterator.hasNext()) {
         Node node = resourceIterator.next();
         delayDtoMap.put(
             node.getProperty(NodeType.AIRPORT.getIdType()).toString(),
             airportTraversal.findDelayedFlights(node, delayTime));
       }
     }
     tx.success();
     tx.close();
   }
   return new ResponseDTO(new Assembler().toDelayDtos(delayDtoMap));
 }
 @Override
 @WebMethod
 public ResponseDTO findCauseOfDepartureDelaysAtEachAirport() {
   Map<String, Map<String, Integer>> airportDelayCauseMap = Maps.newHashMap();
   try (Transaction tx = graphDatabaseService.beginTx()) {
     ResourceIterator<Node> resourceIterator = indexRepository.getNodes(NodeType.AIRPORT);
     if (resourceIterator != null) {
       while (resourceIterator.hasNext()) {
         Node node = resourceIterator.next();
         airportDelayCauseMap.put(
             node.getProperty(NodeType.AIRPORT.getIdType()).toString(),
             airportTraversal.findCauseOfDepartureDelaysAtEachAirport(node));
       }
     }
     tx.success();
     tx.close();
   }
   return new ResponseDTO(new Assembler().toCauseDtos(airportDelayCauseMap));
 }
Example #16
0
 /*
  * This method assumes that the nodes might not be in the same order as the keys and some keys might not have a
  * matching result in the db.
  */
 private List<Tuple> tuplesResult(
     EntityKey[] keys, TupleContext tupleContext, ResourceIterator<Node> nodes) {
   // The list is initialized with null because some keys might not have a corresponding node
   Tuple[] tuples = new Tuple[keys.length];
   while (nodes.hasNext()) {
     Node node = nodes.next();
     for (int i = 0; i < keys.length; i++) {
       if (matches(node, keys[i].getColumnNames(), keys[i].getColumnValues())) {
         tuples[i] =
             new Tuple(
                 new Neo4jTupleSnapshot(
                     node,
                     tupleContext.getAllAssociatedEntityKeyMetadata(),
                     tupleContext.getAllRoles(),
                     keys[i].getMetadata()));
         // We assume there are no duplicated keys
         break;
       }
     }
   }
   return Arrays.asList(tuples);
 }
 @Override
 public void forEachTuple(
     ModelConsumer consumer,
     TupleTypeContext tupleTypeContext,
     EntityKeyMetadata entityKeyMetadata) {
   ResourceIterator<Node> queryNodes = entityQueries.get(entityKeyMetadata).findEntities(dataBase);
   try {
     while (queryNodes.hasNext()) {
       Node next = queryNodes.next();
       Tuple tuple =
           new Tuple(
               EmbeddedNeo4jTupleSnapshot.fromNode(
                   next,
                   tupleTypeContext.getAllAssociatedEntityKeyMetadata(),
                   tupleTypeContext.getAllRoles(),
                   entityKeyMetadata),
               SnapshotType.UPDATE);
       consumer.consume(tuple);
     }
   } finally {
     queryNodes.close();
   }
 }