Unnamed: 0
int64
0
6.7k
func
stringlengths
12
89.6k
target
bool
2 classes
project
stringlengths
45
151
3,300
public class SubGraphExporter { private final SubGraph graph; public SubGraphExporter( SubGraph graph ) { this.graph = graph; } public void export( PrintWriter out ) { appendIndexes( out ); appendConstraints( out ); appendNodes( out ); appendRelationships( out ); } private Collection<String> exportIndexes() { final List<String> result = new ArrayList<>(); for ( IndexDefinition index : graph.getIndexes() ) { if ( !index.isConstraintIndex() ) { Iterator<String> propertyKeys = index.getPropertyKeys().iterator(); if ( !propertyKeys.hasNext() ) { throw new ThisShouldNotHappenError( "Chris", "indexes should have at least one property key" ); } String key = quote( propertyKeys.next() ); if ( propertyKeys.hasNext() ) { throw new RuntimeException( "Exporting compound indexes is not implemented yet" ); } String label = quote( index.getLabel().name() ); result.add( "create index on :" + label + "(" + key + ")" ); } } Collections.sort( result ); return result; } private Collection<String> exportConstraints() { final List<String> result = new ArrayList<>(); for ( ConstraintDefinition constraint : graph.getConstraints() ) { if ( !constraint.isConstraintType( ConstraintType.UNIQUENESS ) ) { throw new RuntimeException( "Exporting constraints other than uniqueness is not implemented yet" ); } Iterator<String> propertyKeys = constraint.getPropertyKeys().iterator(); if ( !propertyKeys.hasNext() ) { throw new ThisShouldNotHappenError( "Chris", "constraints should have at least one property key" ); } String key = quote( propertyKeys.next() ); if ( propertyKeys.hasNext() ) { throw new RuntimeException( "Exporting compound constraints is not implemented yet" ); } String label = quote( constraint.getLabel().name() ); result.add( "create constraint on (n:" + label + ") assert n." + key + " is unique" ); } Collections.sort( result ); return result; } private String quote( String id ) { return "`" + id + "`"; } private String labelString( Node node ) { Iterator<Label> labels = node.getLabels().iterator(); if ( !labels.hasNext() ) { return ""; } StringBuilder result = new StringBuilder(); while ( labels.hasNext() ) { Label next = labels.next(); result.append( ":" ).append( quote( next.name() ) ); } return result.toString(); } private String identifier( Node node ) { return "_" + node.getId(); } private void appendIndexes( PrintWriter out ) { for ( String line : exportIndexes() ) { out.println( line ); } } private void appendConstraints( PrintWriter out ) { for ( String line : exportConstraints() ) { out.println( line ); } } private void appendRelationships( PrintWriter out ) { for ( Node node : graph.getNodes() ) { for ( Relationship rel : node.getRelationships( Direction.OUTGOING ) ) { appendRelationship( out, rel ); } } } private void appendRelationship( PrintWriter out, Relationship rel ) { out.print( "create " ); out.print( identifier( rel.getStartNode() ) ); out.print( "-[:" ); out.print( quote( rel.getType().name() ) ); formatProperties( out, rel ); out.print( "]->" ); out.print( identifier( rel.getEndNode() ) ); out.println(); } private void appendNodes( PrintWriter out ) { for ( Node node : graph.getNodes() ) { appendNode( out, node ); } } private void appendNode( PrintWriter out, Node node ) { out.print( "create (" ); out.print( identifier( node ) ); String labels = labelString( node ); if ( !labels.isEmpty() ) { out.print( labels ); } formatProperties( out, node ); out.println( ")" ); } private void formatProperties( PrintWriter out, PropertyContainer pc ) { if ( !pc.getPropertyKeys().iterator().hasNext() ) { return; } out.print( " " ); final String propertyString = formatProperties( pc ); out.print( propertyString ); } private String formatProperties( PropertyContainer pc ) { StringBuilder result = new StringBuilder(); List<String> keys = Iterables.toList( pc.getPropertyKeys() ); Collections.sort( keys ); for ( String prop : keys ) { if ( result.length() > 0 ) { result.append( ", " ); } result.append( quote( prop ) ).append( ":" ); Object value = pc.getProperty( prop ); result.append( toString( value ) ); } return "{" + result + "}"; } private String toString( Iterator<?> iterator ) { StringBuilder result = new StringBuilder(); while ( iterator.hasNext() ) { if ( result.length() > 0 ) { result.append( ", " ); } Object value = iterator.next(); result.append( toString( value ) ); } return "[" + result + "]"; } private String arrayToString( Object value ) { StringBuilder result = new StringBuilder(); int length = Array.getLength( value ); for ( int i = 0; i < length; i++ ) { if ( i > 0 ) { result.append( ", " ); } result.append( toString( Array.get( value, i ) ) ); } return "[" + result + "]"; } private String toString( Object value ) { if ( value == null ) { return "null"; } if ( value instanceof String ) { return "\"" + ((String) value).replaceAll( "\"", "\\\\\"" ) + "\""; } if ( value instanceof Float || value instanceof Double ) { return String.format( Locale.ENGLISH, "%f", value ); } if ( value instanceof Iterator ) { return toString( ((Iterator) value) ); } if ( value instanceof Iterable ) { return toString( ((Iterable) value).iterator() ); } if ( value.getClass().isArray() ) { return arrayToString( value ); } return value.toString(); } }
false
community_cypher_cypher_src_main_java_org_neo4j_cypher_export_SubGraphExporter.java
3,301
{ @Override public void close() { } @Override public boolean hasNext() { return inner.hasNext(); } @Override public Map<String, Object> next() { return inner.next(); } @Override public void remove() { inner.remove(); } };
false
community_cypher_cypher_src_test_java_org_neo4j_cypher_export_ExportTest.java
3,302
public class ExportTest { private final static String NL = System.getProperty( "line.separator" ); private GraphDatabaseService gdb; private Transaction tx; @Before public void setUp() throws Exception { gdb = new TestGraphDatabaseFactory().newImpermanentDatabase(); tx = gdb.beginTx(); } @After public void tearDown() throws Exception { tx.close(); gdb.shutdown(); } @Test public void testEmptyGraph() throws Exception { assertEquals( "", doExportGraph( gdb ) ); } @Test public void testNodeWithProperties() throws Exception { gdb.createNode().setProperty( "name", "Andres" ); assertEquals( "create (_0 {`name`:\"Andres\"})" + NL, doExportGraph( gdb ) ); } @Test public void testNodeWithFloatProperty() throws Exception { final float floatValue = 10.1f; final String expected = "10.100000"; gdb.createNode().setProperty( "float", floatValue ); assertEquals( "create (_0 {`float`:" + expected + "})" + NL, doExportGraph( gdb ) ); } @Test public void testNodeWithDoubleProperty() throws Exception { final double doubleValue = 123456.123456; final String expected = "123456.123456"; gdb.createNode().setProperty( "double", doubleValue ); assertEquals( "create (_0 {`double`:" + expected + "})" + NL, doExportGraph( gdb ) ); } private String doExportGraph( GraphDatabaseService db ) { SubGraph graph = DatabaseSubGraph.from( db ); return doExportGraph( graph ); } private String doExportGraph( SubGraph graph ) { StringWriter out = new StringWriter(); new SubGraphExporter( graph ).export( new PrintWriter( out ) ); return out.toString(); } @Test public void testFromSimpleCypherResult() throws Exception { Node n = gdb.createNode(); final ExecutionResult result = result( "node", n ); final SubGraph graph = CypherResultSubGraph.from( result, gdb, false ); assertEquals( "create (_" + n.getId() + ")" + NL, doExportGraph( graph ) ); } @Test public void testSingleNode() throws Exception { Node n = gdb.createNode(); final ExecutionResult result = result( "node", n ); final SubGraph graph = CypherResultSubGraph.from( result, gdb, false ); assertEquals( "create (_" + n.getId() + ")" + NL, doExportGraph( graph ) ); } @Test public void testSingleNodeWithProperties() throws Exception { Node n = gdb.createNode(); n.setProperty( "name", "Node1" ); n.setProperty( "age", 42 ); final ExecutionResult result = result( "node", n ); final SubGraph graph = CypherResultSubGraph.from( result, gdb, false ); assertEquals( "create (_" + n.getId() + " {`age`:42, `name`:\"Node1\"})" + NL, doExportGraph( graph ) ); } @Test public void testEscapingOfNodeStringPropertyValue() throws Exception { Node n = gdb.createNode(); n.setProperty( "name", "Brutus \"Brutal\" Howell" ); final ExecutionResult result = result( "node", n ); final SubGraph graph = CypherResultSubGraph.from( result, gdb, false ); assertEquals( "create (_" + n.getId() + " {`name`:\"Brutus \\\"Brutal\\\" Howell\"})" + NL, doExportGraph( graph ) ); } @Test public void testEscapingOfNodeStringArrayPropertyValue() throws Exception { Node n = gdb.createNode(); n.setProperty( "name", new String[]{"Brutus \"Brutal\" Howell", "Dr."} ); final ExecutionResult result = result( "node", n ); final SubGraph graph = CypherResultSubGraph.from( result, gdb, false ); assertEquals( "create (_" + n.getId() + " {`name`:[\"Brutus \\\"Brutal\\\" Howell\", \"Dr.\"]})" + NL, doExportGraph( graph ) ); } @Test public void testEscapingOfRelationshipStringPropertyValue() throws Exception { Node n = gdb.createNode(); final Relationship rel = n.createRelationshipTo( n, DynamicRelationshipType.withName( "REL" ) ); rel.setProperty( "name", "Brutus \"Brutal\" Howell" ); final ExecutionResult result = result( "rel", rel ); final SubGraph graph = CypherResultSubGraph.from( result, gdb, true ); assertEquals( "create (_0)" + NL + "create _0-[:`REL` {`name`:\"Brutus \\\"Brutal\\\" Howell\"}]->_0" + NL, doExportGraph( graph ) ); } @Test public void testEscapingOfRelationshipStringArrayPropertyValue() throws Exception { Node n = gdb.createNode(); final Relationship rel = n.createRelationshipTo( n, DynamicRelationshipType.withName( "REL" ) ); rel.setProperty( "name", new String[]{"Brutus \"Brutal\" Howell", "Dr."} ); final ExecutionResult result = result( "rel", rel ); final SubGraph graph = CypherResultSubGraph.from( result, gdb, true ); assertEquals( "create (_0)" + NL + "create _0-[:`REL` {`name`:[\"Brutus \\\"Brutal\\\" Howell\", \"Dr.\"]}]->_0" + NL, doExportGraph( graph ) ); } @Test public void testSingleNodeWithArrayProperties() throws Exception { Node n = gdb.createNode(); n.setProperty( "name", new String[]{"a", "b"} ); n.setProperty( "age", new int[]{1, 2} ); final ExecutionResult result = result( "node", n ); final SubGraph graph = CypherResultSubGraph.from( result, gdb, false ); assertEquals( "create (_" + n.getId() + " {`age`:[1, 2], `name`:[\"a\", \"b\"]})" + NL, doExportGraph( graph ) ); } @Test public void testSingleNodeLabels() throws Exception { Node n = gdb.createNode(); n.addLabel( DynamicLabel.label( "Foo" ) ); n.addLabel( DynamicLabel.label( "Bar" ) ); final ExecutionResult result = result( "node", n ); final SubGraph graph = CypherResultSubGraph.from( result, gdb, false ); assertEquals( "create (_" + n.getId() + ":`Foo`:`Bar`)" + NL, doExportGraph( graph ) ); } @Test public void testExportIndex() throws Exception { gdb.schema().indexFor( DynamicLabel.label( "Foo" ) ).on( "bar" ).create(); assertEquals( "create index on :`Foo`(`bar`)" + NL , doExportGraph( gdb ) ); } @Test public void testExportUniquenessConstraint() throws Exception { gdb.schema().constraintFor( DynamicLabel.label( "Foo" ) ).assertPropertyIsUnique( "bar" ).create(); assertEquals( "create constraint on (n:`Foo`) assert n.`bar` is unique" + NL, doExportGraph( gdb ) ); } @Test public void testExportIndexesViaCypherResult() throws Exception { final Label label = DynamicLabel.label( "Foo" ); gdb.schema().indexFor( label ).on( "bar" ).create(); gdb.schema().indexFor( label ).on( "bar2" ).create(); commitAndStartNewTransactionAfterSchemaChanges(); Node n = gdb.createNode( label ); final ExecutionResult result = result( "node", n ); final SubGraph graph = CypherResultSubGraph.from( result, gdb, true ); assertEquals( "create index on :`Foo`(`bar2`)" + NL + "create index on :`Foo`(`bar`)" + NL + "create (_0:`Foo`)" + NL, doExportGraph( graph ) ); } @Test public void testExportConstraintsViaCypherResult() throws Exception { final Label label = DynamicLabel.label( "Foo" ); gdb.schema().constraintFor( label ).assertPropertyIsUnique( "bar" ).create(); gdb.schema().constraintFor( label ).assertPropertyIsUnique( "bar2" ).create(); commitAndStartNewTransactionAfterSchemaChanges(); Node n = gdb.createNode( label ); final ExecutionResult result = result( "node", n ); final SubGraph graph = CypherResultSubGraph.from( result, gdb, true ); assertEquals( "create constraint on (n:`Foo`) assert n.`bar2` is unique" + NL + "create constraint on (n:`Foo`) assert n.`bar` is unique" + NL + "create (_0:`Foo`)" + NL, doExportGraph( graph ) ); } private void commitAndStartNewTransactionAfterSchemaChanges() { tx.success(); tx.close(); tx = gdb.beginTx(); } @Test public void testFromRelCypherResult() throws Exception { Node n = gdb.createNode(); final Relationship rel = n.createRelationshipTo( n, DynamicRelationshipType.withName( "REL" ) ); final ExecutionResult result = result( "rel", rel ); final SubGraph graph = CypherResultSubGraph.from( result, gdb, true ); assertEquals( "create (_0)" + NL + "create _0-[:`REL`]->_0" + NL, doExportGraph( graph ) ); } @Test public void testFromPathCypherResult() throws Exception { Node n1 = gdb.createNode(); Node n2 = gdb.createNode(); final Relationship rel = n1.createRelationshipTo( n2, DynamicRelationshipType.withName( "REL" ) ); final Path path = new PathImpl.Builder( n1 ).push( rel ).build(); final ExecutionResult result = result( "path", path ); final SubGraph graph = CypherResultSubGraph.from( result, gdb, true ); assertEquals( "create (_0)" + NL + "create (_1)" + NL + "create _0-[:`REL`]->_1" + NL, doExportGraph( graph ) ); } @SuppressWarnings("unchecked") private ExecutionResult result( String column, Object value ) { ExecutionResult result = Mockito.mock( ExecutionResult.class ); Mockito.when( result.columns() ).thenReturn( asList( column ) ); final Iterator<Map<String, Object>> inner = asList( singletonMap( column, value ) ).iterator(); ResourceIterator<Map<String, Object>> iterator = new ResourceIterator<Map<String, Object>>() { @Override public void close() { } @Override public boolean hasNext() { return inner.hasNext(); } @Override public Map<String, Object> next() { return inner.next(); } @Override public void remove() { inner.remove(); } }; Mockito.when( result.iterator() ).thenReturn( iterator ); return result; } @Test public void testFromSimpleGraph() throws Exception { final Node n0 = gdb.createNode(); final Node n1 = gdb.createNode(); n1.setProperty( "name", "Node1" ); final Relationship relationship = n0.createRelationshipTo( n1, DynamicRelationshipType.withName( "REL" ) ); relationship.setProperty( "related", true ); final SubGraph graph = DatabaseSubGraph.from( gdb ); assertEquals( "create (_" + n0.getId() + ")" + NL + "create (_" + n1.getId() + " {`name`:\"Node1\"})" + NL + "create _" + n0.getId() + "-[:`REL` {`related`:true}]->_" + n1.getId() + NL, doExportGraph( graph ) ); } }
false
community_cypher_cypher_src_test_java_org_neo4j_cypher_export_ExportTest.java
3,303
public class DatabaseSubGraph implements SubGraph { private final GraphDatabaseService gdb; public DatabaseSubGraph( GraphDatabaseService gdb ) { this.gdb = gdb; } public static SubGraph from( GraphDatabaseService gdb ) { return new DatabaseSubGraph(gdb); } @Override public Iterable<Node> getNodes() { final GlobalGraphOperations operations = GlobalGraphOperations.at( gdb ); return operations.getAllNodes(); } @Override public Iterable<Relationship> getRelationships() { final GlobalGraphOperations operations = GlobalGraphOperations.at( gdb ); return operations.getAllRelationships(); } @Override public boolean contains(Relationship relationship) { return relationship.getGraphDatabase().equals(gdb); } @Override public Iterable<IndexDefinition> getIndexes() { return gdb.schema().getIndexes(); } @Override public Iterable<ConstraintDefinition> getConstraints() { return gdb.schema().getConstraints(); } }
false
community_cypher_cypher_src_main_java_org_neo4j_cypher_export_DatabaseSubGraph.java
3,304
public class CypherResultSubGraph implements SubGraph { private final SortedMap<Long, Node> nodes = new TreeMap<>(); private final SortedMap<Long, Relationship> relationships = new TreeMap<>(); private final Collection<Label> labels = new HashSet<>(); private final Collection<IndexDefinition> indexes = new HashSet<>(); private final Collection<ConstraintDefinition> constraints = new HashSet<>(); public void add( Node node ) { final long id = node.getId(); if ( !nodes.containsKey( id ) ) { addNode( id, node ); } } void addNode( long id, Node data ) { nodes.put( id, data ); labels.addAll( asCollection( data.getLabels() ) ); } public void add( Relationship rel ) { final long id = rel.getId(); if ( !relationships.containsKey( id ) ) { addRel( id, rel ); add( rel.getStartNode() ); add( rel.getEndNode() ); } } public static SubGraph from( ExecutionResult result, GraphDatabaseService gds, boolean addBetween ) { final CypherResultSubGraph graph = new CypherResultSubGraph(); final List<String> columns = result.columns(); for ( Map<String, Object> row : result ) { for ( String column : columns ) { final Object value = row.get( column ); graph.addToGraph( value ); } } for ( IndexDefinition def : gds.schema().getIndexes() ) { if ( graph.getLabels().contains( def.getLabel() ) ) { graph.addIndex( def ); } } for ( ConstraintDefinition def : gds.schema().getConstraints() ) { if ( graph.getLabels().contains( def.getLabel() ) ) { graph.addConstraint( def ); } } if ( addBetween ) { graph.addRelationshipsBetweenNodes(); } return graph; } private void addIndex( IndexDefinition def ) { indexes.add( def ); } private void addConstraint( ConstraintDefinition def ) { constraints.add( def ); } private void addRelationshipsBetweenNodes() { Set<Node> newNodes = new HashSet<>(); for ( Node node : nodes.values() ) { for ( Relationship relationship : node.getRelationships() ) { if ( !relationships.containsKey( relationship.getId() ) ) { continue; } final Node other = relationship.getOtherNode( node ); if ( nodes.containsKey( other.getId() ) || newNodes.contains( other ) ) { continue; } newNodes.add( other ); } } for ( Node node : newNodes ) { add( node ); } } private void addToGraph( Object value ) { if ( value instanceof Node ) { add( (Node) value ); } if ( value instanceof Relationship ) { add( (Relationship) value ); } if ( value instanceof Iterable ) { for ( Object inner : (Iterable) value ) { addToGraph( inner ); } } } @Override public Iterable<Node> getNodes() { return nodes.values(); } @Override public Iterable<Relationship> getRelationships() { return relationships.values(); } public Collection<Label> getLabels() { return labels; } void addRel( Long id, Relationship rel ) { relationships.put( id, rel ); } @Override public boolean contains( Relationship relationship ) { return relationships.containsKey( relationship.getId() ); } public Iterable<IndexDefinition> getIndexes() { return indexes; } @Override public Iterable<ConstraintDefinition> getConstraints() { return constraints; } }
false
community_cypher_cypher_src_main_java_org_neo4j_cypher_export_CypherResultSubGraph.java
3,305
@Ignore("Too costly to run by default but useful for testing resource clean up and indexing") public class ManyMergesStressTest { private Random random = new Random(); private String[] SYLLABLES = new String[] { "Om", "Pa", "So", "Hu", "Ma", "Ni", "Ru", "Gu", "Ha", "Ta" }; private final static int TRIES = 8000; @Rule public EmbeddedDatabaseRule dbRule = new EmbeddedDatabaseRule(); @Test public void shouldWorkFine() throws IOException { GraphDatabaseService db = dbRule.getGraphDatabaseService(); Label person = DynamicLabel.label( "Person" ); try ( Transaction tx = db.beginTx() ) { // THIS USED TO CAUSE OUT OF FILE HANDLES // (maybe look at: http://stackoverflow.com/questions/6210348/too-many-open-files-error-on-lucene) db.schema().indexFor( person ).on( "id" ).create(); // THIS SHOULD ALSO WORK // db.schema().constraintFor( person ).on( "id" ).unique().create(); tx.success(); } try ( Transaction tx = db.beginTx() ) { db.schema().indexFor( person ).on( "name" ).create(); tx.success(); } try ( Transaction tx = db.beginTx() ) { db.schema().awaitIndexesOnline( 1, TimeUnit.MINUTES ); tx.success(); } org.neo4j.cypher.javacompat.ExecutionEngine engine = new org.neo4j.cypher.javacompat.ExecutionEngine( db ); for( int count = 0; count < TRIES; count++ ) { Pair<String, String> stringPair = getRandomName(); String ident = stringPair.first(); String name = stringPair.other(); String id = Long.toString( Math.abs( random.nextLong() ) ); String query = format( "MERGE (%s:Person {id: %s}) ON CREATE %s SET %s.name = \"%s\";", ident, id, ident, ident, name ); ExecutionResult result = engine.execute( query ); result.iterator().close(); } } public Pair<String, String> getRandomName() { StringBuilder identBuilder = new StringBuilder(); StringBuilder nameBuilder = new StringBuilder(); for ( int j = 0; j < 10; j++ ) { String part = SYLLABLES[random.nextInt( SYLLABLES.length )]; if ( j != 0 ) { identBuilder.append( '_' ); nameBuilder.append( ' ' ); } identBuilder.append( part ); nameBuilder.append( part ); } return Pair.of( identBuilder.toString(), nameBuilder.toString() ); } }
false
community_cypher_cypher_src_test_java_org_neo4j_cypher_ManyMergesStressTest.java
3,306
SCAN_RESISTANT { @Override public WindowPoolFactory windowPoolFactory( Config config, StringLogger logger ) { return new ScanResistantWindowPoolFactory( config, logger ); } };
false
enterprise_consistency-check_src_main_java_org_neo4j_consistency_store_windowpool_WindowPoolImplementation.java
3,307
MOST_FREQUENTLY_USED { @Override public WindowPoolFactory windowPoolFactory( Config config, StringLogger logger ) { return new DefaultWindowPoolFactory(); } },
false
enterprise_consistency-check_src_main_java_org_neo4j_consistency_store_windowpool_WindowPoolImplementation.java
3,308
class WindowPage extends Page<PersistenceWindow> { public final long firstRecord; public WindowPage( long firstRecord ) { this.firstRecord = firstRecord; } @Override protected void evict(PersistenceWindow window) { window.close(); } @Override protected void hit() { } }
false
enterprise_consistency-check_src_main_java_org_neo4j_consistency_store_windowpool_WindowPage.java
3,309
public class ScanResistantWindowPoolTest { @Test public void shouldMapConsecutiveWindowsWithAppropriateBoundaries() throws Exception { // given int bytesPerRecord = 10; int targetBytesPerPage = 1000; FileMapper fileMapper = mock( FileMapper.class ); ScanResistantWindowPool pool = new ScanResistantWindowPool( new File("storeFileName"), bytesPerRecord, targetBytesPerPage, fileMapper, new StubPageReplacementStrategy(), 100000, mock( MappingStatisticsListener.class ) ); // when pool.acquire( 0, OperationType.READ ); // then verify( fileMapper ).mapWindow( 0, 100, 10 ); // when pool.acquire( 100, OperationType.READ ); // then verify( fileMapper ).mapWindow( 100, 100, 10 ); } @Test public void shouldRejectRecordSizeGreaterThanTargetBytesPerPage() throws Exception { // given int targetBytesPerPage = 4096; int bytesPerRecord = targetBytesPerPage + 1; // when try { new ScanResistantWindowPool( new File("storeFileName"), bytesPerRecord, targetBytesPerPage, mock( FileMapper.class ), mock( PageReplacementStrategy.class ), 100000, mock( MappingStatisticsListener.class ) ); fail( "should have thrown exception" ); } // then catch ( IllegalArgumentException expected ) { // expected } } @Test public void shouldRejectRecordSizeOfZero() throws Exception { // when try { new ScanResistantWindowPool( new File("storeFileName"), 0, 4096, mock( FileMapper.class ), mock( PageReplacementStrategy.class ), 100000, mock( MappingStatisticsListener.class ) ); fail( "should have thrown exception" ); } // then catch ( IllegalArgumentException expected ) { // expected } } @Test public void shouldFailIfFileSizeRequiresMoreThanMaxIntPages() throws Exception { // given int targetBytesPerPage = 1; int bytesPerRecord = 1; FileMapper fileMapper = mock( FileMapper.class ); when( fileMapper.fileSizeInBytes() ).thenReturn( Integer.MAX_VALUE * 2L ); // when try { new ScanResistantWindowPool( new File("storeFileName"), bytesPerRecord, targetBytesPerPage, fileMapper, mock( PageReplacementStrategy.class ), 100000, mock( MappingStatisticsListener.class ) ); fail( "should have thrown exception" ); } // then catch ( IllegalArgumentException expected ) { // expected } } @Test public void shouldRejectWriteOperations() throws Exception { // given int recordSize = 9; int targetBytesPerPage = 4096; ScanResistantWindowPool pool = new ScanResistantWindowPool( new File("storeFileName"), recordSize, targetBytesPerPage, mock( FileMapper.class ), mock( PageReplacementStrategy.class ), 100000, mock( MappingStatisticsListener.class ) ); // when try { pool.acquire( 0, OperationType.WRITE ); fail( "should have thrown exception" ); } // then catch ( UnsupportedOperationException e ) { // expected } } @Test public void closingThePoolShouldCloseAllTheWindows() throws Exception { // given int bytesPerRecord = 10; int targetBytesPerPage = 1000; FileMapper fileMapper = mock( FileMapper.class ); MappedWindow window0 = mock( MappedWindow.class ); when( fileMapper.mapWindow( 0, 100, 10 ) ).thenReturn( window0 ); MappedWindow window1 = mock( MappedWindow.class ); when( fileMapper.mapWindow( 100, 100, 10 ) ).thenReturn( window1 ); ScanResistantWindowPool pool = new ScanResistantWindowPool( new File("storeFileName"), bytesPerRecord, targetBytesPerPage, fileMapper, new StubPageReplacementStrategy(), 100000, mock( MappingStatisticsListener.class ) ); pool.acquire( 0, OperationType.READ ); pool.acquire( 100, OperationType.READ ); // when pool.close(); // then verify( window0 ).close(); verify( window1 ).close(); } }
false
enterprise_consistency-check_src_test_java_org_neo4j_consistency_store_windowpool_ScanResistantWindowPoolTest.java
3,310
{ @Override public void onStatistics( File storeFileName, int acquiredPages, int mappedPages, long samplePeriod ) { // silent } };
false
enterprise_consistency-check_src_main_java_org_neo4j_consistency_store_windowpool_ScanResistantWindowPoolFactory.java
3,311
public class ScanResistantWindowPoolFactory implements WindowPoolFactory { private final int targetBytesPerPage; private final Cart cart; private final int reportingInterval; private final MappingStatisticsListener statisticsListener; public ScanResistantWindowPoolFactory( Config configuration, StringLogger logger ) { this.targetBytesPerPage = pageSize( configuration ); this.cart = new Cart( mappablePages( configuration, targetBytesPerPage ) ); this.reportingInterval = configuration.get( GraphDatabaseSettings.log_mapped_memory_stats_interval ); this.statisticsListener = createStatisticsListener( configuration, logger ); } private static int pageSize( Config configuration ) { long pageSize = configuration.get( GraphDatabaseSettings.mapped_memory_page_size ); if ( pageSize > Integer.MAX_VALUE ) { throw new IllegalArgumentException( format( "configured page size [%d bytes] is too large", pageSize ) ); } return (int) pageSize; } private static int mappablePages( Config configuration, int targetBytesPerPage ) { long bytes = configuration.get( GraphDatabaseSettings.all_stores_total_mapped_memory_size ); long pageCount = bytes / targetBytesPerPage; if ( pageCount > Integer.MAX_VALUE ) { throw new IllegalArgumentException( format( "configured page size [%d bytes] and mapped memory [%d bytes]" + " implies too many pages", targetBytesPerPage, bytes ) ); } return (int) pageCount; } private MappingStatisticsListener createStatisticsListener( Config configuration, StringLogger logger ) { if ( configuration.get( GraphDatabaseSettings.log_mapped_memory_stats ) ) { try { return new LoggingStatisticsListener( configuration.get( GraphDatabaseSettings.log_mapped_memory_stats_filename ) ); } catch ( FileNotFoundException e ) { logger.logMessage( "Unable to create logger for mapped memory statistics; will be silent", e ); } } return new MappingStatisticsListener() { @Override public void onStatistics( File storeFileName, int acquiredPages, int mappedPages, long samplePeriod ) { // silent } }; } @Override public WindowPool create( File storageFileName, int recordSize, StoreChannel fileChannel, Config configuration, StringLogger log ) { try { return new ScanResistantWindowPool( storageFileName, recordSize, targetBytesPerPage, new FileMapper( fileChannel ), cart, reportingInterval, statisticsListener ); } catch ( IOException e ) { throw new UnderlyingStorageException( e ); } } }
false
enterprise_consistency-check_src_main_java_org_neo4j_consistency_store_windowpool_ScanResistantWindowPoolFactory.java
3,312
public class ScanResistantWindowPool implements WindowPool, PageReplacementStrategy.Storage<PersistenceWindow, WindowPage> { private final File storeFileName; private final FileMapper fileMapper; private final PageReplacementStrategy replacementStrategy; private final int bytesPerRecord; private final int recordsPerPage; private final int reportInterval; private final MappingStatisticsListener statisticsListener; private WindowPage[] pages = new WindowPage[0]; private int acquireCount = 0; private int mapCount = 0; public ScanResistantWindowPool( File storeFileName, int bytesPerRecord, int targetBytesPerPage, FileMapper fileMapper, PageReplacementStrategy replacementStrategy, int reportInterval, MappingStatisticsListener statisticsListener ) throws IOException { this.storeFileName = storeFileName; this.bytesPerRecord = bytesPerRecord; this.fileMapper = fileMapper; this.replacementStrategy = replacementStrategy; this.statisticsListener = statisticsListener; this.recordsPerPage = calculateNumberOfRecordsPerPage( bytesPerRecord, targetBytesPerPage ); this.reportInterval = reportInterval; this.setupPages(); } private static int calculateNumberOfRecordsPerPage( int bytesPerRecord, int targetBytesPerPage ) { if ( bytesPerRecord <= 0 || bytesPerRecord > targetBytesPerPage ) { throw new IllegalArgumentException( format( "number of bytes per record [%d] " + "is not in the valid range [1-%d]", bytesPerRecord, targetBytesPerPage ) ); } return targetBytesPerPage / bytesPerRecord; } private void setupPages() throws IOException { // pre-allocate pages that exist already page( fileMapper.fileSizeInBytes() / bytesPerRecord ); } private int pageNumber( long position ) { long pageNumber = position / recordsPerPage; if ( pageNumber + 1 > Integer.MAX_VALUE ) { throw new IllegalArgumentException( format( "Position [record %d] with current page size [%d records/page]" + " implies an impossible page number [%d].", position, recordsPerPage, pageNumber ) ); } return (int) (position / recordsPerPage); } private WindowPage page( long position ) { int pageNumber = pageNumber( position ); if ( pageNumber >= pages.length ) { WindowPage[] newPages = new WindowPage[pageNumber + 1]; System.arraycopy( pages, 0, newPages, 0, pages.length ); for ( int i = pages.length; i < newPages.length; i++ ) { newPages[i] = new WindowPage( i * (long) recordsPerPage ); } pages = newPages; } return pages[pageNumber]; } @Override public PersistenceWindow acquire( long position, OperationType operationType ) { if ( operationType != OperationType.READ ) { throw new UnsupportedOperationException( "Only supports READ operations." ); } try { acquireCount++; return replacementStrategy.acquire( page( position ), this ); } catch ( PageLoadFailureException e ) { throw new UnderlyingStorageException( "Unable to load position[" + position + "] @[" + position * bytesPerRecord + "]", e ); } finally { reportStats(); } } private int lastMapCount; private long lastReportTime = System.currentTimeMillis(); private void reportStats() { if ( acquireCount % reportInterval == 0 ) { int deltaMapCount = mapCount - lastMapCount; lastMapCount = mapCount; long currentTime = System.currentTimeMillis(); long deltaTime = currentTime - lastReportTime; lastReportTime = currentTime; statisticsListener.onStatistics( storeFileName, reportInterval, deltaMapCount, deltaTime ); } } @Override public void release( PersistenceWindow window ) { // we're not using lockable windows, so no action required } @Override public void flushAll() { // current implementation is read-only, so no need to flush } @Override public void close() { for ( WindowPage page : pages ) { replacementStrategy.forceEvict( page ); } } @Override public WindowPoolStats getStats() { return new WindowPoolStats( storeFileName, 0, 0, pages.length, bytesPerRecord * recordsPerPage, acquireCount - mapCount, mapCount, 0, 0, 0, 0, 0 ); } @Override public PersistenceWindow load( WindowPage page ) throws PageLoadFailureException { try { mapCount++; return fileMapper.mapWindow( page.firstRecord, recordsPerPage, bytesPerRecord ); } catch ( IOException e ) { throw new PageLoadFailureException( e ); } } }
false
enterprise_consistency-check_src_main_java_org_neo4j_consistency_store_windowpool_ScanResistantWindowPool.java
3,313
public class MappedWindowTest { @Test public void shouldProvideBufferWithCorrectOffset() throws Exception { // given ByteBuffer byteBuffer = allocateDirect( 150 ); byteBuffer.putInt( 15*5, 42 ); MappedWindow window = new MappedWindow( 10, 15, 100, (MappedByteBuffer) byteBuffer ); // when Buffer buffer = window.getOffsettedBuffer( 105 ); // then assertEquals( 42, buffer.getInt() ); } @Test public void shouldClose() throws Exception { // given // when // then } }
false
enterprise_consistency-check_src_test_java_org_neo4j_consistency_store_windowpool_MappedWindowTest.java
3,314
public class ExecutionResult implements ResourceIterable<Map<String,Object>> { private org.neo4j.cypher.ExecutionResult inner; /** * Constructor used by the Cypher framework. End-users should not * create an ExecutionResult directly, but instead use the result * returned from calling {@link ExecutionEngine#execute(String)}. * * @param projection */ public ExecutionResult( org.neo4j.cypher.ExecutionResult projection ) { inner = projection; } /** * Returns an iterator with the result objects from a single column of the result set. This method is best used for * single column results. * * <p><b>To ensure that any resources, including transactions bound to it, are properly closed, the iterator must * either be fully exhausted, or the {@link org.neo4j.graphdb.ResourceIterator#close() close()} method must be * called.</b></p> * * @param n exact name of the column, as it appeared in the original query * @param <T> desired type cast for the result objects * @return an iterator of the result objects, possibly empty * @throws ClassCastException when the result object can not be cast to the requested type * @throws org.neo4j.graphdb.NotFoundException when the column name does not appear in the original query */ public <T> ResourceIterator<T> columnAs( String n ) { return inner.javaColumnAs( n ); } /** * The exact names used to represent each column in the result set. * * @return List of the column names. */ public List<String> columns() { return inner.javaColumns(); } @Override public String toString() { return inner.toString(); } /** * Provides a textual representation of the query result. * <p><b> * The execution result represented by this object will be consumed in its entirety after this method is called. * Calling any of the other iterating methods on it should not be expected to return any results. * </b></p> * @return Returns the execution result */ public String dumpToString() { return inner.dumpToString(); } /** * Returns statistics about this result. * @return statistics about this result */ public QueryStatistics getQueryStatistics() { return new QueryStatistics( inner.queryStatistics() ); } /** * Returns a string representation of the query plan used to produce this result. * @return a string representation of the query plan used to produce this result. */ public PlanDescription executionPlanDescription() { return inner.executionPlanDescription().asJava(); } public void toString( PrintWriter writer ) { inner.dumpToString( writer ); } /** * Returns an iterator over the <i>return</i> clause of the query. The format is a map that has as keys the names * of the columns or their explicit names (set via 'as') and the value is the calculated value. Each iterator item * is one row of the query result. * * <p><b>To ensure that any resources, including transactions bound to it, are properly closed, the iterator must * either be fully exhausted, or the {@link org.neo4j.graphdb.ResourceIterator#close() close()} method must be * called.</b></p> * * @return An iterator over the result of the query as a map from projected column name to value */ @Override public ResourceIterator<Map<String, Object>> iterator() { return inner.javaIterator(); } }
false
community_cypher_cypher_src_main_java_org_neo4j_cypher_javacompat_ExecutionResult.java
3,315
public class ExecutionResultTest { private GraphDatabaseAPI db; private ExecutionEngine engine; @Before public void setUp() throws Exception { db = (GraphDatabaseAPI) new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder() .newGraphDatabase(); engine = new ExecutionEngine( db ); } @Test public void shouldCloseTransactionsWhenIteratingResults() throws Exception { // Given an execution result that has been started but not exhausted createNode(); createNode(); ExecutionResult executionResult = engine.execute( "MATCH (n) RETURN n" ); ResourceIterator<Map<String, Object>> resultIterator = executionResult.iterator(); resultIterator.next(); assertThat( activeTransaction(), is( notNullValue() ) ); // When resultIterator.close(); // Then assertThat( activeTransaction(), is( nullValue() ) ); } @Test public void shouldCloseTransactionsWhenIteratingOverSingleColumn() throws Exception { // Given an execution result that has been started but not exhausted createNode(); createNode(); ExecutionResult executionResult = engine.execute( "MATCH (n) RETURN n" ); ResourceIterator<Node> resultIterator = executionResult.columnAs("n"); resultIterator.next(); assertThat( activeTransaction(), is( notNullValue() ) ); // When resultIterator.close(); // Then assertThat( activeTransaction(), is( nullValue() ) ); } private void createNode() { try ( Transaction tx = db.beginTx() ) { db.createNode(); tx.success(); } } private javax.transaction.Transaction activeTransaction() throws SystemException { TransactionManager txManager = db.getDependencyResolver().resolveDependency( TransactionManager.class ); return txManager.getTransaction(); } }
false
community_cypher_cypher_src_test_java_org_neo4j_cypher_javacompat_ExecutionResultTest.java
3,316
public class GraphImpl implements Graph { private final String[] value; public GraphImpl(String[] value){ this.value = value; } @Override public Class<? extends Annotation> annotationType() { return null; } @Override public String[] value() { return value; } @Override public NODE[] nodes() { return new NODE[]{}; } @Override public REL[] relationships() { return new REL[]{}; } @Override public boolean autoIndexNodes() { return true; } @Override public boolean autoIndexRelationships() { return true; } }
false
community_cypher_cypher_src_test_java_org_neo4j_cypher_javacompat_GraphImpl.java
3,317
public class DarwinInstallation extends UnixInstallation { @Override protected File getDefaultDirectory() { // cf. http://stackoverflow.com/questions/567874/how-do-i-find-the-users-documents-folder-with-java-in-os-x return new File( new File( System.getProperty( "user.home" ) ), "Documents" ); } }
false
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_config_osx_DarwinInstallation.java
3,318
class VariableSubstitutor { private static final Pattern DEFAULT_PATTERN = Pattern.compile( "\\$\\{([^\\}]+)\\}" ); private final Pattern pattern; public VariableSubstitutor( Pattern pattern ) { this.pattern = pattern; } public VariableSubstitutor() { this( DEFAULT_PATTERN ); } public String substitute( String input, Function<String, String> substitutionFunction ) { if ( input.length() == 0 ) { return ""; } StringBuilder result = new StringBuilder( ); Matcher matcher = pattern.matcher( input ); int cur = 0; while (matcher.find( cur )) { result.append( input.substring( cur, matcher.start() ) ); result.append( substitutionFunction.apply( matcher.group( 1 ) ) ); cur = matcher.end(); } if ( cur < input.length() ) { result.append( input.substring( cur ) ); } return result.toString(); } }
false
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_config_portable_VariableSubstitutor.java
3,319
{ @Override public String apply( String name ) { String var = System.getenv( name ); return var == null ? "" : var; } };
false
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_config_portable_Template.java
3,320
public class Template { private final InputStream templateFile; private final VariableSubstitutor substitutor; private Function<String, String> substitutionFunction; public Template( InputStream templateFile ) { this.templateFile = templateFile; substitutor = new VariableSubstitutor(); substitutionFunction = new Function<String, String>() { @Override public String apply( String name ) { String var = System.getenv( name ); return var == null ? "" : var; } }; } public void write( File file ) throws Exception { try ( BufferedReader reader = new BufferedReader( new InputStreamReader( templateFile, "UTF-8" ) ); PrintWriter writer = new PrintWriter( file )) { String input = reader.readLine(); while ( input != null ) { String output = substitutor.substitute( input, substitutionFunction ); if ( output == null ) { continue; } writer.println( output ); input = reader.readLine(); } } } }
false
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_config_portable_Template.java
3,321
private static class PathAlreadyExistException extends RuntimeException { public PathAlreadyExistException( File path, String description ) { super( format( "%s already exists but is not a %s.", description, path.getAbsolutePath() ) ); } }
false
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_config_portable_PortableInstallation.java
3,322
private static class CannotMakeDirectory extends RuntimeException { public CannotMakeDirectory( File path, String description ) { super( format( "Could not make %s %s", description, path.getAbsolutePath() ) ); } }
false
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_config_portable_PortableInstallation.java
3,323
private static class CannotFindInstallationDirectory extends RuntimeException { public CannotFindInstallationDirectory( Exception cause ) { super( cause ); } }
false
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_config_portable_PortableInstallation.java
3,324
public abstract class PortableInstallation implements Installation { protected void mkdirs( File path, String description ) { if ( path.exists() ) { if ( !path.isDirectory() ) { throw new PathAlreadyExistException( path, description ); } } else if ( !path.mkdirs() ) { throw new CannotMakeDirectory( path, description ); } } @Override public File getPluginsDirectory() { try { File installationDirectory = getInstallationDirectory(); return new File( installationDirectory, "plugins" ); } catch ( URISyntaxException e ) { throw new CannotFindInstallationDirectory( e ); } } @Override public File getInstallationDirectory() throws URISyntaxException { return getInstallationBinDirectory().getParentFile(); } @Override public File getInstallationBinDirectory() throws URISyntaxException { File appFile = new File( Installation.class.getProtectionDomain().getCodeSource().getLocation().toURI() ); return appFile.getParentFile(); } private static class PathAlreadyExistException extends RuntimeException { public PathAlreadyExistException( File path, String description ) { super( format( "%s already exists but is not a %s.", description, path.getAbsolutePath() ) ); } } private static class CannotMakeDirectory extends RuntimeException { public CannotMakeDirectory( File path, String description ) { super( format( "Could not make %s %s", description, path.getAbsolutePath() ) ); } } private static class CannotFindInstallationDirectory extends RuntimeException { public CannotFindInstallationDirectory( Exception cause ) { super( cause ); } } @Override public File getDatabaseDirectory() { List<File> locations = new ArrayList<>(); File defaultDirectory = getDefaultDirectory(); File userHome = new File( System.getProperty( "user.home" ) ); File userDir = new File( System.getProperty( "user.dir" ) ); locations.add( defaultDirectory ); locations.add( userHome ); File documents = selectFirstWritableDirectoryOrElse( locations, userDir ); File neo4jData = new File( documents, "Neo4j" ); File graphdb = new File( neo4jData, "default.graphdb" ); mkdirs( graphdb, "Neo4j data directory" ); return graphdb; } protected abstract File getDefaultDirectory(); private static File selectFirstWritableDirectoryOrElse( List<File> locations, File defaultFile ) { File result = defaultFile.getAbsoluteFile(); for ( File file : locations ) { File candidateFile = file.getAbsoluteFile(); if ( candidateFile.exists() && candidateFile.isDirectory() && candidateFile.canWrite() ) { result = candidateFile; break; } } return result; } @Override public File getDatabaseConfigurationFile() { return new File( getDatabaseDirectory(), NEO4J_PROPERTIES_FILENAME ); } @Override public void initialize() throws Exception { File vmopts = getVmOptionsFile(); if ( !vmopts.exists() ) { createVmOptionsFile( vmopts ); } } private void createVmOptionsFile( File file ) throws Exception { Template template = new Template( getDefaultVmOptions() ); template.write( file ); } @Override public InputStream getDefaultDatabaseConfiguration() { return getResourceStream( DEFAULT_DATABASE_CONFIG_RESOURCE_NAME ); } @Override public InputStream getDefaultServerConfiguration() { return getResourceStream( DEFAULT_SERVER_CONFIG_RESOURCE_NAME ); } @Override public InputStream getDefaultVmOptions() { return getResourceStream( DEFAULT_VMOPTIONS_TEMPLATE_RESOURCE_NAME ); } private InputStream getResourceStream( String defaultDatabaseConfigResourceName ) { return PortableInstallation.class.getResourceAsStream( defaultDatabaseConfigResourceName ); } }
false
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_config_portable_PortableInstallation.java
3,325
public abstract class PortableEnvironment implements Environment { protected void portableEditFile( File file ) throws IOException { if ( !file.exists() ) { file.createNewFile(); } getDesktop().edit( file ); } protected boolean isPortableEditFileSupported() { return desktopSupports( Desktop.Action.EDIT ); } protected boolean desktopSupports( Desktop.Action action ) { return isDesktopSupported() && getDesktop().isSupported( action ); } protected boolean isPortableBrowseSupported() { return desktopSupports( Desktop.Action.BROWSE ); } protected void portableBrowse( String link ) throws IOException, URISyntaxException { getDesktop().browse( new URI( link ) ); } protected boolean isPortableOpenSupported() { return desktopSupports( Desktop.Action.OPEN ); } protected void portableOpen( File file ) throws IOException { getDesktop().open( file ); } }
false
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_config_portable_PortableEnvironment.java
3,326
{ @Override public void run() { databaseActions.stop(); } } );
false
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_Neo4jDesktop.java
3,327
public class IntroDocTest implements GraphHolder { private static final String DOCS_TARGET = "target/docs/dev/general/"; public @Rule TestData<JavaTestDocsGenerator> gen = TestData.producedThrough( JavaTestDocsGenerator.PRODUCER ); public @Rule TestData<Map<String, Node>> data = TestData.producedThrough( GraphDescription.createGraphFor( this, true ) ); private static ImpermanentGraphDatabase graphdb; private static ExecutionEngine engine; @Test @Graph( value = { "John friend Sara", "John friend Joe", "Sara friend Maria", "Joe friend Steve" }, autoIndexNodes = true ) public void intro_examples() throws Exception { try ( Transaction ignored = graphdb.beginTx() ) { Writer fw = AsciiDocGenerator.getFW( DOCS_TARGET, gen.get().getTitle() ); data.get(); fw.append( "\nImagine an example graph like the following one:\n\n" ); fw.append( AsciiDocGenerator.dumpToSeparateFileWithType( new File( DOCS_TARGET ), "intro.graph", AsciidocHelper.createGraphVizWithNodeId( "Example Graph", graphdb(), "cypher-intro" ) ) ); fw.append( "\nFor example, here is a query which finds a user called John and John's friends (though not " + "his direct friends) before returning both John and any friends-of-friends that are found." ); fw.append( "\n\n" ); String query = "MATCH (john {name: 'John'})-[:friend]->()-[:friend]->(fof) RETURN john, fof "; fw.append( AsciiDocGenerator.dumpToSeparateFileWithType( new File( DOCS_TARGET ), "intro.query", createCypherSnippet( query ) ) ); fw.append( "\nResulting in:\n\n" ); fw.append( AsciiDocGenerator.dumpToSeparateFileWithType( new File( DOCS_TARGET ), "intro.result", createQueryResultSnippet( engine.execute( query ).dumpToString() ) ) ); fw.append( "\nNext up we will add filtering to set more parts " + "in motion:\n\nWe take a list of user names " + "and find all nodes with names from this list, match their friends and return " + "only those followed users who have a +name+ property starting with +S+." ); query = "MATCH (user)-[:friend]->(follower) WHERE " + "user.name IN ['Joe', 'John', 'Sara', 'Maria', 'Steve'] AND follower.name =~ 'S.*' " + "RETURN user, follower.name "; fw.append( "\n\n" ); fw.append( AsciiDocGenerator.dumpToSeparateFileWithType( new File( DOCS_TARGET ), "intro.query", createCypherSnippet( query ) ) ); fw.append( "\nResulting in:\n\n" ); fw.append( AsciiDocGenerator.dumpToSeparateFileWithType( new File( DOCS_TARGET ), "intro.result", createQueryResultSnippet( engine.execute( query ).dumpToString() ) ) ); fw.close(); } } @BeforeClass public static void setup() throws IOException { graphdb = (ImpermanentGraphDatabase)new TestGraphDatabaseFactory().newImpermanentDatabase(); graphdb.cleanContent(); engine = new ExecutionEngine( graphdb ); } @AfterClass public static void shutdown() { try { if ( graphdb != null ) graphdb.shutdown(); } finally { graphdb = null; } } @Override public GraphDatabaseService graphdb() { return graphdb; } }
false
community_cypher_cypher-docs_src_test_java_org_neo4j_cypher_javacompat_IntroDocTest.java
3,328
public final class Neo4jDesktop { public static void main( String[] args ) { preStartInitialize(); Neo4jDesktop app = new Neo4jDesktop(); app.start(); } public static void preStartInitialize() { PlatformUI.selectPlatformUI(); DesktopIdentification.register(); } private void start() { try { Installation installation = getInstallation(); installation.initialize(); DesktopModel model = new DesktopModel( installation ); DatabaseActions databaseActions = new DatabaseActions( model ); addShutdownHook( databaseActions ); MainWindow window = new MainWindow( databaseActions, model ); window.display(); } catch ( Exception e ) { alert( e.getMessage() ); e.printStackTrace( System.out ); } } private Installation getInstallation() throws Exception { switch ( OperatingSystemFamily.detect() ) { case WINDOWS: return new WindowsInstallation(); case MAC_OS: return new DarwinInstallation(); case UNIX: return new UnixInstallation(); } return new UnixInstallation(); // This is the most generic one, presumably. } protected void addShutdownHook( final DatabaseActions databaseActions ) { Runtime.getRuntime() .addShutdownHook( new Thread() { @Override public void run() { databaseActions.stop(); } } ); } }
false
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_Neo4jDesktop.java
3,329
public final class DesktopIdentification { /** * Register Desktop as the means by which Neo4j was launched. This information is collected by UDC. * @see org.neo4j.ext.udc.UdcConstants#UDC_PROPERTY_PREFIX */ public static void register() { System.setProperty( "neo4j.ext.udc.launcher", "desktop" ); } }
false
packaging_neo4j-desktop_src_main_java_org_neo4j_desktop_DesktopIdentification.java
3,330
public class RegularExpressionMatcher extends TypeSafeMatcher<String> { private final Pattern pattern; public RegularExpressionMatcher( String pattern ) { this( Pattern.compile( pattern ) ); } public RegularExpressionMatcher( Pattern pattern ) { this.pattern = pattern; } @Override public void describeTo( Description description ) { description.appendText( "matches regular expression " ).appendValue( pattern ); } @Override public boolean matchesSafely( String item ) { return pattern.matcher( item ).find(); } @Factory public static Matcher matchesPattern( Pattern pattern ) { return new RegularExpressionMatcher( pattern ); } @Factory public static Matcher matchesPattern( String pattern ) { return new RegularExpressionMatcher( pattern ); } }
false
community_cypher_cypher_src_test_java_org_neo4j_cypher_javacompat_RegularExpressionMatcher.java
3,331
public class QueryStatistics { private final org.neo4j.cypher.QueryStatistics inner; QueryStatistics( org.neo4j.cypher.QueryStatistics inner ) { this.inner = inner; } /** * Returns the number of nodes created by this query. * @return the number of nodes created by this query. */ public int getNodesCreated() { return inner.nodesCreated(); } /** * Returns the number of relationships created by this query. * @return the number of relationships created by this query. */ public int getRelationshipsCreated() { return inner.relationshipsCreated(); } /** * Returns the number of properties set by this query. Setting a property to the same value again still counts towards this. * @return the number of properties set by this query. */ public int getPropertiesSet() { return inner.propertiesSet(); } /** * Returns the number of nodes deleted by this query. * @return the number of nodes deleted by this query. */ public int getDeletedNodes() { return inner.nodesDeleted(); } /** * Returns the number of relationships deleted by this query. * @return the number of relationships deleted by this query. */ public int getDeletedRelationships() { return inner.relationshipsDeleted(); } /** * Returns the number of labels added to any node by this query. * @return the number of labels added to any node by this query. */ public int getLabelsAdded() { return inner.labelsAdded(); } /** * Returns the number of labels removed from any node by this query. * @return the number of labels removed from any node by this query. */ public int getLabelsRemoved() { return inner.labelsRemoved(); } /** * Returns the number of indexes added by this query. * @return the number of indexes added by this query. */ public int getIndexesAdded() { return inner.indexesAdded(); } /** * Returns the number of indexes removed by this query. * @return the number of indexes removed by this query. */ public int getIndexesRemoved() { return inner.indexesRemoved(); } /** * Returns the number of constraint added by this query. * @return the number of constraint added by this query. */ public int getConstraintsAdded() { return inner.constraintsAdded(); } /** * Returns the number of constraint removed by this query. * @return the number of constraint removed by this query. */ public int getConstraintsRemoved() { return inner.constraintsRemoved(); } /** * If the query updated the graph in any way, this method will return true. * @return if the graph has been updated. */ public boolean containsUpdates() { return inner.containsUpdates(); } @Override public String toString() { return inner.toString(); } }
false
community_cypher_cypher_src_main_java_org_neo4j_cypher_javacompat_QueryStatistics.java
3,332
public class JavaQueryDocTest { @Test public void test() { JavaDocsGenerator gen = new JavaDocsGenerator( "java-cypher-queries", "dev/java" ); JavaQuery jq = new JavaQuery(); jq.run(); assertTrue( jq.columnsString.contains( "n," ) ); assertTrue( jq.columnsString.contains( "n.name" ) ); assertTrue( jq.resultString.contains( "Node[" ) ); assertTrue( jq.resultString.contains( "name" ) ); assertTrue( jq.resultString.contains( "my" ) ); assertTrue( jq.resultString.contains( "1 row" ) ); assertTrue( jq.nodeResult.contains( "Node[" ) ); assertTrue( jq.nodeResult.contains( "my" ) ); assertTrue( jq.rows.contains( "n.name: my node; n: Node[" ) ); assertTrue( jq.rows.contains( "];" ) ); gen.saveToFile( "result", AsciidocHelper.createOutputSnippet( jq.resultString ) ); gen.saveToFile( "columns", AsciidocHelper.createOutputSnippet( jq.columnsString ) ); gen.saveToFile( "node", AsciidocHelper.createOutputSnippet( jq.nodeResult ) ); gen.saveToFile( "rows", AsciidocHelper.createOutputSnippet( jq.rows ) ); } }
false
community_cypher_cypher-docs_src_test_java_org_neo4j_cypher_javacompat_JavaQueryDocTest.java
3,333
public class JavaQuery { private static final String DB_PATH = "target/java-query-db"; String resultString; String columnsString; String nodeResult; String rows = ""; public static void main( String[] args ) { JavaQuery javaQuery = new JavaQuery(); javaQuery.run(); } void run() { clearDbPath(); // START SNIPPET: addData GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase( DB_PATH ); try ( Transaction tx = db.beginTx(); ) { Node myNode = db.createNode(); myNode.setProperty( "name", "my node" ); tx.success(); } // END SNIPPET: addData // START SNIPPET: execute ExecutionEngine engine = new ExecutionEngine( db ); ExecutionResult result; try ( Transaction ignored = db.beginTx() ) { result = engine.execute( "start n=node(*) where n.name = 'my node' return n, n.name" ); // END SNIPPET: execute // START SNIPPET: items Iterator<Node> n_column = result.columnAs( "n" ); for ( Node node : IteratorUtil.asIterable( n_column ) ) { // note: we're grabbing the name property from the node, // not from the n.name in this case. nodeResult = node + ": " + node.getProperty( "name" ); } // END SNIPPET: items } // START SNIPPET: columns List<String> columns = result.columns(); // END SNIPPET: columns // the result is now empty, get a new one result = engine.execute( "start n=node(*) where n.name = 'my node' return n, n.name" ); // START SNIPPET: rows for ( Map<String, Object> row : result ) { for ( Entry<String, Object> column : row.entrySet() ) { rows += column.getKey() + ": " + column.getValue() + "; "; } rows += "\n"; } // END SNIPPET: rows resultString = engine.execute( "start n=node(*) where n.name = 'my node' return n, n.name" ).dumpToString(); columnsString = columns.toString(); db.shutdown(); } private void clearDbPath() { try { deleteRecursively( new File( DB_PATH ) ); } catch ( IOException e ) { throw new RuntimeException( e ); } } }
false
community_cypher_cypher-docs_src_test_java_org_neo4j_cypher_javacompat_JavaQuery.java
3,334
public class JavaExecutionEngineDocTest { private static final ObjectMapper MAPPER = new ObjectMapper(); private static final ObjectWriter WRITER = MAPPER.writerWithDefaultPrettyPrinter(); private static final File docsTargetDir = new File( "target/docs/dev/general" ); private GraphDatabaseService db; private ExecutionEngine engine; private Node andreasNode; private Node johanNode; private Node michaelaNode; @BeforeClass public static void prepare() { docsTargetDir.mkdirs(); } @SuppressWarnings("deprecation") @Before public void setUp() throws IOException { db = new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().newGraphDatabase(); engine = new ExecutionEngine( db ); Transaction tx = db.beginTx(); michaelaNode = db.createNode(); andreasNode = db.createNode(); johanNode = db.createNode(); andreasNode.setProperty( "name", "Andreas" ); johanNode.setProperty( "name", "Johan" ); michaelaNode.setProperty( "name", "Michaela" ); index( andreasNode ); index( johanNode ); index( michaelaNode ); tx.success(); tx.finish(); } @After public void shutdownDb() { if ( db != null ) { db.shutdown(); } db = null; } private void index( Node n ) { db.index().forNodes( "people" ).add( n, "name", n.getProperty( "name" ) ); } public static String parametersToAsciidoc( final Object params ) throws JsonGenerationException, JsonMappingException, IOException { StringBuffer sb = new StringBuffer( 2048 ); String prettifiedJson = WRITER.writeValueAsString( params ); sb.append( "\n.Parameters\n[source,javascript]\n----\n" ) .append( prettifiedJson ) .append( "\n----\n\n" ); return sb.toString(); } private void dumpToFile( final String id, final String query, final Object params ) throws Exception { StringBuffer sb = new StringBuffer( 2048 ); String prettifiedJson = WRITER.writeValueAsString( params ); sb.append( "\n.Parameters\n[source,javascript]\n----\n" ) .append( prettifiedJson ) .append( "\n----\n\n.Query\n" ) .append( AsciidocHelper.createAsciiDocSnippet( "cypher", engine.prettify( query ) ) ); AsciiDocGenerator.dumpToSeparateFile( docsTargetDir, id, sb.toString() ); } @Test public void exampleQuery() throws Exception { // START SNIPPET: JavaQuery ExecutionEngine engine = new ExecutionEngine( db ); ExecutionResult result = engine.execute( "START n=node(0) WHERE 1=1 RETURN n" ); assertThat( result.columns(), hasItem( "n" ) ); Iterator<Node> n_column = result.columnAs( "n" ); assertThat( asIterable( n_column ), hasItem( db.getNodeById( 0 ) ) ); // END SNIPPET: JavaQuery } @Test public void shouldBeAbleToEmitJavaIterables() throws Exception { makeFriends( michaelaNode, andreasNode ); makeFriends( michaelaNode, johanNode ); ExecutionEngine engine = new ExecutionEngine( db ); ExecutionResult result = engine.execute( "START n=node(0) MATCH n-->friend RETURN collect(friend)" ); Iterable<Node> friends = (Iterable<Node>) result.columnAs( "collect(friend)" ).next(); assertThat( friends, hasItems( andreasNode, johanNode ) ); assertThat( friends, instanceOf( Iterable.class ) ); } @Test public void testColumnAreInTheRightOrder() throws Exception { createTenNodes(); String q = "start one=node(1), two=node(2), three=node(3), four=node(4), five=node(5), six=node(6), " + "seven=node(7), eight=node(8), nine=node(9), ten=node(10) " + "return one, two, three, four, five, six, seven, eight, nine, ten"; ExecutionResult result = engine.execute( q ); assertThat( result.dumpToString(), matchesPattern( "one.*two.*three.*four.*five.*six.*seven.*eight.*nine.*ten" ) ); } private void createTenNodes() { try ( Transaction tx = db.beginTx() ) { for ( int i = 0; i < 10; i++ ) { db.createNode(); } tx.success(); } } @Test public void exampleWithParameterForNodeId() throws Exception { // START SNIPPET: exampleWithParameterForNodeId Map<String, Object> params = new HashMap<String, Object>(); params.put( "id", 0 ); String query = "START n=node({id}) RETURN n.name"; ExecutionResult result = engine.execute( query, params ); // END SNIPPET: exampleWithParameterForNodeId assertThat( result.columns(), hasItem( "n.name" ) ); Iterator<Object> n_column = result.columnAs( "n.name" ); assertEquals( "Michaela", n_column.next() ); dumpToFile( "exampleWithParameterForNodeId", query, params ); } @Test public void exampleWithParameterForMultipleNodeIds() throws Exception { // START SNIPPET: exampleWithParameterForMultipleNodeIds Map<String, Object> params = new HashMap<String, Object>(); params.put( "id", Arrays.asList( 0, 1, 2 ) ); String query = "START n=node({id}) RETURN n.name"; ExecutionResult result = engine.execute( query, params ); // END SNIPPET: exampleWithParameterForMultipleNodeIds assertEquals( asList( "Michaela", "Andreas", "Johan" ), this.<String>toList( result, "n.name" ) ); dumpToFile( "exampleWithParameterForMultipleNodeIds", query, params ); } private <T> List<T> toList( ExecutionResult result, String column ) { List<T> results = new ArrayList<T>(); IteratorUtil.addToCollection( result.<T>columnAs( column ), results ); return results; } @Test public void exampleWithStringLiteralAsParameter() throws Exception { // START SNIPPET: exampleWithStringLiteralAsParameter Map<String, Object> params = new HashMap<String, Object>(); params.put( "name", "Johan" ); String query = "MATCH (n) WHERE n.name = {name} RETURN n"; ExecutionResult result = engine.execute( query, params ); // END SNIPPET: exampleWithStringLiteralAsParameter assertEquals( asList( johanNode ), this.<Node>toList( result, "n" ) ); dumpToFile( "exampleWithStringLiteralAsParameter", query, params ); } @Test public void exampleWithParameterForIndexValue() throws Exception { try ( Transaction ignored = db.beginTx() ) { // START SNIPPET: exampleWithParameterForIndexValue Map<String, Object> params = new HashMap<String, Object>(); params.put( "value", "Michaela" ); String query = "START n=node:people(name = {value}) RETURN n"; ExecutionResult result = engine.execute( query, params ); // END SNIPPET: exampleWithParameterForIndexValue assertEquals( asList( michaelaNode ), this.<Node>toList( result, "n" ) ); dumpToFile( "exampleWithParameterForIndexValue", query, params ); } } @Test public void exampleWithParametersForQuery() throws Exception { try ( Transaction ignored = db.beginTx() ) { // START SNIPPET: exampleWithParametersForQuery Map<String, Object> params = new HashMap<String, Object>(); params.put( "query", "name:Andreas" ); String query = "START n=node:people({query}) RETURN n"; ExecutionResult result = engine.execute( query, params ); // END SNIPPET: exampleWithParametersForQuery assertEquals( asList( andreasNode ), this.<Node>toList( result, "n" ) ); dumpToFile( "exampleWithParametersForQuery", query, params ); } } @Test public void exampleWithParameterForNodeObject() throws Exception { // START SNIPPET: exampleWithParameterForNodeObject Map<String, Object> params = new HashMap<String, Object>(); params.put( "node", andreasNode ); String query = "START n=node({node}) RETURN n.name"; ExecutionResult result = engine.execute( query, params ); // END SNIPPET: exampleWithParameterForNodeObject assertThat( result.columns(), hasItem( "n.name" ) ); Iterator<Object> n_column = result.columnAs( "n.name" ); assertEquals( "Andreas", n_column.next() ); } @Test public void exampleWithParameterForSkipAndLimit() throws Exception { // START SNIPPET: exampleWithParameterForSkipLimit Map<String, Object> params = new HashMap<String, Object>(); params.put( "s", 1 ); params.put( "l", 1 ); String query = "MATCH (n) RETURN n.name SKIP {s} LIMIT {l}"; ExecutionResult result = engine.execute( query, params ); // END SNIPPET: exampleWithParameterForSkipLimit assertThat( result.columns(), hasItem( "n.name" ) ); Iterator<Object> n_column = result.columnAs( "n.name" ); assertEquals( "Andreas", n_column.next() ); dumpToFile( "exampleWithParameterForSkipLimit", query, params ); } @Test public void exampleWithParameterRegularExpression() throws Exception { // START SNIPPET: exampleWithParameterRegularExpression Map<String, Object> params = new HashMap<String, Object>(); params.put( "regex", ".*h.*" ); String query = "MATCH (n) WHERE n.name =~ {regex} RETURN n.name"; ExecutionResult result = engine.execute( query, params ); // END SNIPPET: exampleWithParameterRegularExpression dumpToFile( "exampleWithParameterRegularExpression", query, params ); assertThat( result.columns(), hasItem( "n.name" ) ); Iterator<Object> n_column = result.columnAs( "n.name" ); assertEquals( "Michaela", n_column.next() ); assertEquals( "Johan", n_column.next() ); } @Test public void create_node_from_map() throws Exception { // START SNIPPET: create_node_from_map Map<String, Object> props = new HashMap<String, Object>(); props.put( "name", "Andres" ); props.put( "position", "Developer" ); Map<String, Object> params = new HashMap<String, Object>(); params.put( "props", props ); String query = "CREATE ({props})"; engine.execute( query, params ); // END SNIPPET: create_node_from_map dumpToFile( "create_node_from_map", query, params ); ExecutionResult result = engine.execute( "match (n) where n.name = 'Andres' and n.position = 'Developer' return n" ); assertThat( count( result ), is( 1 ) ); } @Test public void create_multiple_nodes_from_map() throws Exception { // START SNIPPET: create_multiple_nodes_from_map Map<String, Object> n1 = new HashMap<String, Object>(); n1.put( "name", "Andres" ); n1.put( "position", "Developer" ); n1.put( "awesome", true ); Map<String, Object> n2 = new HashMap<String, Object>(); n2.put( "name", "Michael" ); n2.put( "position", "Developer" ); n2.put( "children", 3 ); Map<String, Object> params = new HashMap<String, Object>(); List<Map<String, Object>> maps = Arrays.asList( n1, n2 ); params.put( "props", maps ); String query = "CREATE (n:Person {props}) RETURN n"; engine.execute( query, params ); // END SNIPPET: create_multiple_nodes_from_map dumpToFile( "create_multiple_nodes_from_map", query, params ); ExecutionResult result = engine.execute( "match (n:Person) where n.name in ['Andres', 'Michael'] and n.position = 'Developer' return n" ); assertThat( count( result ), is( 2 ) ); result = engine.execute( "match (n:Person) where n.children = 3 return n" ); assertThat( count( result ), is( 1 ) ); result = engine.execute( "match (n:Person) where n.awesome = true return n" ); assertThat( count( result ), is( 1 ) ); } @Test public void set_properties_on_a_node_from_a_map() throws Exception { try(Transaction tx = db.beginTx()) { // START SNIPPET: set_properties_on_a_node_from_a_map Map<String, Object> n1 = new HashMap<>(); n1.put( "name", "Andres" ); n1.put( "position", "Developer" ); Map<String, Object> params = new HashMap<>(); params.put( "props", n1 ); String query = "MATCH (n) WHERE n.name='Michaela' SET n = {props}"; engine.execute( query, params ); // END SNIPPET: set_properties_on_a_node_from_a_map dumpToFile( "set_properties_on_a_node_from_a_map", query, params ); engine.execute( "match (n) where n.name in ['Andres', 'Michael'] and n.position = 'Developer' return n" ); assertThat( michaelaNode.getProperty( "name" ).toString(), is( "Andres" ) ); } } @Test public void create_node_using_create_unique_with_java_maps() throws Exception { Map<String, Object> props = new HashMap<String, Object>(); props.put( "name", "Andres" ); props.put( "position", "Developer" ); Map<String, Object> params = new HashMap<String, Object>(); params.put( "props", props ); String query = "START n=node(0) CREATE UNIQUE p = n-[:REL]->({props}) RETURN last(nodes(p)) AS X"; ExecutionResult result = engine.execute( query, params ); assertThat( count( result ), is( 1 ) ); } @Test public void should_be_able_to_handle_two_params_without_named_nodes() throws Exception { Map<String, Object> props1 = new HashMap<String, Object>(); props1.put( "name", "Andres" ); props1.put( "position", "Developer" ); Map<String, Object> props2 = new HashMap<String, Object>(); props2.put( "name", "Lasse" ); props2.put( "awesome", "true" ); Map<String, Object> params = new HashMap<String, Object>(); params.put( "props1", props1 ); params.put( "props2", props2 ); String query = "START n=node(0) CREATE UNIQUE p = n-[:REL]->({props1})-[:LER]->({props2}) RETURN p"; ExecutionResult result = engine.execute( query, params ); assertThat( count( result ), is( 1 ) ); } @Test public void prettifier_makes_pretty() throws Exception { String given = "match (n)-->() return n"; String expected = String.format("MATCH (n)-->()%nRETURN n"); assertEquals(expected, engine.prettify(given)); } private void makeFriends( Node a, Node b ) { try ( Transaction tx = db.beginTx() ) { a.createRelationshipTo( b, DynamicRelationshipType.withName( "friend" ) ); tx.success(); } } }
false
community_cypher_cypher-docs_src_test_java_org_neo4j_cypher_javacompat_JavaExecutionEngineDocTest.java
3,335
public class JavaCompatibilityTest { private GraphDatabaseService db; private ExecutionEngine engine; @Before public void setUp() throws IOException { db = new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().newGraphDatabase(); engine = new ExecutionEngine( db ); } @Test public void collections_in_collections_look_aiight() throws Exception { ExecutionResult execute = engine.execute( "CREATE (n:TheNode) RETURN [[ [1,2],[3,4] ],[[5,6]]] as x" ); Map<String, Object> next = execute.iterator().next(); List<List<Object>> x = (List<List<Object>>)next.get( "x" ); Iterable objects = x.get( 0 ); assertThat(objects, isA(Iterable.class)); } }
false
community_cypher_cypher_src_test_java_org_neo4j_cypher_javacompat_JavaCompatibilityTest.java
3,336
public class Dijkstra<CostType> implements SingleSourceSingleSinkShortestPath<CostType> { protected CostType startCost; // starting cost for both the start node and // the end node protected Node startNode, endNode; protected RelationshipType[] costRelationTypes; protected Direction relationDirection; protected CostEvaluator<CostType> costEvaluator = null; protected CostAccumulator<CostType> costAccumulator = null; protected Comparator<CostType> costComparator = null; protected boolean calculateAllShortestPaths = false; // Limits protected long maxRelationShipsToTraverse = -1; protected long numberOfTraversedRelationShips = 0; protected long maxNodesToTraverse = -1; protected long numberOfNodesTraversed = 0; protected CostType maxCost = null; /** * @return True if the set limits for the calculation has been reached (but * not exceeded) */ protected boolean limitReached() { if ( maxRelationShipsToTraverse >= 0 && numberOfTraversedRelationShips >= maxRelationShipsToTraverse ) { return true; } if ( maxNodesToTraverse >= 0 && numberOfNodesTraversed >= maxNodesToTraverse ) { return true; } return false; } protected boolean limitReached( CostType cost1, CostType cost2 ) { if ( maxCost != null ) { CostType totalCost = costAccumulator.addCosts( cost1, cost2 ); if ( costComparator.compare( totalCost, maxCost ) > 0 ) { foundPathsMiddleNodes = null; foundPathsCost = null; return true; } } return false; } // Result data protected boolean doneCalculation = false; protected Set<Node> foundPathsMiddleNodes = null; protected CostType foundPathsCost; protected HashMap<Node, List<Relationship>> predecessors1 = new HashMap<Node, List<Relationship>>(); protected HashMap<Node, List<Relationship>> predecessors2 = new HashMap<Node, List<Relationship>>(); /** * Resets the result data to force the computation to be run again when some * result is asked for. */ public void reset() { doneCalculation = false; foundPathsMiddleNodes = null; predecessors1 = new HashMap<Node, List<Relationship>>(); predecessors2 = new HashMap<Node, List<Relationship>>(); // Limits numberOfTraversedRelationShips = 0; numberOfNodesTraversed = 0; } /** * @param startCost Starting cost for both the start node and the end node * @param startNode the start node * @param endNode the end node * @param costRelationTypes the relationship that should be included in the * path * @param relationDirection relationship direction to follow * @param costEvaluator the cost function per relationship * @param costAccumulator adding up the path cost * @param costComparator comparing to path costs */ public Dijkstra( CostType startCost, Node startNode, Node endNode, CostEvaluator<CostType> costEvaluator, CostAccumulator<CostType> costAccumulator, Comparator<CostType> costComparator, Direction relationDirection, RelationshipType... costRelationTypes ) { super(); this.startCost = startCost; this.startNode = startNode; this.endNode = endNode; this.costRelationTypes = costRelationTypes; this.relationDirection = relationDirection; this.costEvaluator = costEvaluator; this.costAccumulator = costAccumulator; this.costComparator = costComparator; } /** * A DijkstraIterator computes the distances to nodes from a specified * starting node, one at a time, following the dijkstra algorithm. * * @author Patrik Larsson */ protected class DijstraIterator implements Iterator<Node> { protected Node startNode; // where do we come from protected HashMap<Node, List<Relationship>> predecessors; // observed distances not yet final protected HashMap<Node, CostType> mySeen; protected HashMap<Node, CostType> otherSeen; // the final distances protected HashMap<Node, CostType> myDistances; protected HashMap<Node, CostType> otherDistances; // Flag that indicates if we should follow egdes in the opposite // direction instead protected boolean backwards = false; // The priority queue protected DijkstraPriorityQueue<CostType> queue; // "Done" flags. The first is set to true when a node is found that is // contained in both myDistances and otherDistances. This means the // calculation has found one of the shortest paths. protected boolean oneShortestPathHasBeenFound = false; protected boolean allShortestPathsHasBeenFound = false; public DijstraIterator( Node startNode, HashMap<Node, List<Relationship>> predecessors, HashMap<Node, CostType> mySeen, HashMap<Node, CostType> otherSeen, HashMap<Node, CostType> myDistances, HashMap<Node, CostType> otherDistances, boolean backwards ) { super(); this.startNode = startNode; this.predecessors = predecessors; this.mySeen = mySeen; this.otherSeen = otherSeen; this.myDistances = myDistances; this.otherDistances = otherDistances; this.backwards = backwards; InitQueue(); } /** * @return The direction to use when searching for relations/edges */ protected Direction getDirection() { if ( backwards ) { if ( relationDirection.equals( Direction.INCOMING ) ) { return Direction.OUTGOING; } if ( relationDirection.equals( Direction.OUTGOING ) ) { return Direction.INCOMING; } } return relationDirection; } // This puts the start node into the queue protected void InitQueue() { queue = new DijkstraPriorityQueueFibonacciImpl<CostType>( costComparator ); queue.insertValue( startNode, startCost ); mySeen.put( startNode, startCost ); } public boolean hasNext() { return !queue.isEmpty() && !limitReached(); } public void remove() { // Not used // Could be used to generate more sollutions, by removing an edge // from the sollution and run again? } /** * This checks if a node has been seen by the other iterator/traverser * as well. In that case a path has been found. In that case, the total * cost for the path is calculated and compared to previously found * paths. * * @param currentNode The node to be examined. * @param currentCost The cost from the start node to this node. * @param otherSideDistances Map over distances from other side. A path * is found and examined if this contains currentNode. */ protected void checkForPath( Node currentNode, CostType currentCost, HashMap<Node, CostType> otherSideDistances ) { // Found a path? if ( otherSideDistances.containsKey( currentNode ) ) { // Is it better than previously found paths? CostType otherCost = otherSideDistances.get( currentNode ); CostType newTotalCost = costAccumulator.addCosts( currentCost, otherCost ); if ( foundPathsMiddleNodes == null ) { foundPathsMiddleNodes = new HashSet<Node>(); } // No previous path found, or equally good one found? if ( foundPathsMiddleNodes.size() == 0 || costComparator.compare( foundPathsCost, newTotalCost ) == 0 ) { foundPathsCost = newTotalCost; // in case we had no // previous path foundPathsMiddleNodes.add( currentNode ); } // New better path found? else if ( costComparator.compare( foundPathsCost, newTotalCost ) > 0 ) { foundPathsMiddleNodes.clear(); foundPathsCost = newTotalCost; foundPathsMiddleNodes.add( currentNode ); } } } public Node next() { Node currentNode = queue.extractMin(); CostType currentCost = mySeen.get( currentNode ); // Already done with this node? if ( myDistances.containsKey( currentNode ) ) { return null; } if ( limitReached() ) { return null; } ++numberOfNodesTraversed; myDistances.put( currentNode, currentCost ); // TODO: remove from seen or not? probably not... because of path // detection // Check if we have found a better path checkForPath( currentNode, currentCost, otherSeen ); // Found a path? (abort traversing from this node) if ( otherDistances.containsKey( currentNode ) ) { oneShortestPathHasBeenFound = true; } else { // Otherwise, follow all edges from this node for ( RelationshipType costRelationType : costRelationTypes ) { for ( Relationship relationship : currentNode.getRelationships( costRelationType, getDirection() ) ) { if ( limitReached() ) { break; } ++numberOfTraversedRelationShips; // Target node Node target = relationship.getOtherNode( currentNode ); // Find out if an eventual path would go in the opposite // direction of the edge boolean backwardsEdge = relationship.getEndNode().equals( currentNode ) ^ backwards; CostType newCost = costAccumulator.addCosts( currentCost, costEvaluator.getCost( relationship, backwardsEdge ? Direction.INCOMING : Direction.OUTGOING ) ); // Already done with target node? if ( myDistances.containsKey( target ) ) { // Have we found a better cost for a node which is // already // calculated? if ( costComparator.compare( myDistances.get( target ), newCost ) > 0 ) { throw new RuntimeException( "Cycle with negative costs found." ); } // Equally good path found? else if ( calculateAllShortestPaths && costComparator.compare( myDistances.get( target ), newCost ) == 0 ) { // Put it in predecessors List<Relationship> myPredecessors = predecessors.get( currentNode ); // Dont do it if this relation is already in // predecessors (other direction) if ( myPredecessors == null || !myPredecessors.contains( relationship ) ) { List<Relationship> predList = predecessors.get( target ); if ( predList == null ) { // This only happens if we get back to // the // start node, which is just bogus } else { predList.add( relationship ); } } } continue; } // Have we found a better cost for this node? if ( !mySeen.containsKey( target ) || costComparator.compare( mySeen.get( target ), newCost ) > 0 ) { // Put it in the queue if ( !mySeen.containsKey( target ) ) { queue.insertValue( target, newCost ); } // or update the entry. (It is important to keep // these // cases apart to limit the size of the queue) else { queue.decreaseValue( target, newCost ); } // Update it mySeen.put( target, newCost ); // Put it in predecessors List<Relationship> predList = new LinkedList<Relationship>(); predList.add( relationship ); predecessors.put( target, predList ); } // Have we found an equal cost for (additonal path to) // this // node? else if ( calculateAllShortestPaths && costComparator.compare( mySeen.get( target ), newCost ) == 0 ) { // Put it in predecessors List<Relationship> predList = predecessors.get( target ); predList.add( relationship ); } } } } // Check how far we need to continue when searching for all shortest // paths if ( calculateAllShortestPaths && oneShortestPathHasBeenFound ) { // If we cannot continue or continuation would only find more // expensive paths: conclude that all shortest paths have been // found. allShortestPathsHasBeenFound = queue.isEmpty() || costComparator.compare( mySeen.get( queue.peek() ), currentCost ) > 0; } return currentNode; } public boolean isDone() { if ( !calculateAllShortestPaths ) { return oneShortestPathHasBeenFound; } return allShortestPathsHasBeenFound; } } /** * Same as calculate(), but will set the flag to calculate all shortest * paths. It sets the flag and then calls calculate, so inheriting classes * only need to override calculate(). * * @return */ public boolean calculateMultiple() { if ( !calculateAllShortestPaths ) { reset(); calculateAllShortestPaths = true; } return calculate(); } /** * Makes the main calculation If some limit is set, the shortest path(s) * that could be found within those limits will be calculated. * * @return True if a path was found. */ public boolean calculate() { // Do this first as a general error check since this is supposed to be // called whenever a result is asked for. if ( startNode == null || endNode == null ) { throw new RuntimeException( "Start or end node undefined." ); } // Don't do it more than once if ( doneCalculation ) { return true; } doneCalculation = true; // Special case when path length is zero if ( startNode.equals( endNode ) ) { foundPathsMiddleNodes = new HashSet<Node>(); foundPathsMiddleNodes.add( startNode ); foundPathsCost = costAccumulator.addCosts( startCost, startCost ); return true; } HashMap<Node, CostType> seen1 = new HashMap<Node, CostType>(); HashMap<Node, CostType> seen2 = new HashMap<Node, CostType>(); HashMap<Node, CostType> dists1 = new HashMap<Node, CostType>(); HashMap<Node, CostType> dists2 = new HashMap<Node, CostType>(); DijstraIterator iter1 = new DijstraIterator( startNode, predecessors1, seen1, seen2, dists1, dists2, false ); DijstraIterator iter2 = new DijstraIterator( endNode, predecessors2, seen2, seen1, dists2, dists1, true ); Node node1 = null; Node node2 = null; while ( iter1.hasNext() && iter2.hasNext() ) { if ( limitReached() ) { break; } if ( iter1.hasNext() ) { node1 = iter1.next(); if ( node1 == null ) { break; } } if ( limitReached() ) { break; } if ( !iter1.isDone() && iter2.hasNext() ) { node2 = iter2.next(); if ( node2 == null ) { break; } } if ( limitReached( seen1.get( node1 ), seen2.get( node2 ) ) ) { break; } if ( iter1.isDone() || iter2.isDone() ) // A path was found { return true; } } return false; } /** * @return The cost for the found path(s). */ public CostType getCost() { if ( startNode == null || endNode == null ) { throw new RuntimeException( "Start or end node undefined." ); } calculate(); return foundPathsCost; } /** * @return All the found paths or null. */ public List<List<PropertyContainer>> getPaths() { if ( startNode == null || endNode == null ) { throw new RuntimeException( "Start or end node undefined." ); } calculateMultiple(); if ( foundPathsMiddleNodes == null || foundPathsMiddleNodes.size() == 0 ) { return Collections.emptyList(); } // Currently we use a set to avoid duplicate paths // TODO: can this be done smarter? Set<List<PropertyContainer>> paths = new HashSet<List<PropertyContainer>>(); for ( Node middleNode : foundPathsMiddleNodes ) { List<List<PropertyContainer>> paths1 = Util.constructAllPathsToNode( middleNode, predecessors1, true, false ); List<List<PropertyContainer>> paths2 = Util.constructAllPathsToNode( middleNode, predecessors2, false, true ); // For all combinations... for ( List<PropertyContainer> part1 : paths1 ) { for ( List<PropertyContainer> part2 : paths2 ) { // Combine them LinkedList<PropertyContainer> path = new LinkedList<PropertyContainer>(); path.addAll( part1 ); path.addAll( part2 ); // Add to collection paths.add( path ); } } } return new LinkedList<List<PropertyContainer>>( paths ); } /** * @return All the found paths or null. */ public List<List<Node>> getPathsAsNodes() { if ( startNode == null || endNode == null ) { throw new RuntimeException( "Start or end node undefined." ); } calculateMultiple(); if ( foundPathsMiddleNodes == null || foundPathsMiddleNodes.size() == 0 ) { return null; } // Currently we use a set to avoid duplicate paths // TODO: can this be done smarter? Set<List<Node>> paths = new HashSet<List<Node>>(); for ( Node middleNode : foundPathsMiddleNodes ) { List<List<Node>> paths1 = Util.constructAllPathsToNodeAsNodes( middleNode, predecessors1, true, false ); List<List<Node>> paths2 = Util.constructAllPathsToNodeAsNodes( middleNode, predecessors2, false, true ); // For all combinations... for ( List<Node> part1 : paths1 ) { for ( List<Node> part2 : paths2 ) { // Combine them LinkedList<Node> path = new LinkedList<Node>(); path.addAll( part1 ); path.addAll( part2 ); // Add to collection paths.add( path ); } } } return new LinkedList<List<Node>>( paths ); } /** * @return All the found paths or null. */ public List<List<Relationship>> getPathsAsRelationships() { if ( startNode == null || endNode == null ) { throw new RuntimeException( "Start or end node undefined." ); } calculateMultiple(); if ( foundPathsMiddleNodes == null || foundPathsMiddleNodes.size() == 0 ) { return null; } // Currently we use a set to avoid duplicate paths // TODO: can this be done smarter? Set<List<Relationship>> paths = new HashSet<List<Relationship>>(); for ( Node middleNode : foundPathsMiddleNodes ) { List<List<Relationship>> paths1 = Util.constructAllPathsToNodeAsRelationships( middleNode, predecessors1, false ); List<List<Relationship>> paths2 = Util.constructAllPathsToNodeAsRelationships( middleNode, predecessors2, true ); // For all combinations... for ( List<Relationship> part1 : paths1 ) { for ( List<Relationship> part2 : paths2 ) { // Combine them LinkedList<Relationship> path = new LinkedList<Relationship>(); path.addAll( part1 ); path.addAll( part2 ); // Add to collection paths.add( path ); } } } return new LinkedList<List<Relationship>>( paths ); } /** * @return One of the shortest paths found or null. */ public List<PropertyContainer> getPath() { if ( startNode == null || endNode == null ) { throw new RuntimeException( "Start or end node undefined." ); } calculate(); if ( foundPathsMiddleNodes == null || foundPathsMiddleNodes.size() == 0 ) { return null; } Node middleNode = foundPathsMiddleNodes.iterator().next(); LinkedList<PropertyContainer> path = new LinkedList<PropertyContainer>(); path.addAll( Util.constructSinglePathToNode( middleNode, predecessors1, true, false ) ); path.addAll( Util.constructSinglePathToNode( middleNode, predecessors2, false, true ) ); return path; } /** * @return One of the shortest paths found or null. */ public List<Node> getPathAsNodes() { if ( startNode == null || endNode == null ) { throw new RuntimeException( "Start or end node undefined." ); } calculate(); if ( foundPathsMiddleNodes == null || foundPathsMiddleNodes.size() == 0 ) { return null; } Node middleNode = foundPathsMiddleNodes.iterator().next(); LinkedList<Node> pathNodes = new LinkedList<Node>(); pathNodes.addAll( Util.constructSinglePathToNodeAsNodes( middleNode, predecessors1, true, false ) ); pathNodes.addAll( Util.constructSinglePathToNodeAsNodes( middleNode, predecessors2, false, true ) ); return pathNodes; } /** * @return One of the shortest paths found or null. */ public List<Relationship> getPathAsRelationships() { if ( startNode == null || endNode == null ) { throw new RuntimeException( "Start or end node undefined." ); } calculate(); if ( foundPathsMiddleNodes == null || foundPathsMiddleNodes.size() == 0 ) { return null; } Node middleNode = foundPathsMiddleNodes.iterator().next(); List<Relationship> path = new LinkedList<Relationship>(); path.addAll( Util.constructSinglePathToNodeAsRelationships( middleNode, predecessors1, false ) ); path.addAll( Util.constructSinglePathToNodeAsRelationships( middleNode, predecessors2, true ) ); return path; } /** * This sets the maximum depth in the form of a maximum number of * relationships to follow. * * @param maxRelationShipsToTraverse */ public void limitMaxRelationShipsToTraverse( long maxRelationShipsToTraverse ) { this.maxRelationShipsToTraverse = maxRelationShipsToTraverse; } /** * This sets the maximum depth in the form of a maximum number of nodes to * scan. * * @param maxRelationShipsToTraverse */ public void limitMaxNodesToTraverse( long maxNodesToTraverse ) { this.maxNodesToTraverse = maxNodesToTraverse; } /** * Set the end node. Will reset the calculation. * * @param endNode the endNode to set */ public void setEndNode( Node endNode ) { reset(); this.endNode = endNode; } /** * Set the start node. Will reset the calculation. * * @param startNode the startNode to set */ public void setStartNode( Node startNode ) { this.startNode = startNode; reset(); } /** * @return the relationDirection */ public Direction getDirection() { return relationDirection; } /** * @return the costRelationType */ public RelationshipType[] getRelationshipTypes() { return costRelationTypes; } /** * Set the evaluator for pruning the paths when the maximum cost is * exceeded. * * @param evaluator The evaluator for */ public void limitMaxCostToTraverse( CostType maxCost ) { this.maxCost = maxCost; } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_shortestpath_Dijkstra.java
3,337
protected class DijstraIterator implements Iterator<Node> { protected Node startNode; // where do we come from protected HashMap<Node, List<Relationship>> predecessors; // observed distances not yet final protected HashMap<Node, CostType> mySeen; protected HashMap<Node, CostType> otherSeen; // the final distances protected HashMap<Node, CostType> myDistances; protected HashMap<Node, CostType> otherDistances; // Flag that indicates if we should follow egdes in the opposite // direction instead protected boolean backwards = false; // The priority queue protected DijkstraPriorityQueue<CostType> queue; // "Done" flags. The first is set to true when a node is found that is // contained in both myDistances and otherDistances. This means the // calculation has found one of the shortest paths. protected boolean oneShortestPathHasBeenFound = false; protected boolean allShortestPathsHasBeenFound = false; public DijstraIterator( Node startNode, HashMap<Node, List<Relationship>> predecessors, HashMap<Node, CostType> mySeen, HashMap<Node, CostType> otherSeen, HashMap<Node, CostType> myDistances, HashMap<Node, CostType> otherDistances, boolean backwards ) { super(); this.startNode = startNode; this.predecessors = predecessors; this.mySeen = mySeen; this.otherSeen = otherSeen; this.myDistances = myDistances; this.otherDistances = otherDistances; this.backwards = backwards; InitQueue(); } /** * @return The direction to use when searching for relations/edges */ protected Direction getDirection() { if ( backwards ) { if ( relationDirection.equals( Direction.INCOMING ) ) { return Direction.OUTGOING; } if ( relationDirection.equals( Direction.OUTGOING ) ) { return Direction.INCOMING; } } return relationDirection; } // This puts the start node into the queue protected void InitQueue() { queue = new DijkstraPriorityQueueFibonacciImpl<CostType>( costComparator ); queue.insertValue( startNode, startCost ); mySeen.put( startNode, startCost ); } public boolean hasNext() { return !queue.isEmpty() && !limitReached(); } public void remove() { // Not used // Could be used to generate more sollutions, by removing an edge // from the sollution and run again? } /** * This checks if a node has been seen by the other iterator/traverser * as well. In that case a path has been found. In that case, the total * cost for the path is calculated and compared to previously found * paths. * * @param currentNode The node to be examined. * @param currentCost The cost from the start node to this node. * @param otherSideDistances Map over distances from other side. A path * is found and examined if this contains currentNode. */ protected void checkForPath( Node currentNode, CostType currentCost, HashMap<Node, CostType> otherSideDistances ) { // Found a path? if ( otherSideDistances.containsKey( currentNode ) ) { // Is it better than previously found paths? CostType otherCost = otherSideDistances.get( currentNode ); CostType newTotalCost = costAccumulator.addCosts( currentCost, otherCost ); if ( foundPathsMiddleNodes == null ) { foundPathsMiddleNodes = new HashSet<Node>(); } // No previous path found, or equally good one found? if ( foundPathsMiddleNodes.size() == 0 || costComparator.compare( foundPathsCost, newTotalCost ) == 0 ) { foundPathsCost = newTotalCost; // in case we had no // previous path foundPathsMiddleNodes.add( currentNode ); } // New better path found? else if ( costComparator.compare( foundPathsCost, newTotalCost ) > 0 ) { foundPathsMiddleNodes.clear(); foundPathsCost = newTotalCost; foundPathsMiddleNodes.add( currentNode ); } } } public Node next() { Node currentNode = queue.extractMin(); CostType currentCost = mySeen.get( currentNode ); // Already done with this node? if ( myDistances.containsKey( currentNode ) ) { return null; } if ( limitReached() ) { return null; } ++numberOfNodesTraversed; myDistances.put( currentNode, currentCost ); // TODO: remove from seen or not? probably not... because of path // detection // Check if we have found a better path checkForPath( currentNode, currentCost, otherSeen ); // Found a path? (abort traversing from this node) if ( otherDistances.containsKey( currentNode ) ) { oneShortestPathHasBeenFound = true; } else { // Otherwise, follow all edges from this node for ( RelationshipType costRelationType : costRelationTypes ) { for ( Relationship relationship : currentNode.getRelationships( costRelationType, getDirection() ) ) { if ( limitReached() ) { break; } ++numberOfTraversedRelationShips; // Target node Node target = relationship.getOtherNode( currentNode ); // Find out if an eventual path would go in the opposite // direction of the edge boolean backwardsEdge = relationship.getEndNode().equals( currentNode ) ^ backwards; CostType newCost = costAccumulator.addCosts( currentCost, costEvaluator.getCost( relationship, backwardsEdge ? Direction.INCOMING : Direction.OUTGOING ) ); // Already done with target node? if ( myDistances.containsKey( target ) ) { // Have we found a better cost for a node which is // already // calculated? if ( costComparator.compare( myDistances.get( target ), newCost ) > 0 ) { throw new RuntimeException( "Cycle with negative costs found." ); } // Equally good path found? else if ( calculateAllShortestPaths && costComparator.compare( myDistances.get( target ), newCost ) == 0 ) { // Put it in predecessors List<Relationship> myPredecessors = predecessors.get( currentNode ); // Dont do it if this relation is already in // predecessors (other direction) if ( myPredecessors == null || !myPredecessors.contains( relationship ) ) { List<Relationship> predList = predecessors.get( target ); if ( predList == null ) { // This only happens if we get back to // the // start node, which is just bogus } else { predList.add( relationship ); } } } continue; } // Have we found a better cost for this node? if ( !mySeen.containsKey( target ) || costComparator.compare( mySeen.get( target ), newCost ) > 0 ) { // Put it in the queue if ( !mySeen.containsKey( target ) ) { queue.insertValue( target, newCost ); } // or update the entry. (It is important to keep // these // cases apart to limit the size of the queue) else { queue.decreaseValue( target, newCost ); } // Update it mySeen.put( target, newCost ); // Put it in predecessors List<Relationship> predList = new LinkedList<Relationship>(); predList.add( relationship ); predecessors.put( target, predList ); } // Have we found an equal cost for (additonal path to) // this // node? else if ( calculateAllShortestPaths && costComparator.compare( mySeen.get( target ), newCost ) == 0 ) { // Put it in predecessors List<Relationship> predList = predecessors.get( target ); predList.add( relationship ); } } } } // Check how far we need to continue when searching for all shortest // paths if ( calculateAllShortestPaths && oneShortestPathHasBeenFound ) { // If we cannot continue or continuation would only find more // expensive paths: conclude that all shortest paths have been // found. allShortestPathsHasBeenFound = queue.isEmpty() || costComparator.compare( mySeen.get( queue.peek() ), currentCost ) > 0; } return currentNode; } public boolean isDone() { if ( !calculateAllShortestPaths ) { return oneShortestPathHasBeenFound; } return allShortestPathsHasBeenFound; } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_shortestpath_Dijkstra.java
3,338
public class DijkstraPriorityQueueFibonacciImpl<CostType> implements DijkstraPriorityQueue<CostType> { /** * Data structure used for the internal priority heap */ protected class HeapObject { private Node node; private CostType cost; public HeapObject( Node node, CostType cost ) { this.node = node; this.cost = cost; } public CostType getCost() { return cost; } public Node getNode() { return node; } /* * Equals is only defined from the stored node, so we can use it to find * entries in the queue */ @Override public boolean equals( Object obj ) { if ( this == obj ) return true; if ( obj == null ) return false; if ( getClass() != obj.getClass() ) return false; final HeapObject other = (HeapObject) obj; if ( node == null ) { if ( other.node != null ) return false; } else if ( !node.equals( other.node ) ) return false; return true; } @Override public int hashCode() { return node == null ? 23 : 14 ^ node.hashCode(); } } Map<Node,FibonacciHeap<HeapObject>.FibonacciHeapNode> heapNodes = new HashMap<Node,FibonacciHeap<HeapObject>.FibonacciHeapNode>(); FibonacciHeap<HeapObject> heap; Comparator<CostType> costComparator; public DijkstraPriorityQueueFibonacciImpl( final Comparator<CostType> costComparator ) { super(); this.costComparator = costComparator; heap = new FibonacciHeap<HeapObject>( new Comparator<HeapObject>() { public int compare( HeapObject o1, HeapObject o2 ) { return costComparator.compare( o1.getCost(), o2.getCost() ); } } ); } public void decreaseValue( Node node, CostType newValue ) { FibonacciHeap<HeapObject>.FibonacciHeapNode fNode = heapNodes .get( node ); heap.decreaseKey( fNode, new HeapObject( node, newValue ) ); } public Node extractMin() { HeapObject heapObject = heap.extractMin(); if ( heapObject == null ) { return null; } return heapObject.getNode(); } public void insertValue( Node node, CostType value ) { FibonacciHeap<HeapObject>.FibonacciHeapNode fNode = heap .insert( new HeapObject( node, value ) ); heapNodes.put( node, fNode ); } public boolean isEmpty() { return heap.isEmpty(); } public Node peek() { FibonacciHeap<HeapObject>.FibonacciHeapNode fNode = heap.getMinimum(); if ( fNode == null ) { return null; } return fNode.getKey().getNode(); } }
false
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_shortestpath_DijkstraPriorityQueueFibonacciImpl.java
3,339
public class NodeIndexFacadeMethods { private static final FacadeMethod<Index<Node>> GET = new FacadeMethod<Index<Node>>( "IndexHits<T> get( String " + "key, Object value )" ) { @Override public void call( Index<Node> self ) { self.get( "foo", "bar" ); } }; private static final FacadeMethod<Index<Node>> QUERY_BY_KEY = new FacadeMethod<Index<Node>>( "IndexHits<T> query(" + " String key, Object queryOrQueryObject )" ) { @Override public void call( Index<Node> self ) { self.query( "foo", "bar" ); } }; private static final FacadeMethod<Index<Node>> QUERY = new FacadeMethod<Index<Node>>( "IndexHits<T> query( Object" + " queryOrQueryObject )" ) { @Override public void call( Index<Node> self ) { self.query( "foo" ); } }; private static final FacadeMethod<Index<Node>> ADD = new FacadeMethod<Index<Node>>( "void add( T entity, " + "String key, Object value )" ) { @Override public void call( Index<Node> self ) { self.add( null, "foo", 42 ); } }; private static final FacadeMethod<Index<Node>> REMOVE_BY_KEY_AND_VALUE = new FacadeMethod<Index<Node>>( "void " + "remove( T entity, String key, Object value )" ) { @Override public void call( Index<Node> self ) { self.remove( null, "foo", 42 ); } }; private static final FacadeMethod<Index<Node>> REMOVE_BY_KEY = new FacadeMethod<Index<Node>>( "void remove( T " + "entity, String key )" ) { @Override public void call( Index<Node> self ) { self.remove( null, "foo" ); } }; private static final FacadeMethod<Index<Node>> REMOVE = new FacadeMethod<Index<Node>>( "void remove( T entity )" ) { @Override public void call( Index<Node> self ) { self.remove( null ); } }; private static final FacadeMethod<Index<Node>> DELETE = new FacadeMethod<Index<Node>>( "void delete()" ) { @Override public void call( Index<Node> self ) { self.delete(); } }; private static final FacadeMethod<Index<Node>> PUT_IF_ABSENT = new FacadeMethod<Index<Node>>( "T putIfAbsent( T " + "entity, String key, Object value )" ) { @Override public void call( Index<Node> self ) { self.putIfAbsent( null, "foo", 42 ); } }; static final Iterable<FacadeMethod<Index<Node>>> ALL_NODE_INDEX_FACADE_METHODS = unmodifiableCollection( asList( GET, QUERY_BY_KEY, QUERY, ADD, REMOVE_BY_KEY_AND_VALUE, REMOVE_BY_KEY, REMOVE, DELETE, PUT_IF_ABSENT ) ); }
false
community_lucene-index_src_test_java_org_neo4j_graphdb_NodeIndexFacadeMethods.java
3,340
{ @Override public void call( Node node ) { consume( node.getRelationships() ); } };
false
community_kernel_src_test_java_org_neo4j_graphdb_NodeFacadeMethods.java
3,341
{ @Override public void call( Node node ) { node.delete(); } };
false
community_kernel_src_test_java_org_neo4j_graphdb_NodeFacadeMethods.java
3,342
{ @Override public void call( Node node ) { consume( node.getPropertyKeys() ); } };
false
community_kernel_src_test_java_org_neo4j_graphdb_NodeFacadeMethods.java
3,343
{ @Override public void call( Node node ) { node.removeProperty( "foo" ); } };
false
community_kernel_src_test_java_org_neo4j_graphdb_NodeFacadeMethods.java
3,344
{ @Override public void call( Node node ) { node.setProperty( "foo", 42 ); } };
false
community_kernel_src_test_java_org_neo4j_graphdb_NodeFacadeMethods.java
3,345
{ @Override public void call( Node node ) { node.getProperty( "foo", 42 ); } };
false
community_kernel_src_test_java_org_neo4j_graphdb_NodeFacadeMethods.java
3,346
{ @Override public void call( Node node ) { consume( node.getLabels() ); } };
false
community_kernel_src_test_java_org_neo4j_graphdb_NodeFacadeMethods.java
3,347
{ @Override public void call( Node node ) { node.hasLabel( QUUX ); } };
false
community_kernel_src_test_java_org_neo4j_graphdb_NodeFacadeMethods.java
3,348
{ @Override public void call( Node node ) { node.removeLabel( QUUX ); } };
false
community_kernel_src_test_java_org_neo4j_graphdb_NodeFacadeMethods.java
3,349
{ @Override public void call( Node node ) { node.addLabel( QUUX ); } };
false
community_kernel_src_test_java_org_neo4j_graphdb_NodeFacadeMethods.java
3,350
{ @Override public void call( Node node ) { //noinspection deprecation node.traverse( BREADTH_FIRST, DEPTH_ONE, ALL, FOO, BOTH, BAR, OUTGOING, BAZ, INCOMING ); } };
false
community_kernel_src_test_java_org_neo4j_graphdb_NodeFacadeMethods.java
3,351
{ @Override public void call( Node node ) { //noinspection deprecation node.traverse( BREADTH_FIRST, DEPTH_ONE, ALL, FOO, BOTH, BAR, OUTGOING ); } };
false
community_kernel_src_test_java_org_neo4j_graphdb_NodeFacadeMethods.java
3,352
{ @Override public void call( Node node ) { //noinspection deprecation node.traverse( BREADTH_FIRST, DEPTH_ONE, ALL, FOO, BOTH ); } };
false
community_kernel_src_test_java_org_neo4j_graphdb_NodeFacadeMethods.java
3,353
{ @Override public void call( Node node ) { node.getProperty( "foo" ); } };
false
community_kernel_src_test_java_org_neo4j_graphdb_NodeFacadeMethods.java
3,354
{ @Override public void call( Node node ) { node.createRelationshipTo( node, FOO ); } };
false
community_kernel_src_test_java_org_neo4j_graphdb_NodeFacadeMethods.java
3,355
{ @Override public void call( Node node ) { node.getSingleRelationship( FOO, BOTH ); } };
false
community_kernel_src_test_java_org_neo4j_graphdb_NodeFacadeMethods.java
3,356
{ @Override public void call( Node node ) { node.hasRelationship( FOO, BOTH ); } };
false
community_kernel_src_test_java_org_neo4j_graphdb_NodeFacadeMethods.java
3,357
{ @Override public void call( Node node ) { consume( node.getRelationships( FOO, BOTH ) ); } };
false
community_kernel_src_test_java_org_neo4j_graphdb_NodeFacadeMethods.java
3,358
{ @Override public void call( Node node ) { node.hasRelationship( BOTH ); } };
false
community_kernel_src_test_java_org_neo4j_graphdb_NodeFacadeMethods.java
3,359
{ @Override public void call( Node node ) { node.hasRelationship(); } };
false
community_kernel_src_test_java_org_neo4j_graphdb_NodeFacadeMethods.java
3,360
{ @Override public void call( Index<Node> self ) { self.get( "foo", "bar" ); } };
false
community_lucene-index_src_test_java_org_neo4j_graphdb_NodeIndexFacadeMethods.java
3,361
{ @Override public void call( Node node ) { node.hasRelationship( BOTH, FOO ); } };
false
community_kernel_src_test_java_org_neo4j_graphdb_NodeFacadeMethods.java
3,362
{ @Override public void call( Index<Node> self ) { self.query( "foo", "bar" ); } };
false
community_lucene-index_src_test_java_org_neo4j_graphdb_NodeIndexFacadeMethods.java
3,363
{ @Override public void call( Relationship relationship ) { relationship.getProperty( "foo" ); } };
false
community_kernel_src_test_java_org_neo4j_graphdb_RelationshipFacadeMethods.java
3,364
{ @Override public void call( Relationship relationship ) { relationship.isType( withName( "foo" ) ); } };
false
community_kernel_src_test_java_org_neo4j_graphdb_RelationshipFacadeMethods.java
3,365
{ @Override public void call( Relationship relationship ) { relationship.getType(); } };
false
community_kernel_src_test_java_org_neo4j_graphdb_RelationshipFacadeMethods.java
3,366
{ @SuppressWarnings("UnusedDeclaration") @Override public void call( Relationship relationship ) { for ( Node node : relationship.getNodes() ) { } } };
false
community_kernel_src_test_java_org_neo4j_graphdb_RelationshipFacadeMethods.java
3,367
{ @Override public void call( Relationship relationship ) { relationship.getOtherNode( null ); } };
false
community_kernel_src_test_java_org_neo4j_graphdb_RelationshipFacadeMethods.java
3,368
{ @Override public void call( Relationship relationship ) { relationship.hasProperty( "foo" ); } };
false
community_kernel_src_test_java_org_neo4j_graphdb_RelationshipFacadeMethods.java
3,369
@SuppressWarnings("UnusedDeclaration") public class RelationshipFacadeMethods { private static final FacadeMethod<Relationship> HAS_PROPERTY = new FacadeMethod<Relationship>( "boolean hasProperty( String key )" ) { @Override public void call( Relationship relationship ) { relationship.hasProperty( "foo" ); } }; private static final FacadeMethod<Relationship> GET_PROPERTY = new FacadeMethod<Relationship>( "Object getProperty( String key )" ) { @Override public void call( Relationship relationship ) { relationship.getProperty( "foo" ); } }; private static final FacadeMethod<Relationship> GET_PROPERTY_WITH_DEFAULT = new FacadeMethod<Relationship>( "Object getProperty( String key, Object defaultValue )" ) { @Override public void call( Relationship relationship ) { relationship.getProperty( "foo", 42 ); } }; private static final FacadeMethod<Relationship> SET_PROPERTY = new FacadeMethod<Relationship>( "void setProperty( String key, Object value )" ) { @Override public void call( Relationship relationship ) { relationship.setProperty( "foo", 42 ); } }; private static final FacadeMethod<Relationship> REMOVE_PROPERTY = new FacadeMethod<Relationship>( "Object removeProperty( String key )" ) { @Override public void call( Relationship relationship ) { relationship.removeProperty( "foo" ); } }; private static final FacadeMethod<Relationship> GET_PROPERTY_KEYS = new FacadeMethod<Relationship>( "Iterable<String> getPropertyKeys()" ) { @Override public void call( Relationship relationship ) { for ( String key : relationship.getPropertyKeys() ) { } } }; private static final FacadeMethod<Relationship> DELETE = new FacadeMethod<Relationship>( "void delete()" ) { @Override public void call( Relationship relationship ) { relationship.delete(); } }; private static final FacadeMethod<Relationship> GET_START_NODE = new FacadeMethod<Relationship>( "Node getStartNode()" ) { @Override public void call( Relationship relationship ) { relationship.getStartNode(); } }; private static final FacadeMethod<Relationship> GET_END_NODE = new FacadeMethod<Relationship>( "Node getEndNode()" ) { @Override public void call( Relationship relationship ) { relationship.getEndNode(); } }; private static final FacadeMethod<Relationship> GET_OTHER_NODE = new FacadeMethod<Relationship>( "Node getOtherNode( Node node )" ) { @Override public void call( Relationship relationship ) { relationship.getOtherNode( null ); } }; private static final FacadeMethod<Relationship> GET_NODES = new FacadeMethod<Relationship>( "Node[] getNodes()" ) { @SuppressWarnings("UnusedDeclaration") @Override public void call( Relationship relationship ) { for ( Node node : relationship.getNodes() ) { } } }; private static final FacadeMethod<Relationship> GET_TYPE = new FacadeMethod<Relationship>( "RelationshipType getType()" ) { @Override public void call( Relationship relationship ) { relationship.getType(); } }; private static final FacadeMethod<Relationship> IS_TYPE = new FacadeMethod<Relationship>( "boolean isType( RelationshipType type )" ) { @Override public void call( Relationship relationship ) { relationship.isType( withName( "foo" ) ); } }; static final Iterable<FacadeMethod<Relationship>> ALL_RELATIONSHIP_FACADE_METHODS = unmodifiableCollection( asList( HAS_PROPERTY, GET_PROPERTY, GET_PROPERTY_WITH_DEFAULT, SET_PROPERTY, REMOVE_PROPERTY, GET_PROPERTY_KEYS, DELETE, GET_START_NODE, GET_END_NODE, GET_OTHER_NODE, GET_NODES, GET_TYPE, IS_TYPE ) ); }
false
community_kernel_src_test_java_org_neo4j_graphdb_RelationshipFacadeMethods.java
3,370
{ @Override public Iterable<Relationship> expand( Path path, BranchState<STATE> state ) { if ( path.length() == 0 ) { return path.endNode().getRelationships( types ); } else { Direction direction = getDirectionOfLastRelationship( path ); return path.endNode().getRelationships( direction, types ); } } @Override public PathExpander<STATE> reverse() { return this; } private Direction getDirectionOfLastRelationship( Path path ) { assert path.length() > 0; Direction direction = Direction.INCOMING; if ( path.endNode().equals( path.lastRelationship().getEndNode() ) ) { direction = Direction.OUTGOING; } return direction; } };
false
community_kernel_src_main_java_org_neo4j_graphdb_PathExpanders.java
3,371
public abstract class PathExpanders { /** * A very permissive {@link PathExpander} that follows any type in any direction. */ @SuppressWarnings("unchecked") public static <STATE> PathExpander<STATE> allTypesAndDirections() { return StandardExpander.DEFAULT; } /** * A very permissive {@link PathExpander} that follows {@code type} in any direction. */ @SuppressWarnings("unchecked") public static <STATE> PathExpander<STATE> forType( RelationshipType type ) { return StandardExpander.create( type, Direction.BOTH ); } /** * A very permissive {@link PathExpander} that follows any type in {@code direction}. */ @SuppressWarnings("unchecked") public static <STATE> PathExpander<STATE> forDirection( Direction direction ) { return StandardExpander.create( direction ); } /** * A very restricted {@link PathExpander} that follows {@code type} in {@code direction}. */ @SuppressWarnings("unchecked") public static <STATE> PathExpander<STATE> forTypeAndDirection( RelationshipType type, Direction direction ) { return StandardExpander.create( type, direction ); } /** * A very restricted {@link PathExpander} that follows only the {@code type}/ {@code direction} pairs that you list. */ @SuppressWarnings("unchecked") public static <STATE> PathExpander<STATE> forTypesAndDirections( RelationshipType type1, Direction direction1, RelationshipType type2, Direction direction2, Object... more ) { return StandardExpander.create( type1, direction1, type2, direction2, more ); } /** * An expander forcing constant relationship direction */ public static <STATE> PathExpander<STATE> forConstantDirectionWithTypes( final RelationshipType... types ) { return new PathExpander<STATE>() { @Override public Iterable<Relationship> expand( Path path, BranchState<STATE> state ) { if ( path.length() == 0 ) { return path.endNode().getRelationships( types ); } else { Direction direction = getDirectionOfLastRelationship( path ); return path.endNode().getRelationships( direction, types ); } } @Override public PathExpander<STATE> reverse() { return this; } private Direction getDirectionOfLastRelationship( Path path ) { assert path.length() > 0; Direction direction = Direction.INCOMING; if ( path.endNode().equals( path.lastRelationship().getEndNode() ) ) { direction = Direction.OUTGOING; } return direction; } }; } private PathExpanders() { // you should never instantiate this } }
false
community_kernel_src_main_java_org_neo4j_graphdb_PathExpanders.java
3,372
public class PathExpanderBuilder { /** * A {@link PathExpanderBuilder} that follows no relationships. You start with this and use * {@link #add(RelationshipType, Direction)} to form a restrictive PathExpander with just a few expansion rules * in it. */ public static PathExpanderBuilder empty() { return new PathExpanderBuilder( StandardExpander.EMPTY ); } /** * A {@link PathExpanderBuilder} that is seeded with all possible relationship types in {@link Direction#BOTH both * directions}. You start with this and {@link #remove(RelationshipType) remove types} to form a permissive * {@link PathExpander} with just a few exceptions in it. */ public static <STATE> PathExpanderBuilder allTypesAndDirections() { return new PathExpanderBuilder( StandardExpander.DEFAULT ); } /** * A {@link PathExpanderBuilder} seeded with all possible types but restricted to {@code direction}. You start * with this and {@link #remove(RelationshipType) remove types} to form a permissive {@link PathExpander} with * just a few exceptions in it. * * @param direction The direction you want to restrict expansions to */ public static PathExpanderBuilder allTypes( Direction direction ) { return new PathExpanderBuilder( StandardExpander.create( direction ) ); } /** * Add a pair of {@code type} and {@link Direction#BOTH} to the PathExpander configuration. */ public PathExpanderBuilder add( RelationshipType type ) { return add( type, BOTH ); } /** * Add a pair of {@code type} and {@code direction} to the PathExpander configuration. */ public PathExpanderBuilder add( RelationshipType type, Direction direction ) { return new PathExpanderBuilder( expander.add( type, direction ) ); } /** * Remove expansion of {@code type} in any direction from the PathExpander configuration. * <p/> * Example: {@code PathExpanderBuilder.allTypesAndDirections().remove(type).add(type, Direction.INCOMING)} * would restrict the {@link PathExpander} to only follow {@code Direction.INCOMING} relationships for {@code * type} while following any other relationship type in either direction. */ public PathExpanderBuilder remove( RelationshipType type ) { return new PathExpanderBuilder( expander.remove( type ) ); } /** * Produce a PathExpander from the configuration you have built up. */ @SuppressWarnings("unchecked") public <STATE> PathExpander<STATE> build() { return expander; } private final StandardExpander expander; private PathExpanderBuilder( StandardExpander expander ) { this.expander = expander; } }
false
community_kernel_src_main_java_org_neo4j_graphdb_PathExpanderBuilder.java
3,373
public class NotInTransactionException extends RuntimeException { public NotInTransactionException() { super(); } public NotInTransactionException( String message ) { super( message ); } public NotInTransactionException( Throwable cause ) { super( cause ); } public NotInTransactionException( String message, Throwable cause ) { super( message, cause ); } }
false
community_kernel_src_main_java_org_neo4j_graphdb_NotInTransactionException.java
3,374
public class NotFoundException extends RuntimeException { public NotFoundException() { super(); } public NotFoundException( String message ) { super( message ); } public NotFoundException( String message, Throwable cause ) { super( message, cause ); } public NotFoundException( Throwable cause ) { super( cause ); } }
false
community_kernel_src_main_java_org_neo4j_graphdb_NotFoundException.java
3,375
{ @Override public void call( Index<Node> self ) { self.putIfAbsent( null, "foo", 42 ); } };
false
community_lucene-index_src_test_java_org_neo4j_graphdb_NodeIndexFacadeMethods.java
3,376
{ @Override public void call( Index<Node> self ) { self.delete(); } };
false
community_lucene-index_src_test_java_org_neo4j_graphdb_NodeIndexFacadeMethods.java
3,377
{ @Override public void call( Index<Node> self ) { self.remove( null ); } };
false
community_lucene-index_src_test_java_org_neo4j_graphdb_NodeIndexFacadeMethods.java
3,378
{ @Override public void call( Index<Node> self ) { self.remove( null, "foo" ); } };
false
community_lucene-index_src_test_java_org_neo4j_graphdb_NodeIndexFacadeMethods.java
3,379
{ @Override public void call( Index<Node> self ) { self.remove( null, "foo", 42 ); } };
false
community_lucene-index_src_test_java_org_neo4j_graphdb_NodeIndexFacadeMethods.java
3,380
{ @Override public void call( Index<Node> self ) { self.add( null, "foo", 42 ); } };
false
community_lucene-index_src_test_java_org_neo4j_graphdb_NodeIndexFacadeMethods.java
3,381
{ @Override public void call( Index<Node> self ) { self.query( "foo" ); } };
false
community_lucene-index_src_test_java_org_neo4j_graphdb_NodeIndexFacadeMethods.java
3,382
{ @Override public void call( Node node ) { consume( node.getRelationships( BOTH ) ); } };
false
community_kernel_src_test_java_org_neo4j_graphdb_NodeFacadeMethods.java
3,383
{ @Override public void call( Node node ) { node.hasRelationship( FOO ); } };
false
community_kernel_src_test_java_org_neo4j_graphdb_NodeFacadeMethods.java
3,384
{ @Override public void run( FileSystemAbstraction fs, File storeDirectory ) { try { File directory = labelScanStoreIndexDirectory( storeDirectory ); assertTrue( "We seem to want to delete the wrong directory here", directory.exists() ); assertTrue( "No index files to delete", directory.listFiles().length > 0 ); deleteRecursively( directory ); } catch ( IOException e ) { throw new RuntimeException( e ); } } };
false
community_lucene-index_src_test_java_org_neo4j_graphdb_LuceneLabelScanStoreChaosIT.java
3,385
{ @Override protected boolean matchesSafely( Neo4jMatchers.Deferred<?> nodes, Description description ) { int foundSize = nodes.collection().size(); if ( foundSize != expectedSize ) { description.appendText( "found " + nodes.collection().toString() ); return false; } return true; } @Override public void describeTo( Description description ) { description.appendText( "collection of size " + expectedSize ); } };
false
community_kernel_src_test_java_org_neo4j_graphdb_Neo4jMatchers.java
3,386
{ @Override protected Iterable<ConstraintDefinition> manifest() { return db.schema().getConstraints( ); } };
false
community_kernel_src_test_java_org_neo4j_graphdb_Neo4jMatchers.java
3,387
{ @Override protected Iterable<ConstraintDefinition> manifest() { return db.schema().getConstraints( label ); } };
false
community_kernel_src_test_java_org_neo4j_graphdb_Neo4jMatchers.java
3,388
{ @Override protected Iterable<String> manifest() { return propertyContainer.getPropertyKeys(); } };
false
community_kernel_src_test_java_org_neo4j_graphdb_Neo4jMatchers.java
3,389
{ @Override protected boolean matches( Object item, Description mismatchDescription ) { try ( Transaction ignored = db.beginTx() ) { if ( inner.matches( item ) ) { return true; } inner.describeMismatch( item, mismatchDescription ); return false; } } @Override public void describeTo( Description description ) { inner.describeTo( description ); } };
false
community_kernel_src_test_java_org_neo4j_graphdb_Neo4jMatchers.java
3,390
public class Neo4jMatchers { public static <T> Matcher<? super T> inTx( final GraphDatabaseService db, final Matcher<T> inner ) { return new DiagnosingMatcher<T>() { @Override protected boolean matches( Object item, Description mismatchDescription ) { try ( Transaction ignored = db.beginTx() ) { if ( inner.matches( item ) ) { return true; } inner.describeMismatch( item, mismatchDescription ); return false; } } @Override public void describeTo( Description description ) { inner.describeTo( description ); } }; } public static TypeSafeDiagnosingMatcher<Node> hasLabel( final Label myLabel ) { return new TypeSafeDiagnosingMatcher<Node>() { @Override public void describeTo( Description description ) { description.appendValue( myLabel ); } @Override protected boolean matchesSafely( Node item, Description mismatchDescription ) { boolean result = item.hasLabel( myLabel ); if ( !result ) { Set<String> labels = asLabelNameSet( item.getLabels() ); mismatchDescription.appendText( labels.toString() ); } return result; } }; } public static TypeSafeDiagnosingMatcher<Node> hasLabels( String... expectedLabels ) { return hasLabels( asSet( expectedLabels ) ); } public static TypeSafeDiagnosingMatcher<Node> hasLabels( Label... expectedLabels ) { Set<String> labelNames = new HashSet<>( expectedLabels.length ); for ( Label l : expectedLabels ) { labelNames.add( l.name() ); } return hasLabels( labelNames ); } public static TypeSafeDiagnosingMatcher<Node> hasNoLabels() { return hasLabels( emptySetOf( String.class ) ); } public static TypeSafeDiagnosingMatcher<Node> hasLabels( final Set<String> expectedLabels ) { return new TypeSafeDiagnosingMatcher<Node>() { private Set<String> foundLabels; @Override public void describeTo( Description description ) { description.appendText( expectedLabels.toString() ); } @Override protected boolean matchesSafely( Node item, Description mismatchDescription ) { foundLabels = asLabelNameSet( item.getLabels() ); if ( foundLabels.size() == expectedLabels.size() && foundLabels.containsAll( expectedLabels ) ) { return true; } mismatchDescription.appendText( "was " + foundLabels.toString() ); return false; } }; } public static TypeSafeDiagnosingMatcher<GlobalGraphOperations> hasNoNodes( final Label withLabel ) { return new TypeSafeDiagnosingMatcher<GlobalGraphOperations>() { @Override protected boolean matchesSafely( GlobalGraphOperations glops, Description mismatchDescription ) { Set<Node> found = asSet( glops.getAllNodesWithLabel( withLabel ) ); if ( !found.isEmpty() ) { mismatchDescription.appendText( "found " + found.toString() ); return false; } return true; } @Override public void describeTo( Description description ) { description.appendText( "no nodes with label " + withLabel ); } }; } public static TypeSafeDiagnosingMatcher<GlobalGraphOperations> hasNodes( final Label withLabel, final Node... expectedNodes ) { return new TypeSafeDiagnosingMatcher<GlobalGraphOperations>() { @Override protected boolean matchesSafely( GlobalGraphOperations glops, Description mismatchDescription ) { Set<Node> expected = asSet( expectedNodes ); Set<Node> found = asSet( glops.getAllNodesWithLabel( withLabel ) ); if ( !expected.equals( found ) ) { mismatchDescription.appendText( "found " + found.toString() ); return false; } return true; } @Override public void describeTo( Description description ) { description.appendText( asSet( expectedNodes ).toString() + " with label " + withLabel ); } }; } public static Set<String> asLabelNameSet( Iterable<Label> enums ) { return asSet( map( new Function<Label, String>() { @Override public String apply( Label from ) { return from.name(); } }, enums ) ); } public static Matcher<? super Iterator<Long>> hasSamePrimitiveItems( final PrimitiveLongIterator actual ) { return new TypeSafeDiagnosingMatcher<Iterator<Long>>() { int len = 0; String actualText = null; String expectedText = null; @Override protected boolean matchesSafely( Iterator<Long> expected, Description actualDescription ) { if ( actualText != null ) { actualDescription.appendText( actualText ); } // compare iterators element-wise while ( expected.hasNext() && actual.hasNext() ) { len++; Long expectedNext = expected.next(); long actualNext = actual.next(); if ( !(expectedNext.equals( actualNext )) ) { actualText = format( "Element %d at position %d", actualNext, len ); expectedText = format( "Element %d at position %d", expectedNext, len ); return false; } } // check that the iterators do not have a different length if ( expected.hasNext() ) { actualText = format("Length %d", len ); expectedText = format( "Length %d", len + 1 ); return false; } if ( actual.hasNext() ) { actualText = format("Length %d", len + 1 ); expectedText = format( "Length %d", len ); return false; } return true; } @Override public void describeTo( Description expectedDescription ) { if ( expectedText != null ) { expectedDescription.appendText( expectedText ); } } }; } public static class PropertyValueMatcher extends TypeSafeDiagnosingMatcher<PropertyContainer> { private final PropertyMatcher propertyMatcher; private final String propertyName; private final Object expectedValue; private PropertyValueMatcher( PropertyMatcher propertyMatcher, String propertyName, Object expectedValue ) { this.propertyMatcher = propertyMatcher; this.propertyName = propertyName; this.expectedValue = expectedValue; } @Override protected boolean matchesSafely( PropertyContainer propertyContainer, Description mismatchDescription ) { if ( !propertyMatcher.matchesSafely( propertyContainer, mismatchDescription ) ) { return false; } Object foundValue = propertyContainer.getProperty( propertyName ); if ( !propertyValuesEqual( expectedValue, foundValue ) ) { mismatchDescription.appendText( "found value " + formatValue( foundValue ) ); return false; } return true; } @Override public void describeTo( Description description ) { propertyMatcher.describeTo( description ); description.appendText( String.format( "having value %s", formatValue( expectedValue ) ) ); } private boolean propertyValuesEqual( Object expected, Object readValue ) { if ( expected.getClass().isArray() ) { return arrayAsCollection( expected ).equals( arrayAsCollection( readValue ) ); } else { return expected.equals( readValue ); } } private String formatValue(Object v) { if (v instanceof String) { return String.format("'%s'", v.toString()); } return v.toString(); } } public static class PropertyMatcher extends TypeSafeDiagnosingMatcher<PropertyContainer> { public final String propertyName; private PropertyMatcher( String propertyName ) { this.propertyName = propertyName; } @Override protected boolean matchesSafely( PropertyContainer propertyContainer, Description mismatchDescription ) { if ( !propertyContainer.hasProperty( propertyName ) ) { mismatchDescription.appendText( String.format( "found property container with property keys: %s", asSet( propertyContainer.getPropertyKeys() ) ) ); return false; } return true; } @Override public void describeTo( Description description ) { description.appendText( String.format( "property container with property name '%s' ", propertyName ) ); } public PropertyValueMatcher withValue( Object value ) { return new PropertyValueMatcher( this, propertyName, value ); } } public static PropertyMatcher hasProperty( String propertyName ) { return new PropertyMatcher( propertyName ); } public static Deferred<Node> findNodesByLabelAndProperty( final Label label, final String propertyName, final Object propertyValue, final GraphDatabaseService db ) { return new Deferred<Node>(db) { @Override protected Iterable<Node> manifest() { return db.findNodesByLabelAndProperty( label, propertyName, propertyValue ); } }; } public static Deferred<IndexDefinition> getIndexes( final GraphDatabaseService db, final Label label ) { return new Deferred<IndexDefinition>( db ) { @Override protected Iterable<IndexDefinition> manifest() { return db.schema().getIndexes( label ); } }; } public static Deferred<String> getPropertyKeys( final GraphDatabaseService db, final PropertyContainer propertyContainer ) { return new Deferred<String>( db ) { @Override protected Iterable<String> manifest() { return propertyContainer.getPropertyKeys(); } }; } public static Deferred<ConstraintDefinition> getConstraints( final GraphDatabaseService db, final Label label ) { return new Deferred<ConstraintDefinition>( db ) { @Override protected Iterable<ConstraintDefinition> manifest() { return db.schema().getConstraints( label ); } }; } public static Deferred<ConstraintDefinition> getConstraints( final GraphDatabaseService db ) { return new Deferred<ConstraintDefinition>( db ) { @Override protected Iterable<ConstraintDefinition> manifest() { return db.schema().getConstraints( ); } }; } /** * Represents test data that can at assertion time produce a collection * * Useful to defer actually doing operations until context has been prepared (such as a transaction created) * * @param <T> The type of objects the collection will contain */ public static abstract class Deferred<T> { private final GraphDatabaseService db; public Deferred( GraphDatabaseService db ) { this.db = db; } protected abstract Iterable<T> manifest(); public Collection<T> collection() { try ( Transaction ignore = db.beginTx() ) { return asCollection( manifest() ); } } } @SafeVarargs public static <T> TypeSafeDiagnosingMatcher<Neo4jMatchers.Deferred<T>> containsOnly( final T... expectedObjects ) { return new TypeSafeDiagnosingMatcher<Neo4jMatchers.Deferred<T>>() { @Override protected boolean matchesSafely( Neo4jMatchers.Deferred<T> nodes, Description description ) { Set<T> expected = asSet( expectedObjects ); Set<T> found = asSet( nodes.collection() ); if ( !expected.equals( found ) ) { description.appendText( "found " + found.toString() ); return false; } return true; } @Override public void describeTo( Description description ) { description.appendText( "exactly " + asSet( expectedObjects ) ); } }; } public static TypeSafeDiagnosingMatcher<Neo4jMatchers.Deferred<?>> hasSize( final int expectedSize ) { return new TypeSafeDiagnosingMatcher<Neo4jMatchers.Deferred<?>>() { @Override protected boolean matchesSafely( Neo4jMatchers.Deferred<?> nodes, Description description ) { int foundSize = nodes.collection().size(); if ( foundSize != expectedSize ) { description.appendText( "found " + nodes.collection().toString() ); return false; } return true; } @Override public void describeTo( Description description ) { description.appendText( "collection of size " + expectedSize ); } }; } public static TypeSafeDiagnosingMatcher<Neo4jMatchers.Deferred<IndexDefinition>> haveState( final GraphDatabaseService db, final Schema.IndexState expectedState ) { return new TypeSafeDiagnosingMatcher<Neo4jMatchers.Deferred<IndexDefinition>>() { @Override protected boolean matchesSafely( Neo4jMatchers.Deferred<IndexDefinition> indexes, Description description ) { for ( IndexDefinition current : indexes.collection() ) { Schema.IndexState currentState = db.schema().getIndexState( current ); if ( !currentState.equals( expectedState ) ) { description.appendValue( current ).appendText( " has state " ).appendValue( currentState ); return false; } } return true; } @Override public void describeTo( Description description ) { description.appendText( "all indexes have state " + expectedState ); } }; } @SafeVarargs public static <T> TypeSafeDiagnosingMatcher<Neo4jMatchers.Deferred<T>> contains( final T... expectedObjects ) { return new TypeSafeDiagnosingMatcher<Neo4jMatchers.Deferred<T>>() { @Override protected boolean matchesSafely( Neo4jMatchers.Deferred<T> nodes, Description description ) { Set<T> expected = asSet( expectedObjects ); Set<T> found = asSet( nodes.collection() ); if ( !found.containsAll( expected ) ) { description.appendText( "found " + found.toString() ); return false; } return true; } @Override public void describeTo( Description description ) { description.appendText( "contains " + asSet( expectedObjects ) ); } }; } public static TypeSafeDiagnosingMatcher<Neo4jMatchers.Deferred<?>> isEmpty( ) { return new TypeSafeDiagnosingMatcher<Deferred<?>>() { @Override protected boolean matchesSafely( Deferred<?> deferred, Description description ) { Collection<?> collection = deferred.collection(); if(!collection.isEmpty()) { description.appendText( "was " + collection.toString() ); return false; } return true; } @Override public void describeTo( Description description ) { description.appendText( "empty collection" ); } }; } public static IndexDefinition createIndex( GraphDatabaseService beansAPI, Label label, String property ) { IndexDefinition indexDef; try ( Transaction tx = beansAPI.beginTx() ) { indexDef = beansAPI.schema().indexFor( label ).on( property ).create(); tx.success(); } waitForIndex( beansAPI, indexDef ); return indexDef; } public static void waitForIndex( GraphDatabaseService beansAPI, IndexDefinition indexDef ) { try ( Transaction ignored = beansAPI.beginTx() ) { beansAPI.schema().awaitIndexOnline( indexDef, 10, SECONDS ); } } public static Object getIndexState( GraphDatabaseService beansAPI, IndexDefinition indexDef ) { try ( Transaction ignored = beansAPI.beginTx() ) { return beansAPI.schema().getIndexState( indexDef ); } } public static ConstraintDefinition createConstraint( GraphDatabaseService db, Label label, String propertyKey ) { try ( Transaction tx = db.beginTx() ) { ConstraintDefinition constraint = db.schema().constraintFor( label ).assertPropertyIsUnique( propertyKey ).create(); tx.success(); return constraint; } } }
false
community_kernel_src_test_java_org_neo4j_graphdb_Neo4jMatchers.java
3,391
public class MandatoryTransactionsForUniquenessConstraintDefinitionTests extends AbstractMandatoryTransactionsTest<ConstraintDefinition> { @Test public void shouldRequireTransactionsWhenCallingMethodsOnUniquenessConstraintDefinitions() throws Exception { assertFacadeMethodsThrowNotInTransaction( obtainEntity(), ALL_CONSTRAINT_DEFINITION_FACADE_METHODS ); } @Override protected ConstraintDefinition obtainEntityInTransaction( GraphDatabaseService graphDatabaseService ) { return graphDatabaseService .schema() .constraintFor( DynamicLabel.label( "Label" ) ) .assertPropertyIsUnique( "property" ) .create(); } }
false
community_kernel_src_test_java_org_neo4j_graphdb_MandatoryTransactionsForUniquenessConstraintDefinitionTests.java
3,392
public class MandatoryTransactionsForSchemaTests extends AbstractMandatoryTransactionsTest<Schema> { @Test public void shouldRequireTransactionsWhenCallingMethodsOnSchema() throws Exception { assertFacadeMethodsThrowNotInTransaction( obtainEntity(), ALL_SCHEMA_FACADE_METHODS ); } @Override protected Schema obtainEntityInTransaction( GraphDatabaseService graphDatabaseService ) { return graphDatabaseService.schema(); } }
false
community_kernel_src_test_java_org_neo4j_graphdb_MandatoryTransactionsForSchemaTests.java
3,393
public class MandatoryTransactionsForRelationshipTests extends AbstractMandatoryTransactionsTest<Relationship> { @Test public void shouldRequireTransactionsWhenCallingMethodsOnRelationshipFacade() throws Exception { assertFacadeMethodsThrowNotInTransaction( obtainEntity(), ALL_RELATIONSHIP_FACADE_METHODS ); } @Override protected Relationship obtainEntityInTransaction( GraphDatabaseService graphDatabaseService ) { return graphDatabaseService .createNode() .createRelationshipTo( graphDatabaseService.createNode(), withName( "foo" ) ); } }
false
community_kernel_src_test_java_org_neo4j_graphdb_MandatoryTransactionsForRelationshipTests.java
3,394
public class MandatoryTransactionsForRelationshipIndexFacadeTests extends AbstractMandatoryTransactionsTest<RelationshipIndex> { @Test public void shouldRequireTransactionsWhenCallingMethodsOnRelationshipIndexFacade() throws Exception { assertFacadeMethodsThrowNotInTransaction( obtainEntity(), ALL_RELATIONSHIP_INDEX_FACADE_METHODS ); } @Override protected RelationshipIndex obtainEntityInTransaction( GraphDatabaseService graphDatabaseService ) { return graphDatabaseService.index().forRelationships( "foo" ); } }
false
community_lucene-index_src_test_java_org_neo4j_graphdb_MandatoryTransactionsForRelationshipIndexFacadeTests.java
3,395
public class MandatoryTransactionsForNodeTests extends AbstractMandatoryTransactionsTest<Node> { @Test public void shouldRequireTransactionsWhenCallingMethodsOnNode() throws Exception { assertFacadeMethodsThrowNotInTransaction( obtainEntity(), ALL_NODE_FACADE_METHODS ); } @Override protected Node obtainEntityInTransaction( GraphDatabaseService graphDatabaseService ) { return graphDatabaseService.createNode(); } }
false
community_kernel_src_test_java_org_neo4j_graphdb_MandatoryTransactionsForNodeTests.java
3,396
public class MandatoryTransactionsForNodeIndexFacadeTests extends AbstractMandatoryTransactionsTest<Index<Node>> { @Test public void shouldRequireTransactionsWhenCallingMethodsOnNodeIndexFacade() throws Exception { assertFacadeMethodsThrowNotInTransaction( obtainEntity(), ALL_NODE_INDEX_FACADE_METHODS ); } @Override protected Index<Node> obtainEntityInTransaction( GraphDatabaseService graphDatabaseService ) { return graphDatabaseService.index().forNodes( "foo" ); } }
false
community_lucene-index_src_test_java_org_neo4j_graphdb_MandatoryTransactionsForNodeIndexFacadeTests.java
3,397
public class MandatoryTransactionsForIndexManagerFacadeTests extends AbstractMandatoryTransactionsTest<IndexManager> { @Test public void shouldRequireTransactionsWhenCallingMethodsOnIndexManagerFacade() throws Exception { assertFacadeMethodsThrowNotInTransaction( obtainEntity(), ALL_INDEX_MANAGER_FACADE_METHODS ); } @Override protected IndexManager obtainEntityInTransaction( GraphDatabaseService graphDatabaseService ) { return graphDatabaseService.index(); } }
false
community_kernel_src_test_java_org_neo4j_graphdb_MandatoryTransactionsForIndexManagerFacadeTests.java
3,398
public class MandatoryTransactionsForIndexHitsFacadeTests { @Rule public ImpermanentDatabaseRule dbRule = new ImpermanentDatabaseRule(); private IndexHits<Node> indexHits; @Before public void before() throws Exception { Index<Node> index = createIndex(); indexHits = queryIndex( index ); } @Test public void shouldMandateTransactionsForUsingIterator() throws Exception { try ( ResourceIterator<Node> iterator = indexHits.iterator() ) { try { iterator.hasNext(); fail( "Transactions are mandatory, also for reads" ); } catch ( NotInTransactionException e ) { // Expected } try { iterator.next(); fail( "Transactions are mandatory, also for reads" ); } catch ( NotInTransactionException e ) { // Expected } } } @Test public void shouldMandateTransactionsForGetSingle() throws Exception { try { indexHits.getSingle(); fail( "Transactions are mandatory, also for reads" ); } catch ( NotInTransactionException e ) { // Expected } } private Index<Node> createIndex() { GraphDatabaseService graphDatabaseService = dbRule.getGraphDatabaseService(); try ( Transaction transaction = graphDatabaseService.beginTx() ) { Index<Node> index = graphDatabaseService.index().forNodes( "foo" ); transaction.success(); return index; } } private IndexHits<Node> queryIndex( Index<Node> index ) { GraphDatabaseService graphDatabaseService = dbRule.getGraphDatabaseService(); try ( Transaction transaction = graphDatabaseService.beginTx() ) { return index.get( "foo", 42 ); } } }
false
community_lucene-index_src_test_java_org_neo4j_graphdb_MandatoryTransactionsForIndexHitsFacadeTests.java
3,399
public class MandatoryTransactionsForIndexDefinitionTests extends AbstractMandatoryTransactionsTest<IndexDefinition> { @Test public void shouldRequireTransactionsWhenCallingMethodsOnIndexDefinitions() throws Exception { assertFacadeMethodsThrowNotInTransaction( obtainEntity(), ALL_INDEX_DEFINITION_FACADE_METHODS ); } @Override protected IndexDefinition obtainEntityInTransaction( GraphDatabaseService graphDatabaseService ) { return graphDatabaseService .schema() .indexFor( DynamicLabel.label( "Label" ) ) .on( "property" ) .create(); } }
false
community_kernel_src_test_java_org_neo4j_graphdb_MandatoryTransactionsForIndexDefinitionTests.java