@Test
  public void testRemoveRelationshipRemovesDocument() {
    AutoIndexer<Relationship> autoIndexer = graphDb.index().getRelationshipAutoIndexer();
    autoIndexer.startAutoIndexingProperty("foo");
    autoIndexer.setEnabled(true);

    newTransaction();

    Node node1 = graphDb.createNode();
    Node node2 = graphDb.createNode();
    Relationship rel = node1.createRelationshipTo(node2, DynamicRelationshipType.withName("foo"));
    rel.setProperty("foo", "bar");

    newTransaction();

    assertThat(
        graphDb.index().forRelationships("relationship_auto_index").query("_id_:*").size(),
        equalTo(1));

    newTransaction();

    rel.delete();

    newTransaction();

    assertThat(
        graphDb.index().forRelationships("relationship_auto_index").query("_id_:*").size(),
        equalTo(0));
  }
Exemple #2
0
  public void rn() throws IOException {
    List<RoadLink> links = loadToDatabase("/Users/duduba/gj.mif", "/Users/duduba/gj.mid", false);

    GraphDatabaseService graphDb = neo.getDb();
    Index<Node> nodeIndex = neo.getNodeIndex();

    for (RoadLink link : links) {
      Transaction tx = graphDb.beginTx();
      try {

        Node fromNode = nodeIndex.get("id", link.fromNode).getSingle();
        if (fromNode == null) {
          fromNode = graphDb.createNode();
          fromNode.setProperty("id", link.fromNode);
          nodeIndex.add(fromNode, "id", link.fromNode);
        }
        Node toNode = nodeIndex.get("id", link.toNode).getSingle();
        if (toNode == null) {
          toNode = graphDb.createNode();
          toNode.setProperty("id", link.toNode);
          nodeIndex.add(toNode, "id", link.toNode);
        }

        Relationship r = fromNode.createRelationshipTo(toNode, Neo.RelTypes.TO);
        r.setProperty("no", link.no);
        r.setProperty("name", link.name);

        tx.success();
      } finally {
        tx.finish();
      }
    }
    logger.debug("haha, it's ok!");
  }
  public Concept getNextConceptToUpdate() {
    synchronized (lock) {
      IndexHits<Node> hits =
          conceptsForUpdate.query(
              new QueryContext(
                      NumericRangeQuery.newLongRange(
                          NamespaceConstants.DATE_UPDATED,
                          Long.MIN_VALUE,
                          Long.MAX_VALUE,
                          true,
                          true))
                  .sort(
                      new Sort(
                          new SortField(NamespaceConstants.DATE_UPDATED, SortField.LONG, false))));

      if (hits.hasNext()) {
        Node job = hits.next();
        System.out.println(job.getId());
        Concept concept = getByNode(job);
        removeFromCU(concept);
        return concept;
      }
    }
    return null;
  }
  @Test
  public void canUpdateShortStringInplace() throws Exception {
    try {
      long recordCount = dynamicRecordsInUse();
      long propCount = propertyRecordsInUse();
      Node node = graphdb.getGraphDatabaseService().createNode();
      node.setProperty("key", "value");

      newTx();

      assertEquals(recordCount, dynamicRecordsInUse());
      assertEquals(propCount + 1, propertyRecordsInUse());
      assertEquals("value", node.getProperty("key"));

      node.setProperty("key", "other");
      commit();

      assertEquals(recordCount, dynamicRecordsInUse());
      assertEquals(propCount + 1, propertyRecordsInUse());
      assertThat(
          node, inTx(graphdb.getGraphDatabaseService(), hasProperty("key").withValue("other")));
    } catch (Exception e) {
      e.printStackTrace();
      throw e;
    }
  }
  /**
   * Removes all nodes with non-valid resource classes from the graph.
   *
   * @param docGraph
   * @param validResourceClasses
   */
  private void preProcessGraph(DocGraph docGraph, Set<String> validResourceClasses) {
    log.info(String.format("Preprocessing DocGraph[%d]", docGraph.getId()));
    Node n;
    int cnt = 0;
    try (Transaction tx = graphDB.beginTx()) {
      for (Long nodeId : docGraph.getNodes()) {
        n = graphDB.getNodeById(nodeId);
        // node's class is resource class and it's not in the valid set
        if (n.hasProperty(Constants.NODE_SUPER_CLASS_KEY)
            && n.getProperty(Constants.NODE_SUPER_CLASS_KEY)
                .equals(Constants.NODE_SUPER_CLASS_RESOURCE_VALUE)
            && !validResourceClasses.contains(getNodeClass(n))) {
          try (Transaction innerTx = graphDB.beginTx()) {

            log.info("Deleting " + n);
            for (Relationship e : n.getRelationships()) {
              e.delete();
            }
            n.delete();
            innerTx.success();
            cnt++;
          }
        }
      }
      tx.success();
    }

    log.info(
        String.format("Preprocessing removed %d nodes from DocGraph[%d]", cnt, docGraph.getId()));
  }
 public void addCardInfoToNeo4j() {
   DBCursor cursor = cardCollection.find();
   DBObject sortObject = new BasicDBObject();
   sortObject.put("name", 1);
   // cursor = cursor.sort(sortObject);
   cursor.addOption(Bytes.QUERYOPTION_NOTIMEOUT);
   int count = 0;
   while (cursor.hasNext()) {
     DBObject cardObject = cursor.next();
     String cardName = cardObject.get("name").toString().toUpperCase();
     if (cardNodes.get(cardName) == null) {
       Node newCardNode = graphDb.createNode();
       newCardNode.setProperty("name", cardName);
       for (String property : cardObject.keySet()) {
         if (!property.equalsIgnoreCase("name")) {
           newCardNode.setProperty(property, cardObject.get(property).toString());
         }
       }
       cardNodes.put(cardName, newCardNode);
     } else {
       Node node = cardNodes.get(cardName);
       for (String property : cardObject.keySet()) {
         if (!property.equalsIgnoreCase("name")) {
           node.setProperty(property, cardObject.get(property).toString());
         }
       }
     }
     count++;
     System.out.println("Processed " + count + " card");
   }
 }
  @Test
  public void shouldOverwriteExistingProperties()
      throws PropertyValueException, NodeNotFoundException {

    long nodeId;
    Transaction tx = database.getGraph().beginTx();
    try {
      Node node = database.getGraph().createNode();
      node.setProperty("remove me", "trash");
      nodeId = node.getId();
      tx.success();
    } finally {
      tx.finish();
    }
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("foo", "bar");
    properties.put("baz", 17);
    actions.setAllNodeProperties(nodeId, properties);
    tx = database.getGraph().beginTx();
    try {
      Node node = database.getGraph().getNodeById(nodeId);
      assertHasProperties(node, properties);
      assertNull(node.getProperty("remove me", null));
    } finally {
      tx.finish();
    }
  }
Exemple #8
0
  @Test
  public void labelShouldBeRemovedAfterCommit() throws Exception {
    // GIVEN
    Transaction tx = db.beginTx();
    Statement statement = statementContextProvider.instance();
    Node node = db.createNode();
    int labelId1 = statement.dataWriteOperations().labelGetOrCreateForName("labello1");
    statement.dataWriteOperations().nodeAddLabel(node.getId(), labelId1);
    statement.close();
    tx.success();
    tx.finish();

    // WHEN
    tx = db.beginTx();
    statement = statementContextProvider.instance();
    statement.dataWriteOperations().nodeRemoveLabel(node.getId(), labelId1);
    statement.close();
    tx.success();
    tx.finish();

    // THEN
    tx = db.beginTx();
    statement = statementContextProvider.instance();
    PrimitiveIntIterator labels = statement.readOperations().nodeGetLabels(node.getId());
    statement.close();
    tx.success();
    tx.finish();

    assertThat(asSet(labels), equalTo(Collections.<Integer>emptySet()));
  }
Exemple #9
0
  @Test
  public void deletingNodeWithLabelsShouldHaveThoseLabelRemovalsReflectedInTransaction()
      throws Exception {
    // GIVEN
    Transaction tx = db.beginTx();
    Label label = label("labello");
    Node node = db.createNode(label);
    tx.success();
    tx.finish();

    tx = db.beginTx();
    Statement statement = statementContextProvider.instance();

    // WHEN
    statement.dataWriteOperations().nodeDelete(node.getId());

    // Then
    int labelId = statement.readOperations().labelGetForName(label.name());
    Set<Integer> labels = asSet(statement.readOperations().nodeGetLabels(node.getId()));
    boolean labelIsSet = statement.readOperations().nodeHasLabel(node.getId(), labelId);
    Set<Long> nodes = asSet(statement.readOperations().nodesGetForLabel(labelId));

    statement.close();

    tx.success();
    tx.finish();

    assertEquals(emptySetOf(Long.class), nodes);
    assertEquals(emptySetOf(Integer.class), labels);
    assertFalse("Label should not be set on node here", labelIsSet);
  }
Exemple #10
0
  @Test
  public void shouldNotBeAbleToCommitIfFailedTransactionContext() throws Exception {
    Transaction tx = db.beginTx();
    Statement statement = statementContextProvider.instance();

    // WHEN
    Node node = null;
    int labelId = -1;
    try {
      node = db.createNode();
      labelId = statement.dataWriteOperations().labelGetOrCreateForName("labello");
      statement.dataWriteOperations().nodeAddLabel(node.getId(), labelId);
      statement.close();
      tx.failure();
      tx.success();
      tx.finish();
      fail("Should have failed");
    } catch (TransactionFailureException e) { // Expected
    }

    // THEN
    tx = db.beginTx();
    statement = statementContextProvider.instance();
    try {
      statement.readOperations().nodeHasLabel(node.getId(), labelId);
      fail("should have thrown exception");
    } catch (EntityNotFoundException e) {
      // Yay!
    }
    tx.finish();
  }
Exemple #11
0
  @Test
  public void transactionStateShouldReflectRemovingLabelImmediately() throws Exception {
    // GIVEN
    Transaction tx = db.beginTx();
    Statement statement = statementContextProvider.instance();
    Node node = db.createNode();
    int labelId1 = statement.dataWriteOperations().labelGetOrCreateForName("labello1");
    int labelId2 = statement.dataWriteOperations().labelGetOrCreateForName("labello2");
    statement.dataWriteOperations().nodeAddLabel(node.getId(), labelId1);
    statement.dataWriteOperations().nodeAddLabel(node.getId(), labelId2);
    statement.close();
    tx.success();
    tx.finish();
    tx = db.beginTx();
    statement = statementContextProvider.instance();

    // WHEN
    statement.dataWriteOperations().nodeRemoveLabel(node.getId(), labelId2);

    // THEN
    PrimitiveIntIterator labelsIterator = statement.readOperations().nodeGetLabels(node.getId());
    Set<Integer> labels = asSet(labelsIterator);
    assertFalse(statement.readOperations().nodeHasLabel(node.getId(), labelId2));
    assertEquals(asSet(labelId1), labels);
    statement.close();
    tx.success();
    tx.finish();
  }
Exemple #12
0
    @SuppressWarnings("unchecked")
    private void expand() {
      Iterable<Relationship> expand = expander.expand(this, BranchState.NO_STATE);
      for (Relationship rel : expand) {
        lastMetadata.rels++;
        Node node = rel.getOtherNode(lastNode);
        Visit visit = visitData.get(node.getId());
        if (visit != null && visit.visited) {
          continue;
        }

        Visit lastVisit = visitData.get(lastNode.getId());
        double tentativeGScore =
            lastVisit.wayLength + lengthEvaluator.getCost(rel, Direction.OUTGOING);
        double estimate = estimateEvaluator.getCost(node, end);

        if (visit == null || !visit.next || tentativeGScore < visit.wayLength) {
          if (visit == null) {
            visit = new Visit(rel.getId(), tentativeGScore, estimate);
            visitData.put(node.getId(), visit);
          } else {
            visit.update(rel.getId(), tentativeGScore, estimate);
          }
          addNext(node, estimate + tentativeGScore, visit);
        }
      }
    }
  @Test
  public void testFindByIdFound() {
    // Arrange
    //
    String id = "ABCDEF";
    SubscriptionExpiry expiry = SubscriptionExpiry.NEVER;
    Subscription expected = Subscription.builder().id(id).expiry(expiry).build();

    when(mock_node.getProperty(eq(Subscription.PROP_ID))).thenReturn(expected.id());
    when(mock_node.getProperty(eq(Subscription.PROP_EXPIRY)))
        .thenReturn(expected.expiry().toString());

    when(mock_db.beginTx()).thenReturn(mock_tx);
    when(mock_db.findNode(eq(label), eq(Subscription.PROP_ID), eq(expected.id())))
        .thenReturn(mock_node);

    // Act
    //
    Subscription subs = s_dao.findById(id);

    // Assert
    //
    assertNotNull(subs);
    assertTrue(expected.equals(subs));
    verify(mock_db, atLeastOnce()).beginTx();
    verify(mock_db, times(1)).findNode(any(), any(), any());
    verify(mock_tx, atLeastOnce()).success();
    verify(mock_tx, times(1)).close();
  }
  public Node createNodeUsuario(Usuario usuario) {
    Node lockNode;
    try (Transaction tx = getManagerConnection().getGraphDb().beginTx()) {
      lockNode = getManagerConnection().getGraphDb().createNode();
      tx.success();
    }

    try (Transaction tx = getManagerConnection().beginTx()) {
      Index<Node> usersIndex = getManagerConnection().getGraphDb().index().forNodes("users");
      Node userNode = usersIndex.get("login", usuario.getLogin()).getSingle();
      if (userNode != null) {
        return userNode;
      }

      tx.acquireWriteLock(lockNode);
      userNode = usersIndex.get("login", usuario.getLogin()).getSingle();
      if (userNode == null) {
        userNode = getManagerConnection().getGraphDb().createNode(DynamicLabel.label("User"));
        usersIndex.add(userNode, "login", usuario.getLogin());
        userNode.setProperty("login", usuario.getLogin());
        userNode.setProperty("nome", usuario.getNome());
        userNode.setProperty("senha", usuario.getSenha());
        userNode.setProperty("type", usuario.getType().getName());
      }
      tx.success();
      return userNode;
    }
  }
  private void removeTupleOperation(
      EntityKey entityKey,
      Node node,
      TupleOperation operation,
      TupleContext tupleContext,
      Set<String> processedAssociationRoles) {
    if (!tupleContext.getTupleTypeContext().isPartOfAssociation(operation.getColumn())) {
      if (isPartOfRegularEmbedded(entityKey.getColumnNames(), operation.getColumn())) {
        // Embedded node
        String[] split = split(operation.getColumn());
        removePropertyForEmbedded(node, split, 0);
      } else if (node.hasProperty(operation.getColumn())) {
        node.removeProperty(operation.getColumn());
      }
    }
    // if the column represents a to-one association, remove the relationship
    else {
      String associationRole = tupleContext.getTupleTypeContext().getRole(operation.getColumn());
      if (!processedAssociationRoles.contains(associationRole)) {

        Iterator<Relationship> relationships =
            node.getRelationships(withName(associationRole)).iterator();

        if (relationships.hasNext()) {
          relationships.next().delete();
        }
      }
    }
  }
Exemple #16
0
  @Test
  public void deletingNodeWithLabelsShouldHaveRemovalReflectedInLabelScans() throws Exception {
    // GIVEN
    Transaction tx = db.beginTx();
    Label label = label("labello");
    Node node = db.createNode(label);
    tx.success();
    tx.finish();

    // AND GIVEN I DELETE IT
    tx = db.beginTx();
    node.delete();
    tx.success();
    tx.finish();

    // WHEN
    tx = db.beginTx();
    Statement statement = statementContextProvider.instance();
    int labelId = statement.readOperations().labelGetForName(label.name());
    PrimitiveLongIterator nodes = statement.readOperations().nodesGetForLabel(labelId);
    Set<Long> nodeSet = asSet(nodes);
    tx.success();
    tx.finish();

    // THEN
    assertThat(nodeSet, equalTo(Collections.<Long>emptySet()));
  }
  private void putOneToOneAssociation(
      Tuple tuple,
      Node node,
      TupleOperation operation,
      TupleContext tupleContext,
      Set<String> processedAssociationRoles) {
    String associationRole = tupleContext.getTupleTypeContext().getRole(operation.getColumn());

    if (!processedAssociationRoles.contains(associationRole)) {
      processedAssociationRoles.add(associationRole);

      EntityKey targetKey =
          getEntityKey(
              tuple,
              tupleContext
                  .getTupleTypeContext()
                  .getAssociatedEntityKeyMetadata(operation.getColumn()));

      // delete the previous relationship if there is one; for a to-one association, the
      // relationship won't have any
      // properties, so the type is uniquely identifying it
      Iterator<Relationship> relationships =
          node.getRelationships(withName(associationRole)).iterator();
      if (relationships.hasNext()) {
        relationships.next().delete();
      }

      // create a new relationship
      Node targetNode =
          entityQueries
              .get(targetKey.getMetadata())
              .findEntity(dataBase, targetKey.getColumnValues());
      node.createRelationshipTo(targetNode, withName(associationRole));
    }
  }
Exemple #18
0
  /**
   * While we transition ownership from the Beans API to the Kernel API for core database
   * interactions, there will be a bit of a mess. Our first goal is an architecture like this:
   *
   * <p>Users / \ Beans API Cypher \ / Kernel API | Kernel Implementation
   *
   * <p>But our current intermediate architecture looks like this:
   *
   * <p>Users / \ Beans API <--- Cypher | \ / | Kernel API | | Kernel Implementation
   *
   * <p>Meaning Kernel API and Beans API both manipulate the underlying kernel, causing lots of
   * corner cases. Most notably, those corner cases are related to Transactions, and the interplay
   * between three transaction APIs: - The Beans API - The JTA Transaction Manager API - The Kernel
   * TransactionContext API
   *
   * <p>In the long term, the goal is for JTA compliant stuff to live outside of the kernel, as an
   * addon. The Kernel API will rule supreme over the land of transactions. We are a long way away
   * from there, however, so as a first intermediary step, the JTA transaction manager rules
   * supreme, and the Kernel API piggybacks on it.
   *
   * <p>This test shows us how to use both the Kernel API and the Beans API together in the same
   * transaction, during the transition phase.
   */
  @Test
  public void mixingBeansApiWithKernelAPI() throws Exception {
    // 1: Start your transactions through the Beans API
    Transaction beansAPITx = db.beginTx();

    // 2: Get a hold of a KernelAPI statement context for the *current* transaction this way:
    Statement statement = statementContextProvider.instance();

    // 3: Now you can interact through both the statement context and the kernel API to manipulate
    // the
    //    same transaction.
    Node node = db.createNode();

    int labelId = statement.dataWriteOperations().labelGetOrCreateForName("labello");
    statement.dataWriteOperations().nodeAddLabel(node.getId(), labelId);

    // 4: Close the StatementContext
    statement.close();

    // 5: Commit through the beans API
    beansAPITx.success();
    beansAPITx.finish();

    // NOTE: Transactions are still thread-bound right now, because we use JTA to "own"
    // transactions,
    // meaning if you use
    // both the Kernel API to create transactions while a Beans API transaction is running in the
    // same
    // thread, the results are undefined.

    // When the Kernel API implementation is done, the Kernel API transaction implementation is not
    // meant
    // to be bound to threads.
  }
 @Test
 @Transactional
 public void testCreateNodeTypeWithProperties() throws Exception {
   Node person = neo4jTemplate.createNodeAs(Node.class, map("name", "name"));
   assertNotNull("created node", person);
   assertEquals("property created", "name", person.getProperty("name"));
 }
 private Object toJsonCompatible(Object value) {
   if (value instanceof Node) {
     final Node node = (Node) value;
     final Map<String, Object> result = SubGraph.toMap(node);
     result.put("_id", node.getId());
     return result;
   }
   if (value instanceof Relationship) {
     final Relationship relationship = (Relationship) value;
     final Map<String, Object> result = SubGraph.toMap(relationship);
     result.put("_id", relationship.getId());
     result.put("_start", relationship.getStartNode().getId());
     result.put("_end", relationship.getEndNode().getId());
     result.put("_type", relationship.getType().name());
     return result;
   }
   if (value instanceof Iterable) {
     final List<Object> result = new ArrayList<Object>();
     for (Object inner : (Iterable) value) {
       result.add(toJsonCompatible(inner));
     }
     return result;
   }
   return value;
 }
  @Test
  public void shouldBeAbleToGetPropertiesOnRelationship() throws Exception {

    long relationshipId;
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("foo", "bar");
    properties.put("neo", "Thomas A. Anderson");
    properties.put("number", 15L);
    Transaction tx = database.getGraph().beginTx();
    try {
      Node startNode = database.getGraph().createNode();
      Node endNode = database.getGraph().createNode();
      Relationship relationship =
          startNode.createRelationshipTo(endNode, DynamicRelationshipType.withName("knows"));
      for (Map.Entry<String, Object> entry : properties.entrySet()) {
        relationship.setProperty(entry.getKey(), entry.getValue());
      }
      relationshipId = relationship.getId();
      tx.success();
    } finally {
      tx.finish();
    }

    Map<String, Object> readProperties =
        serialize(actions.getAllRelationshipProperties(relationshipId));
    assertEquals(properties, readProperties);
  }
Exemple #22
0
  public static void aclerkTest(NeoTwDatabase neoTwDatabase) throws Exception {
    final int aclerkId = 316751683;

    System.out.println("Parsing...");

    JSONObject aclerkJsonObject =
        new JSONObject(
            new String(Files.readAllBytes(Paths.get(SAMPLE_TWITTER_DIR + "aclerk.json"))));

    System.out.println("Inserting...");

    TwUser aclerkTwUser = new TwUser(aclerkJsonObject);
    try (Transaction tx = neoTwDatabase.beginTx()) {
      Node aclerkNode = neoTwDatabase.getOrCreateTwUserNode(aclerkTwUser);

      tx.success();
    }

    System.out.println("Checking...");
    try (Transaction tx = neoTwDatabase.beginTx()) {
      Node aclerkNode = neoTwDatabase.getTwUserNodeById(aclerkTwUser.getId());
      System.out.println(aclerkNode.getProperty("id"));
      System.out.println(aclerkNode.getProperty("screenName"));
      System.out.println(aclerkNode.getProperty("jsonObject"));
    }
  }
  @Test
  public void removeNodesWithARelation() {
    int originalNodeCount = countNodesOf(graphDb);
    int removedNodeCount = 0;

    Transaction tx = graphDb.beginTx();
    try {
      Set<Node> toRemove = new HashSet<Node>();
      for (Node node : graphDb.getAllNodes()) {
        for (Relationship relationship : node.getRelationships(RelationType.ON)) {
          toRemove.add(relationship.getStartNode());
          toRemove.add(relationship.getEndNode());
          relationship.delete();
        }
      }
      for (Node node : toRemove) {
        node.delete();
        removedNodeCount++;
      }
      tx.success();
    } finally {
      tx.finish();
    }

    int finalNodeCount = countNodesOf(graphDb);
    assertEquals(
        Integer.valueOf(originalNodeCount), Integer.valueOf(finalNodeCount + removedNodeCount));
  }
Exemple #24
0
  public static void completeTest(NeoTwDatabase neoTwDatabase) throws Exception {
    // https://api.twitter.com/1.1/search/tweets.json?q=562b47a2e2704e07768b464c

    System.out.println("Parsing...");

    JSONObject completeJsonObject =
        new JSONObject(
            new String(Files.readAllBytes(Paths.get(SAMPLE_TWITTER_DIR + "complete.json"))));

    System.out.println("Inserting...");

    try (Transaction tx = neoTwDatabase.beginTx()) {
      JSONArray statusesJsonArray = completeJsonObject.optJSONArray("statuses");
      for (int i = 0; i < statusesJsonArray.length(); ++i) {
        JSONObject jsonObject = statusesJsonArray.getJSONObject(i);
        TwStatus twStatus = new TwStatus(jsonObject);
        Node node = neoTwDatabase.getOrCreateTwStatusNode(twStatus);
      }
      tx.success();
    }

    System.out.println("Checking...");

    try (Transaction tx = neoTwDatabase.beginTx()) {
      JSONArray statusesJsonArray = completeJsonObject.optJSONArray("statuses");
      for (int i = 0; i < statusesJsonArray.length(); ++i) {
        JSONObject jsonObject = statusesJsonArray.getJSONObject(i);
        TwStatus twStatus = new TwStatus(jsonObject);
        Node node = neoTwDatabase.getTwStatusNodeById(twStatus.getId());
        System.out.println(node.getProperty("jsonObject"));
      }
    }
  }
 private String getNodeSuperClass(Node n) {
   if (n.hasProperty(Constants.NODE_SUPER_CLASS_KEY)) {
     return (String) n.getProperty(Constants.NODE_SUPER_CLASS_KEY);
   } else {
     return "";
   }
 }
Exemple #26
0
  @Test
  public void testRelationshipAddProperty() {
    Node node1 = getGraphDb().createNode();
    Node node2 = getGraphDb().createNode();
    Relationship rel1 = node1.createRelationshipTo(node2, MyRelTypes.TEST);
    Relationship rel2 = node2.createRelationshipTo(node1, MyRelTypes.TEST);
    try {
      rel1.setProperty(null, null);
      fail("Null argument should result in exception.");
    } catch (IllegalArgumentException e) {
    }
    Integer int1 = new Integer(1);
    Integer int2 = new Integer(2);
    String string1 = new String("1");
    String string2 = new String("2");

    // add property
    rel1.setProperty(key1, int1);
    rel2.setProperty(key1, string1);
    rel1.setProperty(key2, string2);
    rel2.setProperty(key2, int2);
    assertTrue(rel1.hasProperty(key1));
    assertTrue(rel2.hasProperty(key1));
    assertTrue(rel1.hasProperty(key2));
    assertTrue(rel2.hasProperty(key2));
    assertTrue(!rel1.hasProperty(key3));
    assertTrue(!rel2.hasProperty(key3));
    assertEquals(int1, rel1.getProperty(key1));
    assertEquals(string1, rel2.getProperty(key1));
    assertEquals(string2, rel1.getProperty(key2));
    assertEquals(int2, rel2.getProperty(key2));

    getTransaction().failure();
  }
 public void delete(ConstructionZoneNode zone) {
   Node n = zone.getNode();
   for (Relationship rel : n.getRelationships()) {
     rel.delete();
   }
   n.delete();
 }
Exemple #28
0
  @Test
  public void testRelationshipChangeProperty2() {
    Integer int1 = new Integer(1);
    Integer int2 = new Integer(2);
    String string1 = new String("1");
    String string2 = new String("2");
    Boolean bool1 = new Boolean(true);
    Boolean bool2 = new Boolean(false);

    Node node1 = getGraphDb().createNode();
    Node node2 = getGraphDb().createNode();
    Relationship rel1 = node1.createRelationshipTo(node2, MyRelTypes.TEST);
    rel1.setProperty(key1, int1);
    rel1.setProperty(key1, int2);
    assertEquals(int2, rel1.getProperty(key1));
    rel1.removeProperty(key1);
    rel1.setProperty(key1, string1);
    rel1.setProperty(key1, string2);
    assertEquals(string2, rel1.getProperty(key1));
    rel1.removeProperty(key1);
    rel1.setProperty(key1, bool1);
    rel1.setProperty(key1, bool2);
    assertEquals(bool2, rel1.getProperty(key1));
    rel1.removeProperty(key1);

    rel1.delete();
    node2.delete();
    node1.delete();
  }
 private Node addNode(EmbeddedGraphDatabase graphDb) {
   Node referenceNode = graphDb.getReferenceNode();
   Node node = graphDb.createNode();
   node.setProperty("theId", node.getId());
   referenceNode.createRelationshipTo(node, MyRels.TEST);
   return node;
 }
  @Test
  public void testStartStopAutoIndexing() throws Exception {
    stopDb();
    config = new HashMap<>();
    config.put(GraphDatabaseSettings.node_keys_indexable.name(), "propName");
    config.put(GraphDatabaseSettings.node_auto_indexing.name(), "true");
    // Now only node properties named propName should be indexed.
    startDb();

    AutoIndexer<Node> autoIndexer = graphDb.index().getNodeAutoIndexer();
    assertTrue(autoIndexer.isEnabled());

    autoIndexer.setEnabled(false);
    assertFalse(autoIndexer.isEnabled());
    newTransaction();

    Node node1 = graphDb.createNode();
    Node node2 = graphDb.createNode();
    node1.setProperty("propName", "node");
    newTransaction();

    assertFalse(autoIndexer.getAutoIndex().get("nodeProp1", "node1").hasNext());
    autoIndexer.setEnabled(true);
    node2.setProperty("propName", "node");

    newTransaction();

    assertEquals(node2, autoIndexer.getAutoIndex().get("propName", "node").getSingle());
  }