@Override
 public Iterator<Long> lookup(Object value) {
   Long result = indexData.get(value);
   return result != null
       ? IteratorUtil.singletonIterator(result)
       : IteratorUtil.<Long>emptyIterator();
 }
 public void verify(String dbPath) {
   EmbeddedGraphDatabase graphDb = new EmbeddedGraphDatabase(dbPath);
   assertEquals(
       "Reference node did not have zero relationships.",
       0,
       IteratorUtil.count(graphDb.getReferenceNode().getRelationships()));
   assertEquals("There was more than one node.", 1, IteratorUtil.count(graphDb.getAllNodes()));
   graphDb.shutdown();
 }
 @Test
 @Transactional
 public void testUpdateBooleanPropertyIsReflectedInIndex() {
   Group group = persist(new Group());
   group.setAdmin(true);
   assertEquals(
       1, IteratorUtil.asCollection(groupRepository.findAllByPropertyValue("admin", true)).size());
   group.setAdmin(false);
   assertEquals(
       0, IteratorUtil.asCollection(groupRepository.findAllByPropertyValue("admin", true)).size());
 }
Example #4
0
  public static int getDocumentSizeForFeature(GraphDatabaseService db, Long id) {
    int documentSize;

    String cacheKey = "DOCUMENT_SIZE_FEATURE_" + id;

    if (vectorSpaceModelCache.getIfPresent(cacheKey) == null) {
      Node startNode = db.getNodeById(id);

      Iterator<Node> classes =
          db.traversalDescription()
              .depthFirst()
              .relationships(withName("HAS_CLASS"), Direction.OUTGOING)
              .evaluator(Evaluators.fromDepth(1))
              .evaluator(Evaluators.toDepth(1))
              .traverse(startNode)
              .nodes()
              .iterator();

      documentSize = IteratorUtil.count(classes);

      vectorSpaceModelCache.put(cacheKey, documentSize);
    } else {
      documentSize = (Integer) vectorSpaceModelCache.getIfPresent(cacheKey);
    }

    return documentSize;
  }
Example #5
0
 private CypherResult doExecuteQuery(String query, boolean canProfile) {
   long time = System.currentTimeMillis();
   Transaction tx = gdb.beginTx();
   javax.transaction.Transaction resumeTx;
   try {
     resumeTx = suspendTx(query);
     ExecutionResult result =
         canProfile ? executionEngine.profile(query) : executionEngine.execute(query);
     final Collection<Map<String, Object>> data = IteratorUtil.asCollection(result);
     time = System.currentTimeMillis() - time;
     resumeTransaction(resumeTx);
     CypherResult cypherResult =
         new CypherResult(
             result.columns(),
             data,
             result.getQueryStatistics(),
             time,
             canProfile ? result.executionPlanDescription() : null,
             prettify(query));
     tx.success();
     return cypherResult;
   } finally {
     tx.close();
   }
 }
 @Override
 protected Object retrieveEntity(PersistentEntity pe, Serializable key) {
   List<Criterion> criteria = new ArrayList<Criterion>(1);
   criteria.add(new IdEquals(key));
   return IteratorUtil.singleOrNull(
       new Neo4jQuery(session, pe, this).executeQuery(pe, new Conjunction(criteria)).iterator());
 }
Example #7
0
  public static Map<Long, Integer> getTermFrequencyMapForDocument(
      GraphDatabaseService db, Long classId) {
    Map<Long, Integer> termDocumentMatrix;

    String cacheKey = "TERM_DOCUMENT_FREQUENCY_" + classId;

    if (vectorSpaceModelCache.getIfPresent(cacheKey) == null) {
      Node classNode = db.getNodeById(classId);

      termDocumentMatrix = new HashMap<>();

      IteratorUtil.asCollection(
              db.traversalDescription()
                  .depthFirst()
                  .relationships(withName("HAS_CLASS"), Direction.INCOMING)
                  .evaluator(Evaluators.fromDepth(1))
                  .evaluator(Evaluators.toDepth(1))
                  .traverse(classNode))
          .stream()
          .forEach(
              p ->
                  termDocumentMatrix.put(
                      p.endNode().getId(), (Integer) p.lastRelationship().getProperty("matches")));

      vectorSpaceModelCache.put(cacheKey, termDocumentMatrix);
    } else {
      termDocumentMatrix = (Map<Long, Integer>) vectorSpaceModelCache.getIfPresent(cacheKey);
    }

    return termDocumentMatrix;
  }
  @Override
  protected OperationResult executeOperation(
      IndexQueryNodeOnNeoPinEntertainmentVideoIndexOperation operation) {
    int resultCode;
    int result;

    Neo4jConnectionStateEmbedded connection = (Neo4jConnectionStateEmbedded) getDbConnectionState();
    Transaction tx = connection.getDb().beginTx();
    try {
      Iterator<Node> nodes =
          connection
              .getDb()
              .index()
              .forNodes(operation.getIndexName())
              .query(operation.getIndexQuery());

      resultCode = 0;
      result = IteratorUtil.count(nodes);
    } catch (Exception e) {
      resultCode = -1;
      result = 0;
    } finally {
      tx.finish();
    }

    return operation.buildResult(resultCode, result);
  }
  private Object unmarshall(PersistentEntity persistentEntity, Long id, Map<String, Object> data) {

    log.debug("unmarshalling entity {}, props {}, {}", id, data);
    EntityAccess entityAccess = new EntityAccess(persistentEntity, persistentEntity.newInstance());
    entityAccess.setConversionService(persistentEntity.getMappingContext().getConversionService());
    entityAccess.setIdentifier(id);
    data.remove("__id__");

    for (PersistentProperty property :
        entityAccess.getPersistentEntity().getPersistentProperties()) {

      String propertyName = property.getName();
      if (property instanceof Simple) { // implicitly sets version property as well
        entityAccess.setProperty(propertyName, data.remove(propertyName));
        //            } else if (property instanceof OneToOne) {
        //                log.error("property " + property.getName() + " is of type " +
        // property.getClass().getSuperclass());
      } else if (property instanceof ToOne) {
        ToOne to = (ToOne) property;

        CypherResult cypherResult =
            getSession()
                .getNativeInterface()
                .execute(
                    CypherBuilder.findRelationshipEndpointIdsFor(to),
                    Collections.singletonMap("id", id));

        Map<String, Object> row = IteratorUtil.singleOrNull(cypherResult);
        if (row != null) {
          Long endpointId = (Long) row.get("id");
          entityAccess.setProperty(
              propertyName,
              getMappingContext()
                  .getProxyFactory()
                  .createProxy(session, to.getAssociatedEntity().getJavaClass(), endpointId));
        }
      } else if ((property instanceof OneToMany) || (property instanceof ManyToMany)) {

        LazyEnititySet lazyEnititySet =
            new LazyEnititySet(
                entityAccess,
                (Association) property,
                getMappingContext().getProxyFactory(),
                getSession());
        entityAccess.setProperty(propertyName, lazyEnititySet);

      } else {
        throw new IllegalArgumentException(
            "property $property.name is of type ${property.class.superclass}");
      }
    }

    if (!data.isEmpty()) {
      GroovyObject go = (GroovyObject) (entityAccess.getEntity());
      go.setProperty(Neo4jGormEnhancer.UNDECLARED_PROPERTIES, data);
    }

    firePostLoadEvent(entityAccess.getPersistentEntity(), entityAccess);
    return entityAccess.getEntity();
  }
 @Override
 protected List<Object> retrieveAllEntities(PersistentEntity pe, Iterable<Serializable> keys) {
   List<Criterion> criterions = new ArrayList<Criterion>(1);
   criterions.add(new In("id", IteratorUtil.asCollection(keys)));
   Junction junction = new Conjunction(criterions);
   return new Neo4jQuery(session, pe, this).executeQuery(pe, junction);
 }
Example #11
0
 @Override
 public T getSingle() {
   try {
     return IteratorUtil.singleOrNull((Iterator<T>) this);
   } finally {
     close();
   }
 }
Example #12
0
 @Test
 public void createAndClearCacheBeforeCommit() {
   Node node = getGraphDb().createNode();
   clearCache();
   node.createRelationshipTo(getGraphDb().createNode(), TEST);
   clearCache();
   assertEquals(1, IteratorUtil.count(node.getRelationships()));
 }
 private void assertPathIs(Iterable<Person> path, Person... expectedPath) {
   ArrayList<Person> pathArray = new ArrayList<Person>();
   IteratorUtil.addToCollection(path, pathArray);
   assertThat(pathArray.size(), equalTo(expectedPath.length));
   for (int i = 0; i < expectedPath.length; i++) {
     assertThat(pathArray.get(i), equalTo(expectedPath[i]));
   }
 }
  /*
   * Helper method to convert an execution result to a collection
   *
   */
  public Set<Node> nodeSetFromResult(ExecutionResult result, String column) {
    Set<Node> nodes = new HashSet<Node>();

    Iterator<Node> columnIterator = result.columnAs(column);
    IteratorUtil.addToCollection(columnIterator, nodes);

    return nodes;
  }
Example #15
0
 public Collection<DynamicRecord> allocateFrom(SchemaRule rule) {
   RecordSerializer serializer = new RecordSerializer();
   serializer = serializer.append(rule);
   Collection<DynamicRecord> records = new ArrayList<>();
   allocateRecordsFromBytes(
       records, serializer.serialize(), IteratorUtil.iterator(forceGetRecord(rule.getId())), this);
   return records;
 }
 public CypherResult(
     java.util.List<String> columns,
     String text,
     Iterable<scala.collection.Map<String, Object>> rows) {
   this.columns = columns;
   this.text = text;
   this.rows = IteratorUtil.addToCollection(iterate(rows), new ArrayList<Map<String, Object>>());
 }
 @SuppressWarnings({"unchecked", "rawtypes"})
 protected Object createPage(Iterable<?> result, Pageable pageable) {
   final List resultList = IteratorUtil.addToCollection(result, new ArrayList());
   if (pageable == null) {
     return new PageImpl(resultList);
   }
   final int currentTotal = pageable.getOffset() + pageable.getPageSize();
   return new PageImpl(resultList, pageable, currentTotal);
 }
 @RequestMapping(value = "/actors/{id}", method = RequestMethod.GET, headers = "Accept=text/html")
 public String singleActorView(Model model, @PathVariable String id) {
   Person person = moviesRepository.getPerson(id);
   model.addAttribute("actor", person);
   model.addAttribute("id", id);
   model.addAttribute("roles", IteratorUtil.asCollection(person.getRoles()));
   addUser(model);
   return "/actors/show";
 }
 @Test
 public void listing3_10_node_labels() {
   usersAndMovies.addLabelToMovies();
   try (Transaction tx = graphDb.beginTx()) {
     ResourceIterable<Node> movies =
         GlobalGraphOperations.at(graphDb).getAllNodesWithLabel(DynamicLabel.label("MOVIES"));
     assertEquals(3, IteratorUtil.count(movies));
     tx.success();
   }
 }
Example #20
0
 @Nullable
 public Integer getLastInsertedBlockHeight() {
   Integer lastInsertedBlockHeight = null;
   try (Transaction ignored = graphDatabase.beginTx()) {
     Node block = IteratorUtil.singleOrNull(graphDatabase.findNodes(LabelType.LatestBlock));
     if (block != null) {
       lastInsertedBlockHeight = new BCBlock(block).getHeight();
     }
   }
   return lastInsertedBlockHeight;
 }
  @Test
  public void shouldHandleSingleItemIterators() throws Exception {
    // Given
    ResourceIterator<Long> it1 = asResourceIterator(iterator(1l));
    ResourceIterator<Long> it2 = asResourceIterator(iterator(5l, 6l, 7l));
    CombiningResourceIterator<Long> combingIterator =
        new CombiningResourceIterator<>(iterator(it1, it2));

    // When I iterate through it, things come back in the right order
    assertThat(IteratorUtil.asList(combingIterator), equalTo(asList(1l, 5l, 6l, 7l)));
  }
 @Test
 @Transactional
 public void shouldFindGroupyByQueryString() {
   Group group = persist(new Group());
   group.setFullTextName("queryableName");
   final Iterable<Group> found =
       groupRepository.findAllByQuery(Group.SEARCH_GROUPS_INDEX, "fullTextName", "queryable*");
   final Collection<Group> result =
       IteratorUtil.addToCollection(found.iterator(), new HashSet<Group>());
   assertEquals(new HashSet<>(Arrays.asList(group)), result);
 }
 @Test
 @Transactional
 public void testFindAllGroupsByIndex() {
   Group group = persist(new Group());
   group.setName(NAME_VALUE);
   Group group2 = persist(new Group());
   group2.setName(NAME_VALUE);
   final Iterable<Group> found = this.groupRepository.findAllByPropertyValue(NAME, NAME_VALUE);
   final Collection<Group> result =
       IteratorUtil.addToCollection(found.iterator(), new HashSet<Group>());
   assertEquals(new HashSet<>(Arrays.asList(group, group2)), result);
 }
  @Test
  public void correctlySaysNodeIsDeleted() throws Exception {
    // Given
    state.nodeDoDelete(1l);
    Node node = mock(Node.class);
    when(node.getId()).thenReturn(1l);
    when(ops.nodeGetAllProperties(1l)).thenReturn(IteratorUtil.<DefinedProperty>emptyIterator());
    when(ops.nodeGetLabels(1l)).thenReturn(PrimitiveIntCollections.emptyIterator());

    // When & Then
    assertThat(snapshot().isDeleted(node), equalTo(true));
  }
 @SuppressWarnings("unchecked")
 @Test
 @Transactional
 public void testQueryVariableRelationshipSingleResult() throws Exception {
   final Collection<Map<String, Object>> result =
       IteratorUtil.asCollection(michael.getOtherTeamMemberData());
   assertThat(
       result,
       hasItems(
           testTeam.simpleRowFor(testTeam.emil, "member"),
           testTeam.simpleRowFor(testTeam.david, "member")));
 }
Example #26
0
 private Iterator<PropertyBlock> propertiesIterator(Map<String, Object> properties) {
   if (properties == null || properties.isEmpty()) {
     return IteratorUtil.emptyIterator();
   }
   return new IteratorWrapper<PropertyBlock, Map.Entry<String, Object>>(
       properties.entrySet().iterator()) {
     @Override
     protected PropertyBlock underlyingObjectToObject(Entry<String, Object> property) {
       return propertyCreator.encodePropertyValue(
           getOrCreatePropertyKeyId(property.getKey()), property.getValue());
     }
   };
 }
Example #27
0
 public static int getDocumentSize(GraphDatabaseService db) {
   int documentSize;
   String cacheKey = "GLOBAL_DOCUMENT_SIZE";
   if (vectorSpaceModelCache.getIfPresent(cacheKey) == null) {
     documentSize =
         IteratorUtil.count(
             GlobalGraphOperations.at(db).getAllNodesWithLabel(DynamicLabel.label("Class")));
     vectorSpaceModelCache.put(cacheKey, documentSize);
   } else {
     documentSize = (Integer) vectorSpaceModelCache.getIfPresent(cacheKey);
   }
   return documentSize;
 }
 private Iterator<Property> loadAllPropertiesOf(PrimitiveRecord primitiveRecord) {
   Collection<PropertyRecord> records =
       propertyStore.getPropertyRecordChain(primitiveRecord.getNextProp());
   if (null == records) {
     return IteratorUtil.emptyIterator();
   }
   List<Property> properties = new ArrayList<>();
   for (PropertyRecord record : records) {
     for (PropertyBlock block : record.getPropertyBlocks()) {
       properties.add(block.getType().readProperty(block.getKeyIndexId(), block, propertyStore));
     }
   }
   return properties.iterator();
 }
 @Test
 public void listing3_11_node_labels_and_property() {
   try {
     usersAndMovies.addLabelToMovies();
   } catch (Exception e) {
     // ignore if index already exist
   }
   try (Transaction tx = graphDb.beginTx()) {
     ResourceIterable<Node> movies =
         graphDb.findNodesByLabelAndProperty(DynamicLabel.label("MOVIES"), "name", "Fargo");
     assertEquals(1, IteratorUtil.count(movies));
     tx.success();
   }
 }
  @Override
  protected List<Usuario> montaLista(ExecutionResult result) {
    Iterator<Node> n_column = result.columnAs("n");
    Usuario usuario = null;
    List<Usuario> usuarios = new ArrayList<>();
    for (Node node : IteratorUtil.asIterable(n_column)) {
      usuario = new Usuario();
      usuario.setNome((String) node.getProperty("nome"));
      usuario.setLogin((String) node.getProperty("login"));

      usuarios.add(usuario);
    }
    return usuarios;
  }