Neo4j browser freezes the whole system - java

I'm using an embedded Neo4j instance in my Spring Boot project (I'm using Spring JPA and Neo4j separately and I'm not using Spring-Boot-Neo4j stuff) and I want to visualise the graph I build using the Neo4j browser that I downloaded from here with the addition of a custom init.coffee that allows it to display images inside the nodes
This is the code I use in order to build my graph. The "buildGraph" function is executed when a request is being received by one of my RestControllers
(the reason I include all of my business logic implementation is because it may help detecting relationships/nodes etc being created/handled in a wrong way)
#Component
public class GraphBuilder
{
private String dbPath;
private int numberOFConnectionsForKeyIndividuals;
private String neo4jBoltAddress;
#Autowired
PersonService personService;
private final GraphDatabaseService graphDb;
public GraphBuilder(#Value("${dbPath}") String dbPath,
#Value("${neo4jBoltAddress}") String neo4jBoltAddress,
#Value("${numberOFConnectionsForKeyIndividuals}") int numberOFConnectionsForKeyIndividuals)
{
GraphDatabaseSettings.BoltConnector bolt = GraphDatabaseSettings.boltConnector( "0" );
this.dbPath = dbPath;
this.neo4jBoltAddress = neo4jBoltAddress;
this.numberOFConnectionsForKeyIndividuals = numberOFConnectionsForKeyIndividuals;
graphDb = new GraphDatabaseFactory()
.newEmbeddedDatabaseBuilder( new File(dbPath) )
.setConfig( bolt.type, "BOLT" )
.setConfig( bolt.enabled, "true" )
.setConfig( bolt.address, neo4jBoltAddress )
.newGraphDatabase();
registerShutdownHook( graphDb );
}
public void buildGraph()
{
List<Long> AsIDs = new ArrayList<>();
Map<Long,Long> personIdToNodeMap = new HashMap<>();
Map<String,List<Long>> nameToId = new HashMap<>();
Map<Long,List<Association>> associationsMap = new HashMap<>();
try ( Transaction tx = graphDb.beginTx() )
{
Schema schema = graphDb.schema();
for(Person person : personService.findAllPersons())
{
Node personNode = graphDb.createNode(new Label() {
#Override
public String name() {
return "Person";
}
});
//mapping persons to their respective nodes
personIdToNodeMap.put(person.getPersonId(),personNode.getId());
//mapping names to the ids of the persons
if(nameToId.get(person.getName()) == null)
{
nameToId.put(person.getName(), new ArrayList<>());
}
nameToId.get(person.getName()).add(person.getPersonId());
personNode.setProperty("Name", person.getName());
for(int a = 0 ; a < person.getAliases().size() ; a++)
{
personNode.setProperty("Alias " + a+1, person.getAliases().get(a).getAlias());
}
personNode.setProperty("Additional Name Information", person.getAdditionalNameInformation() != null ? person.getAdditionalNameInformation() : "");
personNode.setProperty("Id", person.getPersonId());
personNode.setProperty("Date of Birth", person.getDob() != null ? person.getDob() : "");
for(int f = 0 ; f < person.getFacebook().size() ; f++)
{
personNode.setProperty("Facebook " + f+1, person.getFacebook().get(f).getFacebookPage() + " (" + person.getFacebook().get(f).getAdditionalFacebookPageInformation() + ")");
}
personNode.setProperty("Additional Information", person.getInfo() != null ? person.getInfo() : "");
personNode.setProperty("image_url","http://localhost:8888/files/"+person.getPictureFilePath());
personNode.setProperty("Node Type", "Person");
if(person.getAssociations().size() > numberOFConnectionsForKeyIndividuals)
{
personNode.setProperty("Key_Individual","Yes");
}
for(A A : person.getAs())
{
Node ANode = graphDb.createNode(new Label() {
#Override
public String name() {
return "A";
}
});
ANode.setProperty("A", A.getA());
//TODO elaborate more on the A with additional properties
ANode.setProperty("Node Type", "A");
personNode.createRelationshipTo( ANode, EdgeTypes.HAS_DONE );
ANode.setProperty("image_url","http://localhost:8888/images/A.png");
AsIDs.add(ANode.getId());
}
for(Association association : person.getAssociations())
{
if(associationsMap.get(person.getPersonId()) == null)
{
associationsMap.put(person.getPersonId(), new ArrayList<>());
}
associationsMap.get(person.getPersonId()).add(association);
}
}
//Validating and building the association edges
//iterating through the nodes
for(Long personFromId : associationsMap.keySet())
{
//iterating through the associations registered for the node
for(Association associationFrom : associationsMap.get(personFromId))
{
String personNameFrom = associationFrom.getPersonNameFrom();
String personNameTo = associationFrom.getPersonNameTo();
//iterating through the persons whose name matches the other end of the association
if(nameToId.get(personNameTo) != null)
{
for(Long personToId : nameToId.get(personNameTo))
{
//iterating through the associations of the person at the other end of the association
if(associationsMap.get(personToId) != null)
{
List<Association> associationsToRemove = new ArrayList<>();
for(Association associationTo : associationsMap.get(personToId))
{
if(associationTo.getPersonNameTo().equals(personNameFrom) && nameToId.get(personNameFrom).contains(personFromId))
{
if(nameToId.get(personNameFrom).size() == 1)
{
Relationship relationship = graphDb.getNodeById(personIdToNodeMap.get(personFromId))
.createRelationshipTo( graphDb.getNodeById(personIdToNodeMap.get(personToId)), EdgeTypes.ASSOCIATES_WITH );
if(associationFrom.getType() != null)
{
relationship.setProperty("Association Type",associationFrom.getType());
}
associationsToRemove.add(associationTo);
}
else
{
boolean alreadyConnected = false;
for(Relationship rel : graphDb.getNodeById(personIdToNodeMap.get(personFromId)).getRelationships())
{
if( ( rel.getOtherNode(graphDb.getNodeById(personIdToNodeMap.get(personFromId))).
equals(graphDb.getNodeById(personIdToNodeMap.get(personToId))) ) )
{
alreadyConnected = true;
break;
}
}
if(!alreadyConnected)
{
Relationship relationship = graphDb.getNodeById(personIdToNodeMap.get(personFromId))
.createRelationshipTo( graphDb.getNodeById(personIdToNodeMap.get(personToId)), EdgeTypes.PROBABLY_ASSOCIATES_WITH );
if(associationFrom.getType() != null)
{
relationship.setProperty("Association Type",associationFrom.getType());
}
}
// associationsToRemove.add(associationTo);
}
}
}
associationsMap.get(personToId).removeAll(associationsToRemove);
}
}
}
}
}
tx.success();
}
Map<Long,List<String>> AToNamesMap = new HashMap<>();
//detecting names referred in the A's description
try(Transaction txAs = graphDb.beginTx() )
{
for(Long id : AsIDs)
{
Node ANode = graphDb.getNodeById(id);
String A = (String) ANode.getProperty("A");
for(String name : nameToId.keySet())
{
if(A.contains(name)) {
if(AToNamesMap.get(id) == null)
{
AToNamesMap.put(id,new ArrayList<>());
}
AToNamesMap.get(id).add(name);
}
}
}
List<Long> groupedAs = new ArrayList<>();
for(Long id : AsIDs)
{
if(AToNamesMap.get(id)!= null && AToNamesMap.get(id).size() > 1)
{
for(Long otherAID : AToNamesMap.keySet())
{
if(id != otherAID && !groupedAs.contains(otherAID) && !groupedAs.contains(id))
{
if(compareNamesLists(AToNamesMap.get(id), AToNamesMap.get(otherAID)))
{
Relationship rel = graphDb.getNodeById(otherAID).getSingleRelationship(EdgeTypes.HAS_DONE,Direction.INCOMING);
Node otherPersonNode = rel.getStartNode();
if(nameToId.get(otherPersonNode.getProperty("Name")) != null && nameToId.get(otherPersonNode.getProperty("Name")).size() > 1)
{
otherPersonNode.createRelationshipTo(graphDb.getNodeById(id), EdgeTypes.HAS_PROBABLY_DONE);
}
else
{
otherPersonNode.createRelationshipTo(graphDb.getNodeById(id), EdgeTypes.HAD_DONE);
}
rel.delete();
graphDb.getNodeById(otherAID).delete();
groupedAs.add(otherAID);
}
}
}
}
groupedAs.add(id);
}
txAs.success();
}
}
private static void registerShutdownHook( final GraphDatabaseService graphDb )
{
// Registers a shutdown hook for the Neo4j instance so that it
// shuts down nicely when the VM exits (even if you "Ctrl-C" the
// running application).
Runtime.getRuntime().addShutdownHook( new Thread()
{
#Override
public void run()
{
graphDb.shutdown();
}
} );
}
}
When I open the browser and connect it to the bolt that I expose for my embedded neo4j, the browser is able to show all the nodes in my graph database (at the moment less than 100) and it then freezes, causing the entire system to freeze (MacBook Pro 2016, 16GB). This happens around 3/5 times.
I know that the way I make my transactions is not ideal, but as I said all this processing happens before the neo4j browser starts.
Can you advise me on how to solve this issue?
Can you see anything in my code (connection left open etc) Is this a known issue for the neo4j browser?

Related

snmp4j map table to pojo

I have a pojo like this :
public class IpAddress {
private String index ;
private String ip ;
private String netmask ;
// Getter & Setter ....
}
now i wrote a code with snmp4j for fetch table and map result to list of this pojo :
public class MainClass {
private static final Address address = GenericAddress.parse("udp://10.10.10.2/161");
public static void main(String[] args) throws Exception {
CommunityTarget<Address> target = new CommunityTarget<>();
target.setCommunity(new OctetString("private"));
target.setAddress(address);
target.setRetries(5);
target.setTimeout(15000);
target.setVersion(SnmpConstants.version2c);
List<IpAddress> ipAddressList = doWalkTable(".1.3.6.1.2.1.4.20", target);
System.out.println(ipAddressList);
}
public static List<IpAddress> doWalkTable(String tableOid, Target<Address> target) throws IOException {
List<IpAddress> ipAddressList = new ArrayList<>();
TransportMapping<? extends Address> transport = new DefaultUdpTransportMapping();
Snmp snmp = new Snmp(transport);
transport.listen();
TableUtils tableUtils = new TableUtils(snmp, new DefaultPDUFactory());
List<TableEvent> events = tableUtils.getTable(target, new OID[]{new OID(tableOid)}, null, null);
if (events == null || events.size() == 0) {
System.out.println("Error: Unable to read table...");
return ipAddressList;
}
for (TableEvent event : events) {
if (event == null) {
continue;
}
if (event.isError()) {
System.out.println("Error: table OID [" + tableOid + "] " + event.getErrorMessage());
continue;
}
VariableBinding[] varBindings = event.getColumns();
if (varBindings == null || varBindings.length == 0) {
continue;
}
for (VariableBinding varBinding : varBindings) {
if (varBinding == null) {
continue;
}
// -> How can fill ipAddressList ????
}
System.out.println("------------------------------------------------------");
}
snmp.close();
return ipAddressList;
}
}
this is result of snmptable :
# snmptable -v 2c -c public 10.10.10.2 IP-MIB::ipAddrTable
ipAdEntAddr ipAdEntIfIndex ipAdEntNetMask ipAdEntBcastAddr ipAdEntReasmMaxSize
10.10.10.2 2 255.255.255.0 1 18024
115.54.20.12 4 255.255.255.0 1 18024
My problem is :
1) there is any solution to find out OID is table or tree ?
2) I can not understand how can detect row and columns from TableEvent .
result does not have any identifier for calculate number of rows or number of columns .

Algorithm or code to print the binary tree of agents

I try to write code in jade (Java Agent DEvelopment Framework) to print the binary tree of agents in sma. I want to print tree inorder traversal with origin algorithm:
Traverse the left subtree, i.e., call Inorder(left-subtree)
Visit the root.
Traverse the right subtree, i.e., call Inorder(right-subtree)
And my node agent is:
class Noeud {
private Integer value = null;
private AID gauche = null;
private AID droit = null;
private AID pere = null;
}
In my agent to print, I use CyclicBehaviour as extensions. With my code:
public class ReceiveAffichageBehaviour extends CyclicBehaviour{
#Override
public void action() {
MessValueGauche();
MessValue();
MessValueDroit();
}
private void MessValueGauche() {
MessageTemplate messageTemplate = MessageTemplate.and(
MessageTemplate.MatchOntology(Constants.AFFICHAGE_VALUE_GAUCHE),
MessageTemplate.MatchPerformative(ACLMessage.REQUEST)
);
ACLMessage receiveMsg = myAgent.receive(messageTemplate);
if (receiveMsg != null) {
String contenu = receiveMsg.getContent() + "(";
ACLMessage message = new ACLMessage(ACLMessage.REQUEST);
if (noeud.getGauche() == null) {
message.setOntology(Constants.AFFICHAGE_VALUE);
message.addReceiver(myAgent.getAID());
} else {
message.setOntology(Constants.AFFICHAGE_VALUE_GAUCHE);
message.addReceiver(noeud.getGauche());
}
message.setContent(contenu);
myAgent.send(message);
} else {
block();
}
}
private void MessValue() {
MessageTemplate messageTemplate = MessageTemplate.and(
MessageTemplate.MatchOntology(Constants.AFFICHAGE_VALUE),
MessageTemplate.MatchPerformative(ACLMessage.REQUEST)
);
ACLMessage receiveMsg = myAgent.receive(messageTemplate);
if (receiveMsg != null) {
String contenu = receiveMsg.getContent() + (noeud.getValue() == null ? "" : noeud.getValue().toString());
ACLMessage message = new ACLMessage(ACLMessage.REQUEST);
if (noeud.getDroit() == null){
message.setOntology(Constants.AFFICHAGE_VALUE_DROIT);
message.addReceiver(myAgent.getAID());
} else if (noeud.getDroit().equals(receiveMsg.getSender())){
message.setOntology(Constants.AFFICHAGE_VALUE_DROIT);
message.addReceiver(noeud.getPere());
} else {
message.setOntology(Constants.AFFICHAGE_VALUE_GAUCHE);
message.addReceiver(noeud.getDroit());
}
message.setContent(contenu);
myAgent.send(message);
} else {
block();
}
}
private void MessValueDroit() {
MessageTemplate messageTemplate = MessageTemplate.and(
MessageTemplate.MatchOntology(Constants.AFFICHAGE_VALUE_DROIT),
MessageTemplate.MatchPerformative(ACLMessage.REQUEST)
);
ACLMessage receiveMsg = myAgent.receive(messageTemplate);
if (receiveMsg != null) {
String contenu = receiveMsg.getContent() + ")";
ACLMessage message = new ACLMessage(ACLMessage.REQUEST);
message.setContent(contenu);
if (noeud.getDroit() == null && noeud.getGauche() == null ){
if (noeud.getPere().equals(Constants.AID_RACINE)){
message.setPerformative(ACLMessage.CONFIRM);
} else {
message.setOntology(Constants.AFFICHAGE_VALUE_GAUCHE);
}
message.addReceiver(noeud.getPere());
}
myAgent.send(message);
} else {
block();
}
}
I don't know to fix the infini loop in my code. Who can help me the detailed algorithm instead the general? Or could fix my bug in code? Thank you!
A cyclicBehaviour is infinite by nature. Do not use a cyclic if you want the behaviour to stop.
Just use a simpleBehaviour and set the finished boolean at true when you want to remove it from the agent.

Sparksee crashing on session close

When I execute the creation of relationships it crashes on session close.
The code:
#Override
public boolean applyCreate(final RelationshipStorage storage, final long snapshotId)
{
final Session sess = db.newSession();
final Graph graph = sess.getGraph();
final Objects startObjs = findNode(graph, storage.getStartNode());
final Objects endObjs = findNode(graph, storage.getEndNode());
if(startObjs == null || endObjs == null)
{
if(startObjs != null)
{
startObjs.close();
}
if(endObjs != null)
{
endObjs.close();
}
sess.close();
return false;
}
final ObjectsIterator startIt = startObjs.iterator();
final ObjectsIterator endIt = endObjs.iterator();
while(startIt.hasNext())
{
long startNode = startIt.next();
while (endIt.hasNext())
{
final long endNode = endIt.next();
int edgeType = graph.findType(storage.getId());
if (Type.InvalidType == edgeType)
{
edgeType = graph.newEdgeType(storage.getId(), true, false);
}
final long relationship = graph.findOrCreateEdge(edgeType, startNode, endNode);
for (final Map.Entry<String, Object> entry : storage.getProperties().entrySet())
{
graph.setAttribute(relationship,
SparkseeUtils.createOrFindAttributeType(entry.getKey(), entry.getValue(), Type.GlobalType, graph),
SparkseeUtils.getValue(entry.getValue()));
}
int snapshotAttributeId = SparkseeUtils.createOrFindAttributeType(Constants.TAG_SNAPSHOT_ID, snapshotId, Type.GlobalType, graph);
graph.setAttribute(relationship, snapshotAttributeId, SparkseeUtils.getValue(snapshotId));
try
{
int hashAttributeId = SparkseeUtils.createOrFindAttributeType(Constants.TAG_HASH, " ", Type.GlobalType, graph);
graph.setAttribute(relationship, hashAttributeId, SparkseeUtils.getValue(HashCreator.sha1FromRelationship(storage)));
}
catch (NoSuchAlgorithmException e)
{
Log.getLogger().warn("Couldn't execute create node transaction in server: " + id, e);
endObjs.close();
startObjs.close();
startIt.close();
endIt.close();
sess.close();
return false;
}
Log.getLogger().warn("Successfully executed create relationship transaction in server: " + id);
}
}
startObjs.close();
endObjs.close();
startIt.close();
endIt.close();
sess.close();
return true;
}
/**
* Return a Objects array matching the nodeType and properties.
* #param graph the graph.
* #param storage the storage of the node.
* #return Objects which match the attributes.
*/
private Objects findNode(final Graph graph, final NodeStorage storage)
{
Objects objects = null;
if(!storage.getId().isEmpty())
{
int nodeTypeId = SparkseeUtils.createOrFindNodeType(storage, graph);
objects = graph.select(nodeTypeId);
}
for (final Map.Entry<String, Object> entry : storage.getProperties().entrySet())
{
final int attributeId = graph.findAttribute(Type.GlobalType, entry.getKey());
if (objects == null || objects.isEmpty())
{
if(objects != null)
{
objects.close();
}
objects = graph.select(attributeId, Condition.Equal, SparkseeUtils.getValue(entry.getValue()));
}
else
{
objects = graph.select(attributeId, Condition.Equal, SparkseeUtils.getValue(entry.getValue()), objects);
}
}
return objects;
}
The crashlog:
Closing sparkseejava.lang.RuntimeException: Session data still active when closing at
com.sparsity.sparkseejavawrapJNI.delete_sparksee_gdb_Session(Native
Method) at com.sparsity.sparksee.gdb.Session.delete(Session.java:32)
at com.sparsity.sparksee.gdb.Session.close(Session.java:40) at
main.java.com.bag.server.database.SparkseeDatabaseAccess.applyCreate(SparkseeDatabaseAccess.java:595)
at
main.java.com.bag.main.DatabaseLoader.loadGraph(DatabaseLoader.java:97)
at
main.java.com.bag.main.DatabaseLoader.main(DatabaseLoader.java:191)
I can't see what I have to close still.
I closed all iterators and objects.
Original answer on google groups:
https://groups.google.com/forum/#!topic/sparksee/brcfhvFzdjg
I have to close the temporary objects "objects" before I assign a new one to it.
Objects tempObj = graph.select(attributeId, Condition.Equal, SparkseeUtils.getValue(entry.getValue()), objects);
objects.close();
objects = tempObj;

Jackrabbit - Unable to retrieve properties of node

I have created folder using superuser and provided read-only access to folder for application user.
When trying to query all accessible folders(nt:folder), getting properties list as empty.
Partial code to reproduce:
Created folder:
public Node createFolder(Session adminSession) {
try {
Node parentNode = adminSession.getNode("/MyCompany/CommonFolder”);
if(!parentNode.hasNode("T1")){
Node node = parentNode.addNode("T1", "nt:folder");
node.addMixin("et:folderProperties");
node.setProperty("et:folderName", "T1");
node.addMixin("rep:AccessControllable");
session.save(); return node;
}else {
System.out.println("Node already exists");
}
} catch (RepositoryException e) {
e.printStackTrace();
}
return null;
}
Sharing to user(Principal based)
accessControlManager = (JackrabbitAccessControlManager)
adminSession.getAccessControlManager();
accessControlPolicy = accessControlManager.getApplicablePolicies(userPrincipal);
// for ex., principal is appuser1
if(accessControlPolicy != null && accessControlPolicy.length > 0) {
accessControlList = (JackrabbitAccessControlList) accessControlPolicy[0];
}else {
accessControlPolicy = accessControlManager.getPolicies(userPrincipal);
accessControlList = (JackrabbitAccessControlList) accessControlPolicy[0];
}
ValueFactory valueFactory = adminSession.getValueFactory();
//Tried all combinations, even providing with "JCR:ALL";
Privilege[] readPrivilege = new javax.jcr.security.Privilege[] {
accessControlManager.privilegeFromName(
javax.jcr.security.Privilege.JCR_READ),
accessControlManager.privilegeFromName(
javax.jcr.security.Privilege.JCR_NODE_TYPE_MANAGEMENT),
accessControlManager.privilegeFromName(
javax.jcr.security.Privilege.JCR_READ_ACCESS_CONTROL)};
Map<String, Value> restrictions = new HashMap<String, Value>();
restrictions.put("rep:nodePath", valueFactory.createValue("/MyCompany/CommonFolder/T1",
PropertyType.PATH));
restrictions.put("rep:glob", valueFactory.createValue(""));
accessControlList.addEntry(userPrincipal, privileges, true , restrictions);
accessControlManager.setPolicy(accessControlList.getPath(), accessControlList);
adminSession.save();
Printing all applicable folders for user
public void printAllFolders(Session userSession) {
QueryManager queryManager;
try {
queryManager = userSession.getWorkspace().getQueryManager();
String sql = "SELECT * FROM [nt:folder]";
Query query= queryManager.createQuery(sql, Query.JCR_SQL2);
QueryResult result = query.execute();
NodeIterator nodeIterator = result.getNodes();
System.out.println("Printing all applicable folders");
while(nodeIterator.hasNext()) {
Node node = nodeIterator.nextNode();
System.out.println("Folder Name:" + node.getName() + "; path: " + node.getPath());
PropertyIterator pIterator = node.getProperties();
while (pIterator.hasNext()){ //Returning empty for path "/MyCompany/CommonFolder/T1"
Property property = pIterator.nextProperty();
if (property.getDefinition().isMultiple()) {
Value[] values = property.getValues();
for(Value v11: values) {
QValueValue value = (QValueValue)v11;
System.out.println(String.format("Multi-valued property for node:
'%s' - %s has values",node.getName(),
property.getName() ,value.getString()));
}
} else {
QValueValue value = (QValueValue) property.getValue();
String strValue = value.getString();
System.out.println(String.format("property for node: '%s' - %s has value
%s",node.getName(),property.getName(),strValue));
}
}
}
} catch (RepositoryException e) {
e.printStackTrace();
}
}
using Jackrabbit(2.6.0 version) and JCR( 2.0 version).
Node child = cl.addNode("ONE");
child.setProperty("message", ("CL Child" + i));
session.save();
PropertyIterator iter = child.getProperties();
System.out.println("Size" + iter.getSize());
while (iter.hasNext()) {
PropertyImpl key = (PropertyImpl) iter.next();
String value = key.getString();
System.out.println("------------->" + key);
System.out.println("------------->" + value);
}

Neo4j 1.9.4 java community edition persistence

For the life of me, I cannot understand why I am unable to read a graph I already created in neo4j 1.9.4 community edition. In eclipse, I run the following code:
public class neo4jtest {
private GraphDatabaseService graphDb;
private static final String neo4j_db = "c:/tmp/db/neo4j-new-db";
private UniqueFactory<Node> nodefactory;
private static enum RelTypes implements RelationshipType
{
FRIEND, FOLLOWER
}
public neo4jtest() {
graphDb = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(neo4j_db).
setConfig( GraphDatabaseSettings.node_keys_indexable, "ScreenName,ID" ).
setConfig( GraphDatabaseSettings.relationship_keys_indexable, (RelTypes.FRIEND).name()+","+(RelTypes.FOLLOWER).name()).
setConfig( GraphDatabaseSettings.node_auto_indexing, "true" ).
setConfig( GraphDatabaseSettings.relationship_auto_indexing, "true" ).
newGraphDatabase();
//graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(neo4j_db);
registerShutdownHook( graphDb );
nodefactory = new UniqueFactory.UniqueNodeFactory( graphDb, "users" )
{
#Override
protected void initialize( Node created, Map<String, Object> properties )
{
created.setProperty( "ScreenName", properties.get( "ScreenName" ) );
}
};
}
public void exit() {
graphDb.shutdown();
}
public static void main(String[] args) {
neo4jtest n4 = new neo4jtest();
String u1 = "Moe";
//Node unode = n4.createNeo4jGraph(u1);
n4.exploreNeo4jGraph(u1);
n4.exit();
}
public Node createNeo4jGraph(String uname) {
Node firstNode;
Relationship relationship;
// build a graph
try {
Transaction tx = graphDb.beginTx();
firstNode = nodefactory.getOrCreate("ScreenName", uname);
firstNode.setProperty( "ScreenName", uname );
firstNode.setProperty("ID", 1);
Node followerNode = nodefactory.getOrCreate("ScreenName", "Larry");
followerNode.setProperty("ID", 2);
relationship = firstNode.createRelationshipTo( followerNode, RelTypes.FOLLOWER ); // may not be unique
relationship = followerNode.createRelationshipTo(firstNode, RelTypes.FRIEND);
followerNode = nodefactory.getOrCreate("ScreenName", "Curly");
followerNode.setProperty("ID", 3);
relationship = firstNode.createRelationshipTo( followerNode, RelTypes.FOLLOWER ); // may not be unique
relationship = followerNode.createRelationshipTo(firstNode, RelTypes.FRIEND);
tx.success();
return firstNode;
} catch(Exception ex) {}
return null;
}
private void exploreNeo4jGraph(String scname) {
// use the auto indexer to lookup node with string name
// Get the Node auto index
ReadableIndex<Node> autoNodeIndex = graphDb.index()
.getNodeAutoIndexer()
.getAutoIndex();
Node mainUser = autoNodeIndex.get( "ScreenName", scname ).getSingle();
if (mainUser==null) {
// why not use nodefactory to get it?
System.out.println("Auto indexer did not work");
mainUser = nodefactory.getOrCreate("ScreenName", scname);
}
exploreNeo4jGraph(mainUser);
}
private void exploreNeo4jGraph(Node unode) {
// explore the nodes and edges in the graph
if (unode==null) {
System.err.println("Cannot explore from null node!");
return;
}
long currRels = IteratorUtil.count(GlobalGraphOperations.at(graphDb).getAllRelationships());
long currNodes = IteratorUtil.count(GlobalGraphOperations.at(graphDb).getAllNodes());
System.out.println("Number of nodes in graph is " + currNodes);
System.out.println("Number of edges in graph is " + currRels);
int numberOfFollowers = 0;
String output = unode.getProperty( "ScreenName" ) + "'s friends:\n";
Traverser friendsTraverser = getFriends( unode );
for ( Path friendPath : friendsTraverser )
{
output += "At depth " + friendPath.length() + " <= "
+ friendPath.endNode().getProperty( "ScreenName" ) + "\n";
numberOfFollowers++;
}
output += "Number of friends found: " + numberOfFollowers + "\n";
System.out.println(output);
}
private Traverser getFriends(final Node person )
{
TraversalDescription td = Traversal.description()
.breadthFirst()
.relationships( RelTypes.FRIEND, Direction.INCOMING )
.evaluator( Evaluators.excludeStartPosition() );
return td.traverse( person );
}
private static void registerShutdownHook( final GraphDatabaseService graphDb )
{
// Registers a shutdown hook for the Neo4j instance so that it
// shuts down nicely when the VM exits (even if you "Ctrl-C" the
// running application).
Runtime.getRuntime().addShutdownHook( new Thread()
{
#Override
public void run()
{
graphDb.shutdown();
}
} );
}
}
Basically, I uncomment line
Node unode = n4.createNeo4jGraph(u1);
to create the graph.
Then run it again with that line commented to just explore the graph that was created. When I run it again, it does not report the graph that was created. What am I doing wrong?
Thanks,
D
I'd guess you need to close the transaction. From the javadoc:
finish() (in 1.9)
Commits or marks this transaction for rollback, depending on whether success() or failure() has been previously invoked.

Categories

Resources