Java Code Examples for org.neo4j.graphdb.Transaction#success()

The following examples show how to use org.neo4j.graphdb.Transaction#success() . 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: AlgorithmTests.java    From metalcon with GNU General Public License v3.0 6 votes vote down vote up
/**
 * create the test users in the database
 * 
 * @param graphDatabase
 *            social graph database to operate on
 */
public static void createUsers(final AbstractGraphDatabase graphDatabase) {
	USER_IDS = new String[5];
	USERS = new Node[USER_IDS.length];
	final Transaction transaction = graphDatabase.beginTx();

	try {
		for (int i = 0; i < USER_IDS.length; i++) {
			USER_IDS[i] = String.valueOf(i);
			USERS[i] = NeoUtils.createUserNode(USER_IDS[i]);
			USERS[i].setProperty(Properties.User.DISPLAY_NAME, "Testy");
			USERS[i].setProperty(Properties.User.PROFILE_PICTURE_PATH,
					"google.de/somepic");
		}
		transaction.success();
	} finally {
		transaction.finish();
	}
}
 
Example 2
Source File: NodeManagerTest.java    From graphify with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetNodeProperty() throws Exception {
    GraphDatabaseService db = setUpDb();
    NodeManager nodeManager = new NodeManager();
    NodeManager.globalNodeCache.invalidateAll();
    DataNodeManager.dataCache.invalidateAll();
    DataNodeManager dataNodeManager = new DataNodeManager();

    // Write some nodes to the database
    Transaction tx1 = db.beginTx();
    Node a = nodeManager.getOrCreateNode(dataNodeManager, "a", db);
    tx1.success();
    Assert.assertNotNull(a);

    String expected = "success";
    nodeManager.setNodeProperty(a.getId(), "test", expected, db);
    Transaction tx = db.beginTx();
    String actual = (String)NodeManager.getNodeFromGlobalCache(a.getId()).get("test");
    tx.success();

    Assert.assertEquals(expected, actual);
}
 
Example 3
Source File: AllNodesLabeler.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
  logger.info("Starting all nodes labeling...");
  int processedNodes = 0;

  Transaction tx = graphDb.beginTx();

  ResourceIterable<Node> allNodes = graphDb.getAllNodes();
  for (Node n : allNodes) {
    n.addLabel(label);
    if (processedNodes % batchCommitSize == 0) {
      tx.success();
      tx.close();
      tx = graphDb.beginTx();
    }
    processedNodes++;
  }

  logger.info(processedNodes + " nodes labeled.");
  tx.success();
  tx.close();
}
 
Example 4
Source File: AnonymousNodeTagger.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
  logger.info("Starting anonymous nodes tagger...");
  int taggedNodes = 0;
  Transaction tx = graphDb.beginTx();

  ResourceIterable<Node> allNodes = graphDb.getAllNodes();
  for (Node n : allNodes) {
    if (n.hasProperty(anonymousProperty)) {
      n.addLabel(OwlLabels.OWL_ANONYMOUS);
      taggedNodes++;
    }
    if (taggedNodes % batchCommitSize == 0) {
      tx.success();
      tx.close();
      tx = graphDb.beginTx();
    }
  }

  logger.info(taggedNodes + " nodes tagged.");
  tx.success();
  tx.close();
}
 
Example 5
Source File: NeoGraph.java    From neo4jena with Apache License 2.0 6 votes vote down vote up
/**
 * Delete the given triple from the graph.
 */
@Override
public void delete(Triple triple) throws DeleteDeniedException {
	Transaction tx=graphdb.beginTx();
	org.neo4j.graphdb.Node subject = nodeFactory.get(triple.getSubject());
	System.out.println("Subject node:" + subject.getProperty("uri"));
	if(subject!=null) {
		org.neo4j.graphdb.Node object = nodeFactory.get(triple.getObject());
		System.out.println("Object node:" + object.getProperty("uri"));
		if(object!=null) {
			Relationship relation = relationshipFactory.get(subject, triple.getPredicate().getURI(), object);
			System.out.println("Relationship:" +relation.getProperty("uri"));
			if(!subject.hasRelationship())
				subject.delete();
			if(triple.getObject().isLiteral())
				object.delete();
			else if(!object.hasRelationship())
				object.delete();
		}
		tx.success();
	}	
}
 
Example 6
Source File: CategoryProcessor.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Set<Long>> call() throws Exception {
  logger.info("Processsing " + category);
  Map<String, Set<Long>> map = new HashMap<String, Set<Long>>();
  Set<Long> nodeSet = new HashSet<Long>();
  Transaction tx = graphDb.beginTx();
  try {
    for (Path position : graphDb.traversalDescription().uniqueness(Uniqueness.NODE_GLOBAL).depthFirst()
        .relationships(OwlRelationships.RDFS_SUBCLASS_OF, Direction.INCOMING).relationships(OwlRelationships.RDF_TYPE, Direction.INCOMING)
        .relationships(OwlRelationships.OWL_EQUIVALENT_CLASS, Direction.BOTH).relationships(OwlRelationships.OWL_SAME_AS, Direction.BOTH)
        .traverse(root)) {
      Node end = position.endNode();
      nodeSet.add(end.getId());
    }
    logger.info("Discovered " + nodeSet.size() + " nodes for " + category);
    map.put(category, nodeSet);
  } catch (Exception e) {
    logger.warning("IRI not found for category: " + category);
  } finally {
    tx.success();
    tx.close();
  }
  return map;
}
 
Example 7
Source File: ReachabilityIndex.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
public void dropIndex() {
  if (indexExists()) {
    Transaction tx = graphDb.beginTx();

    // ...cleanup the index.
    int counter = 0;
    for (Node n : graphDb.getAllNodes()) {
      n.removeProperty(IN_LIST_PROPERTY);
      n.removeProperty(OUT_LIST_PROPERTY);
      tx = batchTransactions(tx, counter++);
    }

    // reset the flag.
    metaDataNode.setProperty(INDEX_EXISTS_PROPERTY, false);

    tx.success();
    tx.close();
    logger.info("Reachability index dropped.");
  } else {
    logger.warning("There was no reachability index to drop.");
  }
}
 
Example 8
Source File: StatusUpdateManager.java    From metalcon with GNU General Public License v3.0 6 votes vote down vote up
/**
 * store the status update template linking to the latest previous version
 * 
 * @param graphDatabase
 *            social graph database to store the template in
 * @param template
 *            status update template
 * @param previousTemplateNode
 *            template node of the latest previous version
 */
private static void storeStatusUpdateTemplate(
		final AbstractGraphDatabase graphDatabase,
		final StatusUpdateTemplate template, final Node previousTemplateNode) {
	final Transaction transaction = graphDatabase.beginTx();
	try {
		// create template node
		final Node templateNode = StatusUpdateTemplate.createTemplateNode(
				graphDatabase, template);

		// link to the latest previous version
		if (previousTemplateNode != null) {
			templateNode.createRelationshipTo(previousTemplateNode,
					SocialGraphRelationshipType.Templates.PREVIOUS);
		}

		// store the template node
		NeoUtils.storeStatusUpdateTemplateNode(graphDatabase,
				template.getName(), templateNode, previousTemplateNode);

		transaction.success();
	} finally {
		transaction.finish();
	}
}
 
Example 9
Source File: JenaNeoNode.java    From neo4jena with Apache License 2.0 5 votes vote down vote up
/**
 * Get the URI of node.
 */
@Override
public String getURI() {
	Transaction tx = graphDb.beginTx();
	String uri = delegate.getProperty(NeoGraph.PROPERTY_URI).toString();
	tx.success();
	return uri;
}
 
Example 10
Source File: ETransactionImpl.java    From jcypher with Apache License 2.0 5 votes vote down vote up
@Override
public List<JcError> close() {
	List<JcError> errors;
	if (isClosed())
		throw new RuntimeException(ERR_CLOSED);
	if (!isMyThread())
		throw new RuntimeException(ERR_THREAD);
	
	AbstractEmbeddedDBAccess edba = getEDBAccess();
	edba.removeTx();
	if (this.transaction != null) {
		Transaction tx = getTransaction();
		if (failed)
			tx.failure();
		else
			tx.success();
		
		Throwable dbException = null;
		try {
			tx.close();
		} catch(Throwable e) {
			dbException = e;
		}
		errors = DBUtil.buildErrorList(null, dbException);
	} else 
		errors = new ArrayList<JcError>();
	
	if (errors.size() > 0)
		failure();
	setClosed();
	
	return errors;
}
 
Example 11
Source File: ParallelBatchTransaction.java    From neo4j-mazerunner with Apache License 2.0 5 votes vote down vote up
/**
 * Computes a section of the source array and applies updates to those nodes referenced
 * in each block.
 * @throws IOException
 */
protected void computeDirectly() throws IOException {

    Transaction tx = db.beginTx();

    Node partitionNode = null;

    if(analysis.getMode() == ProcessorMode.Partitioned)
        partitionNode = db.getNodeById(analysis.getPartitionDescription().getPartitionId());

    for (int i = mStart; i < mStart + mLength; i++) {
        final Node finalPartitionNode = partitionNode;
        mSource[i].forEachRemaining(line -> {
            switch (analysis.getMode()) {
                case Partitioned:
                    Writer.updatePartitionBlockForRow(line, db, reportBlock, analysis, finalPartitionNode);
                    break;
                case Unpartitioned:
                    Writer.updateBlockForRow(line, db, reportBlock, analysis.getAnalysis());
                    break;
            }

        });
    }

    tx.success();
    tx.close();

}
 
Example 12
Source File: DataRelationshipManager.java    From graphify with Apache License 2.0 5 votes vote down vote up
public void getOrCreateNode(Long start, Long end, GraphDatabaseService db) {
    List<Long> relList = relationshipCache.getIfPresent(start);

    Node startNode = db.getNodeById(start);

    if (relList == null) {
        List<Long> nodeList = new ArrayList<>();
        for(Node endNodes : db.traversalDescription()
                .depthFirst()
                .relationships(withName(relationshipType), Direction.OUTGOING)
                .evaluator(Evaluators.fromDepth(1))
                .evaluator(Evaluators.toDepth(1))
                .traverse(startNode)
                .nodes())
        {
            nodeList.add(endNodes.getId());
        }

        relList = nodeList;
        relationshipCache.put(start, relList);
    }

    if (!relList.contains(end)) {
        Transaction tx = db.beginTx();
        try {
            Node endNode = db.getNodeById(end);
            startNode.createRelationshipTo(endNode, withName(relationshipType));
            tx.success();
        } catch (final Exception e) {
            tx.failure();
        } finally {
            tx.close();
            relList.add(end);
            relationshipCache.put(start, relList);
        }
    }
}
 
Example 13
Source File: JenaNeoNode.java    From neo4jena with Apache License 2.0 5 votes vote down vote up
/**
 * Check if the node is a blank node.
 */
@Override
 public boolean isBlank(){
	Transaction tx = graphDb.beginTx();
	if(node!=null){
		boolean check = node.hasLabel(DynamicLabel.label(NeoGraph.LABEL_BNODE));
		tx.success();
		return check;
	}
	return false;
 }
 
Example 14
Source File: CreateStatusUpdateRequestTest.java    From metalcon with GNU General Public License v3.0 5 votes vote down vote up
/**
 * create a test status update in the database
 * 
 * @param graphDatabase
 *            social graph database to operate on
 * @param statusUpdateId
 *            identifier of the new status update
 */
public static void createStatusUpdate(
		final AbstractGraphDatabase graphDatabase,
		final String statusUpdateId) {
	final Transaction transaction = graphDatabase.beginTx();

	try {
		NeoUtils.createStatusUpdateNode(statusUpdateId);
		transaction.success();
	} finally {
		transaction.finish();
	}
}
 
Example 15
Source File: RoadContracter.java    From atlas with GNU General Public License v3.0 5 votes vote down vote up
public boolean contractRoad() {
    Transaction tx = db.beginTx();
    Iterator<Node> wayStartIterator = db.findNodes(Label.label("WAY_START"));
    while(wayStartIterator.hasNext()) {
        Node wayStartNode = wayStartIterator.next();

    }
    tx.success();
    tx.close();
    return true;
}
 
Example 16
Source File: ReachabilityIndex.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
void commitIndexToGraph(InMemoryReachabilityIndex inMemoryIndex) {
  Transaction tx = graphDb.beginTx();

  int operationCount = 0;
  for (Entry<Long, InOutList> e : inMemoryIndex.entrySet()) {
    Node node = graphDb.getNodeById(e.getKey());
    node.setProperty(IN_LIST_PROPERTY, Longs.toArray(e.getValue().getInList()));
    node.setProperty(OUT_LIST_PROPERTY, Longs.toArray(e.getValue().getOutList()));
    tx = batchTransactions(tx, operationCount++);
  }

  metaDataNode.setProperty(INDEX_EXISTS_PROPERTY, true);
  tx.success();
  tx.close();
}
 
Example 17
Source File: AtlasTraversalTest.java    From atlas with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void getWayNodes() {
    List<FastNode> dummyNodesForWay1 = getDummyNodesForWay(20);
    List<FastNode> dummyNodesForWay2 = getDummyNodesForWay(19);

    FastNode middleNode = dummyNodesForWay1.get(10);
    dummyNodesForWay2.add(10,middleNode);

    Way way1 = getDummyWay(dummyNodesForWay1);
    Way way2 = getDummyWay(dummyNodesForWay2);

    fastWriter.start(graphDatabaseService);
    dummyNodesForWay1.stream().forEach(fastNode ->  fastWriter.addNode(fastNode));
    dummyNodesForWay2.stream().forEach(fastNode ->  fastWriter.addNode(fastNode));
    Node wayNode1 = fastWriter.addWay(way1);
    Node wayNode2 = fastWriter.addWay(way2);

    // because there are two WAY_START nodes
    assertFastNodeCountInDatabase(39,41);

    Transaction tx = graphDatabaseService.beginTx();
    //getNodesInTraversal(wayNode1).forEach(node -> System.out.println(node.getAllProperties().toString()));
    assertPathContainsNodesAndJustNodes(wayNode1, dummyNodesForWay1);
    assertPathContainsNodesAndJustNodes(wayNode2, dummyNodesForWay2);
    tx.success();
    tx.close();
}
 
Example 18
Source File: EdgeLabeler.java    From SciGraph with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
  logger.info("Starting edge labeling...");
  Map<String, String> map = new HashMap<String, String>();
  int processedRels = 0;

  Transaction tx = graphDb.beginTx();
  ResourceIterable<Relationship> rels = graphDb.getAllRelationships();

  for (Relationship rel : rels) {

    if (processedRels % batchCommitSize == 0) {
      tx.success();
      tx.close();
      tx = graphDb.beginTx();
    }

    String relName = rel.getType().name();
    if (map.containsKey(relName)) {
      rel.setProperty(edgeProperty, map.get(relName));
    } else {
      String relLabel = relName;
      String query = "START n = node:node_auto_index(iri='" + relName + "') match (n) return n";
      Result result = graphDb.execute(query);
      if (result.hasNext()) {
        Node n = (Node) result.next().get("n");
        if (n.hasProperty(NodeProperties.LABEL)) {
          relLabel =
              GraphUtil.getProperties(n, NodeProperties.LABEL, String.class).iterator().next();
        }
      }
      rel.setProperty(edgeProperty, relLabel);
      map.put(relName, relLabel);
    }

    processedRels++;
  }

  logger.info(processedRels + " relations labeled.");
  tx.success();
  tx.close();
}
 
Example 19
Source File: Neo4jRiverIntTest.java    From elasticsearch-river-neo4j with Apache License 2.0 4 votes vote down vote up
@Test
  public void testAddAndRemoveNodes() throws InterruptedException {

      Thread.sleep(200); // allow river to start
      String name = UUID.randomUUID().toString();

      // add node to neo4j
      HashMap<String, Object> map = new HashMap<String, Object>();
      map.put("name", name);
      Transaction tx = db.beginTx();
      ArrayList<String> labels = new ArrayList<String>();
org.neo4j.graphdb.Node n = db.createNode(map, labels);
      tx.success();

      CountResponse resp = null;

      int k = 0;
      while (k++ < 100) {

          Thread.sleep(1000); // time for poller to index
          refreshIndex();

          logger.debug("Count request [index={}, type={}, name={}]", new Object[]{index, type, name});
          resp = node.client().count(countRequest(index).types(type).source(queryString(name).defaultField("name").toString())).actionGet();
          if (1 == resp.getCount())
              break;

      }
      assertEquals(1, resp.getCount());

      db.remove(n);

      k = 0;
      while (k++ < 100) {

          Thread.sleep(1000); // time for poller to index
          refreshIndex();

          logger.debug("Count request [index={}, type={}, name={}]", new Object[]{index, type, name});
          resp = node.client().count(countRequest(index).types(type).source(queryString(name).defaultField("name").toString())).actionGet();
          if (0 == resp.getCount())
              break;

      }

      assertEquals(0, resp.getCount());

      shutdown();
  }
 
Example 20
Source File: WriterTest.java    From neo4j-mazerunner with Apache License 2.0 4 votes vote down vote up
private void createSampleGraph(GraphDatabaseService db) {

        List<Node> nodes = new ArrayList<>();

        int max = 200;
        Transaction tx = db.beginTx();
        Node partitionNode = db.createNode();
        partitionNode.addLabel(DynamicLabel.label("Category"));
        tx.success();
        tx.close();
        int count = 0;
        int partitionBlockCount = 50;

        tx = db.beginTx();
        // Create nodes
        for (int i = 0; i < max; i++) {

            nodes.add(db.createNode());
            nodes.get(i).addLabel(DynamicLabel.label("Node"));
            partitionNode.createRelationshipTo(nodes.get(i), withName("HAS_CATEGORY"));
            count++;
            if(count >= partitionBlockCount && i != max - 1) {

                count = 0;
                partitionNode = db.createNode();
                partitionNode.addLabel(DynamicLabel.label("Category"));

                tx.success();
                tx.close();
                tx = db.beginTx();

                System.out.println(i);
            }
        }

        tx.success();
        tx.close();

        tx = db.beginTx();
        // Create PageRank test graph
        for (int i = 0; i < (max / 2) - 1; i++) {
            nodes.get(i).createRelationshipTo(nodes.get(i + (max / 2)), withName("CONNECTED_TO"));
            nodes.get(i + (max / 2)).createRelationshipTo(nodes.get(i + 1), withName("CONNECTED_TO"));
            if(count >= partitionBlockCount / 2 && i != max - 1) {
                tx.success();
                tx.close();
                tx = db.beginTx();

                System.out.println("B: " + i);
            }
            if(i == (max / 2) - 2) {
                nodes.get((i + 1) + (max / 2)).createRelationshipTo(nodes.get(0), withName("CONNECTED_TO"));
                nodes.get(i + 1).createRelationshipTo(nodes.get((max / 2)), withName("CONNECTED_TO"));
            }
        }

        tx.success();
        tx.close();
    }