Unnamed: 0
int64
0
6.7k
func
stringlengths
12
89.6k
target
bool
2 classes
project
stringlengths
45
151
3,000
{ @Override protected Person underlyingObjectToObject( Path path ) { return new Person( path.endNode() ); } };
false
community_embedded-examples_src_main_java_org_neo4j_examples_socnet_Person.java
3,001
{ @Override protected StatusUpdate underlyingObjectToObject( Path path ) { return new StatusUpdate( path.endNode() ); } };
false
community_embedded-examples_src_main_java_org_neo4j_examples_socnet_Person.java
3,002
public class Person { static final String NAME = "name"; // START SNIPPET: the-node private final Node underlyingNode; Person( Node personNode ) { this.underlyingNode = personNode; } protected Node getUnderlyingNode() { return underlyingNode; } // END SNIPPET: the-node // START SNIPPET: delegate-to-the-node public String getName() { return (String)underlyingNode.getProperty( NAME ); } // END SNIPPET: delegate-to-the-node // START SNIPPET: override @Override public int hashCode() { return underlyingNode.hashCode(); } @Override public boolean equals( Object o ) { return o instanceof Person && underlyingNode.equals( ( (Person)o ).getUnderlyingNode() ); } @Override public String toString() { return "Person[" + getName() + "]"; } // END SNIPPET: override public void addFriend( Person otherPerson ) { if ( !this.equals( otherPerson ) ) { Relationship friendRel = getFriendRelationshipTo( otherPerson ); if ( friendRel == null ) { underlyingNode.createRelationshipTo( otherPerson.getUnderlyingNode(), FRIEND ); } } } public int getNrOfFriends() { return IteratorUtil.count( getFriends() ); } public Iterable<Person> getFriends() { return getFriendsByDepth( 1 ); } public void removeFriend( Person otherPerson ) { if ( !this.equals( otherPerson ) ) { Relationship friendRel = getFriendRelationshipTo( otherPerson ); if ( friendRel != null ) { friendRel.delete(); } } } public Iterable<Person> getFriendsOfFriends() { return getFriendsByDepth( 2 ); } public Iterable<Person> getShortestPathTo( Person otherPerson, int maxDepth ) { // use graph algo to calculate a shortest path PathFinder<Path> finder = GraphAlgoFactory.shortestPath( Traversal.expanderForTypes( FRIEND, Direction.BOTH ), maxDepth ); Path path = finder.findSinglePath( underlyingNode, otherPerson.getUnderlyingNode() ); return createPersonsFromNodes( path ); } public Iterable<Person> getFriendRecommendation( int numberOfFriendsToReturn ) { HashSet<Person> friends = new HashSet<Person>(); IteratorUtil.addToCollection( getFriends(), friends ); HashSet<Person> friendsOfFriends = new HashSet<Person>(); IteratorUtil.addToCollection( getFriendsOfFriends(), friendsOfFriends ); friendsOfFriends.removeAll( friends ); ArrayList<RankedPerson> rankedFriends = new ArrayList<RankedPerson>(); for ( Person friend : friendsOfFriends ) { int rank = getNumberOfPathsToPerson( friend ); rankedFriends.add( new RankedPerson( friend, rank ) ); } Collections.sort( rankedFriends, new RankedComparer() ); trimTo( rankedFriends, numberOfFriendsToReturn ); return onlyFriend( rankedFriends ); } public Iterable<StatusUpdate> getStatus() { Relationship firstStatus = underlyingNode.getSingleRelationship( STATUS, Direction.OUTGOING ); if ( firstStatus == null ) { return Collections.emptyList(); } // START SNIPPET: getStatusTraversal TraversalDescription traversal = Traversal.description(). depthFirst(). relationships( NEXT ); // END SNIPPET: getStatusTraversal return new IterableWrapper<StatusUpdate, Path>( traversal.traverse( firstStatus.getEndNode() ) ) { @Override protected StatusUpdate underlyingObjectToObject( Path path ) { return new StatusUpdate( path.endNode() ); } }; } public Iterator<StatusUpdate> friendStatuses() { return new FriendsStatusUpdateIterator( this ); } public void addStatus( String text ) { StatusUpdate oldStatus; if ( getStatus().iterator().hasNext() ) { oldStatus = getStatus().iterator().next(); } else { oldStatus = null; } Node newStatus = createNewStatusNode( text ); if ( oldStatus != null ) { underlyingNode.getSingleRelationship( RelTypes.STATUS, Direction.OUTGOING ).delete(); newStatus.createRelationshipTo( oldStatus.getUnderlyingNode(), RelTypes.NEXT ); } underlyingNode.createRelationshipTo( newStatus, RelTypes.STATUS ); } private GraphDatabaseService graphDb() { return underlyingNode.getGraphDatabase(); } private Node createNewStatusNode( String text ) { Node newStatus = graphDb().createNode(); newStatus.setProperty( StatusUpdate.TEXT, text ); newStatus.setProperty( StatusUpdate.DATE, new Date().getTime() ); return newStatus; } private final class RankedPerson { final Person person; final int rank; private RankedPerson( Person person, int rank ) { this.person = person; this.rank = rank; } public Person getPerson() { return person; } public int getRank() { return rank; } } private class RankedComparer implements Comparator<RankedPerson> { @Override public int compare( RankedPerson a, RankedPerson b ) { return b.getRank() - a.getRank(); } } private void trimTo( ArrayList<RankedPerson> rankedFriends, int numberOfFriendsToReturn ) { while ( rankedFriends.size() > numberOfFriendsToReturn ) { rankedFriends.remove( rankedFriends.size() - 1 ); } } private Iterable<Person> onlyFriend( Iterable<RankedPerson> rankedFriends ) { ArrayList<Person> retVal = new ArrayList<Person>(); for ( RankedPerson person : rankedFriends ) { retVal.add( person.getPerson() ); } return retVal; } private Relationship getFriendRelationshipTo( Person otherPerson ) { Node otherNode = otherPerson.getUnderlyingNode(); for ( Relationship rel : underlyingNode.getRelationships( FRIEND ) ) { if ( rel.getOtherNode( underlyingNode ).equals( otherNode ) ) { return rel; } } return null; } private Iterable<Person> getFriendsByDepth( int depth ) { // return all my friends and their friends using new traversal API TraversalDescription travDesc = Traversal.description() .breadthFirst() .relationships( FRIEND ) .uniqueness( Uniqueness.NODE_GLOBAL ) .evaluator( Evaluators.toDepth( depth ) ) .evaluator( Evaluators.excludeStartPosition() ); return createPersonsFromPath( travDesc.traverse( underlyingNode ) ); } private IterableWrapper<Person, Path> createPersonsFromPath( Traverser iterableToWrap ) { return new IterableWrapper<Person, Path>( iterableToWrap ) { @Override protected Person underlyingObjectToObject( Path path ) { return new Person( path.endNode() ); } }; } private int getNumberOfPathsToPerson( Person otherPerson ) { PathFinder<Path> finder = GraphAlgoFactory.allPaths( Traversal.expanderForTypes( FRIEND, Direction.BOTH ), 2 ); Iterable<Path> paths = finder.findAllPaths( getUnderlyingNode(), otherPerson.getUnderlyingNode() ); return IteratorUtil.count( paths ); } private Iterable<Person> createPersonsFromNodes( final Path path ) { return new IterableWrapper<Person, Node>( path.nodes() ) { @Override protected Person underlyingObjectToObject( Node node ) { return new Person( node ); } }; } }
false
community_embedded-examples_src_main_java_org_neo4j_examples_socnet_Person.java
3,003
private class StatusUpdateComparator implements Comparator<PositionedIterator<StatusUpdate>> { public int compare(PositionedIterator<StatusUpdate> a, PositionedIterator<StatusUpdate> b) { return a.current().getDate().compareTo(b.current().getDate()); } }
false
community_embedded-examples_src_main_java_org_neo4j_examples_socnet_FriendsStatusUpdateIterator.java
3,004
class FriendsStatusUpdateIterator implements Iterator<StatusUpdate> { private ArrayList<PositionedIterator<StatusUpdate>> statuses = new ArrayList<PositionedIterator<StatusUpdate>>(); private StatusUpdateComparator comparator = new StatusUpdateComparator(); public FriendsStatusUpdateIterator( Person person ) { for ( Person friend : person.getFriends() ) { Iterator<StatusUpdate> iterator = friend.getStatus().iterator(); if (iterator.hasNext()) { statuses.add(new PositionedIterator<StatusUpdate>(iterator)); } } sort(); } public boolean hasNext() { return statuses.size() > 0; } public StatusUpdate next() { if ( statuses.size() == 0 ) { throw new NoSuchElementException(); } // START SNIPPET: getActivityStream PositionedIterator<StatusUpdate> first = statuses.get(0); StatusUpdate returnVal = first.current(); if ( !first.hasNext() ) { statuses.remove( 0 ); } else { first.next(); sort(); } return returnVal; // END SNIPPET: getActivityStream } private void sort() { Collections.sort( statuses, comparator ); } public void remove() { throw new UnsupportedOperationException( "Don't know how to do that..." ); } private class StatusUpdateComparator implements Comparator<PositionedIterator<StatusUpdate>> { public int compare(PositionedIterator<StatusUpdate> a, PositionedIterator<StatusUpdate> b) { return a.current().getDate().compareTo(b.current().getDate()); } } }
false
community_embedded-examples_src_main_java_org_neo4j_examples_socnet_FriendsStatusUpdateIterator.java
3,005
@Path( "/helloworld" ) public class HelloWorldResource { private final GraphDatabaseService database; public HelloWorldResource( @Context GraphDatabaseService database ) { this.database = database; } @GET @Produces( MediaType.TEXT_PLAIN ) @Path( "/{nodeId}" ) public Response hello( @PathParam( "nodeId" ) long nodeId ) { // Do stuff with the database return Response.status( Status.OK ).entity( ("Hello World, nodeId=" + nodeId).getBytes( Charset.forName("UTF-8") ) ).build(); } }
false
community_server-examples_src_main_java_org_neo4j_examples_server_unmanaged_HelloWorldResource.java
3,006
public class ShortestPath extends ServerPlugin { @Description( "Find the shortest path between two nodes." ) @PluginTarget( Node.class ) public Iterable<Path> shortestPath( @Source Node source, @Description( "The node to find the shortest path to." ) @Parameter( name = "target" ) Node target, @Description( "The relationship types to follow when searching for the shortest path(s). " + "Order is insignificant, if omitted all types are followed." ) @Parameter( name = "types", optional = true ) String[] types, @Description( "The maximum path length to search for, default value (if omitted) is 4." ) @Parameter( name = "depth", optional = true ) Integer depth ) { PathExpander<?> expander; List<Path> paths = new ArrayList<>(); if ( types == null ) { expander = PathExpanders.allTypesAndDirections(); } else { PathExpanderBuilder expanderBuilder = PathExpanderBuilder.empty(); for ( int i = 0; i < types.length; i++ ) { expanderBuilder = expanderBuilder.add( DynamicRelationshipType.withName( types[i] ) ); } expander = expanderBuilder.build(); } try (Transaction tx = source.getGraphDatabase().beginTx()) { PathFinder<Path> shortestPath = GraphAlgoFactory.shortestPath( expander, depth == null ? 4 : depth.intValue() ); for ( Path path : shortestPath.findAllPaths( source, target ) ) { paths.add( path ); } tx.success(); } return paths; } }
false
community_server-examples_src_main_java_org_neo4j_examples_server_plugins_ShortestPath.java
3,007
@Description( "An extension to the Neo4j Server for getting all nodes or relationships" ) public class GetAll extends ServerPlugin { @Name( "get_all_nodes" ) @Description( "Get all nodes from the Neo4j graph database" ) @PluginTarget( GraphDatabaseService.class ) public Iterable<Node> getAllNodes( @Source GraphDatabaseService graphDb ) { ArrayList<Node> nodes = new ArrayList<>(); try (Transaction tx = graphDb.beginTx()) { for ( Node node : GlobalGraphOperations.at( graphDb ).getAllNodes() ) { nodes.add( node ); } tx.success(); } return nodes; } @Description( "Get all relationships from the Neo4j graph database" ) @PluginTarget( GraphDatabaseService.class ) public Iterable<Relationship> getAllRelationships( @Source GraphDatabaseService graphDb ) { List<Relationship> rels = new ArrayList<>(); try (Transaction tx = graphDb.beginTx()) { for ( Relationship rel : GlobalGraphOperations.at( graphDb ).getAllRelationships() ) { rels.add( rel ); } tx.success(); } return rels; } }
false
community_server-examples_src_main_java_org_neo4j_examples_server_plugins_GetAll.java
3,008
@Description( "Performs a depth two traversal along all relationship types." ) public class DepthTwo extends ServerPlugin { @Description( "Traverse depth two and return the end nodes" ) @PluginTarget( Node.class ) public Iterable<Node> nodesOnDepthTwo( @Source Node node ) { ArrayList<Node> nodes = new ArrayList<>(); try (Transaction tx = node.getGraphDatabase().beginTx()) { for ( Node foundNode : getTraversal( node ).traverse( node ).nodes() ) { nodes.add( foundNode ); } tx.success(); } return nodes; } @Description( "Traverse depth two and return the last relationships" ) @PluginTarget( Node.class ) public Iterable<Relationship> relationshipsOnDepthTwo( @Source Node node ) { List<Relationship> rels = new ArrayList<>(); try (Transaction tx = node.getGraphDatabase().beginTx()) { for ( Relationship rel : getTraversal( node ).traverse( node ).relationships() ) { rels.add( rel ); } tx.success(); } return rels; } @Description( "Traverse depth two and return the paths" ) @PluginTarget( Node.class ) public Iterable<Path> pathsOnDepthTwo( @Source Node node ) { List<Path> paths = new ArrayList<>(); try (Transaction tx = node.getGraphDatabase().beginTx()) { for ( Path path : getTraversal( node ).traverse( node ) ) { paths.add( path ); } tx.success(); } return paths; } private TraversalDescription getTraversal( Node node ) { return node.getGraphDatabase() .traversalDescription() .uniqueness( Uniqueness.RELATIONSHIP_PATH ) .evaluator( Evaluators.atDepth( 2 ) ); } }
false
community_server-examples_src_main_java_org_neo4j_examples_server_plugins_DepthTwo.java
3,009
public class TraversalDefinition { public static final String DEPTH_FIRST = "depth first"; public static final String NODE = "node"; public static final String ALL = "all"; private String uniqueness = NODE; private int maxDepth = 1; private String returnFilter = ALL; private String order = DEPTH_FIRST; private List<Relation> relationships = new ArrayList<Relation>(); public void setOrder( String order ) { this.order = order; } public void setUniqueness( String uniqueness ) { this.uniqueness = uniqueness; } public void setMaxDepth( int maxDepth ) { this.maxDepth = maxDepth; } public void setReturnFilter( String returnFilter ) { this.returnFilter = returnFilter; } public void setRelationships( Relation... relationships ) { this.relationships = Arrays.asList( relationships ); } public String toJson() { StringBuilder sb = new StringBuilder(); sb.append( "{ " ); sb.append( " \"order\" : \"" + order + "\"" ); sb.append( ", " ); sb.append( " \"uniqueness\" : \"" + uniqueness + "\"" ); sb.append( ", " ); if ( relationships.size() > 0 ) { sb.append( "\"relationships\" : [" ); for ( int i = 0; i < relationships.size(); i++ ) { sb.append( relationships.get( i ) .toJsonCollection() ); if ( i < relationships.size() - 1 ) { // Miss off the final comma sb.append( ", " ); } } sb.append( "], " ); } sb.append( "\"return filter\" : { " ); sb.append( "\"language\" : \"builtin\", " ); sb.append( "\"name\" : \"" ); sb.append( returnFilter ); sb.append( "\" }, " ); sb.append( "\"max depth\" : " ); sb.append( maxDepth ); sb.append( " }" ); return sb.toString(); } }
false
community_server-examples_src_main_java_org_neo4j_examples_server_TraversalDefinition.java
3,010
public class ShortestPathDocIT extends AbstractPluginTestBase { private static final String SHORTEST_PATHS = "shortestPath"; protected String getDocumentationSectionName() { return "rest-api"; } @Test public void canFindExtension() throws Exception { long nodeId = helper.createNode( DynamicLabel.label( "test" ) ); Map<String, Object> map = getNodeLevelPluginMetadata( ShortestPath.class, nodeId ); assertTrue( map.keySet().size() > 0 ); } /** * Get shortest path. */ @Documented @Test @Graph( { "A knows B", "B knew C", "A knows D", "D knows E", "E knows C" } ) public void shouldReturnAllShortestPathsOnPost() throws JsonParseException { Node source = data.get().get( "C" ); String sourceUri = functionalTestHelper.nodeUri( source.getId() ); Node target = data.get().get( "A" ); String targetUri = functionalTestHelper.nodeUri( target.getId() ); String uri = (String) getNodeLevelPluginMetadata( ShortestPath.class, source.getId() ).get( SHORTEST_PATHS ); String body = "{\"target\":\"" + targetUri + "\"}"; String result = performPost( uri, body ); List<Map<String, Object>> list = JsonHelper.jsonToList( result ); assertThat( list, notNullValue() ); assertThat( list.size(), equalTo( 1 ) ); Map<String, Object> map = list.get( 0 ); assertThat( map.get( "start" ).toString(), containsString( sourceUri ) ); assertThat( map.get( "end" ).toString(), containsString( targetUri ) ); assertThat( (Integer) map.get( "length" ), equalTo( 2 ) ); } /** * Get shortest path restricted by relationship type. */ @Documented @Test @Graph( { "A knows B", "B likes C", "A knows D", "D knows E", "E knows C" } ) public void shouldReturnAllShortestPathsRestrictedByReltypesOnPost() throws JsonParseException { Node source = data.get().get( "C" ); String sourceUri = functionalTestHelper.nodeUri( source.getId() ); Node target = data.get().get( "A" ); String targetUri = functionalTestHelper.nodeUri( target.getId() ); String uri = (String) getNodeLevelPluginMetadata( ShortestPath.class, source.getId() ).get( SHORTEST_PATHS ); String body = "{\"target\":\"" + targetUri + "\",\"types\":[\"knows\"]}"; String result = performPost( uri, body ); List<Map<String, Object>> list = JsonHelper.jsonToList( result ); assertThat( list, notNullValue() ); assertThat( list.size(), equalTo( 1 ) ); Map<String, Object> map = list.get( 0 ); assertThat( map.get( "start" ).toString(), containsString( sourceUri ) ); assertThat( map.get( "end" ).toString(), containsString( targetUri ) ); assertThat( (Integer) map.get( "length" ), equalTo( 3 ) ); } }
false
community_server-examples_src_test_java_org_neo4j_examples_server_ShortestPathDocIT.java
3,011
public class Relation { public static final String OUT = "out"; public static final String IN = "in"; public static final String BOTH = "both"; private String type; private String direction; public String toJsonCollection() { StringBuilder sb = new StringBuilder(); sb.append( "{ " ); sb.append( " \"type\" : \"" + type + "\"" ); if ( direction != null ) { sb.append( ", \"direction\" : \"" + direction + "\"" ); } sb.append( " }" ); return sb.toString(); } public Relation( String type, String direction ) { setType( type ); setDirection( direction ); } public Relation( String type ) { this( type, null ); } public void setType( String type ) { this.type = type; } public void setDirection( String direction ) { this.direction = direction; } }
false
community_server-examples_src_main_java_org_neo4j_examples_server_Relation.java
3,012
public class GetAllDocIT extends AbstractPluginTestBase { private static final String GET_ALL_RELATIONSHIPS = "getAllRelationships"; private static final String GET_ALL_NODES = "get_all_nodes"; protected String getDocumentationSectionName() { return "rest-api"; } @Test public void testName() throws Exception { Map<String, Object> map = getDatabaseLevelPluginMetadata( GetAll.class ); assertTrue( map.keySet() .size() > 0 ); } @Test public void canGetExtensionDataForGetAllNodes() throws Exception { checkDatabaseLevelExtensionMetadata( GetAll.class, GET_ALL_NODES, "/ext/%s/graphdb/%s" ); } /** * Get all nodes. */ @Documented @Test public void shouldReturnAllNodesOnPost() throws JsonParseException { helper.createNode( DynamicLabel.label( "test" ) ); String uri = (String) getDatabaseLevelPluginMetadata( GetAll.class ).get( GET_ALL_NODES ); String result = performPost( uri ); List<Map<String, Object>> list = JsonHelper.jsonToList( result ); assertThat( list, notNullValue() ); assertThat( list.size(), equalTo( 1 ) ); Map<String, Object> map = list.get( 0 ); assertThat( map.get( "data" ), notNullValue() ); } @Test public void canGetExtensionDataForGetAllRelationships() throws Exception { checkDatabaseLevelExtensionMetadata( GetAll.class, GET_ALL_RELATIONSHIPS, "/ext/%s/graphdb/%s" ); } /** * Get all relationships. */ @Documented @Test public void shouldReturnAllRelationshipsOnPost() throws JsonParseException { helper.createRelationship( "test" ); String uri = (String) getDatabaseLevelPluginMetadata( GetAll.class ).get( GET_ALL_RELATIONSHIPS ); String result = performPost( uri ); List<Map<String, Object>> list = JsonHelper.jsonToList( result ); assertThat( list, notNullValue() ); assertThat( list.size(), equalTo( 1 ) ); Map<String, Object> map = list.get( 0 ); assertThat( map.get( "data" ), notNullValue() ); } }
false
community_server-examples_src_test_java_org_neo4j_examples_server_GetAllDocIT.java
3,013
public class DepthTwoDocIT extends AbstractPluginTestBase { private static final String NODES_ON_DEPTH_TWO = "nodesOnDepthTwo"; private static final String RELATIONSHIPS_ON_DEPTH_TWO = "relationshipsOnDepthTwo"; private static final String PATHS_ON_DEPTH_TWO = "pathsOnDepthTwo"; protected String getDocumentationSectionName() { return "rest-api"; } @Test public void canFindExtension() throws Exception { long nodeId = helper.createNode( DynamicLabel.label( "test" ) ); Map<String, Object> map = getNodeLevelPluginMetadata( DepthTwo.class, nodeId ); assertTrue( map.keySet().size() > 0 ); } /** * Get nodes at depth two. */ @Documented @Test @Graph( { "I know you", "you know him" } ) public void shouldReturnAllNodesAtDepthTwoOnPost() throws JsonParseException { Node node = data.get().get( "I" ); String uri = (String) getNodeLevelPluginMetadata( DepthTwo.class, node.getId() ).get( NODES_ON_DEPTH_TWO ); String result = performPost( uri ); List<Map<String, Object>> list = JsonHelper.jsonToList( result ); assertThat( list, notNullValue() ); assertThat( list.size(), equalTo( 1 ) ); Map<String, Object> map = list.get( 0 ); assertThat( map.get( "data" ).toString(), containsString( "him" ) ); } /** * Get relationships at depth two. */ @Documented @Test @Graph( { "I know you", "you know him" } ) public void shouldReturnAllRelationshipsAtDepthTwoOnPost() throws JsonParseException { Node node = data.get().get( "I" ); String uri = (String) getNodeLevelPluginMetadata( DepthTwo.class, node.getId() ).get( RELATIONSHIPS_ON_DEPTH_TWO ); String result = performPost( uri ); List<Map<String, Object>> list = JsonHelper.jsonToList( result ); assertThat( list, notNullValue() ); assertThat( list.size(), equalTo( 1 ) ); Map<String, Object> map = list.get( 0 ); assertThat( map.get( "type" ).toString(), containsString( "know" ) ); } /** * Get paths at depth two. */ @Documented @Test @Graph( { "I know you", "you know him" } ) public void shouldReturnAllPathsAtDepthTwoOnPost() throws JsonParseException { Node node = data.get().get( "I" ); String uri = (String) getNodeLevelPluginMetadata( DepthTwo.class, node.getId() ).get( PATHS_ON_DEPTH_TWO ); String result = performPost( uri ); List<Map<String, Object>> list = JsonHelper.jsonToList( result ); assertThat( list, notNullValue() ); assertThat( list.size(), equalTo( 1 ) ); Map<String, Object> map = list.get( 0 ); assertThat( (Integer) map.get( "length" ), equalTo( 2 ) ); } }
false
community_server-examples_src_test_java_org_neo4j_examples_server_DepthTwoDocIT.java
3,014
public class CreateSimpleGraph { private static final String SERVER_ROOT_URI = "http://localhost:7474/db/data/"; public static void main( String[] args ) throws URISyntaxException { checkDatabaseIsRunning(); // START SNIPPET: nodesAndProps URI firstNode = createNode(); addProperty( firstNode, "name", "Joe Strummer" ); URI secondNode = createNode(); addProperty( secondNode, "band", "The Clash" ); // END SNIPPET: nodesAndProps // START SNIPPET: addRel URI relationshipUri = addRelationship( firstNode, secondNode, "singer", "{ \"from\" : \"1976\", \"until\" : \"1986\" }" ); // END SNIPPET: addRel // START SNIPPET: addMetaToRel addMetadataToProperty( relationshipUri, "stars", "5" ); // END SNIPPET: addMetaToRel // START SNIPPET: queryForSingers findSingersInBands( firstNode ); // END SNIPPET: queryForSingers } private static void findSingersInBands( URI startNode ) throws URISyntaxException { // START SNIPPET: traversalDesc // TraversalDefinition turns into JSON to send to the Server TraversalDefinition t = new TraversalDefinition(); t.setOrder( TraversalDefinition.DEPTH_FIRST ); t.setUniqueness( TraversalDefinition.NODE ); t.setMaxDepth( 10 ); t.setReturnFilter( TraversalDefinition.ALL ); t.setRelationships( new Relation( "singer", Relation.OUT ) ); // END SNIPPET: traversalDesc // START SNIPPET: traverse URI traverserUri = new URI( startNode.toString() + "/traverse/node" ); WebResource resource = Client.create() .resource( traverserUri ); String jsonTraverserPayload = t.toJson(); ClientResponse response = resource.accept( MediaType.APPLICATION_JSON ) .type( MediaType.APPLICATION_JSON ) .entity( jsonTraverserPayload ) .post( ClientResponse.class ); System.out.println( String.format( "POST [%s] to [%s], status code [%d], returned data: " + System.getProperty( "line.separator" ) + "%s", jsonTraverserPayload, traverserUri, response.getStatus(), response.getEntity( String.class ) ) ); response.close(); // END SNIPPET: traverse } // START SNIPPET: insideAddMetaToProp private static void addMetadataToProperty( URI relationshipUri, String name, String value ) throws URISyntaxException { URI propertyUri = new URI( relationshipUri.toString() + "/properties" ); String entity = toJsonNameValuePairCollection( name, value ); WebResource resource = Client.create() .resource( propertyUri ); ClientResponse response = resource.accept( MediaType.APPLICATION_JSON ) .type( MediaType.APPLICATION_JSON ) .entity( entity ) .put( ClientResponse.class ); System.out.println( String.format( "PUT [%s] to [%s], status code [%d]", entity, propertyUri, response.getStatus() ) ); response.close(); } // END SNIPPET: insideAddMetaToProp private static String toJsonNameValuePairCollection( String name, String value ) { return String.format( "{ \"%s\" : \"%s\" }", name, value ); } private static URI createNode() { // START SNIPPET: createNode final String nodeEntryPointUri = SERVER_ROOT_URI + "node"; // http://localhost:7474/db/data/node WebResource resource = Client.create() .resource( nodeEntryPointUri ); // POST {} to the node entry point URI ClientResponse response = resource.accept( MediaType.APPLICATION_JSON ) .type( MediaType.APPLICATION_JSON ) .entity( "{}" ) .post( ClientResponse.class ); final URI location = response.getLocation(); System.out.println( String.format( "POST to [%s], status code [%d], location header [%s]", nodeEntryPointUri, response.getStatus(), location.toString() ) ); response.close(); return location; // END SNIPPET: createNode } // START SNIPPET: insideAddRel private static URI addRelationship( URI startNode, URI endNode, String relationshipType, String jsonAttributes ) throws URISyntaxException { URI fromUri = new URI( startNode.toString() + "/relationships" ); String relationshipJson = generateJsonRelationship( endNode, relationshipType, jsonAttributes ); WebResource resource = Client.create() .resource( fromUri ); // POST JSON to the relationships URI ClientResponse response = resource.accept( MediaType.APPLICATION_JSON ) .type( MediaType.APPLICATION_JSON ) .entity( relationshipJson ) .post( ClientResponse.class ); final URI location = response.getLocation(); System.out.println( String.format( "POST to [%s], status code [%d], location header [%s]", fromUri, response.getStatus(), location.toString() ) ); response.close(); return location; } // END SNIPPET: insideAddRel private static String generateJsonRelationship( URI endNode, String relationshipType, String... jsonAttributes ) { StringBuilder sb = new StringBuilder(); sb.append( "{ \"to\" : \"" ); sb.append( endNode.toString() ); sb.append( "\", " ); sb.append( "\"type\" : \"" ); sb.append( relationshipType ); if ( jsonAttributes == null || jsonAttributes.length < 1 ) { sb.append( "\"" ); } else { sb.append( "\", \"data\" : " ); for ( int i = 0; i < jsonAttributes.length; i++ ) { sb.append( jsonAttributes[i] ); if ( i < jsonAttributes.length - 1 ) { // Miss off the final comma sb.append( ", " ); } } } sb.append( " }" ); return sb.toString(); } private static void addProperty( URI nodeUri, String propertyName, String propertyValue ) { // START SNIPPET: addProp String propertyUri = nodeUri.toString() + "/properties/" + propertyName; // http://localhost:7474/db/data/node/{node_id}/properties/{property_name} WebResource resource = Client.create() .resource( propertyUri ); ClientResponse response = resource.accept( MediaType.APPLICATION_JSON ) .type( MediaType.APPLICATION_JSON ) .entity( "\"" + propertyValue + "\"" ) .put( ClientResponse.class ); System.out.println( String.format( "PUT to [%s], status code [%d]", propertyUri, response.getStatus() ) ); response.close(); // END SNIPPET: addProp } private static void checkDatabaseIsRunning() { // START SNIPPET: checkServer WebResource resource = Client.create() .resource( SERVER_ROOT_URI ); ClientResponse response = resource.get( ClientResponse.class ); System.out.println( String.format( "GET on [%s], status code [%d]", SERVER_ROOT_URI, response.getStatus() ) ); response.close(); // END SNIPPET: checkServer } }
false
community_server-examples_src_main_java_org_neo4j_examples_server_CreateSimpleGraph.java
3,015
public class Matrix { public enum RelTypes implements RelationshipType { NEO_NODE, KNOWS, CODED_BY } private static final String MATRIX_DB = "target/matrix-db"; private GraphDatabaseService graphDb; private long matrixNodeId; public static void main( String[] args ) throws IOException { Matrix matrix = new Matrix(); matrix.setUp(); System.out.println( matrix.printNeoFriends() ); System.out.println( matrix.printMatrixHackers() ); matrix.shutdown(); } public void setUp() throws IOException { deleteRecursively( new File( MATRIX_DB ) ); graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( MATRIX_DB ); registerShutdownHook(); createNodespace(); } public void shutdown() { graphDb.shutdown(); } public void createNodespace() { try ( Transaction tx = graphDb.beginTx() ) { // Create base Matrix node Node matrix = graphDb.createNode(); matrixNodeId = matrix.getId(); // Create Neo Node thomas = graphDb.createNode(); thomas.setProperty( "name", "Thomas Anderson" ); thomas.setProperty( "age", 29 ); // connect Neo/Thomas to the matrix node matrix.createRelationshipTo( thomas, RelTypes.NEO_NODE ); Node trinity = graphDb.createNode(); trinity.setProperty( "name", "Trinity" ); Relationship rel = thomas.createRelationshipTo( trinity, RelTypes.KNOWS ); rel.setProperty( "age", "3 days" ); Node morpheus = graphDb.createNode(); morpheus.setProperty( "name", "Morpheus" ); morpheus.setProperty( "rank", "Captain" ); morpheus.setProperty( "occupation", "Total badass" ); thomas.createRelationshipTo( morpheus, RelTypes.KNOWS ); rel = morpheus.createRelationshipTo( trinity, RelTypes.KNOWS ); rel.setProperty( "age", "12 years" ); Node cypher = graphDb.createNode(); cypher.setProperty( "name", "Cypher" ); cypher.setProperty( "last name", "Reagan" ); trinity.createRelationshipTo( cypher, RelTypes.KNOWS ); rel = morpheus.createRelationshipTo( cypher, RelTypes.KNOWS ); rel.setProperty( "disclosure", "public" ); Node smith = graphDb.createNode(); smith.setProperty( "name", "Agent Smith" ); smith.setProperty( "version", "1.0b" ); smith.setProperty( "language", "C++" ); rel = cypher.createRelationshipTo( smith, RelTypes.KNOWS ); rel.setProperty( "disclosure", "secret" ); rel.setProperty( "age", "6 months" ); Node architect = graphDb.createNode(); architect.setProperty( "name", "The Architect" ); smith.createRelationshipTo( architect, RelTypes.CODED_BY ); tx.success(); } } /** * Get the Neo node. (a.k.a. Thomas Anderson node) * * @return the Neo node */ private Node getNeoNode() { return graphDb.getNodeById( matrixNodeId ) .getSingleRelationship( RelTypes.NEO_NODE, Direction.OUTGOING ) .getEndNode(); } public String printNeoFriends() { try ( Transaction tx = graphDb.beginTx() ) { Node neoNode = getNeoNode(); // START SNIPPET: friends-usage int numberOfFriends = 0; StringBuilder output = new StringBuilder( String.format( "%s's friends:\n", neoNode.getProperty( "name" ) ) ); Traverser friendsTraverser = getFriends( neoNode ); for ( Node friendNode : friendsTraverser ) { output.append( String.format( "At depth %d => %s\n", friendsTraverser.currentPosition().depth(), friendNode.getProperty( "name" ) ) ); numberOfFriends++; } output.append( String.format( "Number of friends found: %d\n", numberOfFriends ) ); // END SNIPPET: friends-usage return output.toString(); } } // START SNIPPET: get-friends private static Traverser getFriends( final Node person ) { return person.traverse( Order.BREADTH_FIRST, StopEvaluator.END_OF_GRAPH, ReturnableEvaluator.ALL_BUT_START_NODE, RelTypes.KNOWS, Direction.OUTGOING ); } // END SNIPPET: get-friends public String printMatrixHackers() { try ( Transaction tx = graphDb.beginTx() ) { // START SNIPPET: find--hackers-usage StringBuilder output = new StringBuilder("Hackers:\n"); int numberOfHackers = 0; Traverser traverser = findHackers( getNeoNode() ); for ( Node hackerNode : traverser ) { output.append( String.format( "At depth %d => %s\n", traverser.currentPosition().depth(), hackerNode.getProperty( "name" ) ) ); numberOfHackers++; } output.append( String.format( "Number of hackers found: %d\n", numberOfHackers ) ); // END SNIPPET: find--hackers-usage return output.toString(); } } // START SNIPPET: find-hackers private static Traverser findHackers( final Node startNode ) { return startNode.traverse( Order.BREADTH_FIRST, StopEvaluator.END_OF_GRAPH, new ReturnableEvaluator() { @Override public boolean isReturnableNode( final TraversalPosition currentPos ) { return !currentPos.isStartNode() && currentPos.lastRelationshipTraversed() .isType( RelTypes.CODED_BY ); } }, RelTypes.CODED_BY, Direction.OUTGOING, RelTypes.KNOWS, Direction.OUTGOING ); } // END SNIPPET: find-hackers private void registerShutdownHook() { // 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 example before it's completed) Runtime.getRuntime() .addShutdownHook( new Thread() { @Override public void run() { graphDb.shutdown(); } } ); } }
false
community_embedded-examples_src_main_java_org_neo4j_examples_Matrix.java
3,016
public class ImpermanentGraphJavaDocTestBase extends AbstractJavaDocTestBase { @BeforeClass public static void init() { db = new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().newGraphDatabase(); } }
false
community_embedded-examples_src_test_java_org_neo4j_examples_ImpermanentGraphJavaDocTestBase.java
3,017
public class SocnetTest { private static final Random r = new Random( System.currentTimeMillis() ); private static final int nrOfPersons = 20; private GraphDatabaseService graphDb; private PersonRepository personRepository; @Before public void setup() throws Exception { graphDb = new TestGraphDatabaseFactory().newImpermanentDatabase(); try ( Transaction tx = graphDb.beginTx() ) { Index<Node> index = graphDb.index().forNodes( "nodes" ); personRepository = new PersonRepository( graphDb, index ); createPersons(); setupFriendsBetweenPeople( 10 ); tx.success(); } } @After public void teardown() { graphDb.shutdown(); } @Test public void addStatusAndRetrieveIt() throws Exception { Person person; try ( Transaction tx = graphDb.beginTx() ) { person = getRandomPerson(); person.addStatus( "Testing!" ); tx.success(); } try ( Transaction tx = graphDb.beginTx() ) { StatusUpdate update = person.getStatus().iterator().next(); assertThat( update, notNullValue() ); assertThat( update.getStatusText(), equalTo( "Testing!" ) ); assertThat( update.getPerson(), equalTo( person ) ); } } @Test public void multipleStatusesComeOutInTheRightOrder() throws Exception { ArrayList<String> statuses = new ArrayList<>(); statuses.add( "Test1" ); statuses.add( "Test2" ); statuses.add( "Test3" ); try ( Transaction tx = graphDb.beginTx() ) { Person person = getRandomPerson(); for ( String status : statuses ) { person.addStatus( status ); } int i = statuses.size(); for ( StatusUpdate update : person.getStatus() ) { i--; assertThat( update.getStatusText(), equalTo( statuses.get( i ) ) ); } } } @Test public void removingOneFriendIsHandledCleanly() { Person person1; Person person2; int noOfFriends; try ( Transaction tx = graphDb.beginTx() ) { person1 = personRepository.getPersonByName( "person#1" ); person2 = personRepository.getPersonByName( "person#2" ); person1.addFriend( person2 ); noOfFriends = person1.getNrOfFriends(); tx.success(); } try ( Transaction tx = graphDb.beginTx() ) { person1.removeFriend( person2 ); tx.success(); } try ( Transaction tx = graphDb.beginTx() ) { int noOfFriendsAfterChange = person1.getNrOfFriends(); assertThat( noOfFriends, equalTo( noOfFriendsAfterChange + 1 ) ); } } @Test public void retrieveStatusUpdatesInDateOrder() throws Exception { Person person; int numberOfStatuses; try ( Transaction tx = graphDb.beginTx() ) { person = getRandomPersonWithFriends(); numberOfStatuses = 20; for ( int i = 0; i < numberOfStatuses; i++ ) { Person friend = getRandomFriendOf( person ); friend.addStatus( "Dum-deli-dum..." ); } tx.success(); } ArrayList<StatusUpdate> updates; try ( Transaction tx = graphDb.beginTx() ) { updates = fromIterableToArrayList( person.friendStatuses() ); assertThat( updates.size(), equalTo( numberOfStatuses ) ); assertUpdatesAreSortedByDate( updates ); } } @Test public void friendsOfFriendsWorks() throws Exception { try ( Transaction tx = graphDb.beginTx() ) { Person person = getRandomPerson(); Person friend = getRandomFriendOf( person ); for ( Person friendOfFriend : friend.getFriends() ) { if ( !friendOfFriend.equals( person ) ) { // You can't be friends with yourself. assertThat( person.getFriendsOfFriends(), hasItems( friendOfFriend ) ); } } } } @Test public void shouldReturnTheCorrectPersonFromAnyStatusUpdate() throws Exception { try ( Transaction tx = graphDb.beginTx() ) { Person person = getRandomPerson(); person.addStatus( "Foo" ); person.addStatus( "Bar" ); person.addStatus( "Baz" ); for ( StatusUpdate status : person.getStatus() ) { assertThat( status.getPerson(), equalTo( person ) ); } } } @Test public void getPathBetweenFriends() throws Exception { deleteSocialGraph(); Person start; Person middleMan1; Person middleMan2; Person endMan; try ( Transaction tx = graphDb.beginTx() ) { start = personRepository.createPerson( "start" ); middleMan1 = personRepository.createPerson( "middle1" ); middleMan2 = personRepository.createPerson( "middle2" ); endMan = personRepository.createPerson( "endMan" ); // Start -> middleMan1 -> middleMan2 -> endMan start.addFriend( middleMan1 ); middleMan1.addFriend( middleMan2 ); middleMan2.addFriend( endMan ); tx.success(); } try ( Transaction tx = graphDb.beginTx() ) { Iterable<Person> path = start.getShortestPathTo( endMan, 4 ); assertPathIs( path, start, middleMan1, middleMan2, endMan ); //assertThat( path, matchesPathByProperty(Person.NAME, "start", "middle1", "middle2", "endMan")); } } @Test public void singleFriendRecommendation() throws Exception { deleteSocialGraph(); Person a; Person e; try ( Transaction tx = graphDb.beginTx() ) { a = personRepository.createPerson( "a" ); Person b = personRepository.createPerson( "b" ); Person c = personRepository.createPerson( "c" ); Person d = personRepository.createPerson( "d" ); e = personRepository.createPerson( "e" ); // A is friends with B,C and D a.addFriend( b ); a.addFriend( c ); a.addFriend( d ); // E is also friend with B, C and D e.addFriend( b ); e.addFriend( c ); e.addFriend( d ); tx.success(); } try ( Transaction tx = graphDb.beginTx() ) { Person recommendation = IteratorUtil.single( a.getFriendRecommendation( 1 ).iterator() ); assertThat( recommendation, equalTo( e ) ); } } @Test public void weightedFriendRecommendation() throws Exception { deleteSocialGraph(); Person a; Person e; Person f; try ( Transaction tx = graphDb.beginTx() ) { a = personRepository.createPerson( "a" ); Person b = personRepository.createPerson( "b" ); Person c = personRepository.createPerson( "c" ); Person d = personRepository.createPerson( "d" ); e = personRepository.createPerson( "e" ); f = personRepository.createPerson( "f" ); // A is friends with B,C and D a.addFriend( b ); a.addFriend( c ); a.addFriend( d ); // E is only friend with B e.addFriend( b ); // F is friend with B, C, D f.addFriend( b ); f.addFriend( c ); f.addFriend( d ); tx.success(); } try ( Transaction tx = graphDb.beginTx() ) { ArrayList<Person> recommendations = fromIterableToArrayList( a.getFriendRecommendation( 2 ).iterator() ); assertThat( recommendations.get( 0 ), equalTo( f )); assertThat( recommendations.get( 1 ), equalTo( e )); } } private <T> ArrayList<T> fromIterableToArrayList( Iterator<T> iterable ) { ArrayList<T> collection = new ArrayList<>(); IteratorUtil.addToCollection( iterable, collection ); return collection; } private void assertPathIs( Iterable<Person> path, Person... expectedPath ) { ArrayList<Person> pathArray = new ArrayList<>(); 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 ] ) ); } } private void setupFriendsBetweenPeople( int maxNrOfFriendsEach ) { for ( Person person : personRepository.getAllPersons() ) { int nrOfFriends = r.nextInt( maxNrOfFriendsEach ) + 1; for ( int j = 0; j < nrOfFriends; j++ ) { person.addFriend( getRandomPerson() ); } } } private Person getRandomPerson() { return personRepository.getPersonByName( "person#" + r.nextInt( nrOfPersons ) ); } private void deleteSocialGraph() { try ( Transaction tx = graphDb.beginTx() ) { for ( Person person : personRepository.getAllPersons() ) { personRepository.deletePerson( person ); } } } private Person getRandomFriendOf( Person p ) { ArrayList<Person> friends = new ArrayList<>(); IteratorUtil.addToCollection( p.getFriends().iterator(), friends ); return friends.get( r.nextInt( friends.size() ) ); } private Person getRandomPersonWithFriends() { Person p; do { p = getRandomPerson(); } while ( p.getNrOfFriends() == 0 ); return p; } private void createPersons() throws Exception { for ( int i = 0; i < nrOfPersons; i++ ) { personRepository.createPerson( "person#" + i ); } } private void assertUpdatesAreSortedByDate( ArrayList<StatusUpdate> statusUpdates ) { Date date = new Date( 0 ); for ( StatusUpdate update : statusUpdates ) { org.junit.Assert.assertTrue( date.getTime() < update.getDate().getTime() ); // TODO: Should be assertThat(date, lessThan(update.getDate)); } } }
false
community_embedded-examples_src_test_java_org_neo4j_examples_socnet_SocnetTest.java
3,018
{ { add( new TestData( "Start", "SELECT * FROM `Person` WHERE name = 'Anakin'".replace( "`", identifierQuoteString ), "START person=node:Person(name = 'Anakin') RETURN person", "Anakin", "20", "1 row" ) ); add( new TestData( "Match", "SELECT `Email`.* FROM `Person` JOIN `Email` ON `Person`.id = `Email`.person_id WHERE `Person`.name = 'Anakin'".replace( "`", identifierQuoteString ), "START person=node:Person(name = 'Anakin') MATCH person-[:email]->email RETURN email", "anakin@example.com", "anakin@example.org", "2 rows" ) ); add( new TestData( "JoinEntity", "SELECT `Group`.*, `Person_Group`.* FROM `Person` JOIN `Person_Group` ON `Person`.id = `Person_Group`.person_id JOIN `Group` ON `Person_Group`.Group_id=`Group`.id WHERE `Person`.name = 'Bridget'".replace( "`", identifierQuoteString ), "START person=node:Person(name = 'Bridget') MATCH person-[r:belongs_to]->group RETURN group, r", "Admin", "1 row" ) ); add( new TestData( "LeftJoin", "SELECT `Person`.name, `Email`.address FROM `Person` LEFT JOIN `Email` ON `Person`.id = `Email`.person_id".replace( "`", identifierQuoteString ), "START person=node:Person('name: *') OPTIONAL MATCH person-[:email]->email RETURN person.name, email.address", "Anakin", "anakin@example.org", "Bridget", "<null>", "3 rows" ) ); add( new TestData( "RecursiveJoin", /*(*/ null /*"WITH RECURSIVE TransitiveGroup(id, name, belongs_to_group_id) AS ( " + "SELECT child.id, child.name, child.belongs_to_group_id " + "FROM `Group` child " + "WHERE child.name='Admin' " + "UNION ALL SELECT parent.id, parent.name, parent.belongs_to_group_id " + "FROM TransitiveGroup child, `Group` parent " + "WHERE parent.id = child.belongs_to_group_id " + ") SELECT * FROM TransitiveGroup" ).replace( "`", identifierQuoteString )*/, "START person=node:Person('name: Bridget') " + "MATCH person-[:belongs_to*]->group RETURN person.name, group.name", "Bridget", "Admin", "Technichian", "User", "3 rows" ) ); add( new TestData( "Where", "SELECT * FROM `Person` WHERE `Person`.age > 35 AND `Person`.hair = 'blonde'".replace( "`", identifierQuoteString ), "START person=node:Person('name: *') WHERE person.age > 35 AND person.hair = 'blonde' RETURN person", "Bridget", "blonde", "1 row" ) ); add( new TestData( "Return", "SELECT `Person`.name, count(*) FROM `Person` GROUP BY `Person`.name ORDER BY `Person`.name".replace( "`", identifierQuoteString ), "START person=node:Person('name: *') RETURN person.name, count(*) ORDER BY person.name", "Bridget", "Anakin", "2 rows" ) ); } };
false
community_embedded-examples_src_main_java_org_neo4j_examples_CypherSql.java
3,019
{ @Override public void run() { graphDb.shutdown(); } } );
false
community_embedded-examples_src_main_java_org_neo4j_examples_CalculateShortestPath.java
3,020
public class CalculateShortestPath { private static final String DB_PATH = "neo4j-shortest-path"; private static final String NAME_KEY = "name"; private static RelationshipType KNOWS = DynamicRelationshipType.withName( "KNOWS" ); private static GraphDatabaseService graphDb; private static Index<Node> indexService; public static void main( final String[] args ) { deleteFileOrDirectory( new File( DB_PATH ) ); graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( DB_PATH ); indexService = graphDb.index().forNodes( "nodes" ); registerShutdownHook(); try ( Transaction tx = graphDb.beginTx() ) { /* * (Neo) --> (Trinity) * \ ^ * v / * (Morpheus) --> (Cypher) * \ | * v v * (Agent Smith) */ createChain( "Neo", "Trinity" ); createChain( "Neo", "Morpheus", "Trinity" ); createChain( "Morpheus", "Cypher", "Agent Smith" ); createChain( "Morpheus", "Agent Smith" ); tx.success(); } // So let's find the shortest path between Neo and Agent Smith Node neo = getOrCreateNode( "Neo" ); Node agentSmith = getOrCreateNode( "Agent Smith" ); // START SNIPPET: shortestPathUsage PathFinder<Path> finder = GraphAlgoFactory.shortestPath( Traversal.expanderForTypes( KNOWS, Direction.BOTH ), 4 ); Path foundPath = finder.findSinglePath( neo, agentSmith ); System.out.println( "Path from Neo to Agent Smith: " + Traversal.simplePathToString( foundPath, NAME_KEY ) ); // END SNIPPET: shortestPathUsage System.out.println( "Shutting down database ..." ); graphDb.shutdown(); } private static void createChain( String... names ) { for ( int i = 0; i < names.length - 1; i++ ) { Node firstNode = getOrCreateNode( names[i] ); Node secondNode = getOrCreateNode( names[i + 1] ); firstNode.createRelationshipTo( secondNode, KNOWS ); } } private static Node getOrCreateNode( String name ) { Node node = indexService.get( NAME_KEY, name ).getSingle(); if ( node == null ) { node = graphDb.createNode(); node.setProperty( NAME_KEY, name ); indexService.add( node, NAME_KEY, name ); } return node; } private static void registerShutdownHook() { // 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 example before it's completed) Runtime.getRuntime().addShutdownHook( new Thread() { @Override public void run() { graphDb.shutdown(); } } ); } private static void deleteFileOrDirectory( File file ) { if ( file.exists() ) { if ( file.isDirectory() ) { for ( File child : file.listFiles() ) { deleteFileOrDirectory( child ); } } file.delete(); } } }
false
community_embedded-examples_src_main_java_org_neo4j_examples_CalculateShortestPath.java
3,021
public class AclExampleDocTest extends ImpermanentGraphJavaDocTestBase { /** * This example gives a generic overview of an approach to handling Access Control Lists (ACLs) in graphs, * and a simplified example with concrete queries. * * == Generic approach == * * In many scenarios, an application needs to handle security on some form of managed * objects. This example describes one pattern to handle this through the use of a graph structure and traversers * that build a full permissions-structure for any managed object with exclude and include overriding * possibilities. This results in a dynamic construction of ACLs based on the * position and context of the managed object. * * The result is a complex security scheme that can easily be implemented in a graph structure, * supporting permissions overriding, principal and content composition, without duplicating data anywhere. * * image::ACL.png[scaledwidth="100%"] * * === Technique === * * As seen in the example graph layout, there are some key concepts in this domain model: * * * The managed content (folders and files) that are connected by +HAS_CHILD_CONTENT+ relationships * * * The Principal subtree pointing out principals that can act as ACL members, pointed out by the +PRINCIPAL+ relationships. * * * The aggregation of principals into groups, connected by the +IS_MEMBER_OF+ relationship. One principal (user or group) can be part of many groups at the same time. * * * The +SECURITY+ -- relationships, connecting the content composite structure to the principal composite structure, containing a addition/removal modifier property ("++RW+"). * * * === Constructing the ACL === * * The calculation of the effective permissions (e.g. Read, Write, Execute) for a * principal for any given ACL-managed node (content) follows a number of rules that will be encoded into the permissions-traversal: * * === Top-down-Traversal === * * This approach will let you define a generic permission pattern on the root content, * and then refine that for specific sub-content nodes and specific principals. * * . Start at the content node in question traverse upwards to the content root node to determine the path to it. * . Start with a effective optimistic permissions list of "all permitted" (+111+ in a bit encoded ReadWriteExecute case) * or +000+ if you like pessimistic security handling (everything is forbidden unless explicitly allowed). * . Beginning from the topmost content node, look for any +SECURITY+ relationships on it. * . If found, look if the principal in question is part of the end-principal of the +SECURITY+ relationship. * . If yes, add the "+++" permission modifiers to the existing permission pattern, revoke the "+-+" permission modifiers from the pattern. * . If two principal nodes link to the same content node, first apply the more generic prinipals modifiers. * . Repeat the security modifier search all the way down to the target content node, thus overriding more * generic permissions with the set on nodes closer to the target node. * * The same algorithm is applicable for the bottom-up approach, basically just * traversing from the target content node upwards and applying the security modifiers dynamically * as the traverser goes up. * * === Example === * * Now, to get the resulting access rights for e.g. "+user 1+" on the "+My File.pdf+" in a Top-Down * approach on the model in the graph above would go like: * * . Traveling upward, we start with "+Root folder+", and set the permissions to +11+ initially (only considering Read, Write). * . There are two +SECURITY+ relationships to that folder. * User 1 is contained in both of them, but "+root+" is more generic, so apply it first then "+All principals+" `+W` `+R` -> +11+. * . "+Home+" has no +SECURITY+ instructions, continue. * . "+user1 Home+" has +SECURITY+. * First apply "+Regular Users+" (`-R` `-W`) -> +00+, Then "+user 1+" (`+R` `+W`) -> +11+. * . The target node "+My File.pdf+" has no +SECURITY+ modifiers on it, so the effective permissions for "+User 1+" on "+My File.pdf+" are +ReadWrite+ -> +11+. * * == Read-permission example == * * In this example, we are going to examine a tree structure of +directories+ and * +files+. Also, there are users that own files and roles that can be assigned to * users. Roles can have permissions on directory or files structures (here we model * only +canRead+, as opposed to full +rwx+ Unix permissions) and be nested. A more thorough * example of modeling ACL structures can be found at * http://www.xaprb.com/blog/2006/08/16/how-to-build-role-based-access-control-in-sql/[How to Build Role-Based Access Control in SQL]. * * include::ACL-graph.asciidoc[] * * === Find all files in the directory structure === * * In order to find all files contained in this structure, we need a variable length * query that follows all +contains+ relationships and retrieves the nodes at the other * end of the +leaf+ relationships. * * @@query1 * * resulting in: * * @@result1 * * === What files are owned by whom? === * * If we introduce the concept of ownership on files, we then can ask for the owners of the files we find -- * connected via +owns+ relationships to file nodes. * * @@query2 * * Returning the owners of all files below the +FileRoot+ node. * * @@result2 * * * === Who has access to a File? === * * If we now want to check what users have read access to all Files, and define our ACL as * * * The root directory has no access granted. * * Any user having a role that has been granted +canRead+ access to one of the parent folders of a File has read access. * * In order to find users that can read any part of the parent folder hierarchy above the files, * Cypher provides optional variable length path. * * @@query3 * * This will return the +file+, and the directory where the user has the +canRead+ permission along * with the +user+ and their +role+. * * @@result3 * * The results listed above contain +null+ for optional path segments, which can be mitigated by either asking several * queries or returning just the really needed values. * */ @Documented @Graph( value = { "Root has Role", "Role subRole SUDOers", "Role subRole User", "User member User1", "User member User2", "Root has FileRoot", "FileRoot contains Home", "Home contains HomeU1", "Home contains HomeU2", "HomeU1 leaf File1", "HomeU2 contains Desktop", "Desktop leaf File2", "FileRoot contains etc", "etc contains init.d", "SUDOers member Admin1", "SUDOers member Admin2", "User1 owns File1", "User2 owns File2", "SUDOers canRead FileRoot"}) @Test public void ACL_structures_in_graphs() { data.get(); gen.get().addSnippet( "graph1", createGraphViz("The Domain Structure", graphdb(), gen.get().getTitle()) ); //Files //TODO: can we do open ended? String query = "match ({name: 'FileRoot'})-[:contains*0..]->(parentDir)-[:leaf]->(file) return file"; gen.get().addSnippet( "query1", createCypherSnippet( query ) ); String result = engine.execute( query ) .dumpToString(); assertTrue( result.contains("File1") ); gen.get() .addSnippet( "result1", createQueryResultSnippet( result ) ); //Ownership query = "match ({name: 'FileRoot'})-[:contains*0..]->()-[:leaf]->(file)<-[:owns]-(user) return file, user"; gen.get().addSnippet( "query2", createCypherSnippet( query ) ); result = engine.execute( query ) .dumpToString(); assertTrue( result.contains("File1") ); assertTrue( result.contains("User1") ); assertTrue( result.contains("User2") ); assertTrue( result.contains("File2") ); assertFalse( result.contains("Admin1") ); assertFalse( result.contains("Admin2") ); gen.get() .addSnippet( "result2", createQueryResultSnippet( result ) ); //ACL query = "MATCH (file)<-[:leaf]-()<-[:contains*0..]-(dir) " + "OPTIONAL MATCH (dir)<-[:canRead]-(role)-[:member]->(readUser) " + "WHERE file.name =~ 'File.*' " + "RETURN file.name, dir.name, role.name, readUser.name"; gen.get().addSnippet( "query3", createCypherSnippet( query ) ); result = engine.execute( query ) .dumpToString(); assertTrue( result.contains("File1") ); assertTrue( result.contains("File2") ); assertTrue( result.contains("Admin1") ); assertTrue( result.contains("Admin2") ); gen.get() .addSnippet( "result3", createQueryResultSnippet( result ) ); } }
false
community_embedded-examples_src_test_java_org_neo4j_examples_AclExampleDocTest.java
3,022
public abstract class AbstractJavaDocTestBase implements GraphHolder { public @Rule TestData<JavaTestDocsGenerator> gen = TestData.producedThrough( JavaTestDocsGenerator.PRODUCER ); public @Rule TestData<Map<String, Node>> data = TestData.producedThrough( GraphDescription.createGraphFor( this, true ) ); protected ExecutionEngine engine; protected static GraphDatabaseService db; @AfterClass public static void shutdownDb() { try { if ( db != null ) db.shutdown(); } finally { db = null; } } @Override public GraphDatabaseService graphdb() { return db; } protected String createCypherSnippet( String cypherQuery ) { String snippet = org.neo4j.cypher.internal.compiler.v2_0.prettifier.Prettifier$.MODULE$.apply( cypherQuery ); return AsciidocHelper.createAsciiDocSnippet( "cypher", snippet ); } @Before public void setUp() { GraphDatabaseService graphdb = graphdb(); cleanDatabaseContent( graphdb ); gen.get().setGraph( graphdb ); engine = new ExecutionEngine( graphdb ); } @After public void doc() { gen.get().document( "target/docs/dev", "examples" ); } }
false
community_embedded-examples_src_test_java_org_neo4j_examples_AbstractJavaDocTestBase.java
3,023
private static abstract class Snapshot { final String filename; Snapshot( String filename ) { this.filename = filename; } @Override public String toString() { return getClass().getSimpleName() + "[" + filename + "]"; } abstract Snapshot dump( File targetDir ); }
false
manual_cypherdoc_src_main_java_org_neo4j_doc_cypherdoc_TestFailureException.java
3,024
private static class InMemorySnapshot extends Snapshot { private final byte[] bytes; InMemorySnapshot( String filename, byte[] bytes ) { super( filename ); this.bytes = bytes; } @Override public Snapshot dump( File targetDir ) { File target = new File( targetDir, filename ); try ( FileOutputStream output = new FileOutputStream( target ) ) { output.write( bytes ); return new DumpedSnapshot( target.getAbsolutePath() ); } catch ( IOException e ) { return this; } } }
false
manual_cypherdoc_src_main_java_org_neo4j_doc_cypherdoc_TestFailureException.java
3,025
private static class DumpedSnapshot extends Snapshot { public DumpedSnapshot( String path ) { super( path ); } @Override public Snapshot dump( File targetDir ) { return this; } }
false
manual_cypherdoc_src_main_java_org_neo4j_doc_cypherdoc_TestFailureException.java
3,026
class TestFailureException extends RuntimeException { final Result result; private List<Snapshot> snapshots = new ArrayList<>(); TestFailureException( Result result, List<String> failedTests ) { super( message( failedTests ) ); this.result = result; } private static String message( List<String> failedTests ) { StringBuilder message = new StringBuilder( "Query validation failed:" ); for ( String test : failedTests ) { message.append( CypherDoc.EOL ) .append( "\tQuery result doesn't contain the string '" ).append( test ).append( "'." ); } return message.toString(); } @Override public String toString() { StringBuilder message = new StringBuilder( getMessage() ); message.append( CypherDoc.EOL ) .append( "Query:" ).append( CypherDoc.EOL ).append( '\t' ) .append( CypherDoc.indent( result.query ) ); message.append( CypherDoc.EOL ) .append( "Result:" ).append( CypherDoc.EOL ).append( '\t' ) .append( CypherDoc.indent( result.text ) ); message.append( CypherDoc.EOL ) .append( "Profile:" ).append( CypherDoc.EOL ).append( '\t' ) .append( CypherDoc.indent( result.profile ) ); if ( !snapshots.isEmpty() ) { message.append( CypherDoc.EOL ).append( "Snapshots:" ); for ( Snapshot snapshot : snapshots ) { message.append( CypherDoc.EOL ).append( '\t' ).append( snapshot ); } } return message.toString(); } synchronized void addSnapshot( String key, byte[] bytes ) { snapshots.add( new InMemorySnapshot( key, bytes ) ); } synchronized void dumpSnapshots( File targetDir ) { List<Snapshot> prior = snapshots; snapshots = new ArrayList<>( prior.size() ); for ( Snapshot snapshot : prior ) { snapshots.add( snapshot.dump( targetDir ) ); } } private static abstract class Snapshot { final String filename; Snapshot( String filename ) { this.filename = filename; } @Override public String toString() { return getClass().getSimpleName() + "[" + filename + "]"; } abstract Snapshot dump( File targetDir ); } private static class InMemorySnapshot extends Snapshot { private final byte[] bytes; InMemorySnapshot( String filename, byte[] bytes ) { super( filename ); this.bytes = bytes; } @Override public Snapshot dump( File targetDir ) { File target = new File( targetDir, filename ); try ( FileOutputStream output = new FileOutputStream( target ) ) { output.write( bytes ); return new DumpedSnapshot( target.getAbsolutePath() ); } catch ( IOException e ) { return this; } } } private static class DumpedSnapshot extends Snapshot { public DumpedSnapshot( String path ) { super( path ); } @Override public Snapshot dump( File targetDir ) { return this; } } }
false
manual_cypherdoc_src_main_java_org_neo4j_doc_cypherdoc_TestFailureException.java
3,027
class State { final ExecutionEngine engine; final GraphDatabaseService database; Result latestResult; State( ExecutionEngine engine, GraphDatabaseService database ) { this.engine = engine; this.database = database; } }
false
manual_cypherdoc_src_main_java_org_neo4j_doc_cypherdoc_State.java
3,028
class Result { final String query; final String text; final String profile; public Result( String query, ExecutionResult result ) { this.query = query; text = result.dumpToString(); String profileText; try { profileText = result.executionPlanDescription().toString(); } catch ( Exception ex ) { profileText = ex.getMessage(); } profile = profileText; } }
false
manual_cypherdoc_src_main_java_org_neo4j_doc_cypherdoc_Result.java
3,029
public class OutputHelper { private static final String PASSTHROUGH_BLOCK = "++++"; static String passthroughMarker( String role, String htmlElement, String docbookElement ) { StringBuilder sb = new StringBuilder( 64 ); sb.append( '<' ) .append( htmlElement ) .append( " class=\"" ) .append( role ) .append( "\"></" ) .append( htmlElement ) .append( '>' ); String html = sb.toString(); sb = new StringBuilder( 64 ); sb.append( '<' ) .append( docbookElement ) .append( " role=\"" ) .append( role ) .append( "\"></" ) .append( docbookElement ) .append( '>' ); String docbook = sb.toString(); return passthroughHtmlAndDocbook( html, docbook ); } private static String passthroughHtml( String html ) { return OutputHelper.passthroughWithCondition( "ifdef::backend-html,backend-html5,backend-xhtml11,backend-deckjs[]", html ); } private static String passthroughDocbook( String docbook ) { return OutputHelper.passthroughWithCondition( "ifndef::backend-html,backend-html5,backend-xhtml11,backend-deckjs[]", docbook ); } private static String passthroughHtmlAndDocbook( String html, String docbook ) { return passthroughHtml( html ) + CypherDoc.EOL + passthroughDocbook( docbook ) + CypherDoc.EOL; } private static String passthroughWithCondition( String condition, String content ) { return StringUtils.join( new String[] { condition, OutputHelper.PASSTHROUGH_BLOCK, content, OutputHelper.PASSTHROUGH_BLOCK, "endif::[]" }, CypherDoc.EOL ); } }
false
manual_cypherdoc_src_main_java_org_neo4j_doc_cypherdoc_OutputHelper.java
3,030
public class Main { private static final String[] EXTENSIONS = new String[] { "asciidoc", "adoc" }; /** * Transforms the given files or directories (searched recursively for * .asciidoc or .adoc files). The output file name is based on the input * file name (and the relative path if a directory got searched). The first * argument is the base destination directory. * * @param args base destination directory, followed by files/directories to parse. */ public static void main( String[] args ) throws Exception { if ( args.length < 2 ) { throw new IllegalArgumentException( "Destination directory and at least one source must be specified." ); } File destination = null; for ( String name : args ) { File file = FileUtils.getFile( name ); if ( destination == null ) { if ( file.exists() && !file.isDirectory() ) { throw new IllegalArgumentException( "Destination directory must either not exist or be a directory." ); } destination = file; } else { if ( file.isFile() ) { executeFile( file, file.getName(), destination ); } else if ( file.isDirectory() ) { for ( File fileInDir : FileUtils.listFiles( file, EXTENSIONS, true ) ) { String fileInDirName = fileInDir.getAbsolutePath() .substring( file.getAbsolutePath().length() + 1 ) .replace( '/', '-' ) .replace( '\\', '-' ); executeFile( fileInDir, fileInDirName, destination ); } } } } } /** * Parse a single file. */ private static void executeFile( File file, String name, File destinationDir ) throws Exception { try { String input = FileUtils.readFileToString( file ); String output = CypherDoc.parse( input ); FileUtils.forceMkdir( destinationDir ); File targetFile = FileUtils.getFile( destinationDir, name ); FileUtils.writeStringToFile( targetFile, output ); } catch ( TestFailureException failure ) { failure.dumpSnapshots( destinationDir ); throw failure; } } }
false
manual_cypherdoc_src_main_java_org_neo4j_doc_cypherdoc_Main.java
3,031
public class CypherDocTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void fullDocumentBlockParsing() throws IOException { String content = FileUtils.readFileToString( resourceFile( "/hello-world.asciidoc" ) ); List<Block> blocks = CypherDoc.parseBlocks( content ); List<BlockType> types = new ArrayList<BlockType>(); for ( Block block : blocks ) { types.add( block.type ); } assertThat( types, equalTo( Arrays.asList( BlockType.TITLE, BlockType.TEXT, BlockType.HIDE, BlockType.SETUP, BlockType.QUERY, BlockType.TEST, BlockType.TABLE, BlockType.GRAPH, BlockType.TEXT, BlockType.OUTPUT, BlockType.QUERY, BlockType.TEST ) ) ); } @Test public void toLittleContentBlockParsing() { expectedException.expect( IllegalArgumentException.class ); CypherDoc.parseBlocks( "x\ny\n" ); } @Test public void shouldEmitProfileOnTestFailure() throws Exception { // given String content = FileUtils.readFileToString( resourceFile( "/failing-query.asciidoc" ) ); // when try { CypherDoc.parse( content ); fail( "expected exception" ); } // then catch ( TestFailureException e ) { String failure = e.toString(); assertThat( failure, containsString( "Query result doesn't contain the string '1 row'." ) ); assertThat( failure, containsString( "Query:" + CypherDoc.EOL + '\t' + CypherDoc.indent( e.result.query ) ) ); assertThat( failure, containsString( "Result:" + CypherDoc.EOL + '\t' + CypherDoc.indent( e.result.text ) ) ); assertThat( failure, containsString( "Profile:" + CypherDoc.EOL + '\t' + CypherDoc.indent( e.result.profile ) ) ); } } @Test public void fullDocumentParsing() throws IOException { String content = FileUtils.readFileToString( resourceFile( "/hello-world.asciidoc" ) ); String output = CypherDoc.parse( content ); assertThat( output, allOf( containsString( "[[cypherdoc-hello-world]]" ), containsString( "<p class=\"cypherdoc-console\"></p>" ), containsString( "[source,cypher]" ), containsString( "[queryresult]" ), containsString( "{Person|name = \\'Adam\\'\\l}" ), containsString( "= Hello World =" ) ) ); assertThat( output, allOf( containsString( "<span class=\"hide-query\"></span>" ), containsString( "<span class=\"setup-query\"></span>" ), containsString( "<span class=\"query-output\"></span>" ), containsString( "<simpara role=\"query-output\"></simpara>" ) ) ); } private File resourceFile( String resource ) throws IOException { try { return new File( getClass().getResource( resource ).toURI() ); } catch ( NullPointerException | URISyntaxException e ) { throw new IOException( "Could not find resource: " + resource, e ); } } }
false
manual_cypherdoc_src_test_java_org_neo4j_doc_cypherdoc_CypherDocTest.java
3,032
public final class CypherDoc { static final String EOL = System.getProperty( "line.separator" ); private CypherDoc() { } /** * Parse a string as CypherDoc-enhanced AsciiDoc. */ public static String parse( String input ) { List<Block> blocks = parseBlocks( input ); EphemeralFileSystemAbstraction fs = new EphemeralFileSystemAbstraction(); GraphDatabaseService database = new TestGraphDatabaseFactory().setFileSystem( fs ).newImpermanentDatabase(); TestFailureException failure = null; try { ExecutionEngine engine = new ExecutionEngine( database ); return executeBlocks( blocks, new State( engine, database ) ); } catch ( TestFailureException exception ) { dumpStoreFiles( fs, failure = exception, "before-shutdown" ); throw exception; } finally { database.shutdown(); if ( failure != null ) { dumpStoreFiles( fs, failure, "after-shutdown" ); } } } static List<Block> parseBlocks( String input ) { String[] lines = input.split( EOL ); if ( lines.length < 3 ) { throw new IllegalArgumentException( "To little content, only " + lines.length + " lines." ); } List<Block> blocks = new ArrayList<>(); List<String> currentBlock = new ArrayList<>(); for ( String line : lines ) { if ( line.trim().isEmpty() ) { if ( !currentBlock.isEmpty() ) { blocks.add( Block.getBlock( currentBlock ) ); currentBlock = new ArrayList<>(); } } else if ( line.startsWith( "//" ) && !line.startsWith( "////" ) && currentBlock.isEmpty() ) { blocks.add( Block.getBlock( Collections.singletonList( line ) ) ); } else { currentBlock.add( line ); } } if ( !currentBlock.isEmpty() ) { blocks.add( Block.getBlock( currentBlock ) ); } return blocks; } private static String executeBlocks( List<Block> blocks, State state ) { StringBuilder output = new StringBuilder( 4096 ); boolean hasConsole = false; for ( Block block : blocks ) { if ( block.type == BlockType.CONSOLE ) { hasConsole = true; } output.append( block.process( state ) ) .append( EOL ) .append( EOL ); } if ( !hasConsole ) { output.append( BlockType.CONSOLE.process( null, state ) ); } return output.toString(); } static String indent( String string ) { return string.replace( "\r\n", "\n" ).replace( "\n", EOL + "\t" ); } private static void dumpStoreFiles( EphemeralFileSystemAbstraction fs, TestFailureException exception, String when ) { ByteArrayOutputStream snapshot = new ByteArrayOutputStream(); try { fs.dumpZip( snapshot ); exception.addSnapshot( when + ".zip", snapshot.toByteArray() ); } catch ( IOException e ) { snapshot.reset(); e.printStackTrace( new PrintStream( snapshot ) ); exception.addSnapshot( "dump-exception-" + when + ".txt", snapshot.toByteArray() ); } } }
false
manual_cypherdoc_src_main_java_org_neo4j_doc_cypherdoc_CypherDoc.java
3,033
CONSOLE { @Override boolean isA( List<String> block ) { return isACommentWith( block, "console" ); } @Override String process( Block block, State state ) { return OutputHelper.passthroughMarker( "cypherdoc-console", "p", "simpara" ); } },
false
manual_cypherdoc_src_main_java_org_neo4j_doc_cypherdoc_BlockType.java
3,034
GRAPH { @Override boolean isA( List<String> block ) { return isACommentWith( block, "graph" ); } @Override String process( Block block, State state ) { String first = block.lines.get( 0 ); String id = ""; if ( first.length() > 8 ) { id = first.substring( first.indexOf( "graph" ) + 5 ).trim(); if ( id.indexOf( ':' ) != -1 ) { id = first.substring( first.indexOf( ':' ) + 1 ).trim(); } } GraphvizWriter writer = new GraphvizWriter( AsciiDocSimpleStyle.withAutomaticRelationshipTypeColors() ); ByteArrayOutputStream out = new ByteArrayOutputStream(); try (Transaction tx = state.database.beginTx()) { writer.emit( out, Walker.fullGraph( state.database ) ); tx.success(); } catch ( IOException e ) { e.printStackTrace(); } StringBuilder output = new StringBuilder( 512 ); try { String dot = out.toString( "UTF-8" ); output.append( "[\"dot\", \"cypherdoc-" ) .append( id ) .append( '-' ) .append( Integer.toHexString( dot.hashCode() ) ) .append( ".svg\", \"neoviz\"]\n----\n" ) .append( dot ) .append( "----\n" ); } catch ( UnsupportedEncodingException e ) { e.printStackTrace(); } return output.toString(); } },
false
manual_cypherdoc_src_main_java_org_neo4j_doc_cypherdoc_BlockType.java
3,035
QUERY { @Override boolean isA( List<String> block ) { String first = block.get( 0 ); if ( first.charAt( 0 ) != '[' ) { return false; } if ( first.contains( "source" ) && first.contains( "cypher" ) ) { return true; } if ( block.size() > 4 && first.startsWith( "[[" ) ) { String second = block.get( 1 ); if ( second.contains( "source" ) && second.contains( "cypher" ) ) { return true; } } return false; } @Override String process( Block block, State state ) { List<String> queryLines = new ArrayList<String>(); boolean queryStarted = false; for ( String line : block.lines ) { if ( !queryStarted ) { if ( line.startsWith( CODE_BLOCK ) ) { queryStarted = true; } } else { if ( line.startsWith( CODE_BLOCK ) ) { break; } else { queryLines.add( line ); } } } String query = StringUtils.join( queryLines, CypherDoc.EOL ); try (Transaction tx = state.database.beginTx()) { state.latestResult = new Result( query, state.engine.profile( query ) ); tx.success(); } String prettifiedQuery = state.engine.prettify( query ); StringBuilder output = new StringBuilder( 512 ); output.append( AsciidocHelper.createCypherSnippetFromPreformattedQuery( prettifiedQuery ) ) .append( CypherDoc.EOL ) .append( CypherDoc.EOL ); return output.toString(); } },
false
manual_cypherdoc_src_main_java_org_neo4j_doc_cypherdoc_BlockType.java
3,036
TEST { @Override String process( Block block, State state ) { List<String> tests = block.lines.subList( 1, block.lines.size() - 1 ); String result = state.latestResult.text; List<String> failures = new ArrayList<String>(); for ( String test : tests ) { if ( !result.contains( test ) ) { failures.add( test ); } } if ( !failures.isEmpty() ) { throw new TestFailureException( state.latestResult, failures ); } return ""; } @Override boolean isA( List<String> block ) { return isACommentWith( block, "//" ); } },
false
manual_cypherdoc_src_main_java_org_neo4j_doc_cypherdoc_BlockType.java
3,037
TABLE { @Override String process( Block block, State state ) { return AsciidocHelper.createQueryResultSnippet( state.latestResult.text ); } @Override boolean isA( List<String> block ) { return isACommentWith( block, "table" ); } },
false
manual_cypherdoc_src_main_java_org_neo4j_doc_cypherdoc_BlockType.java
3,038
public class CypherSql { private static final int COLUMN_MAX_WIDTH = 25; private static final String LINE_SEGMENT = new String( new char[COLUMN_MAX_WIDTH] ).replace( '\0', '-' ); private static final String SPACE_SEGMENT = new String( new char[COLUMN_MAX_WIDTH] ).replace( '\0', ' ' ); private Connection sqldb; private String identifierQuoteString; private final GraphDatabaseService graphdb; private final ExecutionEngine engine; List<TestData> queries; public CypherSql( final GraphDatabaseService graphdb ) { this.graphdb = graphdb; this.engine = new ExecutionEngine( graphdb ); } public static void main( String[] args ) throws SQLException { CypherSql instance = new CypherSql( new GraphDatabaseFactory().newEmbeddedDatabase( "target/cyphersql" + System.currentTimeMillis() ) ); instance.createDbs(); instance.run(); instance.shutdown(); } void createDbs() throws SQLException { sqldb = DriverManager.getConnection( "jdbc:hsqldb:mem:cyphersqltests;shutdown=true" ); sqldb.setAutoCommit( true ); identifierQuoteString = sqldb.getMetaData() .getIdentifierQuoteString(); createPersons(); createGroups(); createEmail(); /* CREATE TABLE "Person"(name VARCHAR(20), id INT PRIMARY KEY, age INT, hair VARCHAR(20)); CREATE TABLE "Group"(name VARCHAR(20), id INT PRIMARY KEY, belongs_to_group_id INT); CREATE TABLE "Person_Group"(person_id INT, group_id INT); CREATE TABLE "Email"(address VARCHAR(20), comment VARCHAR(20), person_id INT); INSERT INTO "Person" (name, id, age, hair) VALUES ('Anakin', 1, 20, 'blonde'); INSERT INTO "Person" (name, id, age, hair) VALUES ('Bridget', 2, 40, 'blonde'); INSERT INTO "Group" (name, id) VALUES ('User', 1); INSERT INTO "Group" (name, id) VALUES ('Manager', 2); INSERT INTO "Group" (name, id) VALUES ('Technichian', 3); INSERT INTO "Group" (name, id) VALUES ('Admin', 4); INSERT INTO "Person_Group" (person_id,group_id) VALUES ((SELECT "Person".id FROM "Person" WHERE "Person".name = 'Bridget' ), (SELECT "Group".id FROM "Group" WHERE "Group".name = 'Admin' )); INSERT INTO "Person_Group" (person_id,group_id) VALUES ((SELECT "Person".id FROM "Person" WHERE "Person".name = 'Anakin' ), (SELECT "Group".id FROM "Group" WHERE "Group".name = 'User' )); UPDATE "Group" SET belongs_to_group_id = (SELECT "Group".id FROM "Group" WHERE "Group".name ='Technichian' ) WHERE name='Admin'; UPDATE "Group" SET belongs_to_group_id = (SELECT "Group".id FROM "Group" WHERE "Group".name ='User' ) WHERE name='Technichian'; UPDATE "Group" SET belongs_to_group_id = (SELECT "Group".id FROM "Group" WHERE "Group".name ='User' ) WHERE name='Manager'; INSERT INTO "Email" (address, comment) VALUES ('anakin@example.com', 'home'); INSERT INTO "Email" (address, comment) VALUES ('anakin@example.org', 'work'); UPDATE "Email" SET person_id = (SELECT "Person".id FROM "Person" WHERE "Person".name ='Anakin' ) WHERE address='anakin@example.com'; UPDATE "Email" SET person_id = (SELECT "Person".id FROM "Person" WHERE "Person".name ='Anakin' ) WHERE address='anakin@example.org'; WITH RECURSIVE TransitiveGroup(id, name, belongs_to_group_id) AS ( SELECT child.id, child.name, child.belongs_to_group_id FROM "Group" child WHERE child.name='Admin' UNION ALL SELECT parent.id, parent.name, parent.belongs_to_group_id FROM TransitiveGroup child, "Group" parent WHERE parent.id = child.belongs_to_group_id ) SELECT * FROM TransitiveGroup */ queries = new ArrayList<TestData>() { { add( new TestData( "Start", "SELECT * FROM `Person` WHERE name = 'Anakin'".replace( "`", identifierQuoteString ), "START person=node:Person(name = 'Anakin') RETURN person", "Anakin", "20", "1 row" ) ); add( new TestData( "Match", "SELECT `Email`.* FROM `Person` JOIN `Email` ON `Person`.id = `Email`.person_id WHERE `Person`.name = 'Anakin'".replace( "`", identifierQuoteString ), "START person=node:Person(name = 'Anakin') MATCH person-[:email]->email RETURN email", "anakin@example.com", "anakin@example.org", "2 rows" ) ); add( new TestData( "JoinEntity", "SELECT `Group`.*, `Person_Group`.* FROM `Person` JOIN `Person_Group` ON `Person`.id = `Person_Group`.person_id JOIN `Group` ON `Person_Group`.Group_id=`Group`.id WHERE `Person`.name = 'Bridget'".replace( "`", identifierQuoteString ), "START person=node:Person(name = 'Bridget') MATCH person-[r:belongs_to]->group RETURN group, r", "Admin", "1 row" ) ); add( new TestData( "LeftJoin", "SELECT `Person`.name, `Email`.address FROM `Person` LEFT JOIN `Email` ON `Person`.id = `Email`.person_id".replace( "`", identifierQuoteString ), "START person=node:Person('name: *') OPTIONAL MATCH person-[:email]->email RETURN person.name, email.address", "Anakin", "anakin@example.org", "Bridget", "<null>", "3 rows" ) ); add( new TestData( "RecursiveJoin", /*(*/ null /*"WITH RECURSIVE TransitiveGroup(id, name, belongs_to_group_id) AS ( " + "SELECT child.id, child.name, child.belongs_to_group_id " + "FROM `Group` child " + "WHERE child.name='Admin' " + "UNION ALL SELECT parent.id, parent.name, parent.belongs_to_group_id " + "FROM TransitiveGroup child, `Group` parent " + "WHERE parent.id = child.belongs_to_group_id " + ") SELECT * FROM TransitiveGroup" ).replace( "`", identifierQuoteString )*/, "START person=node:Person('name: Bridget') " + "MATCH person-[:belongs_to*]->group RETURN person.name, group.name", "Bridget", "Admin", "Technichian", "User", "3 rows" ) ); add( new TestData( "Where", "SELECT * FROM `Person` WHERE `Person`.age > 35 AND `Person`.hair = 'blonde'".replace( "`", identifierQuoteString ), "START person=node:Person('name: *') WHERE person.age > 35 AND person.hair = 'blonde' RETURN person", "Bridget", "blonde", "1 row" ) ); add( new TestData( "Return", "SELECT `Person`.name, count(*) FROM `Person` GROUP BY `Person`.name ORDER BY `Person`.name".replace( "`", identifierQuoteString ), "START person=node:Person('name: *') RETURN person.name, count(*) ORDER BY person.name", "Bridget", "Anakin", "2 rows" ) ); } }; } private void createPersons() throws SQLException { String tableName = "Person"; String tableDefinition = "name VARCHAR(20), id INT PRIMARY KEY, age INT, hair VARCHAR(20)"; String[] fields = new String[] { "name", "id", "age", "hair" }; Object[][] values = new Object[][] { { "Anakin", 1, 20, "blonde" }, { "Bridget", 2, 40, "blonde" } }; createEntities( tableName, tableDefinition, fields, values ); } private void createGroups() throws SQLException { String tableName = "Group"; String tableDefinition = "name VARCHAR(20), id INT PRIMARY KEY, belongs_to_group_id INT"; String[] fields = new String[] { "name", "id" }; Object[][] values = new Object[][] { { "User", 1 }, { "Manager", 2 }, { "Technichian", 3 }, { "Admin", 4 } }; createEntities( tableName, tableDefinition, fields, values ); String sourceEntity = "Person"; String sourceMatchAttribute = "name"; String targetEntity = tableName; String targetMatchAttribute = "name"; Object[][] relationships = new Object[][] { { "Bridget", "Admin" }, { "Anakin", "User" } }; createRelationships( sourceEntity, sourceMatchAttribute, targetEntity, targetMatchAttribute, relationships, "belongs_to" ); sourceEntity = tableName; relationships = new Object[][] { { "Technichian", "Admin" }, { "User", "Technichian" }, { "User", "Manager" } }; createSelfRelationships( sourceEntity, sourceMatchAttribute, relationships, "belongs_to" ); } private void createEmail() throws SQLException { String tableName = "Email"; String tableDefinition = "address VARCHAR(20), comment VARCHAR(20), person_id INT"; String[] fields = new String[] { "address", "comment" }; Object[][] values = new Object[][] { { "anakin@example.com", "home" }, { "anakin@example.org", "work" } }; createEntities( tableName, tableDefinition, fields, values ); String sourceEntity = "Person"; String sourceMatchAttribute = "name"; String targetEntity = tableName; String targetMatchAttribute = fields[0]; Object[][] relationships = new Object[][] { { "Anakin", "anakin@example.com" }, { "Anakin", "anakin@example.org" } }; createSimpleRelationships( sourceEntity, sourceMatchAttribute, targetEntity, targetMatchAttribute, relationships, "email" ); } private void createSimpleRelationships( String sourceEntity, String sourceMatchAttribute, String targetEntity, String targetMatchAttribute, Object[][] relationships, String relationshipType ) throws SQLException { PreparedStatement prep = prepareSimpleRelationshipStatement( sourceEntity, sourceMatchAttribute, targetEntity, targetMatchAttribute ); insertIntoRdbms( prep, relationships ); createRelationshipsInGraphdb( sourceEntity, sourceMatchAttribute, targetEntity, targetMatchAttribute, relationships, relationshipType ); } private void createSelfRelationships( String entity, String matchAttribute, Object[][] relationships, String relationshipType ) throws SQLException { String targetAttribute = relationshipType + "_" + entity.toLowerCase() + "_id"; PreparedStatement prep = prepareSelfJoinRelationshipStatement( entity, matchAttribute, targetAttribute ); insertIntoRdbms( prep, relationships ); // get the correct direction for graphdb for ( Object[] objects : relationships ) { Collections.reverse( Arrays.asList(objects) ); } createRelationshipsInGraphdb( entity, matchAttribute, entity, matchAttribute, relationships, relationshipType ); } private void createRelationships( String sourceEntity, String sourceMatchAttribute, String targetEntity, String targetMatchAttribute, Object[][] relationships, String relationshipType ) throws SQLException { String relationship = sourceEntity + "_" + targetEntity; PreparedStatement prep = prepareRelationshipStatement( sourceEntity, sourceMatchAttribute, targetEntity, targetMatchAttribute, relationship ); insertIntoRdbms( prep, relationships ); createRelationshipsInGraphdb( sourceEntity, sourceMatchAttribute, targetEntity, targetMatchAttribute, relationships, relationshipType ); } private void createRelationshipsInGraphdb( String sourceEntity, String sourceMatchAttribute, String targetEntity, String targetMatchAttribute, Object[][] relationships, String relationshipType ) { try ( Transaction tx = graphdb.beginTx() ) { RelationshipType type = DynamicRelationshipType.withName( relationshipType ); Index<Node> sourceIndex = graphdb.index() .forNodes( sourceEntity ); Index<Node> targetIndex = graphdb.index() .forNodes( targetEntity ); for ( Object[] relationship : relationships ) { Node sourceNode = sourceIndex.get( sourceMatchAttribute, relationship[0] ) .getSingle(); Node targetNode = targetIndex.get( targetMatchAttribute, relationship[1] ) .getSingle(); sourceNode.createRelationshipTo( targetNode, type ); } tx.success(); } } private void createEntities( String tableName, String tableDefinition, String[] fields, Object[][] values ) throws SQLException { createTable( tableName, tableDefinition ); PreparedStatement prep = prepareInsertStatement( tableName, fields ); insertIntoRdbms( prep, values ); insertIntoGraphdb( tableName, fields, values ); } private void insertIntoGraphdb( String tableName, String[] fields, Object[][] values ) { try ( Transaction tx = graphdb.beginTx() ) { Index<Node> index = graphdb.index() .forNodes( tableName ); for ( Object[] value : values ) { Node node = graphdb.createNode(); for ( int i = 0; i < fields.length; i++ ) { node.setProperty( fields[i], value[i] ); if ( i == 0 ) { index.add( node, fields[i], value[i] ); } } } tx.success(); } } private void insertIntoRdbms( PreparedStatement prep, Object[][] values ) throws SQLException { for ( Object[] value : values ) { ParameterMetaData metaData = prep.getParameterMetaData(); for ( int i = 0; i < metaData.getParameterCount(); i++ ) { int parameterType = metaData.getParameterType( i + 1 ); switch ( parameterType ) { case Types.INTEGER: prep.setInt( i + 1, (Integer) value[i] ); break; case Types.VARCHAR: prep.setString( i + 1, (String) value[i] ); break; default: throw new RuntimeException( "Unknown SQL type: " + parameterType ); } } prep.executeUpdate(); } prep.close(); } private void createTable( String name, String definition ) throws SQLException { String sql = "CREATE TABLE " + identifierQuoteString + name + identifierQuoteString + "(" + definition + ")"; try ( Statement statement = sqldb.createStatement() ) { statement.execute( sql ); } } private PreparedStatement prepareInsertStatement( String tableName, String[] fields ) throws SQLException { StringBuilder sql = new StringBuilder( 100 ); String fieldList = String.valueOf( Arrays.asList( fields ) ); fieldList = fieldList.substring( 1, fieldList.length() - 1 ); String valueList = new String( new char[fields.length - 1] ).replace( "\0", ", ?" ); sql.append( "INSERT INTO " ) .append( identifierQuoteString ) .append( tableName ) .append( identifierQuoteString ) .append( " (" ) .append( fieldList ) .append( ") VALUES (?" ) .append( valueList ) .append( ")" ); return sqldb.prepareStatement( sql.toString() ); } private PreparedStatement prepareSimpleRelationshipStatement( String sourceEntity, String sourceMatchAttribute, String targetEntity, String targetMatchAttribute) throws SQLException { StringBuilder sql = new StringBuilder( 100 ); sql.append( "UPDATE " ) .append( identifierQuoteString ) .append( targetEntity ) .append( identifierQuoteString ) .append( " SET " ) .append( sourceEntity.toLowerCase() ) .append( "_id = (SELECT " ) .append( identifierQuoteString ) .append( sourceEntity ) .append( identifierQuoteString ) .append( ".id FROM " ) .append( identifierQuoteString ) .append( sourceEntity ) .append( identifierQuoteString ) .append( " WHERE " ) .append( identifierQuoteString ) .append( sourceEntity ) .append( identifierQuoteString ) .append( "." ) .append( sourceMatchAttribute ) .append( " =? ) WHERE " ) .append( targetMatchAttribute ) .append( "=?" ); return sqldb.prepareStatement( sql.toString() ); } private PreparedStatement prepareSelfJoinRelationshipStatement( String entity, String matchAttribute, String targetAttribute ) throws SQLException { StringBuilder sql = new StringBuilder( 100 ); sql.append( "UPDATE " ) .append( identifierQuoteString ) .append( entity ) .append( identifierQuoteString ) .append( " SET " ) .append( targetAttribute ) .append( " = (SELECT " ) .append( identifierQuoteString ) .append( entity ) .append( identifierQuoteString ) .append( ".id FROM " ) .append( identifierQuoteString ) .append( entity ) .append( identifierQuoteString ) .append( " WHERE " ) .append( identifierQuoteString ) .append( entity ) .append( identifierQuoteString ) .append( "." ) .append( matchAttribute ) .append( " =? ) WHERE " ) .append( matchAttribute ) .append( "=?" ); return sqldb.prepareStatement( sql.toString() ); } private PreparedStatement prepareRelationshipStatement( String sourceEntity, String sourceMatchAttribute, String targetEntity, String targetMatchAttribute, String joinEntity ) throws SQLException { String sourceColumnName = sourceEntity.toLowerCase() + "_id"; String targetColumnName = targetEntity.toLowerCase() + "_id"; StringBuilder sql = new StringBuilder( 100 ); sql.append( sourceColumnName ) .append( " INT, " ) .append( targetColumnName ) .append( " INT" ); createTable( joinEntity, sql.toString() ); sql.setLength( 0 ); sql.append( "INSERT INTO " ) .append( identifierQuoteString ) .append( joinEntity ) .append( identifierQuoteString ) .append( " (" ) .append( sourceColumnName ) .append( "," ) .append( targetColumnName ) .append( ") VALUES ((SELECT " ) .append( identifierQuoteString ) .append( sourceEntity ) .append( identifierQuoteString ) .append( ".id FROM " ) .append( identifierQuoteString ) .append( sourceEntity ) .append( identifierQuoteString ) .append( " WHERE " ) .append( identifierQuoteString ) .append( sourceEntity ) .append( identifierQuoteString ) .append( "." ) .append( sourceMatchAttribute ) .append( " = ? ), (SELECT " ) .append( identifierQuoteString ) .append( targetEntity ) .append( identifierQuoteString ) .append( ".id FROM " ) .append( identifierQuoteString ) .append( targetEntity ) .append( identifierQuoteString ) .append( " WHERE " ) .append( identifierQuoteString ) .append( targetEntity ) .append( identifierQuoteString ) .append( "." ) .append( targetMatchAttribute ) .append( " = ? ))" ); return sqldb.prepareStatement( sql.toString() ); } /** * Execute all queries */ void run() throws SQLException { for ( TestData query : queries ) { System.out.println( "\n*** " + query.name + " ***\n" ); if ( query.sql != null ) { System.out.println( query.sql ); System.out.println( executeSql( query.sql ) ); } System.out.println( query.cypher ); System.out.println( executeCypher( query.cypher ) ); } } void shutdown() throws SQLException { sqldb.close(); graphdb.shutdown(); } String executeCypher( String cypher ) { try ( Transaction transaction = graphdb.beginTx() ) { ExecutionResult executionResult = engine.execute( cypher ); return executionResult.dumpToString(); } } String executeSql( String sql ) throws SQLException { StringBuilder builder = new StringBuilder( 512 ); try ( Statement statement = sqldb.createStatement() ) { if ( statement.execute( sql ) ) { try ( ResultSet result = statement.getResultSet() ) { ResultSetMetaData meta = result.getMetaData(); int rowCount = 0; int columnCount = meta.getColumnCount(); String line = new String( new char[columnCount] ).replace( "\0", "+" + LINE_SEGMENT ) + "+\n"; builder.append( line ); for ( int i = 1; i <= columnCount; i++ ) { String output = meta.getColumnLabel( i ); printColumn( builder, output ); } builder.append( "|\n" ) .append( line ); while ( result.next() ) { rowCount++; for ( int i = 1; i <= columnCount; i++ ) { String output = result.getString( i ); printColumn( builder, output ); } builder.append( "|\n" ); } builder.append( line ) .append( rowCount ) .append( " rows\n" ); } } else { throw new RuntimeException( "Couldn't execute: " + sql ); } } return builder.toString(); } private void printColumn( StringBuilder builder, String value ) { if ( value == null ) { value = "<null>"; } builder.append( "| " ) .append( value ) .append( SPACE_SEGMENT.substring( value.length() + 1 ) ); } public static class TestData { public final String name; public final String sql; public final String cypher; public final String[] matchStrings; /** * Create a sql/cypher test. * * @param name the name of the test * @param sql the sql query string * @param cypher the cypher query string * @param matchStrings strings that should exist in the query result */ public TestData( String name, String sql, String cypher, String... matchStrings ) { this.name = name; this.sql = sql; this.cypher = cypher; this.matchStrings = matchStrings; } } }
false
community_embedded-examples_src_main_java_org_neo4j_examples_CypherSql.java
3,039
public static class TestData { public final String name; public final String sql; public final String cypher; public final String[] matchStrings; /** * Create a sql/cypher test. * * @param name the name of the test * @param sql the sql query string * @param cypher the cypher query string * @param matchStrings strings that should exist in the query result */ public TestData( String name, String sql, String cypher, String... matchStrings ) { this.name = name; this.sql = sql; this.cypher = cypher; this.matchStrings = matchStrings; } }
false
community_embedded-examples_src_main_java_org_neo4j_examples_CypherSql.java
3,040
class UniqueFactoryGetOrCreate extends GetOrCreate<UniqueFactory<Node>> { @Override public Node getOrCreateUser( String username, GraphDatabaseService graphDb, UniqueFactory<Node> uniqueFactory ) { return getOrCreateUserWithUniqueFactory( username, graphDb, uniqueFactory ); } @Override void assertUserExistsUniquely( GraphDatabaseService graphDb, Transaction tx, String username ) { super.assertUserExistsUniquely( graphDb, tx, username ); //To change body of overridden methods use assertUserExistsUniquelyInIndex( graphDb, tx, username ); } }
false
community_embedded-examples_src_test_java_org_neo4j_examples_GetOrCreateDocIT.java
3,041
public class CypherSqlDocIT extends ImpermanentGraphJavaDocTestBase { private static CypherSql cyperSql; @BeforeClass public static void setUpDbs() throws SQLException { cyperSql = new CypherSql( new TestGraphDatabaseFactory().newImpermanentDatabase() ); cyperSql.createDbs(); } @AfterClass public static void tearDownDbs() throws SQLException { cyperSql.shutdown(); } /** * This guide is for people who understand SQL. You can use that prior * knowledge to quickly get going with Cypher and start exploring Neo4j. * * [[query-sql-start]] * == Start == * * SQL starts with the result you want -- we `SELECT` what we want and then * declare how to source it. In Cypher, the `START` clause is quite a * different concept which specifies starting points in the graph from which * the query will execute. * * From a SQL point of view, the identifiers in `START` are like table names * that point to a set of nodes or relationships. The set can be listed * literally, come via parameters, or as I show in the following example, be * defined by an index look-up. * * So in fact rather than being `SELECT`-like, the `START` clause is * somewhere between the `FROM` and the `WHERE` clause in SQL. * * .SQL Query * @@Start-sql-query * * @@Start-sql-result * * .Cypher Query * @@Start-cypher-query * * @@Start-cypher-result * * Cypher allows multiple starting points. This should not be strange from a SQL perspective -- * every table in the `FROM` clause is another starting point. * * [[query-sql-match]] * == Match == * * Unlike SQL which operates on sets, Cypher predominantly works on sub-graphs. * The relational equivalent is the current set of tuples being evaluated during a `SELECT` query. * * The shape of the sub-graph is specified in the `MATCH` clause. * The `MATCH` clause is analogous to the `JOIN` in SQL. A normal a->b relationship is an * inner join between nodes a and b -- both sides have to have at least one match, or nothing is returned. * * We'll start with a simple example, where we find all email addresses that are connected to * the person ``Anakin''. This is an ordinary one-to-many relationship. * * .SQL Query * @@Match-sql-query * * @@Match-sql-result * * .Cypher Query * @@Match-cypher-query * * @@Match-cypher-result * * There is no join table here, but if one is necessary the next example will show how to do that, writing the pattern relationship like so: * `-[r:belongs_to]->` will introduce (the equivalent of) join table available as the variable `r`. * In reality this is a named relationship in Cypher, so we're saying ``join `Person` to `Group` via `belongs_to`.'' * To illustrate this, consider this image, comparing the SQL model and Neo4j/Cypher. * * ifdef::nonhtmloutput[] * image::RDBMSvsGraph.svg[scaledwidth="100%"] * endif::nonhtmloutput[] * ifndef::nonhtmloutput[] * image::RDBMSvsGraph.svg.png[scaledwidth="100%"] * endif::nonhtmloutput[] * * And here are example queries: * * .SQL Query * @@JoinEntity-sql-query * * @@JoinEntity-sql-result * * .Cypher Query * @@JoinEntity-cypher-query * * @@JoinEntity-cypher-result * * An http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html[outer join] is just as easy. * Add +OPTIONAL+ before the match and it's an optional relationship between nodes -- the outer join of Cypher. * * Whether it's a left outer join, or a right outer join is defined by which side of the pattern has a starting point. * This example is a left outer join, because the bound node is on the left side: * * .SQL Query * @@LeftJoin-sql-query * * @@LeftJoin-sql-result * * .Cypher Query * @@LeftJoin-cypher-query * * @@LeftJoin-cypher-result * * Relationships in Neo4j are first class citizens -- it's like the SQL tables are pre-joined with each other. * So, naturally, Cypher is designed to be able to handle highly connected data easily. * * One such domain is tree structures -- anyone that has tried storing tree structures in SQL knows * that you have to work hard to get around the limitations of the relational model. * There are even books on the subject. * * To find all the groups and sub-groups that Bridget belongs to, this query is enough in Cypher: * * .Cypher Query * @@RecursiveJoin-cypher-query * * @@RecursiveJoin-cypher-result * * The * after the relationship type means that there can be multiple hops across +belongs_to+ relationships between group and user. * Some SQL dialects have recursive abilities, that allow the expression of queries like this, but you may have a hard time wrapping your head around those. * Expressing something like this in SQL is hugely impractical if not practically impossible. * * [[query-sql-where]] * == Where == * * This is the easiest thing to understand -- it's the same animal in both languages. * It filters out result sets/subgraphs. * Not all predicates have an equivalent in the other language, but the concept is the same. * * .SQL Query * @@Where-sql-query * * @@Where-sql-result * * .Cypher Query * @@Where-cypher-query * * @@Where-cypher-result * * [[query-sql-return]] * == Return == * This is SQL's `SELECT`. * We just put it in the end because it felt better to have it there -- * you do a lot of matching and filtering, and finally, you return something. * * Aggregate queries work just like they do in SQL, apart from the fact that there is no explicit `GROUP BY` clause. * Everything in the return clause that is not an aggregate function will be used as the grouping columns. * * .SQL Query * @@Return-sql-query * * @@Return-sql-result * * .Cypher Query * @@Return-cypher-query * * @@Return-cypher-result * * Order by is the same in both languages -- `ORDER BY` expression `ASC`/`DESC`. * Nothing weird here. * * // == Recursive queries == * * * */ @Test @Documented @Title( "From SQL to Cypher" ) public void test() throws Exception { for ( CypherSql.TestData query : cyperSql.queries ) { String rawSqlResult = null; if ( query.sql != null ) { String sqlSnippet = createSqlSnippet( query.sql ); gen.get() .addSnippet( query.name + "-sql-query", sqlSnippet ); rawSqlResult = cyperSql.executeSql( query.sql ); String sqlResult = createQueryResultSnippet( rawSqlResult ); gen.get() .addSnippet( query.name + "-sql-result", sqlResult ); } String cypherSnippet = createCypherSnippet( query.cypher ); gen.get() .addSnippet( query.name + "-cypher-query", cypherSnippet ); String rawCypherResult = cyperSql.executeCypher( query.cypher ); String cypherResult = createQueryResultSnippet( rawCypherResult ); gen.get() .addSnippet( query.name + "-cypher-result", cypherResult ); for ( String match : query.matchStrings ) { if ( query.sql != null ) { assertTrue( "SQL result doesn't contain: '" + match + "'", rawSqlResult.contains( match ) ); } assertTrue( "Cypher result doesn't contain: '" + match + "'", rawCypherResult.contains( match ) ); } } } }
false
community_embedded-examples_src_test_java_org_neo4j_examples_CypherSqlDocIT.java
3,042
abstract class ThreadRunner<D> implements Runnable { static final int NUM_USERS = 100; final GetOrCreate<D> impl; ThreadRunner( GetOrCreate<D> impl ) { this.impl = impl; } abstract D createDependency(); @Override public void run() { final D dependency = createDependency(); final List<GetOrCreateTask<D>> threads = new ArrayList<>(); int numThreads = Runtime.getRuntime().availableProcessors() * 2; for ( int i = 0; i < numThreads; i++ ) { String threadName = format( "%s thread %d", GetOrCreateDocIT.class.getSimpleName(), i ); threads.add( new GetOrCreateTask<>( db, NUM_USERS, impl, threadName, dependency ) ); } for ( Thread thread : threads ) { thread.start(); } RuntimeException failure = null; List<List<Node>> results = new ArrayList<>(); for ( GetOrCreateTask<D> thread : threads ) { try { thread.join(); if ( failure == null ) { failure = thread.failure; } results.add( thread.result ); } catch ( InterruptedException e ) { e.printStackTrace(); } } if ( failure != null ) { throw failure; } assertEquals( numThreads, results.size() ); List<Node> firstResult = results.remove( 0 ); for ( List<Node> subresult : results ) { assertEquals( firstResult, subresult ); } for ( int i = 0; i < NUM_USERS; i++ ) { final String username = getUsername( i ); GraphDatabaseService graphdb = graphdb(); impl.getOrCreateUser( username, graphdb, dependency ); try ( Transaction tx = graphdb.beginTx() ) { impl.assertUserExistsUniquely( graphdb, tx, username ); } catch ( NoSuchElementException e ) { throw new RuntimeException( format( "User '%s' not created uniquely.", username ), e ); } } } }
false
community_embedded-examples_src_test_java_org_neo4j_examples_GetOrCreateDocIT.java
3,043
class PessimisticGetOrCreate extends GetOrCreate<Node> { @Override public Node getOrCreateUser( String username, GraphDatabaseService graphDb, Node lockNode ) { return getOrCreateUserPessimistically( username, graphDb, lockNode ); } }
false
community_embedded-examples_src_test_java_org_neo4j_examples_GetOrCreateDocIT.java
3,044
private static class GetOrCreateTask<D> extends Thread { private final GraphDatabaseService db; private final int numUsers; private final GetOrCreate<D> impl; private final D dependency; volatile List<Node> result; volatile RuntimeException failure; GetOrCreateTask( GraphDatabaseService db, int numUsers, GetOrCreate<D> impl, String name, D dependency ) { super( name ); this.db = db; this.numUsers = numUsers; this.impl = impl; this.dependency = dependency; } @Override public void run() { try { List<Node> subresult = new ArrayList<>(); for ( int j = 0; j < numUsers; j++ ) { subresult.add( impl.getOrCreateUser( getUsername( j ), db, dependency) ); } this.result = subresult; } catch ( RuntimeException e ) { failure = e; } } }
false
community_embedded-examples_src_test_java_org_neo4j_examples_GetOrCreateDocIT.java
3,045
abstract class GetOrCreate<D> { abstract Node getOrCreateUser( String username, GraphDatabaseService graphDb, D dependency ); void assertUserExistsUniquely( GraphDatabaseService graphDb, Transaction tx, String username ) { assertUserExistsUniquelyInGraphDb( graphDb, tx, username ); } }
false
community_embedded-examples_src_test_java_org_neo4j_examples_GetOrCreateDocIT.java
3,046
class CypherGetOrCreate extends GetOrCreate<ExecutionEngine> { @Override public Node getOrCreateUser( String username, GraphDatabaseService graphDb, ExecutionEngine engine ) { return getOrCreateWithCypher( username, graphDb, engine ); } }
false
community_embedded-examples_src_test_java_org_neo4j_examples_GetOrCreateDocIT.java
3,047
{ @Override protected void initialize( Node created, Map<String, Object> properties ) { created.addLabel( DynamicLabel.label( "User" ) ); created.setProperty( "name", properties.get( "name" ) ); } };
false
community_embedded-examples_src_test_java_org_neo4j_examples_GetOrCreateDocIT.java
3,048
new ThreadRunner<ExecutionEngine>( new CypherGetOrCreate() ) { @Override ExecutionEngine createDependency() { return createExecutionEngineAndConstraint( graphdb() ); } }.run();
false
community_embedded-examples_src_test_java_org_neo4j_examples_GetOrCreateDocIT.java
3,049
new ThreadRunner<UniqueFactory<Node>>( new UniqueFactoryGetOrCreate() ) { @Override UniqueFactory<Node> createDependency() { return createUniqueFactory( graphdb() ); } }.run();
false
community_embedded-examples_src_test_java_org_neo4j_examples_GetOrCreateDocIT.java
3,050
{ @Override Node createDependency() { return createLockNode( graphdb() ); } }.run();
false
community_embedded-examples_src_test_java_org_neo4j_examples_GetOrCreateDocIT.java
3,051
public class GetOrCreateDocIT extends AbstractJavaDocTestBase { @BeforeClass public static void init() { db = new GraphDatabaseFactory().newEmbeddedDatabase( TargetDirectory.forTest( GetOrCreateDocIT.class ).makeGraphDbDir().getAbsolutePath() ); } abstract class GetOrCreate<D> { abstract Node getOrCreateUser( String username, GraphDatabaseService graphDb, D dependency ); void assertUserExistsUniquely( GraphDatabaseService graphDb, Transaction tx, String username ) { assertUserExistsUniquelyInGraphDb( graphDb, tx, username ); } } class PessimisticGetOrCreate extends GetOrCreate<Node> { @Override public Node getOrCreateUser( String username, GraphDatabaseService graphDb, Node lockNode ) { return getOrCreateUserPessimistically( username, graphDb, lockNode ); } } class UniqueFactoryGetOrCreate extends GetOrCreate<UniqueFactory<Node>> { @Override public Node getOrCreateUser( String username, GraphDatabaseService graphDb, UniqueFactory<Node> uniqueFactory ) { return getOrCreateUserWithUniqueFactory( username, graphDb, uniqueFactory ); } @Override void assertUserExistsUniquely( GraphDatabaseService graphDb, Transaction tx, String username ) { super.assertUserExistsUniquely( graphDb, tx, username ); //To change body of overridden methods use assertUserExistsUniquelyInIndex( graphDb, tx, username ); } } class CypherGetOrCreate extends GetOrCreate<ExecutionEngine> { @Override public Node getOrCreateUser( String username, GraphDatabaseService graphDb, ExecutionEngine engine ) { return getOrCreateWithCypher( username, graphDb, engine ); } } abstract class ThreadRunner<D> implements Runnable { static final int NUM_USERS = 100; final GetOrCreate<D> impl; ThreadRunner( GetOrCreate<D> impl ) { this.impl = impl; } abstract D createDependency(); @Override public void run() { final D dependency = createDependency(); final List<GetOrCreateTask<D>> threads = new ArrayList<>(); int numThreads = Runtime.getRuntime().availableProcessors() * 2; for ( int i = 0; i < numThreads; i++ ) { String threadName = format( "%s thread %d", GetOrCreateDocIT.class.getSimpleName(), i ); threads.add( new GetOrCreateTask<>( db, NUM_USERS, impl, threadName, dependency ) ); } for ( Thread thread : threads ) { thread.start(); } RuntimeException failure = null; List<List<Node>> results = new ArrayList<>(); for ( GetOrCreateTask<D> thread : threads ) { try { thread.join(); if ( failure == null ) { failure = thread.failure; } results.add( thread.result ); } catch ( InterruptedException e ) { e.printStackTrace(); } } if ( failure != null ) { throw failure; } assertEquals( numThreads, results.size() ); List<Node> firstResult = results.remove( 0 ); for ( List<Node> subresult : results ) { assertEquals( firstResult, subresult ); } for ( int i = 0; i < NUM_USERS; i++ ) { final String username = getUsername( i ); GraphDatabaseService graphdb = graphdb(); impl.getOrCreateUser( username, graphdb, dependency ); try ( Transaction tx = graphdb.beginTx() ) { impl.assertUserExistsUniquely( graphdb, tx, username ); } catch ( NoSuchElementException e ) { throw new RuntimeException( format( "User '%s' not created uniquely.", username ), e ); } } } } private static String getUsername( int j ) { return format( "User%d", j ); } private static class GetOrCreateTask<D> extends Thread { private final GraphDatabaseService db; private final int numUsers; private final GetOrCreate<D> impl; private final D dependency; volatile List<Node> result; volatile RuntimeException failure; GetOrCreateTask( GraphDatabaseService db, int numUsers, GetOrCreate<D> impl, String name, D dependency ) { super( name ); this.db = db; this.numUsers = numUsers; this.impl = impl; this.dependency = dependency; } @Override public void run() { try { List<Node> subresult = new ArrayList<>(); for ( int j = 0; j < numUsers; j++ ) { subresult.add( impl.getOrCreateUser( getUsername( j ), db, dependency) ); } this.result = subresult; } catch ( RuntimeException e ) { failure = e; } } } @Test public void testPessimisticLocking() { new ThreadRunner<Node>( new PessimisticGetOrCreate() ) { @Override Node createDependency() { return createLockNode( graphdb() ); } }.run(); } @Test public void getOrCreateWithUniqueFactory() throws Exception { new ThreadRunner<UniqueFactory<Node>>( new UniqueFactoryGetOrCreate() ) { @Override UniqueFactory<Node> createDependency() { return createUniqueFactory( graphdb() ); } }.run(); } @Test public void getOrCreateUsingCypher() throws Exception { new ThreadRunner<ExecutionEngine>( new CypherGetOrCreate() ) { @Override ExecutionEngine createDependency() { return createExecutionEngineAndConstraint( graphdb() ); } }.run(); } public Node getOrCreateUserPessimistically( String username, GraphDatabaseService graphDb, Node lockNode ) { // START SNIPPET: pessimisticLocking try ( Transaction tx = graphDb.beginTx() ) { Index<Node> usersIndex = graphDb.index().forNodes( "users" ); Node userNode = usersIndex.get( "name", username ).getSingle(); if ( userNode != null ) { return userNode; } tx.acquireWriteLock( lockNode ); userNode = usersIndex.get( "name", username ).getSingle(); if ( userNode == null ) { userNode = graphDb.createNode( DynamicLabel.label( "User" ) ); usersIndex.add( userNode, "name", username ); userNode.setProperty( "name", username ); } tx.success(); return userNode; } // END SNIPPET: pessimisticLocking } public static Node createLockNode( GraphDatabaseService graphDb ) { // START SNIPPET: prepareLockNode try ( Transaction tx = graphDb.beginTx() ) { final Node lockNode = graphDb.createNode(); tx.success(); return lockNode; } // END SNIPPET: prepareLockNode } private UniqueFactory<Node> createUniqueFactory( GraphDatabaseService graphDb ) { // START SNIPPET: prepareUniqueFactory try ( Transaction tx = graphDb.beginTx() ) { UniqueFactory.UniqueNodeFactory result = new UniqueFactory.UniqueNodeFactory( graphDb, "users" ) { @Override protected void initialize( Node created, Map<String, Object> properties ) { created.addLabel( DynamicLabel.label( "User" ) ); created.setProperty( "name", properties.get( "name" ) ); } }; tx.success(); return result; } // END SNIPPET: prepareUniqueFactory } public Node getOrCreateUserWithUniqueFactory( String username, GraphDatabaseService graphDb, UniqueFactory<Node> factory ) { // START SNIPPET: getOrCreateWithFactory try ( Transaction tx = graphDb.beginTx() ) { Node node = factory.getOrCreate( "name", username ); tx.success(); return node; } // END SNIPPET: getOrCreateWithFactory } private Node getOrCreateWithCypher( String username, GraphDatabaseService graphDb, ExecutionEngine engine ) { // START SNIPPET: getOrCreateWithCypher Node result = null; ResourceIterator<Node> resultIterator = null; try ( Transaction tx = graphDb.beginTx() ) { String queryString = "MERGE (n:User {name: {name}}) RETURN n"; Map<String, Object> parameters = new HashMap<>(); parameters.put( "name", username ); resultIterator = engine.execute( queryString, parameters ).columnAs( "n" ); result = resultIterator.next(); tx.success(); return result; } // END SNIPPET: getOrCreateWithCypher finally { if ( resultIterator != null ) { if ( resultIterator.hasNext() ) { Node other = resultIterator.next(); //noinspection ThrowFromFinallyBlock throw new IllegalStateException( "Merge returned more than one node: " + result + " and " + other ); } } } } private ExecutionEngine createExecutionEngineAndConstraint( GraphDatabaseService graphdb ) { // START SNIPPET: prepareExecutionEngineAndConstraint try ( Transaction tx = graphdb.beginTx() ) { graphdb.schema() .constraintFor( DynamicLabel.label( "User" ) ) .assertPropertyIsUnique( "name" ) .create(); tx.success(); } return new ExecutionEngine( graphdb() ); // END SNIPPET: prepareExecutionEngineAndConstraint } private static void assertUserExistsUniquelyInIndex( GraphDatabaseService graph, Transaction tx, String username ) { assertNotNull( format( "User '%s' not created.", username ), graph.index() .forNodes( "users" ) .get( "name", username ) .getSingle() ); tx.success(); } private static void assertUserExistsUniquelyInGraphDb( GraphDatabaseService graph, Transaction tx, String username ) { Label label = DynamicLabel.label( "User" ); Node result = singleOrNull( graph.findNodesByLabelAndProperty( label, "name", username ) ); assertNotNull( format( "User '%s' not created.", username ), result ); tx.success(); } }
false
community_embedded-examples_src_test_java_org_neo4j_examples_GetOrCreateDocIT.java
3,052
public class EmbeddedNeo4jWithNewIndexingDocTest { @Test public void justExecuteIt() { EmbeddedNeo4jWithNewIndexing.main( null ); } }
false
community_embedded-examples_src_test_java_org_neo4j_examples_EmbeddedNeo4jWithNewIndexingDocTest.java
3,053
public class EmbeddedNeo4jWithNewIndexing { private static final String DB_PATH = "target/neo4j-store-with-new-indexing"; public static void main( final String[] args ) { System.out.println( "Starting database ..." ); // START SNIPPET: startDb GraphDatabaseService graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( DB_PATH ); // END SNIPPET: startDb { // START SNIPPET: createIndex IndexDefinition indexDefinition; try ( Transaction tx = graphDb.beginTx() ) { Schema schema = graphDb.schema(); indexDefinition = schema.indexFor( DynamicLabel.label( "User" ) ) .on( "username" ) .create(); tx.success(); } // END SNIPPET: createIndex // START SNIPPET: wait try ( Transaction tx = graphDb.beginTx() ) { Schema schema = graphDb.schema(); schema.awaitIndexOnline( indexDefinition, 10, TimeUnit.SECONDS ); } // END SNIPPET: wait } { // START SNIPPET: addUsers try ( Transaction tx = graphDb.beginTx() ) { Label label = DynamicLabel.label( "User" ); // Create some users for ( int id = 0; id < 100; id++ ) { Node userNode = graphDb.createNode( label ); userNode.setProperty( "username", "user" + id + "@neo4j.org" ); } System.out.println( "Users created" ); tx.success(); } // END SNIPPET: addUsers } { // START SNIPPET: findUsers Label label = DynamicLabel.label( "User" ); int idToFind = 45; String nameToFind = "user" + idToFind + "@neo4j.org"; try ( Transaction tx = graphDb.beginTx() ) { try ( ResourceIterator<Node> users = graphDb.findNodesByLabelAndProperty( label, "username", nameToFind ).iterator() ) { ArrayList<Node> userNodes = new ArrayList<>(); while ( users.hasNext() ) { userNodes.add( users.next() ); } for ( Node node : userNodes ) { System.out.println( "The username of user " + idToFind + " is " + node.getProperty( "username" ) ); } } } // END SNIPPET: findUsers } { // START SNIPPET: resourceIterator Label label = DynamicLabel.label( "User" ); int idToFind = 45; String nameToFind = "user" + idToFind + "@neo4j.org"; try ( Transaction tx = graphDb.beginTx(); ResourceIterator<Node> users = graphDb .findNodesByLabelAndProperty( label, "username", nameToFind ) .iterator() ) { Node firstUserNode; if ( users.hasNext() ) { firstUserNode = users.next(); } users.close(); } // END SNIPPET: resourceIterator } { // START SNIPPET: updateUsers try ( Transaction tx = graphDb.beginTx() ) { Label label = DynamicLabel.label( "User" ); int idToFind = 45; String nameToFind = "user" + idToFind + "@neo4j.org"; for ( Node node : graphDb.findNodesByLabelAndProperty( label, "username", nameToFind ) ) { node.setProperty( "username", "user" + ( idToFind + 1 ) + "@neo4j.org" ); } tx.success(); } // END SNIPPET: updateUsers } { // START SNIPPET: deleteUsers try ( Transaction tx = graphDb.beginTx() ) { Label label = DynamicLabel.label( "User" ); int idToFind = 46; String nameToFind = "user" + idToFind + "@neo4j.org"; for ( Node node : graphDb.findNodesByLabelAndProperty( label, "username", nameToFind ) ) { node.delete(); } tx.success(); } // END SNIPPET: deleteUsers } { // START SNIPPET: dropIndex try ( Transaction tx = graphDb.beginTx() ) { Label label = DynamicLabel.label( "User" ); for ( IndexDefinition indexDefinition : graphDb.schema() .getIndexes( label ) ) { // There is only one index indexDefinition.drop(); } tx.success(); } // END SNIPPET: dropIndex } System.out.println( "Shutting down database ..." ); // START SNIPPET: shutdownDb graphDb.shutdown(); // END SNIPPET: shutdownDb } }
false
community_embedded-examples_src_main_java_org_neo4j_examples_EmbeddedNeo4jWithNewIndexing.java
3,054
public class EmbeddedNeo4jWithIndexingDocTest { @Test public void justExecuteIt() { EmbeddedNeo4jWithIndexing.main( null ); } }
false
community_embedded-examples_src_test_java_org_neo4j_examples_EmbeddedNeo4jWithIndexingDocTest.java
3,055
{ @Override public void run() { shutdown(); } } );
false
community_embedded-examples_src_main_java_org_neo4j_examples_EmbeddedNeo4jWithIndexing.java
3,056
public class EmbeddedNeo4jWithIndexing { private static final String DB_PATH = "target/neo4j-store"; private static final String USERNAME_KEY = "username"; private static GraphDatabaseService graphDb; private static Index<Node> nodeIndex; public static void main( final String[] args ) { // START SNIPPET: startDb graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( DB_PATH ); registerShutdownHook(); // END SNIPPET: startDb // START SNIPPET: addUsers try ( Transaction tx = graphDb.beginTx() ) { nodeIndex = graphDb.index().forNodes( "nodes" ); // Create some users and index their names with the IndexService for ( int id = 0; id < 100; id++ ) { createAndIndexUser( idToUserName( id ) ); } // END SNIPPET: addUsers // Find a user through the search index // START SNIPPET: findUser int idToFind = 45; String userName = idToUserName( idToFind ); Node foundUser = nodeIndex.get( USERNAME_KEY, userName ).getSingle(); System.out.println( "The username of user " + idToFind + " is " + foundUser.getProperty( USERNAME_KEY ) ); // END SNIPPET: findUser // Delete the persons and remove them from the index for ( Node user : nodeIndex.query( USERNAME_KEY, "*" ) ) { nodeIndex.remove( user, USERNAME_KEY, user.getProperty( USERNAME_KEY ) ); user.delete(); } tx.success(); } shutdown(); } private static void shutdown() { graphDb.shutdown(); } // START SNIPPET: helperMethods private static String idToUserName( final int id ) { return "user" + id + "@neo4j.org"; } private static Node createAndIndexUser( final String username ) { Node node = graphDb.createNode(); node.setProperty( USERNAME_KEY, username ); nodeIndex.add( node, USERNAME_KEY, username ); return node; } // END SNIPPET: helperMethods private static void registerShutdownHook() { // Registers a shutdown hook for the Neo4j and index service instances // so that it shuts down nicely when the VM exits (even if you // "Ctrl-C" the running example before it's completed) Runtime.getRuntime().addShutdownHook( new Thread() { @Override public void run() { shutdown(); } } ); } }
false
community_embedded-examples_src_main_java_org_neo4j_examples_EmbeddedNeo4jWithIndexing.java
3,057
public class EmbeddedNeo4jDocTest { private static EmbeddedNeo4j hello; private static JavaDocsGenerator gen; @BeforeClass public static void setUpBeforeClass() throws Exception { hello = new EmbeddedNeo4j(); gen = new JavaDocsGenerator( "hello-world-java", "dev" ); } @Test public void test() { hello.createDb(); String graph = AsciidocHelper.createGraphVizDeletingReferenceNode( "Hello World Graph", hello.graphDb, "java" ); assertFalse( graph.isEmpty() ); gen.saveToFile( "graph", graph ); assertFalse( hello.greeting.isEmpty() ); gen.saveToFile( "output", hello.greeting + "\n\n" ); hello.removeData(); hello.shutDown(); } }
false
community_embedded-examples_src_test_java_org_neo4j_examples_EmbeddedNeo4jDocTest.java
3,058
{ @Override public void run() { graphDb.shutdown(); } } );
false
community_embedded-examples_src_main_java_org_neo4j_examples_EmbeddedNeo4j.java
3,059
public class EmbeddedNeo4j { private static final String DB_PATH = "target/neo4j-hello-db"; public String greeting; // START SNIPPET: vars GraphDatabaseService graphDb; Node firstNode; Node secondNode; Relationship relationship; // END SNIPPET: vars // START SNIPPET: createReltype private static enum RelTypes implements RelationshipType { KNOWS } // END SNIPPET: createReltype public static void main( final String[] args ) { EmbeddedNeo4j hello = new EmbeddedNeo4j(); hello.createDb(); hello.removeData(); hello.shutDown(); } void createDb() { clearDb(); // START SNIPPET: startDb graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( DB_PATH ); registerShutdownHook( graphDb ); // END SNIPPET: startDb // START SNIPPET: transaction try ( Transaction tx = graphDb.beginTx() ) { // Database operations go here // END SNIPPET: transaction // START SNIPPET: addData firstNode = graphDb.createNode(); firstNode.setProperty( "message", "Hello, " ); secondNode = graphDb.createNode(); secondNode.setProperty( "message", "World!" ); relationship = firstNode.createRelationshipTo( secondNode, RelTypes.KNOWS ); relationship.setProperty( "message", "brave Neo4j " ); // END SNIPPET: addData // START SNIPPET: readData System.out.print( firstNode.getProperty( "message" ) ); System.out.print( relationship.getProperty( "message" ) ); System.out.print( secondNode.getProperty( "message" ) ); // END SNIPPET: readData greeting = ( (String) firstNode.getProperty( "message" ) ) + ( (String) relationship.getProperty( "message" ) ) + ( (String) secondNode.getProperty( "message" ) ); // START SNIPPET: transaction tx.success(); } // END SNIPPET: transaction } private void clearDb() { try { FileUtils.deleteRecursively( new File( DB_PATH ) ); } catch ( IOException e ) { throw new RuntimeException( e ); } } void removeData() { try ( Transaction tx = graphDb.beginTx() ) { // START SNIPPET: removingData // let's remove the data firstNode.getSingleRelationship( RelTypes.KNOWS, Direction.OUTGOING ).delete(); firstNode.delete(); secondNode.delete(); // END SNIPPET: removingData tx.success(); } } void shutDown() { System.out.println(); System.out.println( "Shutting down database ..." ); // START SNIPPET: shutdownServer graphDb.shutdown(); // END SNIPPET: shutdownServer } // START SNIPPET: shutdownHook 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(); } } ); } // END SNIPPET: shutdownHook }
false
community_embedded-examples_src_main_java_org_neo4j_examples_EmbeddedNeo4j.java
3,060
public class DocumentationDocTest extends ImpermanentGraphJavaDocTestBase { /** * This is a sample documentation test, demonstrating different ways of * bringing code and other artifacts into Asciidoc form. The title of the * generated document is determined from the method name, replacing "+_+" with * " ". * * Below you see a number of different ways to generate text from source, * inserting it into the JavaDoc documentation (really being Asciidoc markup) * via the +@@+ snippet markers and programmatic adding with runtime data * in the Java code. * * - The annotated graph as http://www.graphviz.org/[GraphViz]-generated visualization: * * @@graph * * - A sample Cypher query: * * @@cypher * * - A sample text output snippet: * * @@output * * - a generated source link to the original GIThub source for this test: * * @@github * * - The full source for this example as a source snippet, highlighted as Java code: * * @@sampleDocumentation * * This is the end of this chapter. */ @Test // signaling this to be a documentation test @Documented // the graph data setup as simple statements @Graph( "I know you" ) // title is determined from the method name public void hello_world_Sample_Chapter() { // initialize the graph with the annotation data data.get(); gen.get().addTestSourceSnippets( this.getClass(), "sampleDocumentation" ); gen.get() .addGithubTestSourceLink( "github", this.getClass(), "community/embedded-examples" ); gen.get().addSnippet( "output", createOutputSnippet( "Hello graphy world!" ) ); gen.get().addSnippet( "graph", createGraphVizWithNodeId( "Hello World Graph", graphdb(), gen.get().getTitle() ) ); // A cypher snippet referring to the generated graph in the start clause gen.get().addSnippet( "cypher", createCypherSnippet( "start n = node(" + data.get().get( "I" ).getId() + ") return n" ) ); } }
false
community_embedded-examples_src_test_java_org_neo4j_examples_DocumentationDocTest.java
3,061
{ @Override protected Person underlyingObjectToObject( Relationship personRel ) { return new Person( personRel.getEndNode() ); } };
false
community_embedded-examples_src_main_java_org_neo4j_examples_socnet_PersonRepository.java
3,062
public class StatusUpdate { private final Node underlyingNode; static final String TEXT = "TEXT"; static final String DATE = "DATE"; public StatusUpdate( Node underlyingNode ) { this.underlyingNode = underlyingNode; } public Node getUnderlyingNode() { return underlyingNode; } public Person getPerson() { return new Person( getPersonNode() ); } private Node getPersonNode() { TraversalDescription traversalDescription = Traversal.description(). depthFirst(). relationships( NEXT, Direction.INCOMING ). relationships( STATUS, Direction.INCOMING ). evaluator( Evaluators.includeWhereLastRelationshipTypeIs( STATUS ) ); Traverser traverser = traversalDescription.traverse( getUnderlyingNode() ); return IteratorUtil.singleOrNull( traverser.iterator() ).endNode(); } public String getStatusText() { return (String)underlyingNode.getProperty( TEXT ); } public Date getDate() { Long l = (Long)underlyingNode.getProperty( DATE ); return new Date( l ); } }
false
community_embedded-examples_src_main_java_org_neo4j_examples_socnet_StatusUpdate.java
3,063
{ @Override public void close() throws IOException, IndexEntryConflictException { if ( IndexUpdateMode.ONLINE == mode ) { updatesCommitted.addAll( updates ); } } @Override public void remove( Iterable<Long> nodeIds ) throws IOException { throw new UnsupportedOperationException( "not expected" ); } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_IndexCRUDIT.java
3,064
public class ExactDepthPathFinder extends TraversalPathFinder { private final PathExpander expander; private final int onDepth; private final int startThreshold; public ExactDepthPathFinder( RelationshipExpander expander, int onDepth, int startThreshold ) { this( toPathExpander( expander ), onDepth, startThreshold ); } public ExactDepthPathFinder( PathExpander expander, int onDepth, int startThreshold ) { this.expander = expander; this.onDepth = onDepth; this.startThreshold = startThreshold; } @Override protected Traverser instantiateTraverser( Node start, Node end ) { TraversalDescription side = traversal().breadthFirst().expand( expander ).uniqueness( RELATIONSHIP_GLOBAL ).order( new BranchOrderingPolicy() { public BranchSelector create( TraversalBranch startSource, PathExpander expander ) { return new LiteDepthFirstSelector( startSource, startThreshold, expander ); } } ); return bidirectionalTraversal() .startSide( side.evaluator( toDepth( onDepth/2 ) ) ) .endSide( side.evaluator( toDepth( onDepth-onDepth/2 ) ) ) .collisionEvaluator( atDepth( onDepth ) ) // TODO Level side selector will make the traversal return wrong result, why? // .sideSelector( SideSelectorPolicies.LEVEL, onDepth ) .traverse( start, end ); } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_path_ExactDepthPathFinder.java
3,065
{ @Override public Iterator<WeightedPath> iterator() { return new StopAfterWeightIterator( traverser.iterator(), costEvaluator ); } };
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_path_Dijkstra.java
3,066
public class Dijkstra implements PathFinder<WeightedPath> { private static final TraversalDescription TRAVERSAL = traversal().uniqueness( Uniqueness.NONE ); private final PathExpander expander; private final InitialBranchState stateFactory; private final CostEvaluator<Double> costEvaluator; private Traverser lastTraverser; public Dijkstra( PathExpander expander, CostEvaluator<Double> costEvaluator ) { this( expander, InitialBranchState.NO_STATE, costEvaluator ); } public Dijkstra( PathExpander expander, InitialBranchState stateFactory, CostEvaluator<Double> costEvaluator ) { this.expander = expander; this.costEvaluator = costEvaluator; this.stateFactory = stateFactory; } public Dijkstra( RelationshipExpander expander, CostEvaluator<Double> costEvaluator ) { this( toPathExpander( expander ), costEvaluator ); } @Override public Iterable<WeightedPath> findAllPaths( Node start, final Node end ) { final Traverser traverser = traverser( start, end, true ); return new Iterable<WeightedPath>() { @Override public Iterator<WeightedPath> iterator() { return new StopAfterWeightIterator( traverser.iterator(), costEvaluator ); } }; } private Traverser traverser( Node start, final Node end, boolean forMultiplePaths ) { return (lastTraverser = TRAVERSAL.expand( expander, stateFactory ) .order( new SelectorFactory( forMultiplePaths, costEvaluator ) ) .evaluator( Evaluators.includeWhereEndNodeIs( end ) ).traverse( start ) ); } @Override public WeightedPath findSinglePath( Node start, Node end ) { return firstOrNull( new StopAfterWeightIterator( traverser( start, end, false ).iterator(), costEvaluator ) ); } @Override public TraversalMetadata metadata() { return lastTraverser.metadata(); } private static class SelectorFactory extends BestFirstSelectorFactory<Double, Double> { private final CostEvaluator<Double> evaluator; SelectorFactory( boolean forMultiplePaths, CostEvaluator<Double> evaluator ) { super( forMultiplePaths ); this.evaluator = evaluator; } @Override protected Double calculateValue( TraversalBranch next ) { return next.length() == 0 ? 0d : evaluator.getCost( next.lastRelationship(), Direction.OUTGOING ); } @Override protected Double addPriority( TraversalBranch source, Double currentAggregatedValue, Double value ) { return withDefault( currentAggregatedValue, 0d ) + withDefault( value, 0d ); } private <T> T withDefault( T valueOrNull, T valueIfNull ) { return valueOrNull != null ? valueOrNull : valueIfNull; } @Override protected Double getStartData() { return 0d; } } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_path_Dijkstra.java
3,067
public class AllSimplePaths extends AllPaths { public AllSimplePaths( int maxDepth, RelationshipExpander expander ) { super( maxDepth, expander ); } public AllSimplePaths( int maxDepth, PathExpander expander ) { super( maxDepth, expander ); } @Override protected Uniqueness uniqueness() { return Uniqueness.NODE_PATH; } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_path_AllSimplePaths.java
3,068
public class AllPaths extends TraversalPathFinder { private final PathExpander expander; private final int maxDepth; private final TraversalDescription base; public AllPaths( int maxDepth, RelationshipExpander expander ) { this( maxDepth, toPathExpander( expander ) ); } public AllPaths( int maxDepth, PathExpander expander ) { this.maxDepth = maxDepth; this.expander = expander; this.base = traversal().depthFirst().uniqueness( uniqueness() ); } protected Uniqueness uniqueness() { return Uniqueness.RELATIONSHIP_PATH; } @Override protected Traverser instantiateTraverser( Node start, Node end ) { // // Legacy single-directional traversal (for reference or something) // return traversal().expand( expander ).depthFirst().uniqueness( uniqueness() ) // .evaluator( toDepth( maxDepth ) ).evaluator( Evaluators.includeWhereEndNodeIs( end ) ) // .traverse( start ); // Bidirectional traversal return bidirectionalTraversal() .startSide( base.expand( expander ).evaluator( toDepth( maxDepth/2 ) ) ) .endSide( base.expand( expander.reverse() ).evaluator( toDepth( maxDepth-maxDepth/2 ) ) ) .traverse( start, end ); } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_path_AllPaths.java
3,069
private static class Visit { private double wayLength; // accumulated cost to get here (g) private double estimate; // heuristic estimate of cost to reach end (h) private long cameFromRelationship; private boolean visited; private boolean next; Visit( long cameFromRelationship, double wayLength, double estimate ) { update( cameFromRelationship, wayLength, estimate ); } void update( long cameFromRelationship, double wayLength, double estimate ) { this.cameFromRelationship = cameFromRelationship; this.wayLength = wayLength; this.estimate = estimate; } double getFscore() { return wayLength + estimate; } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_path_AStar.java
3,070
private static class Metadata implements TraversalMetadata { private int rels; private int paths; @Override public int getNumberOfPathsReturned() { return paths; } @Override public int getNumberOfRelationshipsTraversed() { return rels; } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_path_AStar.java
3,071
private class AStarIterator extends PrefetchingIterator<Node> implements Path { private final Node start; private final Node end; private Node lastNode; private final PriorityMap<Node, Node, Double> nextPrioritizedNodes = PriorityMap.<Node, Double>withSelfKeyNaturalOrder(); private final Map<Long, Visit> visitData = new HashMap<Long, Visit>(); AStarIterator( Node start, Node end ) { this.start = start; this.end = end; Visit visit = new Visit( -1, 0, estimateEvaluator.getCost( start, end ) ); addNext( start, visit.getFscore(), visit ); this.visitData.put( start.getId(), visit ); } private void addNext( Node node, double fscore, Visit visit ) { nextPrioritizedNodes.put( node, fscore ); visit.next = true; } private Node popLowestScoreNode() { Entry<Node, Double> top = nextPrioritizedNodes.pop(); if ( top == null ) { return null; } Node node = top.getEntity(); Visit visit = visitData.get( node.getId() ); visit.visited = true; visit.next = false; return node; } @Override protected Node fetchNextOrNull() { if ( lastNode != null ) { expand(); } return (lastNode = popLowestScoreNode()); } @SuppressWarnings( "unchecked" ) private void expand() { for ( Relationship rel : expander.expand( this, BranchState.NO_STATE ) ) { 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 ); } } } @Override public Node startNode() { return start; } @Override public Node endNode() { return lastNode; } @Override public Relationship lastRelationship() { throw new UnsupportedOperationException(); } @Override public Iterable<Relationship> relationships() { throw new UnsupportedOperationException(); } @Override public Iterable<Relationship> reverseRelationships() { throw new UnsupportedOperationException(); } @Override public Iterable<Node> nodes() { throw new UnsupportedOperationException(); } @Override public Iterable<Node> reverseNodes() { throw new UnsupportedOperationException(); } @Override public int length() { throw new UnsupportedOperationException(); } @Override public Iterator<PropertyContainer> iterator() { throw new UnsupportedOperationException(); } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_path_AStar.java
3,072
public class AStar implements PathFinder<WeightedPath> { private final PathExpander<?> expander; private final CostEvaluator<Double> lengthEvaluator; private final EstimateEvaluator<Double> estimateEvaluator; private Metadata lastMetadata; public AStar( RelationshipExpander expander, CostEvaluator<Double> lengthEvaluator, EstimateEvaluator<Double> estimateEvaluator ) { this( toPathExpander( expander ), lengthEvaluator, estimateEvaluator ); } public AStar( PathExpander<?> expander, CostEvaluator<Double> lengthEvaluator, EstimateEvaluator<Double> estimateEvaluator ) { this.expander = expander; this.lengthEvaluator = lengthEvaluator; this.estimateEvaluator = estimateEvaluator; } @Override public WeightedPath findSinglePath( Node start, Node end ) { lastMetadata = new Metadata(); AStarIterator iterator = new AStarIterator( start, end ); while ( iterator.hasNext() ) { Node node = iterator.next(); GraphDatabaseService graphDb = node.getGraphDatabase(); if ( node.equals( end ) ) { // Hit, return path double weight = iterator.visitData.get( node.getId() ).wayLength; LinkedList<Relationship> rels = new LinkedList<Relationship>(); Relationship rel = graphDb.getRelationshipById( iterator.visitData.get( node.getId() ).cameFromRelationship ); while ( rel != null ) { rels.addFirst( rel ); node = rel.getOtherNode( node ); long nextRelId = iterator.visitData.get( node.getId() ).cameFromRelationship; rel = nextRelId == -1 ? null : graphDb.getRelationshipById( nextRelId ); } Path path = toPath( start, rels ); lastMetadata.paths++; return new WeightedPathImpl( weight, path ); } } return null; } @Override public Iterable<WeightedPath> findAllPaths( final Node node, final Node end ) { return option( findSinglePath( node, end ) ); } @Override public TraversalMetadata metadata() { return lastMetadata; } private Path toPath( Node start, LinkedList<Relationship> rels ) { PathImpl.Builder builder = new PathImpl.Builder( start ); for ( Relationship rel : rels ) { builder = builder.push( rel ); } return builder.build(); } private static class Visit { private double wayLength; // accumulated cost to get here (g) private double estimate; // heuristic estimate of cost to reach end (h) private long cameFromRelationship; private boolean visited; private boolean next; Visit( long cameFromRelationship, double wayLength, double estimate ) { update( cameFromRelationship, wayLength, estimate ); } void update( long cameFromRelationship, double wayLength, double estimate ) { this.cameFromRelationship = cameFromRelationship; this.wayLength = wayLength; this.estimate = estimate; } double getFscore() { return wayLength + estimate; } } private class AStarIterator extends PrefetchingIterator<Node> implements Path { private final Node start; private final Node end; private Node lastNode; private final PriorityMap<Node, Node, Double> nextPrioritizedNodes = PriorityMap.<Node, Double>withSelfKeyNaturalOrder(); private final Map<Long, Visit> visitData = new HashMap<Long, Visit>(); AStarIterator( Node start, Node end ) { this.start = start; this.end = end; Visit visit = new Visit( -1, 0, estimateEvaluator.getCost( start, end ) ); addNext( start, visit.getFscore(), visit ); this.visitData.put( start.getId(), visit ); } private void addNext( Node node, double fscore, Visit visit ) { nextPrioritizedNodes.put( node, fscore ); visit.next = true; } private Node popLowestScoreNode() { Entry<Node, Double> top = nextPrioritizedNodes.pop(); if ( top == null ) { return null; } Node node = top.getEntity(); Visit visit = visitData.get( node.getId() ); visit.visited = true; visit.next = false; return node; } @Override protected Node fetchNextOrNull() { if ( lastNode != null ) { expand(); } return (lastNode = popLowestScoreNode()); } @SuppressWarnings( "unchecked" ) private void expand() { for ( Relationship rel : expander.expand( this, BranchState.NO_STATE ) ) { 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 ); } } } @Override public Node startNode() { return start; } @Override public Node endNode() { return lastNode; } @Override public Relationship lastRelationship() { throw new UnsupportedOperationException(); } @Override public Iterable<Relationship> relationships() { throw new UnsupportedOperationException(); } @Override public Iterable<Relationship> reverseRelationships() { throw new UnsupportedOperationException(); } @Override public Iterable<Node> nodes() { throw new UnsupportedOperationException(); } @Override public Iterable<Node> reverseNodes() { throw new UnsupportedOperationException(); } @Override public int length() { throw new UnsupportedOperationException(); } @Override public Iterator<PropertyContainer> iterator() { throw new UnsupportedOperationException(); } } private static class Metadata implements TraversalMetadata { private int rels; private int paths; @Override public int getNumberOfPathsReturned() { return paths; } @Override public int getNumberOfRelationshipsTraversed() { return rels; } } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_path_AStar.java
3,073
public class StressCentrality<ShortestPathCostType> extends ShortestPathBasedCentrality<Double,ShortestPathCostType> { protected Double globalFactor; /** * Default constructor. * @param singleSourceShortestPath * Underlying singleSourceShortestPath. * @param nodeSet * A set containing the nodes for which centrality values should * be computed. */ public StressCentrality( SingleSourceShortestPath<ShortestPathCostType> singleSourceShortestPath, Set<Node> nodeSet ) { super( singleSourceShortestPath, new DoubleAdder(), 0.0, nodeSet ); } @Override public void reset() { super.reset(); globalFactor = 1.0; if ( singleSourceShortestPath.getDirection().equals( Direction.BOTH ) ) { globalFactor = 0.5; } } /** * This recursively updates the node stress (number of paths through a * node). * @param node * The start node * @param skipFirstNode * If true, the start node is not updated. Useful, since the * first node in any path doesnt need to be updated. * @param successors * @param counter * Object that can return the number of paths from the initial * start node to any node. * @param stresses * A map used to limit the recursion where possible (dynamic * programming) * @return */ protected Double getAndUpdateNodeStress( Node node, boolean skipFirstNode, Map<Node,List<Relationship>> successors, PathCounter counter, Map<Node,Double> stresses ) { Double stress = stresses.get( node ); if ( stress != null ) { return stress; } stress = (double) 0; List<Relationship> succs = successors.get( node ); if ( succs == null || succs.size() == 0 ) { return (double) 0; } for ( Relationship relationship : succs ) { Node otherNode = relationship.getOtherNode( node ); Double otherStress = getAndUpdateNodeStress( otherNode, false, successors, counter, stresses ); stress += (otherStress + 1) * counter.getNumberOfPathsToNode( node ); } if ( !skipFirstNode ) { stresses.put( node, stress ); // When adding to the final result (and only then), take the global // factor into account. addCentralityToNode( node, stress * globalFactor ); } return stress; } @Override public void processShortestPaths( Node node, SingleSourceShortestPath<ShortestPathCostType> singleSourceShortestPath ) { // Extract predecessors and successors Map<Node,List<Relationship>> predecessors = singleSourceShortestPath .getPredecessors(); Map<Node,List<Relationship>> successors = Util .reversedPredecessors( predecessors ); PathCounter counter = new Util.PathCounter( predecessors ); // Recursively update the node dependencies getAndUpdateNodeStress( node, true, successors, counter, new HashMap<Node,Double>() ); } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_centrality_StressCentrality.java
3,074
public abstract class ShortestPathBasedCentrality<CentralityType,ShortestPathCostType> { protected SingleSourceShortestPath<ShortestPathCostType> singleSourceShortestPath; protected CostAccumulator<CentralityType> centralityAccumulator; protected CentralityType zeroValue; protected Set<Node> nodeSet; protected boolean doneCalculation = false; /** * This map over centrality values is made available to the algorithms * inheriting this class. It is supposed to be filled with the method * addCentralityToNode. */ protected Map<Node,CentralityType> centralities = null; /** * Default constructor. * @param singleSourceShortestPath * The underlying shortest path algorithm. * @param centralityAccumulator * When centralities are built through sums, this makes it * possible to call addCentralityToNode several times, which then * uses this object to add values together. * @param zeroValue * The default value to start with. * @param nodeSet * The set of nodes values should be stored for. */ public ShortestPathBasedCentrality( SingleSourceShortestPath<ShortestPathCostType> singleSourceShortestPath, CostAccumulator<CentralityType> centralityAccumulator, CentralityType zeroValue, Set<Node> nodeSet ) { super(); this.singleSourceShortestPath = singleSourceShortestPath; this.centralityAccumulator = centralityAccumulator; this.zeroValue = zeroValue; this.nodeSet = nodeSet; reset(); } /** * The calculation is normally only done once, this resets it so it can be * run again. Also used locally for initialization. */ public void reset() { doneCalculation = false; centralities = new HashMap<Node,CentralityType>(); for ( Node node : nodeSet ) { centralities.put( node, zeroValue ); } } /** * This adds a value to a given node in the centralities Map. If the Map * does not contain the node, it is added. * @param node * @param value */ protected void addCentralityToNode( Node node, CentralityType value ) { CentralityType centrality = centralities.get( node ); if ( centrality == null ) { centrality = zeroValue; } centralities.put( node, centralityAccumulator.addCosts( centrality, value ) ); } /** * This sets a value for a given node in the centralities Map. If the Map * does not contain the node, it is added. * @param node * @param value */ protected void setCentralityForNode( Node node, CentralityType value ) { centralities.put( node, value ); } /** * This can be used to retrieve the result for every node. Will return null * if the node is not contained in the node set initially given. * @param node * @return */ public CentralityType getCentrality( Node node ) { calculate(); return centralities.get( node ); } /** * Runs the calculation. This should not need to be called explicitly, since * all attempts to retrieve any kind of result should automatically call * this. */ public void calculate() { // Don't do it more than once if ( doneCalculation ) { return; } doneCalculation = true; // For all nodes... for ( Node startNode : nodeSet ) { // Prepare the singleSourceShortestPath singleSourceShortestPath.reset(); singleSourceShortestPath.setStartNode( startNode ); // Process processShortestPaths( startNode, singleSourceShortestPath ); } } /** * This is the abstract method all centrality algorithms based on this class * need to implement. It is called once for every node in the node set, * along with a SingleSourceShortestPath starting in that node. * @param node * @param singleSourceShortestPath */ public abstract void processShortestPaths( Node node, SingleSourceShortestPath<ShortestPathCostType> singleSourceShortestPath ); }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_centrality_ShortestPathBasedCentrality.java
3,075
public class ParallellCentralityCalculation<ShortestPathCostType> { protected SingleSourceShortestPath<ShortestPathCostType> singleSourceShortestPath; protected Set<Node> nodeSet; List<ShortestPathBasedCentrality<?,ShortestPathCostType>> calculations = new LinkedList<ShortestPathBasedCentrality<?,ShortestPathCostType>>(); protected boolean doneCalculation = false; /** * Default constructor. * @param singleSourceShortestPath * Underlying singleSourceShortestPath. * @param nodeSet * A set containing the nodes for which centrality values should * be computed. */ public ParallellCentralityCalculation( SingleSourceShortestPath<ShortestPathCostType> singleSourceShortestPath, Set<Node> nodeSet ) { super(); this.singleSourceShortestPath = singleSourceShortestPath; this.nodeSet = nodeSet; } /** * This adds a centrality measure to be included in the calculation. * @param shortestPathBasedCentrality * The centrality algorithm. */ public void addCalculation( ShortestPathBasedCentrality<?,ShortestPathCostType> shortestPathBasedCentrality ) { if ( doneCalculation ) { throw new RuntimeException( "Trying to add a centrality calculation to a parallell computation that has already been done." ); } calculations.add( shortestPathBasedCentrality ); shortestPathBasedCentrality.doneCalculation = true; } /** * Method that will perform the calculation. After this we are of course * unable to add more measures to this object. */ public void calculate() { // Don't do it more than once if ( doneCalculation ) { return; } doneCalculation = true; // For all nodes... for ( Node startNode : nodeSet ) { // Prepare the singleSourceShortestPath singleSourceShortestPath.reset(); singleSourceShortestPath.setStartNode( startNode ); // Process for ( ShortestPathBasedCentrality<?,ShortestPathCostType> calculation : calculations ) { calculation.processShortestPaths( startNode, singleSourceShortestPath ); } } } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_centrality_ParallellCentralityCalculation.java
3,076
public class NetworkRadius<ShortestPathCostType> extends ShortestPathBasedCentrality<ShortestPathCostType,ShortestPathCostType> { Comparator<ShortestPathCostType> distanceComparator; // Underlying eccentricity computation protected Eccentricity<ShortestPathCostType> eccentricity; protected ShortestPathCostType radius; /** * Default constructor. * @param singleSourceShortestPath * Underlying singleSourceShortestPath. * @param zeroValue * Default value. * @param nodeSet * A set containing the nodes for which centrality values should * be computed. * @param distanceComparator * Object being able to compare eccentricity values (path * distances), in order to sort out the smallest. */ public NetworkRadius( SingleSourceShortestPath<ShortestPathCostType> singleSourceShortestPath, ShortestPathCostType zeroValue, Set<Node> nodeSet, Comparator<ShortestPathCostType> distanceComparator ) { super( singleSourceShortestPath, null, zeroValue, nodeSet ); this.distanceComparator = distanceComparator; eccentricity = new Eccentricity<ShortestPathCostType>( singleSourceShortestPath, zeroValue, nodeSet, distanceComparator ); } @Override public void processShortestPaths( Node node, SingleSourceShortestPath<ShortestPathCostType> singleSourceShortestPath ) { eccentricity.processShortestPaths( node, singleSourceShortestPath ); ShortestPathCostType centrality = eccentricity.getCentrality( node ); if ( radius == null || distanceComparator.compare( centrality, radius ) < 0 ) { radius = centrality; } } @Override public ShortestPathCostType getCentrality( Node node ) { // This might be a bit ugly, but good for warnings if ( node != null ) { throw new RuntimeException( "Getting network radius with a specific node as argument, which means nonsense." ); } calculate(); return radius; } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_centrality_NetworkRadius.java
3,077
public class NetworkDiameter<ShortestPathCostType> extends ShortestPathBasedCentrality<ShortestPathCostType,ShortestPathCostType> { Comparator<ShortestPathCostType> distanceComparator; // Underlying eccentricity computation protected Eccentricity<ShortestPathCostType> eccentricity; protected ShortestPathCostType diameter; /** * Default constructor. * @param singleSourceShortestPath * Underlying singleSourceShortestPath. * @param zeroValue * Default value. * @param nodeSet * A set containing the nodes for which centrality values should * be computed. * @param distanceComparator * Object being able to compare eccentricity values (path * distances), in order to sort out the largest. */ public NetworkDiameter( SingleSourceShortestPath<ShortestPathCostType> singleSourceShortestPath, ShortestPathCostType zeroValue, Set<Node> nodeSet, Comparator<ShortestPathCostType> distanceComparator ) { super( singleSourceShortestPath, null, zeroValue, nodeSet ); this.distanceComparator = distanceComparator; eccentricity = new Eccentricity<ShortestPathCostType>( singleSourceShortestPath, zeroValue, nodeSet, distanceComparator ); } @Override public void processShortestPaths( Node node, SingleSourceShortestPath<ShortestPathCostType> singleSourceShortestPath ) { eccentricity.processShortestPaths( node, singleSourceShortestPath ); ShortestPathCostType centrality = eccentricity.getCentrality( node ); if ( diameter == null || distanceComparator.compare( centrality, diameter ) > 0 ) { diameter = centrality; } } @Override public ShortestPathCostType getCentrality( Node node ) { // This might be a bit ugly, but good for warnings if ( node != null ) { throw new RuntimeException( "Getting network diameter with a specific node as argument, which means nonsense." ); } calculate(); return diameter; } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_centrality_NetworkDiameter.java
3,078
public class EigenvectorCentralityPower implements EigenvectorCentrality { protected Direction relationDirection; protected CostEvaluator<Double> costEvaluator; protected Set<Node> nodeSet; protected Set<Relationship> relationshipSet; protected double precision = 0.001; protected boolean doneCalculation = false; protected Map<Node,Double> values; protected int totalIterations = 0; private int maxIterations = Integer.MAX_VALUE; /** * @param relationDirection * The direction in which the paths should follow the * relationships. * @param costEvaluator * @see CostEvaluator * @param nodeSet * The set of nodes the calculation should be run on. * @param relationshipSet * The set of relationships that should be processed. * @param precision * Precision factor (ex. 0.01 for 1% error). Note that this is * not the error from the correct values, but the amount of * change tolerated in one iteration. */ public EigenvectorCentralityPower( Direction relationDirection, CostEvaluator<Double> costEvaluator, Set<Node> nodeSet, Set<Relationship> relationshipSet, double precision ) { super(); this.relationDirection = relationDirection; this.costEvaluator = costEvaluator; this.nodeSet = nodeSet; this.relationshipSet = relationshipSet; this.precision = precision; } /** * This can be used to retrieve the result for every node. Will return null * if the node is not contained in the node set initially given, or doesn't * receive a result because no relationship points to it. The calculation is * done the first time this method is run. Upon successive requests, the old * result is returned, unless the calculation is reset via {@link #reset()} * @param node * @return */ public Double getCentrality( Node node ) { calculate(); return values.get( node ); } /** * This resets the calculation if we for some reason would like to redo it. */ public void reset() { doneCalculation = false; } /** * Internal calculate method that will do the calculation. This can however * be called externally to manually trigger the calculation. */ public void calculate() { // Don't do it more than once if ( doneCalculation ) { return; } doneCalculation = true; values = new HashMap<Node,Double>(); totalIterations = 0; // generate a random start vector Random random = new Random( System.currentTimeMillis() ); for ( Node node : nodeSet ) { values.put( node, random.nextDouble() ); } normalize( values ); runIterations( maxIterations ); } /** * This runs a number of iterations in the computation and stops when enough * precision has been reached. A maximum number of iterations to perform is * supplied. NOTE: For maxNrIterations > 0 at least one iteration will be * run, regardless if good precision has already been reached or not. This * method also ignores the global limit defined by maxIterations. * @param maxNrIterations * The maximum number of iterations to run. * @return the number of iterations performed. if this is lower than the * given maxNrIterations the desired precision has been reached. */ public int runIterations( int maxNrIterations ) { if ( maxNrIterations <= 0 ) { return 0; } int localIterations = 0; while ( true ) { ++localIterations; ++totalIterations; Map<Node,Double> newValues = new HashMap<Node,Double>(); // "matrix multiplication" for ( Relationship relationship : relationshipSet ) { if ( relationDirection.equals( Direction.BOTH ) || relationDirection.equals( Direction.OUTGOING ) ) { processRelationship( newValues, relationship, false ); } if ( relationDirection.equals( Direction.BOTH ) || relationDirection.equals( Direction.INCOMING ) ) { processRelationship( newValues, relationship, true ); } } normalize( newValues ); if ( timeToStop( values, newValues ) ) { values = newValues; break; } values = newValues; if ( localIterations >= maxNrIterations ) { break; } } // If the first value is negative (possibly the whole vector), negate // the whole vector if ( values.get( nodeSet.iterator().next() ) < 0 ) { for ( Node node : nodeSet ) { values.put( node, -values.get( node ) ); } } return localIterations; } /** * Stop condition for the iteration. * @return true if enough precision has been achieved. */ private boolean timeToStop( Map<Node,Double> oldValues, Map<Node,Double> newValues ) { for ( Node node : oldValues.keySet() ) { if ( newValues.get( node ) == null ) { return false; } if ( oldValues.get( node ) == 0.0 ) { if ( Math.abs( newValues.get( node ) ) > precision ) { return false; } continue; } double factor = newValues.get( node ) / oldValues.get( node ); factor = Math.abs( factor ); if ( factor - precision > 1.0 || factor + precision < 1.0 ) { return false; } } return true; } /** * Internal method used in the "matrix multiplication" in each iteration. */ protected void processRelationship( Map<Node,Double> newValues, Relationship relationship, boolean backwards ) { Node startNode = relationship.getStartNode(); if ( backwards ) { startNode = relationship.getEndNode(); } Node endNode = relationship.getOtherNode( startNode ); Double newValue = newValues.get( endNode ); if ( newValue == null ) { newValue = 0.0; } if ( values.get( startNode ) != null ) { newValue += values.get( startNode ) * costEvaluator.getCost( relationship, backwards ? Direction.INCOMING : Direction.OUTGOING ); } newValues.put( endNode, newValue ); } /** * Normalizes a vector represented as a Map. * @param vector */ protected void normalize( Map<Node,Double> vector ) { // Compute vector length double sum = 0; for ( Node node : vector.keySet() ) { double d = vector.get( node ); sum += d * d; } sum = Math.sqrt( sum ); // Divide all components if ( sum > 0.0 ) { for ( Node node : vector.keySet() ) { vector.put( node, vector.get( node ) / sum ); } } } /** * @return the number of iterations made. */ public int getTotalIterations() { return totalIterations; } /** * @return the maxIterations */ public int getMaxIterations() { return maxIterations; } /** * Limit the maximum number of iterations to run. Per default, * the maximum iterations are set to Integer.MAX_VALUE, which should * be limited to 50-100 normally. * @param maxIterations * the maxIterations to set */ public void setMaxIterations( int maxIterations ) { this.maxIterations = maxIterations; } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_centrality_EigenvectorCentralityPower.java
3,079
public class EigenvectorCentralityArnoldi implements EigenvectorCentrality { protected Direction relationDirection; protected CostEvaluator<Double> costEvaluator; protected Set<Node> nodeSet; protected Set<Relationship> relationshipSet; protected double precision = 0.001; protected boolean doneCalculation = false; protected Map<Node,Double> values; protected int totalIterations = 0; private int maxIterations = Integer.MAX_VALUE; /** * @param relationDirection * The direction in which the paths should follow the * relationships. * @param costEvaluator * @see CostEvaluator * @param nodeSet * The set of nodes the calculation should be run on. * @param relationshipSet * The set of relationships that should be processed. * @param precision * Precision factor (ex. 0.01 for 1% error). Note that this is * not the error from the correct values, but the amount of * change tolerated in one iteration. */ public EigenvectorCentralityArnoldi( Direction relationDirection, CostEvaluator<Double> costEvaluator, Set<Node> nodeSet, Set<Relationship> relationshipSet, double precision ) { super(); this.relationDirection = relationDirection; this.costEvaluator = costEvaluator; this.nodeSet = nodeSet; this.relationshipSet = relationshipSet; this.precision = precision; } /** * This can be used to retrieve the result for every node. Will return null * if the node is not contained in the node set initially given, or doesn't * receive a result because no relationship points to it. * @param node * @return */ public Double getCentrality( Node node ) { calculate(); return values.get( node ); } /** * This resets the calculation if we for some reason would like to redo it. */ public void reset() { doneCalculation = false; } /** * Internal calculate method that will do the calculation. This can however * be called externally to manually trigger the calculation.The calculation is * done the first time this method is run. Upon successive requests, the old * result is returned, unless the calculation is reset via {@link #reset()} */ public void calculate() { // Don't do it more than once if ( doneCalculation ) { return; } doneCalculation = true; values = new HashMap<Node,Double>(); totalIterations = 0; // generate a random start vector Random random = new Random( System.currentTimeMillis() ); for ( Node node : nodeSet ) { values.put( node, random.nextDouble() ); } normalize( values ); runIterations( maxIterations ); } /** * Stop condition for the iteration. * @return true if enough precision has been achieved. */ private boolean timeToStop( Map<Node,Double> oldValues, Map<Node,Double> newValues ) { for ( Node node : oldValues.keySet() ) { if ( newValues.get( node ) == null ) { return false; } if ( oldValues.get( node ) == 0.0 ) { if ( Math.abs( newValues.get( node ) ) > precision ) { return false; } continue; } double factor = newValues.get( node ) / oldValues.get( node ); factor = Math.abs( factor ); if ( factor - precision > 1.0 || factor + precision < 1.0 ) { return false; } } return true; } /** * This runs a number of iterations in the computation and stops when enough * precision has been reached. A maximum number of iterations to perform is * supplied. NOTE: For maxNrIterations > 0 at least one iteration will be * run, regardless if good precision has already been reached or not. This * method also ignores the global limit defined by maxIterations. * @param maxNrIterations * The maximum number of iterations to run. * @return the number of iterations performed. if this is lower than the * given maxNrIterations the desired precision has been reached. */ public int runIterations( int maxNrIterations ) { if ( maxNrIterations <= 0 ) { return 0; } int localIterations = 0; while ( localIterations < maxNrIterations ) { Map<Node,Double> oldValues = values; localIterations += runInternalArnoldi( 3 ); if ( timeToStop( oldValues, values ) ) { break; } } // If the first value is negative (possibly the whole vector), negate // the whole vector if ( values.get( nodeSet.iterator().next() ) < 0 ) { for ( Node node : nodeSet ) { values.put( node, -values.get( node ) ); } } return localIterations; } /** * This runs the Arnoldi decomposition in a specified number of steps. * @param iterations * The number of steps to perform, i.e. the dimension of the H * matrix. * @return The number of iterations actually performed. This can be less * than the input argument if the starting vector is not linearly * dependent on that many eigenvectors. */ protected int runInternalArnoldi( int iterations ) { // Create a list of the nodes, in order to quickly translate an index // into a node. ArrayList<Node> nodes = new ArrayList<Node>( nodeSet.size() ); for ( Node node : nodeSet ) { nodes.add( node ); } DoubleMatrix hMatrix = new DoubleMatrix(); DoubleMatrix qMatrix = new DoubleMatrix(); for ( int i = 0; i < nodes.size(); ++i ) { qMatrix.set( 0, i, values.get( nodes.get( i ) ) ); } int localIterations = 1; // The main arnoldi iteration loop while ( true ) { ++totalIterations; Map<Node,Double> newValues = new HashMap<Node,Double>(); // "matrix multiplication" for ( Relationship relationship : relationshipSet ) { if ( relationDirection.equals( Direction.BOTH ) || relationDirection.equals( Direction.OUTGOING ) ) { processRelationship( newValues, relationship, false ); } if ( relationDirection.equals( Direction.BOTH ) || relationDirection.equals( Direction.INCOMING ) ) { processRelationship( newValues, relationship, true ); } } // Orthogonalize for ( int j = 0; j < localIterations; ++j ) { DoubleVector qj = qMatrix.getRow( j ); // vector product double product = 0; for ( int i = 0; i < nodes.size(); ++i ) { Double d1 = newValues.get( nodes.get( i ) ); Double d2 = qj.get( i ); if ( d1 != null && d2 != null ) { product += d1 * d2; } } hMatrix.set( j, localIterations - 1, product ); if ( product != 0.0 ) { // vector subtraction for ( int i = 0; i < nodes.size(); ++i ) { Node node = nodes.get( i ); Double value = newValues.get( node ); if ( value == null ) { value = 0.0; } Double qValue = qj.get( i ); if ( qValue != null ) { newValues.put( node, value - product * qValue ); } } } } double normalizeFactor = normalize( newValues ); values = newValues; DoubleVector qVector = new DoubleVector(); for ( int i = 0; i < nodes.size(); ++i ) { qVector.set( i, newValues.get( nodes.get( i ) ) ); } qMatrix.setRow( localIterations, qVector ); if ( normalizeFactor == 0.0 || localIterations >= nodeSet.size() || localIterations >= iterations ) { break; } hMatrix.set( localIterations, localIterations - 1, normalizeFactor ); ++localIterations; } // employ the power method to find eigenvector to h Random random = new Random( System.currentTimeMillis() ); DoubleVector vector = new DoubleVector(); for ( int i = 0; i < nodeSet.size(); ++i ) { vector.set( i, random.nextDouble() ); } MatrixUtil.normalize( vector ); boolean powerDone = false; int its = 0; double powerPrecision = 0.1; while ( !powerDone ) { DoubleVector newVector = MatrixUtil.multiply( hMatrix, vector ); MatrixUtil.normalize( newVector ); powerDone = true; for ( Integer index : vector.getIndices() ) { if ( newVector.get( index ) == null ) { continue; } double factor = Math.abs( newVector.get( index ) / vector.get( index ) ); if ( factor - powerPrecision > 1.0 || factor + powerPrecision < 1.0 ) { powerDone = false; break; } } vector = newVector; ++its; if ( its > 100 ) { break; } } // multiply q and vector to get a ritz vector DoubleVector ritzVector = new DoubleVector(); for ( int r = 0; r < nodeSet.size(); ++r ) { for ( int c = 0; c < localIterations; ++c ) { ritzVector.incrementValue( r, vector.get( c ) * qMatrix.get( c, r ) ); } } for ( int i = 0; i < nodeSet.size(); ++i ) { values.put( nodes.get( i ), ritzVector.get( i ) ); } normalize( values ); return localIterations; } /** * Internal method used in the "matrix multiplication" in each iteration. */ protected void processRelationship( Map<Node,Double> newValues, Relationship relationship, boolean backwards ) { Node startNode = relationship.getStartNode(); if ( backwards ) { startNode = relationship.getEndNode(); } Node endNode = relationship.getOtherNode( startNode ); Double newValue = newValues.get( endNode ); if ( newValue == null ) { newValue = 0.0; } if ( values.get( startNode ) != null ) { newValue += values.get( startNode ) * costEvaluator.getCost( relationship, backwards ? Direction.INCOMING : Direction.OUTGOING ); } newValues.put( endNode, newValue ); } /** * Normalizes a vector represented as a Map. * @param vector * @return the initial length of the vector. */ protected double normalize( Map<Node,Double> vector ) { // Compute vector length double sum = 0; for ( Node node : vector.keySet() ) { Double d = vector.get( node ); if ( d == null ) { d = 0.0; vector.put( node, 0.0 ); } sum += d * d; } sum = Math.sqrt( sum ); // Divide all components if ( sum > 0.0 ) { for ( Node node : vector.keySet() ) { vector.put( node, vector.get( node ) / sum ); } } return sum; } /** * @return the number of iterations made. */ public int getTotalIterations() { return totalIterations; } /** * @return the maxIterations */ public int getMaxIterations() { return maxIterations; } /** * Limit the maximum number of iterations to run. Per default, * the maximum iterations are set to Integer.MAX_VALUE, which should * be limited to 50-100 normally. * @param maxIterations * the maxIterations to set */ public void setMaxIterations( int maxIterations ) { this.maxIterations = maxIterations; } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_centrality_EigenvectorCentralityArnoldi.java
3,080
public class Eccentricity<ShortestPathCostType> extends ShortestPathBasedCentrality<ShortestPathCostType,ShortestPathCostType> { Comparator<ShortestPathCostType> distanceComparator; /** * Default constructor. * @param singleSourceShortestPath * Underlying singleSourceShortestPath. * @param zeroValue * Default value. * @param nodeSet * A set containing the nodes for which centrality values should * be computed. * @param distanceComparator * Object being able to compare distances, in order to sort out * the largest. */ public Eccentricity( SingleSourceShortestPath<ShortestPathCostType> singleSourceShortestPath, ShortestPathCostType zeroValue, Set<Node> nodeSet, Comparator<ShortestPathCostType> distanceComparator ) { super( singleSourceShortestPath, null, zeroValue, nodeSet ); this.distanceComparator = distanceComparator; } /* * Since we dont need to do the calculation for all the nodes before we get * a usable result, we can just calculate the result for any given node when * it is asked for. This function just checks if the value has been computed * before, and computes it if needed. */ @Override public ShortestPathCostType getCentrality( Node node ) { ShortestPathCostType centrality = centralities.get( node ); if ( centrality == null ) { return null; } // Not calculated yet, or if it actually is 0 it is very fast to // compute so just do it. if ( centrality.equals( zeroValue ) ) { singleSourceShortestPath.reset(); singleSourceShortestPath.setStartNode( node ); processShortestPaths( node, singleSourceShortestPath ); } // When the value is calculated, just retrieve it normally return centralities.get( node ); } @Override public void processShortestPaths( Node node, SingleSourceShortestPath<ShortestPathCostType> singleSourceShortestPath ) { ShortestPathCostType maximumDistance = null; for ( Node targetNode : nodeSet ) { ShortestPathCostType targetDistance = singleSourceShortestPath .getCost( targetNode ); if ( maximumDistance == null || distanceComparator.compare( maximumDistance, targetDistance ) < 0 ) { maximumDistance = targetDistance; } } if ( maximumDistance != null ) { setCentralityForNode( node, maximumDistance ); } } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_centrality_Eccentricity.java
3,081
public class ClosenessCentrality<ShortestPathCostType> extends ShortestPathBasedCentrality<ShortestPathCostType,ShortestPathCostType> { CostDivider<ShortestPathCostType> centralityDivider; /** * Default constructor. * @param singleSourceShortestPath * Underlying singleSourceShortestPath. * @param centralityAccumulator * Object capable of adding distances. Needed since an "average" * will be computed. * @param zeroValue * Default value and starting value to the accumulator. * @param nodeSet * A set containing the nodes for which centrality values should * be computed. * @param centralityDivider * An object capable of inverting a distance. */ public ClosenessCentrality( SingleSourceShortestPath<ShortestPathCostType> singleSourceShortestPath, CostAccumulator<ShortestPathCostType> centralityAccumulator, ShortestPathCostType zeroValue, Set<Node> nodeSet, CostDivider<ShortestPathCostType> centralityDivider ) { super( singleSourceShortestPath, centralityAccumulator, zeroValue, nodeSet ); this.centralityDivider = centralityDivider; } /* * Since we dont need to do the calculation for all the nodes before we get * a usable result, we can just calculate the result for any given node when * it is asked for. This function just checks if the value has been computed * before, and computes it if needed. */ @Override public ShortestPathCostType getCentrality( Node node ) { ShortestPathCostType centrality = centralities.get( node ); if ( centrality == null ) { return null; } // Not calculated yet, or if it actually is 0 it is very fast to // compute so just do it. if ( centrality.equals( zeroValue ) ) { singleSourceShortestPath.reset(); singleSourceShortestPath.setStartNode( node ); processShortestPaths( node, singleSourceShortestPath ); } // When the value is calculated, just retrieve it normally return centralities.get( node ); } @Override public void processShortestPaths( Node node, SingleSourceShortestPath<ShortestPathCostType> singleSourceShortestPath ) { ShortestPathCostType shortestPathSum = null; for ( Node targetNode : nodeSet ) { if ( shortestPathSum == null ) { shortestPathSum = singleSourceShortestPath.getCost( targetNode ); } else { shortestPathSum = centralityAccumulator.addCosts( shortestPathSum, singleSourceShortestPath .getCost( targetNode ) ); } } // TODO: what should the result be when sum is 0 ? if ( !shortestPathSum.equals( zeroValue ) ) { setCentralityForNode( node, centralityDivider.divideByCost( 1.0, shortestPathSum ) ); } } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_centrality_ClosenessCentrality.java
3,082
public class BetweennessCentrality<ShortestPathCostType> extends ShortestPathBasedCentrality<Double,ShortestPathCostType> { protected Double globalFactor; /** * Default constructor. * @param singleSourceShortestPath * Underlying singleSourceShortestPath. * @param nodeSet * A set containing the nodes for which centrality values should * be computed. */ public BetweennessCentrality( SingleSourceShortestPath<ShortestPathCostType> singleSourceShortestPath, Set<Node> nodeSet ) { super( singleSourceShortestPath, new DoubleAdder(), 0.0, nodeSet ); } @Override public void reset() { super.reset(); globalFactor = 1.0; if ( singleSourceShortestPath.getDirection().equals( Direction.BOTH ) ) { globalFactor = 0.5; } } /** * This recursively updates the node dependencies * @param node * The start node * @param skipFirstNode * If true, the start node is not updated. Useful, since the * first node in any path doesnt need to be updated. * @param successors * @param counter * Object that can return the number of paths from the initial * start node to any node. * @param dependencies * A map used to limit the recursion where possible (dynamic * programming) * @return */ protected Double getAndUpdateNodeDependency( Node node, boolean skipFirstNode, Map<Node,List<Relationship>> successors, PathCounter counter, Map<Node,Double> dependencies ) { Double dependency = dependencies.get( node ); if ( dependency != null ) { return dependency; } dependency = (double) 0; List<Relationship> succs = successors.get( node ); if ( succs == null || succs.size() == 0 ) { return (double) 0; } for ( Relationship relationship : succs ) { Node otherNode = relationship.getOtherNode( node ); Double otherDependency = getAndUpdateNodeDependency( otherNode, false, successors, counter, dependencies ); dependency += (otherDependency + 1) * counter.getNumberOfPathsToNode( node ) / counter.getNumberOfPathsToNode( otherNode ); } if ( !skipFirstNode ) { dependencies.put( node, dependency ); // When adding to the final result (and only then), take the global // factor into account. addCentralityToNode( node, dependency * globalFactor ); } return dependency; } @Override public void processShortestPaths( Node node, SingleSourceShortestPath<ShortestPathCostType> singleSourceShortestPath ) { // Extract predecessors and successors Map<Node,List<Relationship>> predecessors = singleSourceShortestPath .getPredecessors(); Map<Node,List<Relationship>> successors = Util .reversedPredecessors( predecessors ); PathCounter counter = new Util.PathCounter( predecessors ); // Recursively update the node dependencies getAndUpdateNodeDependency( node, true, successors, counter, new HashMap<Node,Double>() ); } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_centrality_BetweennessCentrality.java
3,083
public class AncestorsUtil { /** * * @param nodeSet Set of nodes for which the LCA will be found. * @return The LCA node if there's one, null otherwise. */ public static Node lowestCommonAncestor(List<Node> nodeSet, RelationshipExpander expander) { Node lowerCommonAncestor = null; if (nodeSet.size() > 1) { Node firstNode = nodeSet.get(0); LinkedList<Node> firstAncestors = getAncestorsPlusSelf(firstNode, expander); for (int i = 1; i < nodeSet.size() && !firstAncestors.isEmpty(); i++) { Node currentNode = nodeSet.get(i); lookForCommonAncestor(firstAncestors, currentNode, expander); } if(!firstAncestors.isEmpty()){ lowerCommonAncestor = firstAncestors.get(0); } } return lowerCommonAncestor; } private static LinkedList<Node> getAncestorsPlusSelf(Node node, RelationshipExpander expander) { LinkedList<Node> ancestors = new LinkedList<Node>(); ancestors.add(node); Iterator<Relationship> relIterator = expander.expand(node).iterator(); while (relIterator.hasNext()) { Relationship rel = relIterator.next(); node = rel.getOtherNode(node); ancestors.add(node); relIterator = expander.expand(node).iterator(); } return ancestors; } private static void lookForCommonAncestor(LinkedList<Node> commonAncestors, Node currentNode, RelationshipExpander expander) { while (currentNode != null) { for (int i = 0; i < commonAncestors.size(); i++) { Node node = commonAncestors.get(i); if (node.getId() == currentNode.getId()) { for (int j = 0; j < i; j++) { commonAncestors.pollFirst(); } return; } } Iterator<Relationship> relIt = expander.expand(currentNode).iterator(); if (relIt.hasNext()) { Relationship rel = relIt.next(); currentNode = rel.getOtherNode(currentNode); }else{ currentNode = null; } } } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_ancestor_AncestorsUtil.java
3,084
private static class SelectorFactory extends BestFirstSelectorFactory<Double, Double> { private final CostEvaluator<Double> evaluator; SelectorFactory( boolean forMultiplePaths, CostEvaluator<Double> evaluator ) { super( forMultiplePaths ); this.evaluator = evaluator; } @Override protected Double calculateValue( TraversalBranch next ) { return next.length() == 0 ? 0d : evaluator.getCost( next.lastRelationship(), Direction.OUTGOING ); } @Override protected Double addPriority( TraversalBranch source, Double currentAggregatedValue, Double value ) { return withDefault( currentAggregatedValue, 0d ) + withDefault( value, 0d ); } private <T> T withDefault( T valueOrNull, T valueIfNull ) { return valueOrNull != null ? valueOrNull : valueIfNull; } @Override protected Double getStartData() { return 0d; } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_path_Dijkstra.java
3,085
{ public BranchSelector create( TraversalBranch startSource, PathExpander expander ) { return new LiteDepthFirstSelector( startSource, startThreshold, expander ); } } );
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_path_ExactDepthPathFinder.java
3,086
class StressTest extends StressCentrality<Double> { public StressTest( SingleSourceShortestPath<Double> singleSourceShortestPath, Set<Node> nodeSet ) { super( singleSourceShortestPath, nodeSet ); } public void test() { // avoid starting the real calculation by mistake this.doneCalculation = true; // set things up Node startNode = graph.getNode( "c" ); singleSourceShortestPath.reset(); singleSourceShortestPath.setStartNode( startNode ); processShortestPaths( startNode, singleSourceShortestPath ); Double adjustment = 0.5; // since direction is BOTH assertCentrality( this, "a", 0.0 * adjustment ); assertCentrality( this, "b", 1.0 * adjustment ); assertCentrality( this, "c", 0.0 * adjustment ); assertCentrality( this, "d", 2.0 * adjustment ); assertCentrality( this, "e", 1.0 * adjustment ); assertCentrality( this, "f", 0.0 * adjustment ); } }
false
community_graph-algo_src_test_java_org_neo4j_graphalgo_centrality_StressCentralityTest.java
3,087
public class ShortestPath implements PathFinder<Path> { private final int maxDepth; private final int maxResultCount; private final PathExpander expander; private final HitDecider hitDecider; private Metadata lastMetadata; /** * Constructs a new shortest path algorithm. * @param maxDepth the maximum depth for the traversal. Returned paths * will never have a greater {@link Path#length()} than {@code maxDepth}. * @param expander the {@link RelationshipExpander} to use for deciding * which relationships to expand for each {@link Node}. */ public ShortestPath( int maxDepth, PathExpander expander ) { this( maxDepth, expander, Integer.MAX_VALUE, false ); } public ShortestPath( int maxDepth, RelationshipExpander expander ) { this( maxDepth, toPathExpander( expander ), Integer.MAX_VALUE, false ); } /** * Constructs a new shortest path algorithm. * @param maxDepth the maximum depth for the traversal. Returned paths * will never have a greater {@link Path#length()} than {@code maxDepth}. * @param expander the {@link RelationshipExpander} to use for deciding * which relationships to expand for each {@link Node}. * @param maxResultCount the maximum number of hits to return. If this number * of hits are encountered the traversal will stop. */ public ShortestPath( int maxDepth, PathExpander expander, int maxResultCount ) { this( maxDepth, expander, maxResultCount, false ); } public ShortestPath( int maxDepth, RelationshipExpander expander, int maxResultCount ) { this( maxDepth, toPathExpander( expander ), maxResultCount ); } /** * Constructs a new shortest path algorithm. * @param maxDepth the maximum depth for the traversal. Returned paths * will never have a greater {@link Path#length()} than {@code maxDepth}. * @param expander the {@link RelationshipExpander} to use for deciding * which relationships to expand for each {@link Node}. * @param maxResultCount the maximum number of hits to return. If this number * of hits are encountered the traversal will stop. * @param findPathsOnMaxDepthOnly if {@code true} then it will only try to * find paths on that particular depth ({@code maxDepth}). */ public ShortestPath( int maxDepth, PathExpander expander, int maxResultCount, boolean findPathsOnMaxDepthOnly ) { this.maxDepth = maxDepth; this.expander = expander; this.maxResultCount = maxResultCount; this.hitDecider = findPathsOnMaxDepthOnly ? new DepthHitDecider( maxDepth ) : YES_HIT_DECIDER; } public ShortestPath( int maxDepth, RelationshipExpander relExpander, int maxResultCount, boolean findPathsOnMaxDepthOnly ) { this( maxDepth, toPathExpander( relExpander ), maxResultCount, findPathsOnMaxDepthOnly ); } public Iterable<Path> findAllPaths( Node start, Node end ) { return internalPaths( start, end, false ); } public Path findSinglePath( Node start, Node end ) { Iterator<Path> paths = internalPaths( start, end, true ).iterator(); return paths.hasNext() ? paths.next() : null; } private Iterable<Path> internalPaths( Node start, Node end, boolean stopAsap ) { lastMetadata = new Metadata(); if ( start.equals( end ) ) { return Arrays.asList( PathImpl.singular( start ) ); } Hits hits = new Hits(); Collection<Long> sharedVisitedRels = new HashSet<Long>(); MutableInteger sharedFrozenDepth = new MutableInteger( MutableInteger.NULL ); MutableBoolean sharedStop = new MutableBoolean(); MutableInteger sharedCurrentDepth = new MutableInteger( 0 ); final DirectionData startData = new DirectionData( start, sharedVisitedRels, sharedFrozenDepth, sharedStop, sharedCurrentDepth, expander ); final DirectionData endData = new DirectionData( end, sharedVisitedRels, sharedFrozenDepth, sharedStop, sharedCurrentDepth, expander.reverse() ); while ( startData.hasNext() || endData.hasNext() ) { goOneStep( startData, endData, hits, startData, stopAsap ); goOneStep( endData, startData, hits, startData, stopAsap ); } Collection<Hit> least = hits.least(); return least != null ? hitsToPaths( least, start, end, stopAsap ) : Collections.<Path>emptyList(); } @Override public TraversalMetadata metadata() { return lastMetadata; } // Few long-lived instances private static class Hit { private final DirectionData start; private final DirectionData end; private final Node connectingNode; Hit( DirectionData start, DirectionData end, Node connectingNode ) { this.start = start; this.end = end; this.connectingNode = connectingNode; } @Override public int hashCode() { return connectingNode.hashCode(); } @Override public boolean equals( Object obj ) { Hit o = (Hit) obj; return connectingNode.equals( o.connectingNode ); } } private void goOneStep( DirectionData directionData, DirectionData otherSide, Hits hits, DirectionData startSide, boolean stopAsap ) { if ( !directionData.hasNext() ) { return; } Node nextNode = directionData.next(); LevelData otherSideHit = otherSide.visitedNodes.get( nextNode ); if ( otherSideHit != null ) { // This is a hit int depth = directionData.currentDepth + otherSideHit.depth; if ( !hitDecider.isHit( depth ) ) { return; } if ( directionData.sharedFrozenDepth.value == MutableInteger.NULL ) { directionData.sharedFrozenDepth.value = depth; } if ( depth <= directionData.sharedFrozenDepth.value ) { directionData.haveFoundSomething = true; if ( depth < directionData.sharedFrozenDepth.value ) { directionData.sharedFrozenDepth.value = depth; // TODO Is it really ok to just stop the other side here? // I'm basing that decision on that it was the other side // which found the deeper paths (correct assumption?) otherSide.stop = true; } // Add it to the list of hits DirectionData startSideData = directionData == startSide ? directionData : otherSide; DirectionData endSideData = directionData == startSide ? otherSide : directionData; if ( hits.add( new Hit( startSideData, endSideData, nextNode ), depth ) >= maxResultCount ) { directionData.stop = true; otherSide.stop = true; lastMetadata.paths++; } else if ( stopAsap ) { // This side found a hit, but wait for the other side to complete its current depth // to see if it finds a shorter path. (i.e. stop this side and freeze the depth). // but only if the other side has not stopped, otherwise we might miss shorter paths if (otherSide.stop == true) return; directionData.stop = true; } } } } // Two long-lived instances private class DirectionData extends PrefetchingIterator<Node> { private final Node startNode; private int currentDepth; private Iterator<Relationship> nextRelationships; private final Collection<Node> nextNodes = new ArrayList<Node>(); private Map<Node, LevelData> visitedNodes = new HashMap<Node, LevelData>(); private final Collection<Long> sharedVisitedRels; private final DirectionDataPath lastPath; private final MutableInteger sharedFrozenDepth; private final MutableBoolean sharedStop; private final MutableInteger sharedCurrentDepth; private boolean haveFoundSomething; private boolean stop; private final PathExpander expander; DirectionData( Node startNode, Collection<Long> sharedVisitedRels, MutableInteger sharedFrozenDepth, MutableBoolean sharedStop, MutableInteger sharedCurrentDepth, PathExpander expander ) { this.startNode = startNode; this.visitedNodes.put( startNode, new LevelData( null, 0 ) ); this.nextNodes.add( startNode ); this.sharedFrozenDepth = sharedFrozenDepth; this.sharedStop = sharedStop; this.sharedCurrentDepth = sharedCurrentDepth; this.expander = expander; this.sharedVisitedRels = sharedVisitedRels; this.lastPath = new DirectionDataPath( startNode ); if ( sharedCurrentDepth.value < maxDepth ) { prepareNextLevel(); } else { this.nextRelationships = Collections.<Relationship>emptyList().iterator(); } } private void prepareNextLevel() { Collection<Node> nodesToIterate = new ArrayList<Node>( filterNextLevelNodes( this.nextNodes ) ); this.nextNodes.clear(); this.lastPath.setLength( currentDepth ); this.nextRelationships = new NestingIterator<Relationship, Node>( nodesToIterate.iterator() ) { @Override protected Iterator<Relationship> createNestedIterator( Node node ) { lastPath.setEndNode( node ); return expander.expand( lastPath, BranchState.NO_STATE ).iterator(); } }; this.currentDepth++; this.sharedCurrentDepth.value++; } @Override protected Node fetchNextOrNull() { while ( true ) { Relationship nextRel = fetchNextRelOrNull(); if ( nextRel == null ) { return null; } lastMetadata.rels++; if ( !hitDecider.canVisitRelationship( sharedVisitedRels, nextRel ) ) { continue; } Node result = nextRel.getOtherNode( this.lastPath.endNode() ); LevelData levelData = this.visitedNodes.get( result ); boolean createdLevelData = false; if ( levelData == null ) { levelData = new LevelData( nextRel, this.currentDepth ); this.visitedNodes.put( result, levelData ); createdLevelData = true; } if ( this.currentDepth == levelData.depth && !createdLevelData ) { levelData.addRel( nextRel ); } // Was this level data created right now, i.e. have we visited this node before? // In that case don't add it as next node to traverse if ( createdLevelData ) { this.nextNodes.add( result ); return result; } } } private boolean canGoDeeper() { return this.sharedFrozenDepth.value == MutableInteger.NULL && this.sharedCurrentDepth.value < maxDepth; } private Relationship fetchNextRelOrNull() { if ( this.stop || this.sharedStop.value ) { return null; } boolean hasComeTooFarEmptyHanded = this.sharedFrozenDepth.value != MutableInteger.NULL && this.sharedCurrentDepth.value > this.sharedFrozenDepth.value && !this.haveFoundSomething; if ( hasComeTooFarEmptyHanded ) { return null; } if ( !this.nextRelationships.hasNext() ) { if ( canGoDeeper() ) { prepareNextLevel(); } } return this.nextRelationships.hasNext() ? this.nextRelationships.next() : null; } } // Two long-lived instances private static class DirectionDataPath implements Path { private final Node startNode; private Node endNode; private int length; DirectionDataPath( Node startNode ) { this.startNode = startNode; this.endNode = startNode; this.length = 0; } void setEndNode( Node endNode ) { this.endNode = endNode; } void setLength( int length ) { this.length = length; } @Override public Node startNode() { return startNode; } @Override public Node endNode() { return endNode; } @Override public Relationship lastRelationship() { throw new UnsupportedOperationException(); } @Override public Iterable<Relationship> relationships() { throw new UnsupportedOperationException(); } @Override public Iterable<Relationship> reverseRelationships() { throw new UnsupportedOperationException(); } @Override public Iterable<Node> nodes() { throw new UnsupportedOperationException(); } @Override public Iterable<Node> reverseNodes() { throw new UnsupportedOperationException(); } @Override public int length() { return length; } @Override public Iterator<PropertyContainer> iterator() { throw new UnsupportedOperationException(); } } protected Collection<Node> filterNextLevelNodes( Collection<Node> nextNodes ) { return nextNodes; } // Few long-lived instances private static class MutableInteger { private static final int NULL = -1; private int value; MutableInteger( int initialValue ) { this.value = initialValue; } } // Few long-lived instances private static class MutableBoolean { private boolean value; } // Many long-lived instances private static class LevelData { private long[] relsToHere; private int depth; LevelData( Relationship relToHere, int depth ) { if ( relToHere != null ) { addRel( relToHere ); } this.depth = depth; } void addRel( Relationship rel ) { long[] newRels = null; if ( relsToHere == null ) { newRels = new long[1]; } else { newRels = new long[relsToHere.length+1]; System.arraycopy( relsToHere, 0, newRels, 0, relsToHere.length ); } newRels[newRels.length-1] = rel.getId(); relsToHere = newRels; } } // One long lived instance private static class Hits { private Map<Integer, Collection<Hit>> hits = new HashMap<Integer, Collection<Hit>>(); private int lowestDepth; private int totalHitCount; int add( Hit hit, int atDepth ) { Collection<Hit> depthHits = hits.get( atDepth ); if ( depthHits == null ) { depthHits = new HashSet<Hit>(); hits.put( atDepth, depthHits ); } if ( depthHits.add( hit ) ) { totalHitCount++; } if ( lowestDepth == 0 || atDepth < lowestDepth ) { lowestDepth = atDepth; } return totalHitCount; } Collection<Hit> least() { return hits.get( lowestDepth ); } } // Methods for converting data representing paths to actual Path instances. // It's rather tricky just because this algo stores as little info as possible // required to build paths from hit information. private static class PathData { private final LinkedList<Relationship> rels; private final Node node; PathData( Node node, LinkedList<Relationship> rels ) { this.rels = rels; this.node = node; } } private static Iterable<Path> hitsToPaths(Collection<Hit> depthHits, Node start, Node end, boolean stopAsap) { Collection<Path> paths = new ArrayList<Path>(); for ( Hit hit : depthHits ) { Iterable<LinkedList<Relationship>> startPaths = getPaths(hit.connectingNode, hit.start, stopAsap); Iterable<LinkedList<Relationship>> endPaths = getPaths(hit.connectingNode, hit.end, stopAsap); for ( LinkedList<Relationship> startPath : startPaths ) { PathImpl.Builder startBuilder = toBuilder( start, startPath ); for ( LinkedList<Relationship> endPath : endPaths ) { PathImpl.Builder endBuilder = toBuilder( end, endPath ); Path path = startBuilder.build( endBuilder ); paths.add( path ); } } } return paths; } private static Iterable<LinkedList<Relationship>> getPaths(Node connectingNode, DirectionData data, boolean stopAsap) { LevelData levelData = data.visitedNodes.get(connectingNode); if ( levelData.depth == 0 ) { Collection<LinkedList<Relationship>> result = new ArrayList<LinkedList<Relationship>>(); result.add( new LinkedList<Relationship>() ); return result; } Collection<PathData> set = new ArrayList<PathData>(); GraphDatabaseService graphDb = data.startNode.getGraphDatabase(); for ( long rel : levelData.relsToHere ) { set.add( new PathData(connectingNode, new LinkedList<Relationship>( Arrays.asList( graphDb.getRelationshipById( rel ) ) ) ) ); if (stopAsap) break; } for ( int i = 0; i < levelData.depth - 1; i++ ) { // One level Collection<PathData> nextSet = new ArrayList<PathData>(); for ( PathData entry : set ) { // One path... Node otherNode = entry.rels.getFirst().getOtherNode( entry.node ); LevelData otherLevelData = data.visitedNodes.get( otherNode ); int counter = 0; for ( long rel : otherLevelData.relsToHere ) { // ...may split into several paths LinkedList<Relationship> rels = ++counter == otherLevelData.relsToHere.length ? // This is a little optimization which reduces number of // lists being copied entry.rels : new LinkedList<Relationship>( entry.rels ); rels.addFirst( graphDb.getRelationshipById( rel ) ); nextSet.add( new PathData( otherNode, rels ) ); if (stopAsap) break; } } set = nextSet; } return new IterableWrapper<LinkedList<Relationship>, PathData>( set ) { @Override protected LinkedList<Relationship> underlyingObjectToObject( PathData object ) { return object.rels; } }; } private static Builder toBuilder( Node startNode, LinkedList<Relationship> rels ) { PathImpl.Builder builder = new PathImpl.Builder( startNode ); for ( Relationship rel : rels ) { builder = builder.push( rel ); } return builder; } private static interface HitDecider { boolean isHit( int depth ); boolean canVisitRelationship( Collection<Long> rels, Relationship rel ); } private static final HitDecider YES_HIT_DECIDER = new HitDecider() { public boolean isHit( int depth ) { return true; } public boolean canVisitRelationship( Collection<Long> rels, Relationship rel ) { return true; } }; private static class DepthHitDecider implements HitDecider { private final int depth; DepthHitDecider( int depth ) { this.depth = depth; } public boolean isHit( int depth ) { return this.depth == depth; } public boolean canVisitRelationship( Collection<Long> rels, Relationship rel ) { return rels.add( rel.getId() ); } } private static class Metadata implements TraversalMetadata { private int rels; private int paths; @Override public int getNumberOfPathsReturned() { return paths; } @Override public int getNumberOfRelationshipsTraversed() { return rels; } } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_path_ShortestPath.java
3,088
public class TraversalShortestPath extends TraversalPathFinder { private final PathExpander expander; private final int maxDepth; private final Integer maxResultCount; public TraversalShortestPath( RelationshipExpander expander, int maxDepth ) { this( toPathExpander( expander ), maxDepth ); } public TraversalShortestPath( PathExpander expander, int maxDepth ) { this.expander = expander; this.maxDepth = maxDepth; this.maxResultCount = null; } public TraversalShortestPath( RelationshipExpander expander, int maxDepth, int maxResultCount ) { this( toPathExpander( expander ), maxDepth, maxResultCount ); } public TraversalShortestPath( PathExpander expander, int maxDepth, int maxResultCount ) { this.expander = expander; this.maxDepth = maxDepth; this.maxResultCount = maxResultCount; } @Override protected Traverser instantiateTraverser( Node start, Node end ) { TraversalDescription sideBase = traversal().breadthFirst().uniqueness( NODE_PATH ); return bidirectionalTraversal() .mirroredSides( sideBase.expand( expander ) ) .sideSelector( LEVEL_STOP_DESCENT_ON_RESULT, maxDepth ) .collisionEvaluator( toDepth( maxDepth ) ) .traverse( start, end ); } @Override protected Integer maxResultCount() { return maxResultCount; } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_path_TraversalShortestPath.java
3,089
public abstract class TraversalPathFinder implements PathFinder<Path> { private Traverser lastTraverser; @Override public Path findSinglePath( Node start, Node end ) { return firstOrNull( findAllPaths( start, end ) ); } protected Integer maxResultCount() { return null; } @Override public Iterable<Path> findAllPaths( Node start, Node end ) { lastTraverser = instantiateTraverser( start, end ); Integer maxResultCount = maxResultCount(); return maxResultCount != null ? new LimitingIterable<Path>( lastTraverser, maxResultCount ) : lastTraverser; } protected abstract Traverser instantiateTraverser( Node start, Node end ); @Override public TraversalMetadata metadata() { if ( lastTraverser == null ) { throw new IllegalStateException( "No traversal has been made" ); } return lastTraverser.metadata(); } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_path_TraversalPathFinder.java
3,090
private class SelectorFactory extends BestFirstSelectorFactory<PositionData, Double> { private final Node end; SelectorFactory( Node end, boolean forMultiplePaths ) { super( forMultiplePaths ); this.end = end; } @Override protected PositionData addPriority( TraversalBranch source, PositionData currentAggregatedValue, Double value ) { return new PositionData( currentAggregatedValue.wayLengthG + value, estimateEvaluator.getCost( source.endNode(), end ) ); } @Override protected Double calculateValue( TraversalBranch next ) { return next.length() == 0 ? 0d : costEvaluator.getCost( next.lastRelationship(), Direction.OUTGOING ); } @Override protected PositionData getStartData() { return new PositionData( 0, 0 ); } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_path_TraversalAStar.java
3,091
private static class PositionData implements Comparable<PositionData> { private final double wayLengthG; private final double estimateH; public PositionData( double wayLengthG, double estimateH ) { this.wayLengthG = wayLengthG; this.estimateH = estimateH; } Double f() { return this.estimateH + this.wayLengthG; } @Override public int compareTo( PositionData o ) { return f().compareTo( o.f() ); } @Override public String toString() { return "g:" + wayLengthG + ", h:" + estimateH; } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_path_TraversalAStar.java
3,092
{ @Override public Iterator<WeightedPath> iterator() { return new StopAfterWeightIterator( lastTraverser.iterator(), costEvaluator ); } };
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_path_TraversalAStar.java
3,093
public class TraversalAStar implements PathFinder<WeightedPath> { private final TraversalDescription traversalDescription; private final CostEvaluator<Double> costEvaluator; private Traverser lastTraverser; private final EstimateEvaluator<Double> estimateEvaluator; @SuppressWarnings( "unchecked" ) public <T> TraversalAStar( PathExpander<T> expander, CostEvaluator<Double> costEvaluator, EstimateEvaluator<Double> estimateEvaluator ) { this( expander, NO_STATE, costEvaluator, estimateEvaluator ); } public <T> TraversalAStar( PathExpander<T> expander, InitialBranchState<T> initialState, CostEvaluator<Double> costEvaluator, EstimateEvaluator<Double> estimateEvaluator ) { this.costEvaluator = costEvaluator; this.estimateEvaluator = estimateEvaluator; this.traversalDescription = traversal().uniqueness( Uniqueness.NONE ).expand( expander, initialState ); } @SuppressWarnings( "unchecked" ) public TraversalAStar( RelationshipExpander expander, CostEvaluator<Double> costEvaluator, EstimateEvaluator<Double> estimateEvaluator ) { this( toPathExpander( expander ), costEvaluator, estimateEvaluator ); } @Override public Iterable<WeightedPath> findAllPaths( Node start, final Node end ) { return findPaths( start, end, true ); } @Override public WeightedPath findSinglePath( Node start, Node end ) { return firstOrNull( findPaths( start, end, false ) ); } private Iterable<WeightedPath> findPaths( Node start, Node end, boolean multiplePaths ) { lastTraverser = traversalDescription.order( new SelectorFactory( end, multiplePaths ) ).evaluator( includeWhereEndNodeIs( end ) ).traverse( start ); return new Iterable<WeightedPath>() { @Override public Iterator<WeightedPath> iterator() { return new StopAfterWeightIterator( lastTraverser.iterator(), costEvaluator ); } }; } @Override public TraversalMetadata metadata() { return lastTraverser.metadata(); } private static class PositionData implements Comparable<PositionData> { private final double wayLengthG; private final double estimateH; public PositionData( double wayLengthG, double estimateH ) { this.wayLengthG = wayLengthG; this.estimateH = estimateH; } Double f() { return this.estimateH + this.wayLengthG; } @Override public int compareTo( PositionData o ) { return f().compareTo( o.f() ); } @Override public String toString() { return "g:" + wayLengthG + ", h:" + estimateH; } } private class SelectorFactory extends BestFirstSelectorFactory<PositionData, Double> { private final Node end; SelectorFactory( Node end, boolean forMultiplePaths ) { super( forMultiplePaths ); this.end = end; } @Override protected PositionData addPriority( TraversalBranch source, PositionData currentAggregatedValue, Double value ) { return new PositionData( currentAggregatedValue.wayLengthG + value, estimateEvaluator.getCost( source.endNode(), end ) ); } @Override protected Double calculateValue( TraversalBranch next ) { return next.length() == 0 ? 0d : costEvaluator.getCost( next.lastRelationship(), Direction.OUTGOING ); } @Override protected PositionData getStartData() { return new PositionData( 0, 0 ); } } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_path_TraversalAStar.java
3,094
private static class PathData { private final LinkedList<Relationship> rels; private final Node node; PathData( Node node, LinkedList<Relationship> rels ) { this.rels = rels; this.node = node; } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_path_ShortestPath.java
3,095
private static class MutableInteger { private static final int NULL = -1; private int value; MutableInteger( int initialValue ) { this.value = initialValue; } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_path_ShortestPath.java
3,096
private static class MutableBoolean { private boolean value; }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_path_ShortestPath.java
3,097
private static class Metadata implements TraversalMetadata { private int rels; private int paths; @Override public int getNumberOfPathsReturned() { return paths; } @Override public int getNumberOfRelationshipsTraversed() { return rels; } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_path_ShortestPath.java
3,098
private static class LevelData { private long[] relsToHere; private int depth; LevelData( Relationship relToHere, int depth ) { if ( relToHere != null ) { addRel( relToHere ); } this.depth = depth; } void addRel( Relationship rel ) { long[] newRels = null; if ( relsToHere == null ) { newRels = new long[1]; } else { newRels = new long[relsToHere.length+1]; System.arraycopy( relsToHere, 0, newRels, 0, relsToHere.length ); } newRels[newRels.length-1] = rel.getId(); relsToHere = newRels; } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_path_ShortestPath.java
3,099
private static class Hits { private Map<Integer, Collection<Hit>> hits = new HashMap<Integer, Collection<Hit>>(); private int lowestDepth; private int totalHitCount; int add( Hit hit, int atDepth ) { Collection<Hit> depthHits = hits.get( atDepth ); if ( depthHits == null ) { depthHits = new HashSet<Hit>(); hits.put( atDepth, depthHits ); } if ( depthHits.add( hit ) ) { totalHitCount++; } if ( lowestDepth == 0 || atDepth < lowestDepth ) { lowestDepth = atDepth; } return totalHitCount; } Collection<Hit> least() { return hits.get( lowestDepth ); } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_path_ShortestPath.java