Unnamed: 0
int64
0
6.7k
func
stringlengths
12
89.6k
target
bool
2 classes
project
stringlengths
45
151
2,000
private static class RotateIndexLogTask implements Task { @Override public void run( GraphDatabaseAPI graphdb ) { try { graphdb.getDependencyResolver().resolveDependency( XaDataSourceManager.class ) .getXaDataSource( LuceneDataSource.DEFAULT_NAME ).rotateLogicalLog(); setSuccess( graphdb, true ); } catch ( Exception e ) { setSuccess( graphdb, false ); throw Exceptions.launderedException( e ); } finally { rotateDone(); } } private void setSuccess( GraphDatabaseAPI graphdb, boolean success ) { try(Transaction tx = graphdb.beginTx()) { Node node = graphdb.createNode(); node.setProperty( "success", success ); tx.success(); } } }
false
community_neo4j_src_test_java_synchronization_TestConcurrentRotation.java
2,001
private static class LoadIndexesTask implements Task { private final int count; private final boolean resume; public LoadIndexesTask( int count, boolean resume ) { this.count = count; this.resume = resume; } @Override public void run( GraphDatabaseAPI graphdb ) { try(Transaction ignored = graphdb.beginTx()) { for ( int i = 0; i < count; i++ ) graphdb.index().forNodes( "index" + i ).get( "name", i ).getSingle(); } if ( resume ) resumeFlushThread(); } }
false
community_neo4j_src_test_java_synchronization_TestConcurrentRotation.java
2,002
private static class CreateInitialStateTask implements Task { @Override public void run( GraphDatabaseAPI graphdb ) { try(Transaction tx = graphdb.beginTx()) { for ( int i = 0; i < 3; i++ ) graphdb.index().forNodes( "index" + i ).add( graphdb.createNode(), "name", "" + i ); tx.success(); } } }
false
community_neo4j_src_test_java_synchronization_TestConcurrentRotation.java
2,003
{ @Override protected void callback( DebugInterface debug ) throws KillSubProcess { this.disable(); barrier2.countDown(); } };
false
community_neo4j_src_test_java_synchronization_TestConcurrentRotation.java
2,004
{ @Override protected void callback( DebugInterface debug ) throws KillSubProcess { thread.resume(); this.disable(); } };
false
community_neo4j_src_test_java_synchronization_TestConcurrentRotation.java
2,005
{ private int counter = 0; @Override protected void callback( DebugInterface debug ) throws KillSubProcess { if ( counter++ > 0 ) return; thread = debug.thread().suspend( this ); this.disable(); barrier1.countDown(); } };
false
community_neo4j_src_test_java_synchronization_TestConcurrentRotation.java
2,006
{ @Override protected void callback( DebugInterface debug ) throws KillSubProcess { if ( twoPhaseCommitIn( debug.thread() ) ) { debug.thread().suspend( null ); this.disable(); afterWrite.countDown(); throw KillSubProcess.withExitCode( -1 ); } } private boolean twoPhaseCommitIn( DebuggedThread thread ) { return !Boolean.parseBoolean( thread.getLocal( 1, "onePhase" ) ); } }, new BreakPoint( Crash.class, "run", InternalAbstractGraphDatabase.class )
false
community_neo4j_src_test_java_recovery_TestRecoveryIssues.java
2,007
{ @Override public boolean accept( LogEntry item ) { // Let through everything exception COMMIT/DONE for the last tx boolean shouldPruneEntry = item.getIdentifier() == lastIdentifier.get() && (item instanceof LogEntry.Commit || item instanceof LogEntry.Done); return !shouldPruneEntry; } };
false
community_neo4j_src_test_java_recovery_TestIndexingServiceRecovery.java
2,008
abstract class RelationshipTypeColor extends RelationshipColor { private final Map<String, String> colors = new HashMap<String, String>(); private final Map<String, String> fontColors = new HashMap<String, String>(); @Override protected final String getColor( Relationship relationship ) { RelationshipType type = relationship.getType(); String result = colors.get( type.name() ); if ( result == null ) { result = getColor( type ); if ( result == null ) { result = "black"; } colors.put( type.name(), result ); } return result; } @Override protected final String getFontColor( Relationship relationship ) { RelationshipType type = relationship.getType(); String result = fontColors.get( type.name() ); if ( result == null ) { result = getFontColor( type ); if ( result == null ) { result = "black"; } fontColors.put( type.name(), result ); } return result; } /** * Get the font color for a relationship type. Only invoked once for * each relationship type in the graph. * @param type * the relationship type to get the font color for. * @return the name of the font color for the relationship type. */ protected String getFontColor( RelationshipType type ) { return getColor( type ); } /** * Get the color for a relationship type. Only invoked once for each * relationship type in the graph. * @param type * the relationship type to get the color for. * @return the name of the color for the relationship type. */ protected abstract String getColor( RelationshipType type ); }
false
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_StyleParameter.java
2,009
INCOMING() { @Override void configure( AutoNodeColor style ) { style.directions = new Direction[] { Direction.INCOMING }; style.differentiateOnDirection = false; } },
false
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_color_AutoNodeColor.java
2,010
BOTH() { @Override void configure( AutoNodeColor style ) { style.directions = new Direction[] { Direction.INCOMING, Direction.OUTGOING }; style.differentiateOnDirection = true; } },
false
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_color_AutoNodeColor.java
2,011
DEFAULT() { @Override void configure( AutoNodeColor style ) { BOTH_IGNORE_DIRECTION.configure( style ); } },
false
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_color_AutoNodeColor.java
2,012
public class AutoNodeColor extends StyleParameter.NodeColor { private final DefaultColorMapping<Set<String>> colors; private Direction[] directions; private boolean differentiateOnDirection; private boolean differentiateOnDirectionOnly = false; private ColorMapper<Node> ncm = null; public AutoNodeColor() { NodeColorConfig.DEFAULT.configure( this ); this.colors = new DefaultColorMapping<Set<String>>(); } public AutoNodeColor( ColorMapper<Node> ncm ) { NodeColorConfig.DEFAULT.configure( this ); this.colors = new DefaultColorMapping<Set<String>>( ncm.getColors() ); this.ncm = ncm; } public AutoNodeColor( NodeColorConfig config ) { config.configure( this ); this.colors = new DefaultColorMapping<Set<String>>(); } public AutoNodeColor( NodeColorConfig config, ColorMapper<Node> ncm ) { config.configure( this ); this.colors = new DefaultColorMapping<Set<String>>( ncm.getColors() ); this.ncm = ncm; } @Override protected String getColor( Node node ) { if ( ncm != null ) { Color color = ncm.getColor( node ); if ( color != null ) { return colors.getColor( color ); } } Set<String> relationshipTypeAndDirections = new HashSet<String>(); for ( Direction direction : directions ) { if ( differentiateOnDirectionOnly ) { if ( node.hasRelationship( direction ) ) { relationshipTypeAndDirections.add( direction.name() ); } } else { for ( Relationship relationship : node.getRelationships( direction ) ) { String key = relationship.getType() .name(); if ( differentiateOnDirection ) { key += direction.name(); } relationshipTypeAndDirections.add( key ); } } } return colors.getColor( relationshipTypeAndDirections ); } public enum NodeColorConfig { /** * Alias for BOTH_IGNORE_DIRECTION. */ DEFAULT() { @Override void configure( AutoNodeColor style ) { BOTH_IGNORE_DIRECTION.configure( style ); } }, /** * Differentiate on relationship type and direction. */ BOTH() { @Override void configure( AutoNodeColor style ) { style.directions = new Direction[] { Direction.INCOMING, Direction.OUTGOING }; style.differentiateOnDirection = true; } }, /** * Differentiate on relationship type, ignore direction. */ BOTH_IGNORE_DIRECTION() { @Override void configure( AutoNodeColor style ) { style.directions = new Direction[] { Direction.INCOMING, Direction.OUTGOING }; style.differentiateOnDirection = false; } }, /** * Only look at incoming relationships. */ INCOMING() { @Override void configure( AutoNodeColor style ) { style.directions = new Direction[] { Direction.INCOMING }; style.differentiateOnDirection = false; } }, /** * Only look at outgoing relationships. */ OUTGOING() { @Override void configure( AutoNodeColor style ) { style.directions = new Direction[] { Direction.OUTGOING }; style.differentiateOnDirection = false; } }, /** * Differentiate only on if a node has incoming or outgoing * relationships. */ DIRECTION() { @Override void configure( AutoNodeColor style ) { style.directions = new Direction[] { Direction.INCOMING, Direction.OUTGOING }; style.differentiateOnDirectionOnly = true; } }; abstract void configure( AutoNodeColor style ); } }
false
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_color_AutoNodeColor.java
2,013
public class TestNewGraphvizWriter { enum type implements RelationshipType { KNOWS, WORKS_FOR } private GraphDatabaseService neo; @Before public void setUp() { neo = new GraphDatabaseFactory().newEmbeddedDatabase( "target/neo" ); } @After public void tearDown() { neo.shutdown(); } @Test public void testSimpleGraph() throws Exception { Transaction tx = neo.beginTx(); try { final Node emil = neo.createNode(); emil.setProperty( "name", "Emil Eifrém" ); emil.setProperty( "age", 30 ); final Node tobias = neo.createNode(); tobias.setProperty( "name", "Tobias \"thobe\" Ivarsson" ); tobias.setProperty( "age", 23 ); tobias.setProperty( "hours", new int[] { 10, 10, 4, 4, 0 } ); final Node johan = neo.createNode(); johan.setProperty( "!<>)", "!<>)" ); johan.setProperty( "name", "!<>Johan '\\n00b' !<>Svensson" ); final Relationship emilKNOWStobias = emil.createRelationshipTo( tobias, type.KNOWS ); emilKNOWStobias.setProperty( "since", "2003-08-17" ); final Relationship johanKNOWSemil = johan.createRelationshipTo( emil, type.KNOWS ); final Relationship tobiasKNOWSjohan = tobias.createRelationshipTo( johan, type.KNOWS ); final Relationship tobiasWORKS_FORemil = tobias .createRelationshipTo( emil, type.WORKS_FOR ); OutputStream out = new ByteArrayOutputStream(); GraphvizWriter writer = new GraphvizWriter(); writer.emit( out, Walker.crosscut( emil.traverse( Order.DEPTH_FIRST, StopEvaluator.END_OF_GRAPH, ReturnableEvaluator.ALL, type.KNOWS, Direction.BOTH, type.WORKS_FOR, Direction.BOTH ), type.KNOWS, type.WORKS_FOR ) ); tx.success(); out.toString(); } finally { tx.finish(); } } }
false
community_graphviz_src_test_java_org_neo4j_visualization_graphviz_TestNewGraphvizWriter.java
2,014
{ @Override protected Iterable<Node> nodes() { return asList( emil, tobias, johan ); } @Override protected Iterable<Relationship> relationships() { return asList( emilKNOWStobias, johanKNOWSemil, tobiasKNOWSjohan, tobiasWORKS_FORemil ); } };
false
community_graphviz_src_test_java_org_neo4j_visualization_graphviz_TestGraphvizSubgraphOutput.java
2,015
{ @Override public String getSubgraphFor( Node node ) { if ( node.hasProperty( "country_of_residence" ) ) { return (String) node.getProperty( "country_of_residence" ); } return null; } };
false
community_graphviz_src_test_java_org_neo4j_visualization_graphviz_TestGraphvizSubgraphOutput.java
2,016
public class TestGraphvizSubgraphOutput { enum type implements RelationshipType { KNOWS, WORKS_FOR } private GraphDatabaseService neo; @Before public void setUp() { neo = new GraphDatabaseFactory().newEmbeddedDatabase( "target/neo" ); } @After public void tearDown() { neo.shutdown(); } @Test public void testSimpleGraph() throws Exception { Transaction tx = neo.beginTx(); try { final Node emil = neo.createNode(); emil.setProperty( "name", "Emil Eifrém" ); emil.setProperty( "country_of_residence", "USA" ); final Node tobias = neo.createNode(); tobias.setProperty( "name", "Tobias Ivarsson" ); tobias.setProperty( "country_of_residence", "Sweden" ); final Node johan = neo.createNode(); johan.setProperty( "name", "Johan Svensson" ); johan.setProperty( "country_of_residence", "Sweden" ); final Relationship emilKNOWStobias = emil.createRelationshipTo( tobias, type.KNOWS ); final Relationship johanKNOWSemil = johan.createRelationshipTo( emil, type.KNOWS ); final Relationship tobiasKNOWSjohan = tobias.createRelationshipTo( johan, type.KNOWS ); final Relationship tobiasWORKS_FORemil = tobias.createRelationshipTo( emil, type.WORKS_FOR ); OutputStream out = new ByteArrayOutputStream(); SubgraphMapper subgraphMapper = new SubgraphMapper() { @Override public String getSubgraphFor( Node node ) { if ( node.hasProperty( "country_of_residence" ) ) { return (String) node.getProperty( "country_of_residence" ); } return null; } }; GraphvizWriter writer = new GraphvizWriter(); SubgraphMapper.SubgraphMappingWalker walker = new SubgraphMapper.SubgraphMappingWalker( subgraphMapper ) { @Override protected Iterable<Node> nodes() { return asList( emil, tobias, johan ); } @Override protected Iterable<Relationship> relationships() { return asList( emilKNOWStobias, johanKNOWSemil, tobiasKNOWSjohan, tobiasWORKS_FORemil ); } }; writer.emit( out, walker ); tx.success(); System.out.println( out.toString() ); } finally { tx.finish(); } } }
false
community_graphviz_src_test_java_org_neo4j_visualization_graphviz_TestGraphvizSubgraphOutput.java
2,017
{ public String format( String key, PropertyType type, Object value ) { return configuration.escapeLabel( key ) + " : " + type.typeName; } };
false
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_StyleParameter.java
2,018
PROPERTY_AS_KEY_COLON_TYPE { @Override public final void configure( final StyleConfiguration configuration ) { PropertyFormatter format = new PropertyFormatter() { public String format( String key, PropertyType type, Object value ) { return configuration.escapeLabel( key ) + " : " + type.typeName; } }; configuration.setNodePropertyFomatter( format ); configuration.setRelationshipPropertyFomatter( format ); } };
false
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_StyleParameter.java
2,019
{ public String format( String key, PropertyType type, Object value ) { return configuration.escapeLabel( key ) + " = " + configuration.escapeLabel( PropertyType.format( value ) ); } };
false
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_StyleParameter.java
2,020
PROPERTY_AS_KEY_EQUALS_VALUE { @Override public final void configure( final StyleConfiguration configuration ) { PropertyFormatter format = new PropertyFormatter() { public String format( String key, PropertyType type, Object value ) { return configuration.escapeLabel( key ) + " = " + configuration.escapeLabel( PropertyType.format( value ) ); } }; configuration.setNodePropertyFomatter( format ); configuration.setRelationshipPropertyFomatter( format ); } },
false
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_StyleParameter.java
2,021
{ public String format( String key, PropertyType type, Object value ) { return configuration.escapeLabel( key ) + " = " + configuration.escapeLabel(PropertyType.format( value )) + " : " + type.typeName; } };
false
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_StyleParameter.java
2,022
PROPERTY_AS_KEY_EQUALS_VALUE_COLON_TYPE { @Override public final void configure( final StyleConfiguration configuration ) { PropertyFormatter format = new PropertyFormatter() { public String format( String key, PropertyType type, Object value ) { return configuration.escapeLabel( key ) + " = " + configuration.escapeLabel(PropertyType.format( value )) + " : " + type.typeName; } }; configuration.setNodePropertyFomatter( format ); configuration.setRelationshipPropertyFomatter( format ); } },
false
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_StyleParameter.java
2,023
NO_RELATIONSHIP_LABEL { @Override public final void configure( StyleConfiguration configuration ) { configuration.displayRelationshipLabel( false ); } },
false
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_StyleParameter.java
2,024
{ public boolean acceptProperty( String key ) { return false; } } );
false
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_StyleParameter.java
2,025
NO_RELATIONSHIP_PROPERTIES { @Override public final void configure( StyleConfiguration configuration ) { configuration .setRelationshipPropertyFilter( new PropertyFilter() { public boolean acceptProperty( String key ) { return false; } } ); } },
false
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_StyleParameter.java
2,026
{ public boolean accept( Relationship item ) { return reversedOrder( item ); } } );
false
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_StyleParameter.java
2,027
abstract class ReverseRelationshipOrder implements StyleParameter { public void configure( StyleConfiguration configuration ) { configuration.setRelationshipReverseOrderPredicate( new Predicate<Relationship>() { public boolean accept( Relationship item ) { return reversedOrder( item ); } } ); } protected abstract boolean reversedOrder( Relationship edge ); }
false
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_StyleParameter.java
2,028
final class ReverseOrderRelationshipTypes extends ReverseRelationshipOrder { private final Set<String> reversedTypes = new HashSet<String>(); public ReverseOrderRelationshipTypes( RelationshipType... types ) { for ( RelationshipType type : types ) { reversedTypes.add( type.name() ); } } @Override protected boolean reversedOrder( Relationship edge ) { return reversedTypes.contains( edge.getType().name() ); } }
false
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_StyleParameter.java
2,029
BOTH_IGNORE_DIRECTION() { @Override void configure( AutoNodeColor style ) { style.directions = new Direction[] { Direction.INCOMING, Direction.OUTGOING }; style.differentiateOnDirection = false; } },
false
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_color_AutoNodeColor.java
2,030
OUTGOING() { @Override void configure( AutoNodeColor style ) { style.directions = new Direction[] { Direction.OUTGOING }; style.differentiateOnDirection = false; } },
false
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_color_AutoNodeColor.java
2,031
{ @Override protected void createNeoDataSource() { // Register our little special recovery listener neoDataSource = new NeoStoreXaDataSource( config, storeFactory, logging.getMessagesLog( NeoStoreXaDataSource.class ), xaFactory, stateFactory, transactionInterceptorProviders, jobScheduler, logging, updateableSchemaState, new NonTransactionalTokenNameLookup( labelTokenHolder, propertyKeyTokenHolder ), dependencyResolver, txManager, propertyKeyTokenHolder, labelTokenHolder, relationshipTypeTokenHolder, persistenceManager, lockManager, this, recoveryMonitor ); xaDataSourceManager.registerDataSource( neoDataSource ); } };
false
community_neo4j_src_test_java_recovery_TestIndexingServiceRecovery.java
2,032
DIRECTION() { @Override void configure( AutoNodeColor style ) { style.directions = new Direction[] { Direction.INCOMING, Direction.OUTGOING }; style.differentiateOnDirectionOnly = true; } };
false
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_color_AutoNodeColor.java
2,033
{ @SuppressWarnings( "deprecation" ) @Override public GraphDatabaseService newEmbeddedDatabase( String path ) { GraphDatabaseFactoryState state = getStateCopy(); return new EmbeddedGraphDatabase( path, stringMap(), state.databaseDependencies() ) { @Override protected void createNeoDataSource() { // Register our little special recovery listener neoDataSource = new NeoStoreXaDataSource( config, storeFactory, logging.getMessagesLog( NeoStoreXaDataSource.class ), xaFactory, stateFactory, transactionInterceptorProviders, jobScheduler, logging, updateableSchemaState, new NonTransactionalTokenNameLookup( labelTokenHolder, propertyKeyTokenHolder ), dependencyResolver, txManager, propertyKeyTokenHolder, labelTokenHolder, relationshipTypeTokenHolder, persistenceManager, lockManager, this, recoveryMonitor ); xaDataSourceManager.registerDataSource( neoDataSource ); } }; } }.newEmbeddedDatabase( storeDir.getAbsolutePath() );
false
community_neo4j_src_test_java_recovery_TestIndexingServiceRecovery.java
2,034
{ @Override public void applyingRecoveredData( Collection<Long> nodeIds ) { affectedNodeIds.addAll( nodeIds ); } @Override public void appliedRecoveredData( Iterable<NodePropertyUpdate> updates ) { for ( NodePropertyUpdate update : updates ) { allUpdates.add( update ); } } };
false
community_neo4j_src_test_java_recovery_TestIndexingServiceRecovery.java
2,035
public class TestIndexingServiceRecovery { @Test public void shouldRecoverSchemaIndexesAfterNeoStoreFullyRecovered() throws Exception { // GIVEN a db with schema and some data in it File storeDir = forTest( getClass() ).makeGraphDbDir(); Long[] nodeIds = createSchemaData( storeDir ); // crashed store that has at least one 2PC transaction executeSubProcess( getClass(), 30, SECONDS, args( storeDir.getAbsolutePath(), nodeIds ) ); // and that 2PC transaction is missing the 2PC commit record in the neostore data source, // which simulates a 2PC transaction where not all data sources have committed fully. makeItLookLikeNeoStoreDataSourceDidntCommitLastTransaction( storeDir ); // WHEN recovering that store Pair<Collection<Long>, Collection<NodePropertyUpdate>> updatesSeenDuringRecovery = recoverStore( storeDir ); // THEN the index should be recovered with the expected data from neostore int labelId = 0, propertyKey = 0; // TODO bad assuming id 0 assertEquals( "Test contains invalid assumptions. Recovery process should have seen updates around these nodes", asSet( nodeIds ), updatesSeenDuringRecovery.first() ); assertEquals( asSet( add( nodeIds[0], propertyKey, value, new long[] {labelId} ) ), updatesSeenDuringRecovery.other() ); } // The process that will crash the db uses this main method public static void main( String[] args ) { GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase( args[0] ); // Set the property that we'll want to recover try ( Transaction tx = db.beginTx() ) { Node node = db.getNodeById( parseLong( args[1] ) ); node.setProperty( key, value ); tx.success(); } try ( Transaction tx = db.beginTx() ) { // Create an arbitrary 2PC transaction with which we'll use to break shit later on Node otherNode = db.getNodeById( parseLong( args[2] ) ); otherNode.setProperty( "some key", "some value" ); db.index().forNodes( "nodes" ).add( otherNode, key, value ); tx.success(); } // Crash on purpose System.exit( 0 ); } private Pair<Collection<Long>,Collection<NodePropertyUpdate>> recoverStore( File storeDir ) { final Collection<Long> affectedNodeIds = new HashSet<>(); final Collection<NodePropertyUpdate> allUpdates = new HashSet<>(); final IndexingService.Monitor recoveryMonitor = new IndexingService.MonitorAdapter() { @Override public void applyingRecoveredData( Collection<Long> nodeIds ) { affectedNodeIds.addAll( nodeIds ); } @Override public void appliedRecoveredData( Iterable<NodePropertyUpdate> updates ) { for ( NodePropertyUpdate update : updates ) { allUpdates.add( update ); } } }; GraphDatabaseService db = new GraphDatabaseFactory() { @SuppressWarnings( "deprecation" ) @Override public GraphDatabaseService newEmbeddedDatabase( String path ) { GraphDatabaseFactoryState state = getStateCopy(); return new EmbeddedGraphDatabase( path, stringMap(), state.databaseDependencies() ) { @Override protected void createNeoDataSource() { // Register our little special recovery listener neoDataSource = new NeoStoreXaDataSource( config, storeFactory, logging.getMessagesLog( NeoStoreXaDataSource.class ), xaFactory, stateFactory, transactionInterceptorProviders, jobScheduler, logging, updateableSchemaState, new NonTransactionalTokenNameLookup( labelTokenHolder, propertyKeyTokenHolder ), dependencyResolver, txManager, propertyKeyTokenHolder, labelTokenHolder, relationshipTypeTokenHolder, persistenceManager, lockManager, this, recoveryMonitor ); xaDataSourceManager.registerDataSource( neoDataSource ); } }; } }.newEmbeddedDatabase( storeDir.getAbsolutePath() ); db.shutdown(); return Pair.of( affectedNodeIds, allUpdates ); } private Long[] createSchemaData( File storeDir ) { GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase( storeDir.getAbsolutePath() ); try { try ( Transaction tx = db.beginTx() ) { db.schema().indexFor( label ).on( key ).create(); tx.success(); } try ( Transaction tx = db.beginTx() ) { db.schema().awaitIndexesOnline( 10, SECONDS ); tx.success(); } long nodeId; try ( Transaction tx = db.beginTx() ) { Node node = db.createNode( label ); nodeId = node.getId(); tx.success(); } long otherNodeId; try ( Transaction tx = db.beginTx() ) { otherNodeId = db.createNode().getId(); tx.success(); } return new Long[] {nodeId, otherNodeId}; } finally { db.shutdown(); } } private void makeItLookLikeNeoStoreDataSourceDidntCommitLastTransaction( File storeDir ) throws IOException { // Capture the identifier of the last transaction File logFile = single( iterator( oneOrTwo( fs, new File( storeDir, LOGICAL_LOG_DEFAULT_NAME ) ) ) ); final AtomicInteger lastIdentifier = new AtomicInteger(); filterNeostoreLogicalLog( fs, logFile, LogTestUtils.findLastTransactionIdentifier( lastIdentifier ) ); // Filter any commit/prepare/done entries from that transaction LogHook<LogEntry> prune = new LogHookAdapter<LogEntry>() { @Override public boolean accept( LogEntry item ) { // Let through everything exception COMMIT/DONE for the last tx boolean shouldPruneEntry = item.getIdentifier() == lastIdentifier.get() && (item instanceof LogEntry.Commit || item instanceof LogEntry.Done); return !shouldPruneEntry; } }; File tempFile = filterNeostoreLogicalLog( fs, logFile, prune ); fs.deleteFile( logFile ); fs.renameFile( tempFile, logFile ); } private String[] args( String absolutePath, Long[] nodeIds ) { List<String> result = new ArrayList<>(); result.add( absolutePath ); for ( Long id : nodeIds ) { result.add( String.valueOf( id ) ); } return result.toArray( new String[result.size()] ); } @SuppressWarnings( "deprecation" ) private final FileSystemAbstraction fs = new DefaultFileSystemAbstraction(); private static final Label label = label( "Label" ); private static final String key = "key", value = "Value"; }
false
community_neo4j_src_test_java_recovery_TestIndexingServiceRecovery.java
2,036
static class WriteTransaction implements Task { @Override public void run( GraphDatabaseAPI graphdb ) { Transaction tx = graphdb.beginTx(); Node node; try { // hack to get around another bug node = graphdb.createNode(); tx.success(); } finally { tx.finish(); } tx = graphdb.beginTx(); try { node.setProperty( "correct", "yes" ); graphdb.index().forNodes( "nodes" ).add( node, "name", "value" ); tx.success(); } finally { tx.finish(); } } }
false
enterprise_ha_src_test_java_recovery_TestDoubleRecovery.java
2,037
static class Verification implements Task { @Override public void run( GraphDatabaseAPI graphdb ) { assertNotNull( "No graph database", graphdb ); Index<Node> index = graphdb.index().forNodes( "nodes" ); assertNotNull( "No index", index ); Node node = index.get( "name", "value" ).getSingle(); assertNotNull( "could not get the node", node ); assertEquals( "yes", node.getProperty( "correct" ) ); } }
false
enterprise_ha_src_test_java_recovery_TestDoubleRecovery.java
2,038
static class Crash implements Task { @Override public void run( GraphDatabaseAPI graphdb ) { throw new AssertionError( "Should not reach here - the breakpoint should avoid it" ); } }
false
enterprise_ha_src_test_java_recovery_TestDoubleRecovery.java
2,039
{ @Override protected void shutdown( GraphDatabaseService graphdb, boolean normal ) { if ( normal ) super.shutdown( graphdb, normal ); } };
false
enterprise_ha_src_test_java_recovery_TestDoubleRecovery.java
2,040
{ @Override protected void callback( DebugInterface debug ) throws KillSubProcess { if ( twoPhaseCommitIn( debug.thread() ) ) { debug.thread().suspend( null ); this.disable(); afterWrite.countDown(); throw KillSubProcess.withExitCode( -1 ); } } private boolean twoPhaseCommitIn( DebuggedThread thread ) { return !Boolean.parseBoolean( thread.getLocal( 1, "onePhase" ) ); } };
false
enterprise_ha_src_test_java_recovery_TestDoubleRecovery.java
2,041
{ @Override protected void callback( DebugInterface debug ) throws KillSubProcess { afterCrash.countDown(); throw KillSubProcess.withExitCode( -1 ); } };
false
enterprise_ha_src_test_java_recovery_TestDoubleRecovery.java
2,042
@SuppressWarnings( "serial" ) @Ignore public class TestDoubleRecovery extends AbstractSubProcessTestBase { private static final byte[] NEOKERNL = { 'N', 'E', 'O', 'K', 'E', 'R', 'N', 'L', '\0' }; private final CountDownLatch afterWrite = new CountDownLatch( 1 ), afterCrash = new CountDownLatch( 1 ); /* * 1) Do a 2PC transaction, crash when both resource have been prepared and txlog * says "mark as committing" for that tx. * 2) Do recovery and then crash again. * 3) Do recovery and see so that all data is in there. * Also do an incremental backup just to make sure that the logs have gotten the * right records injected. */ @Test public void crashAfter2PCMarkAsCommittingThenCrashAgainAndRecover() throws Exception { String backupDirectory = "target/var/backup-db"; FileUtils.deleteRecursively( new File( backupDirectory ) ); OnlineBackup.from( InetAddress.getLocalHost().getHostAddress() ).full( backupDirectory ); for ( BreakPoint bp : breakpoints( 0 ) ) bp.enable(); runInThread( new WriteTransaction() ); afterWrite.await(); startSubprocesses(); runInThread( new Crash() ); afterCrash.await(); startSubprocesses(); OnlineBackup.from( InetAddress.getLocalHost().getHostAddress() ).incremental( backupDirectory ); run( new Verification() ); GraphDatabaseAPI db = (GraphDatabaseAPI) new GraphDatabaseFactory().newEmbeddedDatabase( backupDirectory ); try { new Verification().run( db ); } finally { db.shutdown(); } } static class WriteTransaction implements Task { @Override public void run( GraphDatabaseAPI graphdb ) { Transaction tx = graphdb.beginTx(); Node node; try { // hack to get around another bug node = graphdb.createNode(); tx.success(); } finally { tx.finish(); } tx = graphdb.beginTx(); try { node.setProperty( "correct", "yes" ); graphdb.index().forNodes( "nodes" ).add( node, "name", "value" ); tx.success(); } finally { tx.finish(); } } } static class Crash implements Task { @Override public void run( GraphDatabaseAPI graphdb ) { throw new AssertionError( "Should not reach here - the breakpoint should avoid it" ); } } static class Verification implements Task { @Override public void run( GraphDatabaseAPI graphdb ) { assertNotNull( "No graph database", graphdb ); Index<Node> index = graphdb.index().forNodes( "nodes" ); assertNotNull( "No index", index ); Node node = index.get( "name", "value" ).getSingle(); assertNotNull( "could not get the node", node ); assertEquals( "yes", node.getProperty( "correct" ) ); } } private final BreakPoint ON_CRASH = new BreakPoint( Crash.class, "run", GraphDatabaseAPI.class ) { @Override protected void callback( DebugInterface debug ) throws KillSubProcess { afterCrash.countDown(); throw KillSubProcess.withExitCode( -1 ); } }; private final BreakPoint BEFORE_ANY_DATASOURCE_2PC = new BreakPoint( XaResourceHelpImpl.class, "commit", Xid.class, boolean.class ) { @Override protected void callback( DebugInterface debug ) throws KillSubProcess { if ( twoPhaseCommitIn( debug.thread() ) ) { debug.thread().suspend( null ); this.disable(); afterWrite.countDown(); throw KillSubProcess.withExitCode( -1 ); } } private boolean twoPhaseCommitIn( DebuggedThread thread ) { return !Boolean.parseBoolean( thread.getLocal( 1, "onePhase" ) ); } }; private final BreakPoint[] breakpointsForBefore2PC = new BreakPoint[] { ON_CRASH, BEFORE_ANY_DATASOURCE_2PC }; @Override protected BreakPoint[] breakpoints( int id ) { return breakpointsForBefore2PC; } private final Bootstrapper bootstrap = bootstrap( this, MapUtil.stringMap( OnlineBackupSettings.online_backup_enabled.name(), Settings.TRUE ) ); @Override protected Bootstrapper bootstrap( int id ) throws IOException { return bootstrap; } private static Bootstrapper bootstrap( TestDoubleRecovery test, Map<String, String> config ) { try { return new Bootstrapper( test, 0, config ) { @Override protected void shutdown( GraphDatabaseService graphdb, boolean normal ) { if ( normal ) super.shutdown( graphdb, normal ); } }; } catch ( IOException e ) { throw new RuntimeException( e ); } } /** * Create a log file that fixes a store that has been subject to this issue. * * Parameters: [filename] [globalId.time] [globalId.sequence] * * Example: TestDoubleRecovery tm_tx_log.1 661819753510181175 3826 */ public static void main( String... args ) throws Exception { GraphDatabaseAPI graphdb = (GraphDatabaseAPI) new GraphDatabaseFactory().newEmbeddedDatabase( "target/test-data/junk" ); try { new WriteTransaction().run( graphdb ); } finally { graphdb.shutdown(); } TxLog log = new TxLog( new File(args[0]), new DefaultFileSystemAbstraction(), new Monitors() ); byte globalId[] = new byte[NEOKERNL.length + 16]; System.arraycopy( NEOKERNL, 0, globalId, 0, NEOKERNL.length ); ByteBuffer byteBuf = ByteBuffer.wrap( globalId ); byteBuf.position( NEOKERNL.length ); byteBuf.putLong( Long.parseLong( args[1] ) ).putLong( Long.parseLong( args[2] ) ); log.txStart( globalId ); log.addBranch( globalId, UTF8.encode( "414141" ) ); log.addBranch( globalId, LuceneDataSource.DEFAULT_BRANCH_ID ); log.markAsCommitting( globalId, ForceMode.unforced ); log.force(); log.close(); } }
false
enterprise_ha_src_test_java_recovery_TestDoubleRecovery.java
2,043
{ private final Set<Integer> prune = new HashSet<Integer>(); @Override public boolean accept( LogEntry item ) { if ( item instanceof TwoPhaseCommit ) { prune.add( item.getIdentifier() ); return false; } else if ( prune.contains( item.getIdentifier() ) ) return false; return true; } @Override public void file( File file ) { } @Override public void done( File file ) { } } );
false
community_neo4j_src_test_java_recovery_CreateTransactionsAndDie.java
2,044
@Ignore( "Used from another test case and is not a test case in itself" ) public class CreateTransactionsAndDie { public static void main( String[] args ) { String storeDir = args[0]; int count = parseInt( args[1] ); GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase( storeDir ); for ( int i = 0; i < 2; i++ ) create1pcTx( db ); for ( int i = 0; i < count; i++ ) create2pcTx( db ); // Intentionally don't shutdown the db cleanly exit( 0 ); } private static void create1pcTx( GraphDatabaseService db ) { try(Transaction tx = db.beginTx()) { db.createNode(); tx.success(); } } private static void create2pcTx( GraphDatabaseService db ) { try(Transaction tx = db.beginTx()) { Node node = db.createNode(); db.index().forNodes( "index" ).add( node, "key", "value" ); tx.success(); } } public static String produceNonCleanDbWhichWillRecover2PCsOnStartup( String name, int nrOf2PcTransactionsToRecover ) throws Exception { FileSystemAbstraction fileSystem = new DefaultFileSystemAbstraction(); String dir = TargetDirectory.forTest( CreateTransactionsAndDie.class ).cleanDirectory( name ).getAbsolutePath(); assertEquals( 0, createUncleanDb( dir, nrOf2PcTransactionsToRecover ) ); filterTxLog( fileSystem, dir, EVERYTHING_BUT_DONE_RECORDS ); remove2PCAndDoneFromLog( fileSystem, dir ); // Here we have produced a state which looks like a couple of 2PC transactions // that are marked as committed, but not actually committed. return dir; } private static int createUncleanDb( String dir, int nrOf2PcTransactionsToRecover ) throws Exception { Process process = Runtime.getRuntime().exec( new String[]{ "java", "-cp", System.getProperty( "java.class.path" ), CreateTransactionsAndDie.class.getName(), dir, "" + nrOf2PcTransactionsToRecover } ); return new ProcessStreamHandler( process, true ).waitForResult(); } private static void remove2PCAndDoneFromLog( FileSystemAbstraction fileSystem, String dir ) throws IOException { filterNeostoreLogicalLog( fileSystem, dir, new LogTestUtils.LogHook<LogEntry>() { private final Set<Integer> prune = new HashSet<Integer>(); @Override public boolean accept( LogEntry item ) { if ( item instanceof TwoPhaseCommit ) { prune.add( item.getIdentifier() ); return false; } else if ( prune.contains( item.getIdentifier() ) ) return false; return true; } @Override public void file( File file ) { } @Override public void done( File file ) { } } ); } }
false
community_neo4j_src_test_java_recovery_CreateTransactionsAndDie.java
2,045
{ @Override public <R, E extends Throwable> R accept( Visitor<R, E> visitor ) throws E { for ( Node node : nodes ) { visitor.visitNode( node ); for ( Relationship relationship : node.getRelationships( types ) ) { if ( nodes.contains( relationship.getOtherNode( node ) ) ) { visitor.visitRelationship( relationship ); } } } return visitor.done(); } };
false
community_graphviz_src_main_java_org_neo4j_walk_Walker.java
2,046
{ @Override public <R, E extends Throwable> R accept( Visitor<R, E> visitor ) throws E { for ( Node node : GlobalGraphOperations.at( graphDb ).getAllNodes() ) { visitor.visitNode( node ); for ( Relationship edge : node.getRelationships( Direction.OUTGOING ) ) { visitor.visitRelationship( edge ); } } return visitor.done(); } };
false
community_graphviz_src_main_java_org_neo4j_walk_Walker.java
2,047
public abstract class Walker { public abstract <R, E extends Throwable> R accept( Visitor<R, E> visitor ) throws E; public static Walker fullGraph( final GraphDatabaseService graphDb ) { return new Walker() { @Override public <R, E extends Throwable> R accept( Visitor<R, E> visitor ) throws E { for ( Node node : GlobalGraphOperations.at( graphDb ).getAllNodes() ) { visitor.visitNode( node ); for ( Relationship edge : node.getRelationships( Direction.OUTGOING ) ) { visitor.visitRelationship( edge ); } } return visitor.done(); } }; } public static Walker crosscut( Iterable<Node> traverser, final RelationshipType... types ) { final Set<Node> nodes = new HashSet<Node>(); for ( Node node : traverser ) { nodes.add( node ); } return new Walker() { @Override public <R, E extends Throwable> R accept( Visitor<R, E> visitor ) throws E { for ( Node node : nodes ) { visitor.visitNode( node ); for ( Relationship relationship : node.getRelationships( types ) ) { if ( nodes.contains( relationship.getOtherNode( node ) ) ) { visitor.visitRelationship( relationship ); } } } return visitor.done(); } }; } }
false
community_graphviz_src_main_java_org_neo4j_walk_Walker.java
2,048
public class SimpleRelationshipTypeColorMapper implements ColorMapper<RelationshipType> { private final Map<String, Color> mappings; /** * Map relationship types represented as strings to colors. * * @param mappings relationship type names to color mappings */ public SimpleRelationshipTypeColorMapper( Map<String, Color> mappings ) { this.mappings = mappings; } @Override public Color getColor( RelationshipType type ) { return mappings.get( type.name() ); } @Override public Collection<Color> getColors() { return mappings.values(); } }
false
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_color_SimpleRelationshipTypeColorMapper.java
2,049
public class SimpleNodeColorMapper implements ColorMapper<Node> { private final Map<Object, Color> mappings; private final String propertyKey; /** * Map from property values to colors. * * @param propertyKey the key to the value we will map * @param mappings property values to color mappings */ public SimpleNodeColorMapper( String propertyKey, Map<Object, Color> mappings ) { this.propertyKey = propertyKey; this.mappings = mappings; } @Override public Color getColor( Node entity ) { return mappings.get( entity.getProperty( propertyKey, null ) ); } @Override public Collection<Color> getColors() { return mappings.values(); } }
false
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_color_SimpleNodeColorMapper.java
2,050
public class DefaultColorMapping<E> { private final List<String> availableColors = new ArrayList<String>(); private int usedAvailableColors = 0; private final Map<E, String> colorMappings = new HashMap<E, String>(); /** * Map colors using the full set of colors in {@link Color}. */ public DefaultColorMapping() { this( Collections.<Color>emptyList() ); } /** * Map colors from {@link Color} while excluding the reserved colors. * * Both the dark and light variation of the colors are excluded, even though * only the dark variation will be used by the reserved mapping. * * @param reservedColors colors this mapper shouldn't use */ public DefaultColorMapping( Collection<Color> reservedColors ) { Color[] existingColors = Color.values(); // add the dark colors first, then the lighter ones for ( Color color : existingColors ) { if ( !reservedColors.contains( color ) ) { availableColors.add( color.dark ); } } for ( Color color : existingColors ) { if ( !reservedColors.contains( color ) ) { availableColors.add( color.light ); } } } /** * Get the color for a key as a string. * * @param key the key * @return the color as a String */ protected String getColor( E key ) { String color = colorMappings.get( key ); if ( color == null ) { color = availableColors.get( usedAvailableColors % availableColors.size() ); usedAvailableColors++; colorMappings.put( key, color ); } return color; } /** * Get the color string value for a reserved color. * * @param color * @return */ protected String getColor( Color color ) { return color.dark; } }
false
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_color_DefaultColorMapping.java
2,051
public class AutoRelationshipTypeColor extends RelationshipTypeColor { private final DefaultColorMapping<String> colors; private ColorMapper<RelationshipType> rtcm = null; /** * Use default color mappings. */ public AutoRelationshipTypeColor() { this.colors = new DefaultColorMapping<String>(); } /** * Reserve and map colors for relationship types. Any non-mapped * relationship types will be automatically mapped to non-reserved colors. * * @param rtcm relationship type to color mapper */ public AutoRelationshipTypeColor( ColorMapper<RelationshipType> rtcm ) { this.rtcm = rtcm; this.colors = new DefaultColorMapping<String>( rtcm.getColors() ); } @Override protected String getColor( RelationshipType type ) { if ( rtcm != null ) { Color color = rtcm.getColor( type ); if ( color != null ) { return colors.getColor( color ); } } return colors.getColor( type.name() ); } }
false
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_color_AutoRelationshipTypeColor.java
2,052
{ @Override public Iterator<Node> iterator() { return nodeManager.getAllNodes(); } };
false
community_kernel_src_main_java_org_neo4j_tooling_GlobalGraphOperations.java
2,053
public class GlobalGraphOperations { private final NodeManager nodeManager; private final ThreadToStatementContextBridge statementCtxProvider; private GlobalGraphOperations( GraphDatabaseService db ) { GraphDatabaseAPI dbApi = (GraphDatabaseAPI) db; DependencyResolver resolver = dbApi.getDependencyResolver(); this.nodeManager = resolver.resolveDependency( NodeManager.class ); this.statementCtxProvider = resolver.resolveDependency( ThreadToStatementContextBridge.class ); } /** * Get a {@link GlobalGraphOperations} for the given {@code db}. * * @param db the {@link GraphDatabaseService} to get global operations for. * @return {@link GlobalGraphOperations} for the given {@code db}. */ public static GlobalGraphOperations at( GraphDatabaseService db ) { return new GlobalGraphOperations( db ); } /** * Returns all nodes in the graph. * * @return all nodes in the graph. */ public Iterable<Node> getAllNodes() { assertInTransaction(); return new Iterable<Node>() { @Override public Iterator<Node> iterator() { return nodeManager.getAllNodes(); } }; } /** * Returns all relationships in the graph. * * @return all relationships in the graph. */ public Iterable<Relationship> getAllRelationships() { assertInTransaction(); return new Iterable<Relationship>() { @Override public Iterator<Relationship> iterator() { return nodeManager.getAllRelationships(); } }; } /** * Returns all relationship types currently in the underlying store. Relationship types are * added to the underlying store the first time they are used in a successfully committed * {@link Node#createRelationshipTo node.createRelationshipTo(...)}. Note that this method is * guaranteed to return all known relationship types, but it does not guarantee that it won't * return <i>more</i> than that (e.g. it can return "historic" relationship types that no longer * have any relationships in the graph). * * @return all relationship types in the underlying store */ public Iterable<RelationshipType> getAllRelationshipTypes() { assertInTransaction(); return nodeManager.getRelationshipTypes(); } /** * Returns all labels currently in the underlying store. Labels are added to the store the first * they are used. This method guarantees that it will return all labels currently in use. However, * it may also return <i>more</i> than that (e.g. it can return "historic" labels that are no longer used). * * Please take care that the returned {@link ResourceIterable} is closed correctly and as soon as possible * inside your transaction to avoid potential blocking of write operations. * * @return all labels in the underlying store. */ public ResourceIterable<Label> getAllLabels() { assertInTransaction(); return new ResourceIterable<Label>() { @Override public ResourceIterator<Label> iterator() { Statement statement = statementCtxProvider.instance(); return ResourceClosingIterator.newResourceIterator( statement, map( new Function<Token, Label>() { @Override public Label apply( Token labelToken ) { return label( labelToken.name() ); } }, statement.readOperations().labelsGetAllTokens() ) ); } }; } /** * Returns all property keys currently in the underlying store. This method guarantees that it will return all * property keys currently in use. However, it may also return <i>more</i> than that (e.g. it can return "historic" * labels that are no longer used). * * Please take care that the returned {@link ResourceIterable} is closed correctly and as soon as possible * inside your transaction to avoid potential blocking of write operations. * * @return all property keys in the underlying store. */ public ResourceIterable<String> getAllPropertyKeys() { assertInTransaction(); return new ResourceIterable<String>() { @Override public ResourceIterator<String> iterator() { Statement statement = statementCtxProvider.instance(); return ResourceClosingIterator.newResourceIterator( statement, map( new Function<Token, String>() { @Override public String apply( Token propertyToken ) { return propertyToken.name(); } }, statement.readOperations().propertyKeyGetAllTokens() ) ); } }; } /** * Returns all {@link Node nodes} with a specific {@link Label label}. * * Please take care that the returned {@link ResourceIterable} is closed correctly and as soon as possible * inside your transaction to avoid potential blocking of write operations. * * @param label the {@link Label} to return nodes for. * @return {@link Iterable} containing nodes with a specific label. */ public ResourceIterable<Node> getAllNodesWithLabel( final Label label ) { assertInTransaction(); return new ResourceIterable<Node>() { @Override public ResourceIterator<Node> iterator() { return allNodesWithLabel( label.name() ); } }; } private ResourceIterator<Node> allNodesWithLabel( String label ) { Statement statement = statementCtxProvider.instance(); int labelId = statement.readOperations().labelGetForName( label ); if ( labelId == KeyReadOperations.NO_SUCH_LABEL ) { statement.close(); return emptyIterator(); } final PrimitiveLongIterator nodeIds = statement.readOperations().nodesGetForLabel( labelId ); return ResourceClosingIterator.newResourceIterator( statement, map( new FunctionFromPrimitiveLong<Node>() { @Override public Node apply( long nodeId ) { return nodeManager.getNodeById( nodeId ); } }, nodeIds ) ); } private void assertInTransaction() { statementCtxProvider.assertInTransaction(); } }
false
community_kernel_src_main_java_org_neo4j_tooling_GlobalGraphOperations.java
2,054
public class GenerateDefaultNeo4jProperties { public static void main( String[] args ) throws ClassNotFoundException { for( String settingsClassName : args ) { Class settingsClass = GenerateDefaultNeo4jProperties.class.getClassLoader().loadClass( settingsClassName ); ResourceBundle bundle = new SettingsResourceBundle(settingsClass); if (bundle.containsKey( "description" )) { System.out.println( "# " ); System.out.println( "# "+bundle.getString( "description" ) ); System.out.println( "# " ); System.out.println( ); } Set<String> keys = bundle.keySet(); for( String property : keys ) { if (property.endsWith( ".description" )) { // Output description String name = property.substring( 0, property.lastIndexOf( "." ) ); System.out.println( "# "+bundle.getString( property ) ); // Output optional options String optionsKey = name+".options"; if (bundle.containsKey( optionsKey )) { String[] options = bundle.getString( optionsKey ).split( "," ); if (bundle.containsKey( name+".option."+options[0] )) { System.out.println("# Valid settings:"); for( String option : options ) { String description = bundle.getString( name + ".option." + option ); char[] spaces = new char[ option.length() + 3 ]; Arrays.fill( spaces,' ' ); description = description.replace( "\n", "\n#"+ new String( spaces ) ); System.out.println("# "+option+": "+ description ); } } else { System.out.println("# Valid settings:"+bundle.getString( optionsKey )); } } String defaultKey = name + ".default"; if (bundle.containsKey( defaultKey )) { System.out.println( name+"="+bundle.getString( defaultKey ) ); } else { System.out.println( "# "+name+"=" ); } System.out.println( ); } } } } }
false
community_kernel_src_main_java_org_neo4j_tooling_GenerateDefaultNeo4jProperties.java
2,055
{ @Override public void evaluate() throws Throwable { try { base.evaluate(); } finally { for ( Closeable resource : resources ) { resource.close(); } } } };
false
community_kernel_src_test_java_org_neo4j_test_ResourceCollection.java
2,056
private static class RepeatStatement extends Statement { private final int times; private final Statement statement; private RepeatStatement( int times, Statement statement ) { this.times = times; this.statement = statement; } @Override public void evaluate() throws Throwable { for ( int i = 0; i < times; i++ ) { statement.evaluate(); } } }
false
community_kernel_src_test_java_org_neo4j_test_RepeatRule.java
2,057
public class RepeatRule implements TestRule { @Retention( RetentionPolicy.RUNTIME ) @Target(ElementType.METHOD) public @interface Repeat { public abstract int times(); } private static class RepeatStatement extends Statement { private final int times; private final Statement statement; private RepeatStatement( int times, Statement statement ) { this.times = times; this.statement = statement; } @Override public void evaluate() throws Throwable { for ( int i = 0; i < times; i++ ) { statement.evaluate(); } } } @Override public Statement apply( Statement base, Description description ) { Repeat repeat = description.getAnnotation(Repeat.class); if(repeat != null) { return new RepeatStatement( repeat.times(), base ); } return base; } }
false
community_kernel_src_test_java_org_neo4j_test_RepeatRule.java
2,058
public class ReflectionUtil { private static final ReflectionFactory reflectionFactory = ReflectionFactory.getReflectionFactory(); public static void setStaticFinalField( Field field, Object value ) throws NoSuchFieldException, IllegalAccessException { field.setAccessible( true ); final Field modifiersField = Field.class.getDeclaredField( "modifiers" ); modifiersField.setAccessible( true ); int modifiers = modifiersField.getInt( field ); modifiers &= ~Modifier.FINAL; modifiersField.setInt( field, modifiers ); final FieldAccessor fieldAccessor = reflectionFactory.newFieldAccessor( field, false ); fieldAccessor.set( null, value ); } public static <T> T getPrivateField( Object target, String fieldName, Class<T> fieldType ) throws Exception { Class<?> type = target.getClass(); Field field = getField( fieldName, type ); if ( !fieldType.isAssignableFrom( field.getType() ) ) { throw new IllegalArgumentException( "Field type does not match " + field.getType() + " is no subclass of " + "" + fieldType ); } field.setAccessible( true ); return fieldType.cast( field.get( target ) ); } private static Field getField( String fieldName, Class<? extends Object> type ) throws NoSuchFieldException { if ( type == null ) { throw new NoSuchFieldException( fieldName ); } try { Field field = type.getDeclaredField( fieldName ); if ( field != null ) { return field; } } catch ( NoSuchFieldError e ) { // Ignore - it might be in the super type } catch ( NoSuchFieldException e ) { // Ignore - it might be in the super type } return getField( fieldName, type.getSuperclass() ); } }
false
community_kernel_src_test_java_org_neo4j_test_ReflectionUtil.java
2,059
public final class Property { public static Property property( String key, Object value ) { return new Property( key, value ); } public static <E extends PropertyContainer> E set( E entity, Property... properties ) { for ( Property property : properties ) { entity.setProperty( property.key, property.value ); } return entity; } private final String key; private final Object value; private Property( String key, Object value ) { this.key = key; this.value = value; } public String key() { return key; } public Object value() { return value; } @Override public String toString() { return String.format( "%s: %s", key, value ); } }
false
community_kernel_src_test_java_org_neo4j_test_Property.java
2,060
{ @Override public boolean cancel( boolean mayInterruptIfRunning ) { try { return realFuture.cancel( mayInterruptIfRunning ); } finally { processOutput.done(); } } @Override public boolean isCancelled() { return realFuture.isCancelled(); } @Override public boolean isDone() { return realFuture.isDone(); } @Override public Integer get() throws InterruptedException, ExecutionException { try { return realFuture.get(); } finally { processOutput.done(); } } @Override public Integer get( long timeout, TimeUnit unit ) throws InterruptedException, ExecutionException, TimeoutException { try { return realFuture.get( timeout, unit ); } finally { processOutput.done(); } } };
false
community_kernel_src_test_java_org_neo4j_test_ProcessUtil.java
2,061
public class ProcessUtil { public static void executeSubProcess( Class<?> mainClass, long timeout, TimeUnit unit, String... arguments ) throws Exception { Future<Integer> future = startSubProcess( mainClass, arguments ); int result = future.get( timeout, unit ); if ( result != 0 ) { throw new RuntimeException( "Process for " + mainClass + " with arguments " + Arrays.toString( arguments ) + " failed, returned exit value " + result ); } } public static Future<Integer> startSubProcess( Class<?> mainClass, String... arguments ) throws IOException { List<String> args = new ArrayList<>(); args.addAll( asList( "java", "-cp", System.getProperty( "java.class.path" ), mainClass.getName() ) ); args.addAll( asList( arguments ) ); Process process = Runtime.getRuntime().exec( args.toArray( new String[args.size()] ) ); final ProcessStreamHandler processOutput = new ProcessStreamHandler( process, false ); processOutput.launch(); final Future<Integer> realFuture = FutureAdapter.processFuture( process ); return new Future<Integer>() { @Override public boolean cancel( boolean mayInterruptIfRunning ) { try { return realFuture.cancel( mayInterruptIfRunning ); } finally { processOutput.done(); } } @Override public boolean isCancelled() { return realFuture.isCancelled(); } @Override public boolean isDone() { return realFuture.isDone(); } @Override public Integer get() throws InterruptedException, ExecutionException { try { return realFuture.get(); } finally { processOutput.done(); } } @Override public Integer get( long timeout, TimeUnit unit ) throws InterruptedException, ExecutionException, TimeoutException { try { return realFuture.get( timeout, unit ); } finally { processOutput.done(); } } }; } }
false
community_kernel_src_test_java_org_neo4j_test_ProcessUtil.java
2,062
public class ProcessStreamHandler { private final Thread out; private final Thread err; private final Process process; /** * Convenience constructor assuming the local output streams are * {@link System.out} and {@link System.err} for the process's OutputStream * and ErrorStream respectively. * * Set quiet to true if you just want to consume the output to avoid locking up the process. * * @param process The process whose output to consume. */ public ProcessStreamHandler( Process process, boolean quiet ) { this( process, quiet, "", quiet ? IGNORE_FAILURES : PRINT_FAILURES ); } public ProcessStreamHandler( Process process, boolean quiet, String prefix, StreamExceptionHandler failureHandler ) { this( process, quiet, prefix, failureHandler, System.out, System.err ); } public ProcessStreamHandler( Process process, boolean quiet, String prefix, StreamExceptionHandler failureHandler, PrintStream out, PrintStream err ) { this.process = process; this.out = new Thread( new StreamConsumer( process.getInputStream(), out, quiet, prefix, failureHandler ) ); this.err = new Thread( new StreamConsumer( process.getErrorStream(), err, quiet, prefix, failureHandler ) ); } /** * Starts the consumer threads. Calls {@link Thread#start()}. */ public void launch() { out.start(); err.start(); } /** * Joins with the consumer Threads. Calls {@link Thread#join()} on the two * consumers. */ public void done() { try { out.join(); } catch( InterruptedException e ) { Thread.interrupted(); e.printStackTrace(); } try { err.join(); } catch( InterruptedException e ) { Thread.interrupted(); e.printStackTrace(); } } public void cancel() { out.interrupt(); err.interrupt(); } public int waitForResult() { launch(); try { try { return process.waitFor(); } catch( InterruptedException e ) { Thread.interrupted(); return 0; } } finally { done(); } } }
false
community_kernel_src_test_java_org_neo4j_test_ProcessStreamHandler.java
2,063
{ @Override public void evaluate() throws Throwable { executor = new OtherThreadExecutor<>( description.getDisplayName(), timeout, unit, initialState() ); try { base.evaluate(); } finally { try { executor.close(); } finally { executor = null; } } } };
false
community_kernel_src_test_java_org_neo4j_test_OtherThreadRule.java
2,064
{ @Override protected boolean matchesSafely( OtherThreadRule rule ) { try { rule.executor.waitUntilThreadState( Thread.State.WAITING, Thread.State.TIMED_WAITING ); return true; } catch ( TimeoutException e ) { rule.executor.printStackTrace( System.err ); return false; } } @Override public void describeTo( org.hamcrest.Description description ) { description.appendText( "Thread blocked in state WAITING" ); } };
false
community_kernel_src_test_java_org_neo4j_test_OtherThreadRule.java
2,065
public class OtherThreadRule<STATE> implements TestRule { private final long timeout; private final TimeUnit unit; private volatile OtherThreadExecutor<STATE> executor; public OtherThreadRule() { this( 10, SECONDS ); } public OtherThreadRule( long timeout, TimeUnit unit ) { this.timeout = timeout; this.unit = unit; } public <RESULT> Future<RESULT> execute( OtherThreadExecutor.WorkerCommand<STATE, RESULT> cmd ) { Future<RESULT> future = executor.executeDontWait( cmd ); try { executor.awaitStartExecuting(); } catch ( InterruptedException e ) { throw new RuntimeException( "Interrupted while awaiting start of execution.", e ); } return future; } protected STATE initialState() { return null; } public static Matcher<OtherThreadRule> isWaiting() { return new TypeSafeMatcher<OtherThreadRule>() { @Override protected boolean matchesSafely( OtherThreadRule rule ) { try { rule.executor.waitUntilThreadState( Thread.State.WAITING, Thread.State.TIMED_WAITING ); return true; } catch ( TimeoutException e ) { rule.executor.printStackTrace( System.err ); return false; } } @Override public void describeTo( org.hamcrest.Description description ) { description.appendText( "Thread blocked in state WAITING" ); } }; } @Override public String toString() { OtherThreadExecutor<STATE> otherThread = executor; if ( otherThread == null ) { return "OtherThreadRule[state=dead]"; } return otherThread.toString(); } // Implementation of TestRule @Override public Statement apply( final Statement base, final Description description ) { return new Statement() { @Override public void evaluate() throws Throwable { executor = new OtherThreadExecutor<>( description.getDisplayName(), timeout, unit, initialState() ); try { base.evaluate(); } finally { try { executor.close(); } finally { executor = null; } } } }; } }
false
community_kernel_src_test_java_org_neo4j_test_OtherThreadRule.java
2,066
public static class WaitDetails { private final StackTraceElement[] stackTrace; public WaitDetails( StackTraceElement[] stackTrace ) { this.stackTrace = stackTrace; } @Override public String toString() { StringBuilder builder = new StringBuilder(); for ( StackTraceElement element : stackTrace ) { builder.append( format( element.toString() + "%n" ) ); } return builder.toString(); } }
false
community_kernel_src_test_java_org_neo4j_test_OtherThreadExecutor.java
2,067
private static final class AnyThreadState implements Predicate<Thread> { private final Set<State> possibleStates; private final Set<Thread.State> seenStates = new HashSet<>(); private AnyThreadState( State... possibleStates ) { this.possibleStates = new HashSet<>( asList( possibleStates ) ); } @Override public boolean accept( Thread thread ) { State threadState = thread.getState(); seenStates.add( threadState ); return possibleStates.contains( threadState ); } @Override public String toString() { return "Any of thread states " + possibleStates + ", but saw " + seenStates; } }
false
community_kernel_src_test_java_org_neo4j_test_OtherThreadExecutor.java
2,068
{ @Override public void run() { try { super.run(); } finally { OtherThreadExecutor.this.thread = null; } } };
false
community_kernel_src_test_java_org_neo4j_test_OtherThreadExecutor.java
2,069
{ @Override public R call() throws Exception { executionState = ExecutionState.EXECUTING; try { return cmd.doWork( state ); } finally { executionState = ExecutionState.EXECUTED; } } } );
false
community_kernel_src_test_java_org_neo4j_test_OtherThreadExecutor.java
2,070
{ @Override public boolean accept( Thread thread ) { return actual.accept( thread ) || executionState == ExecutionState.EXECUTED; } };
false
community_kernel_src_test_java_org_neo4j_test_OtherThreadExecutor.java
2,071
public class OtherThreadExecutor<T> implements ThreadFactory, Visitor<LineLogger, RuntimeException>, Closeable { private final ExecutorService commandExecutor = newSingleThreadExecutor( this ); protected final T state; private volatile Thread thread; private volatile ExecutionState executionState; private final String name; private final long timeout; private Exception lastExecutionTrigger; private static final class AnyThreadState implements Predicate<Thread> { private final Set<State> possibleStates; private final Set<Thread.State> seenStates = new HashSet<>(); private AnyThreadState( State... possibleStates ) { this.possibleStates = new HashSet<>( asList( possibleStates ) ); } @Override public boolean accept( Thread thread ) { State threadState = thread.getState(); seenStates.add( threadState ); return possibleStates.contains( threadState ); } @Override public String toString() { return "Any of thread states " + possibleStates + ", but saw " + seenStates; } } public static Predicate<Thread> anyThreadState( State... possibleStates ) { return new AnyThreadState( possibleStates ); } public Predicate<Thread> orExecutionCompleted( final Predicate<Thread> actual ) { return new Predicate<Thread>() { @Override public boolean accept( Thread thread ) { return actual.accept( thread ) || executionState == ExecutionState.EXECUTED; } }; } private static enum ExecutionState { REQUESTED_EXECUTION, EXECUTING, EXECUTED } public OtherThreadExecutor( String name, T initialState ) { this( name, 10, SECONDS, initialState ); } public OtherThreadExecutor( String name, long timeout, TimeUnit unit, T initialState ) { this.name = name; this.state = initialState; this.timeout = MILLISECONDS.convert( timeout, unit ); } public <R> Future<R> executeDontWait( final WorkerCommand<T, R> cmd ) { lastExecutionTrigger = new Exception(); executionState = ExecutionState.REQUESTED_EXECUTION; return commandExecutor.submit( new Callable<R>() { @Override public R call() throws Exception { executionState = ExecutionState.EXECUTING; try { return cmd.doWork( state ); } finally { executionState = ExecutionState.EXECUTED; } } } ); } public <R> R execute( WorkerCommand<T, R> cmd ) throws Exception { return executeDontWait( cmd ).get(); } public <R> R execute( WorkerCommand<T, R> cmd, long timeout, TimeUnit unit ) throws Exception { Future<R> future = executeDontWait( cmd ); boolean success = false; try { awaitStartExecuting(); R result = future.get( timeout, unit ); success = true; return result; } finally { if ( !success ) { future.cancel( true ); } } } void awaitStartExecuting() throws InterruptedException { while ( executionState == ExecutionState.REQUESTED_EXECUTION ) { Thread.sleep( 10 ); } } public <R> R awaitFuture( Future<R> future ) throws InterruptedException, ExecutionException, TimeoutException { return future.get( timeout, MILLISECONDS ); } public interface WorkerCommand<T, R> { R doWork( T state ) throws Exception; } @Override public Thread newThread( Runnable r ) { Thread thread = new Thread( r, getClass().getName() + ":" + name ) { @Override public void run() { try { super.run(); } finally { OtherThreadExecutor.this.thread = null; } } }; this.thread = thread; return thread; } @Override public String toString() { Thread thread = this.thread; return format( "%s[%s,state=%s]", getClass().getSimpleName(), name, thread == null ? "dead" : thread.getState() ); } public WaitDetails waitUntilWaiting() throws TimeoutException { return waitUntilThreadState( Thread.State.WAITING ); } public WaitDetails waitUntilBlocked() throws TimeoutException { return waitUntilThreadState( Thread.State.BLOCKED ); } public WaitDetails waitUntilThreadState( final Thread.State... possibleStates ) throws TimeoutException { return waitUntil( new AnyThreadState( possibleStates ) ); } public WaitDetails waitUntil( Predicate<Thread> condition ) throws TimeoutException { long end = System.currentTimeMillis() + timeout; Thread thread = getThread(); while ( !condition.accept( thread ) || executionState == ExecutionState.REQUESTED_EXECUTION ) { try { Thread.sleep( 1 ); } catch ( InterruptedException e ) { // whatever } if ( System.currentTimeMillis() > end ) { throw new TimeoutException( "The executor didn't meet condition '" + condition + "' inside an executing command for " + timeout + " ms" ); } } return new WaitDetails( thread.getStackTrace() ); } public static class WaitDetails { private final StackTraceElement[] stackTrace; public WaitDetails( StackTraceElement[] stackTrace ) { this.stackTrace = stackTrace; } @Override public String toString() { StringBuilder builder = new StringBuilder(); for ( StackTraceElement element : stackTrace ) { builder.append( format( element.toString() + "%n" ) ); } return builder.toString(); } } private Thread getThread() { Thread thread = null; while ( thread == null ) { thread = this.thread; } return thread; } @Override public void close() { commandExecutor.shutdown(); try { commandExecutor.awaitTermination( 10, TimeUnit.SECONDS ); } catch ( Exception e ) { commandExecutor.shutdownNow(); } } @Override public boolean visit( LineLogger logger ) { logger.logLine( getClass().getName() + ", " + this + " state:" + state + " thread:" + thread + " execution:" + executionState ); if ( thread != null ) { logger.logLine( "Thread state:" + thread.getState() ); logger.logLine( "" ); for ( StackTraceElement element : thread.getStackTrace() ) { logger.logLine( element.toString() ); } } else { logger.logLine( "No operations performed yet, so no thread" ); } if ( lastExecutionTrigger != null ) { logger.logLine( "" ); logger.logLine( "Last execution triggered from:" ); for ( StackTraceElement element : lastExecutionTrigger.getStackTrace() ) { logger.logLine( element.toString() ); } } return true; } void printStackTrace( PrintStream out ) { Thread thread = getThread(); out.println( thread ); for ( StackTraceElement trace : thread.getStackTrace() ) { out.println( "\tat " + trace ); } } }
false
community_kernel_src_test_java_org_neo4j_test_OtherThreadExecutor.java
2,072
private static abstract class Voice { abstract void restore( boolean failure ) throws IOException; }
false
community_kernel_src_test_java_org_neo4j_test_Mute.java
2,073
{ @Override void restore( boolean failure ) throws IOException { replace( old ).flush(); if ( failure ) { old.write( buffer.toByteArray() ); } } };
false
community_kernel_src_test_java_org_neo4j_test_Mute.java
2,074
err { @Override PrintStream replace( PrintStream replacement ) { PrintStream old = java.lang.System.err; java.lang.System.setErr( replacement ); return old; } };
false
community_kernel_src_test_java_org_neo4j_test_Mute.java
2,075
public class ResourceCollection implements TestRule { private final LinkedList<Closeable> resources = new LinkedList<Closeable>(); @Override public Statement apply( final Statement base, Description description ) { return new Statement() { @Override public void evaluate() throws Throwable { try { base.evaluate(); } finally { for ( Closeable resource : resources ) { resource.close(); } } } }; } public <T extends Closeable> T add( T resource ) { resources.addFirst( resource ); return resource; } }
false
community_kernel_src_test_java_org_neo4j_test_ResourceCollection.java
2,076
public class StreamConsumer implements Runnable { public interface StreamExceptionHandler { void handle( IOException failure ); } public static StreamExceptionHandler PRINT_FAILURES = new StreamExceptionHandler() { @Override public void handle( IOException failure ) { failure.printStackTrace(); } }; public static StreamExceptionHandler IGNORE_FAILURES = new StreamExceptionHandler() { @Override public void handle( IOException failure ) { } }; private final BufferedReader in; private final Writer out; private final boolean quiet; private final String prefix; private final StreamExceptionHandler failureHandler; private final Exception stackTraceOfOrigin; public StreamConsumer( InputStream in, OutputStream out, boolean quiet ) { this( in, out, quiet, "", quiet ? IGNORE_FAILURES : PRINT_FAILURES ); } public StreamConsumer( InputStream in, OutputStream out, boolean quiet, String prefix, StreamExceptionHandler failureHandler ) { this.quiet = quiet; this.prefix = prefix; this.failureHandler = failureHandler; this.in = new BufferedReader(new InputStreamReader( in )); this.out = new OutputStreamWriter( out ); this.stackTraceOfOrigin = new Exception("Stack trace of thread that created this StreamConsumer"); } @Override public void run() { try { String line; while ( ( line = in.readLine()) != null) { if ( !quiet ) { out.write( prefix+line+"\n" ); out.flush(); } } } catch ( IOException exc ) { exc.addSuppressed( stackTraceOfOrigin ); failureHandler.handle( exc ); } } }
false
community_kernel_src_test_java_org_neo4j_test_StreamConsumer.java
2,077
{ @Override public void evaluate() throws Throwable { Voice[] voices = captureVoices(); boolean failure = true; try { base.evaluate(); failure = false; } finally { releaseVoices( voices, failure ); } } };
false
community_kernel_src_test_java_org_neo4j_test_Mute.java
2,078
{ @Override public void handle( IOException failure ) { failure.printStackTrace(); } };
false
community_kernel_src_test_java_org_neo4j_test_StreamConsumer.java
2,079
{ @Override public boolean accept( ManagedCluster cluster ) { return count( cluster.getMaster().getDependencyResolver().resolveDependency( Slaves.class ).getSlaves () ) >= cluster.size() - 1; } @Override public String toString() { return "Master should see all slaves as available"; } };
false
enterprise_ha_src_test_java_org_neo4j_test_ha_ClusterManager.java
2,080
{ @Override public boolean accept( ManagedCluster cluster ) { return count( cluster.getMaster().getDependencyResolver().resolveDependency( Slaves.class ).getSlaves () ) >= count; } @Override public String toString() { return "Master should see " + count + " slaves as available"; } };
false
enterprise_ha_src_test_java_org_neo4j_test_ha_ClusterManager.java
2,081
{ @Override public Clusters clusters() throws Throwable { return clusters; } };
false
enterprise_ha_src_test_java_org_neo4j_test_ha_ClusterManager.java
2,082
{ @Override public Clusters clusters() throws Exception { DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document clustersXmlDoc = documentBuilder.parse( clustersXml.toURL().openStream() ); return new ClustersXMLSerializer( documentBuilder ).read( clustersXmlDoc ); } };
false
enterprise_ha_src_test_java_org_neo4j_test_ha_ClusterManager.java
2,083
{ @Override public void evaluate() throws Throwable { if ( file.exists() ) { assertTrue( file + " should not exist", file.isFile() && file.delete() ); } writer = new PrintWriter( file ); try { base.evaluate(); } finally { try { writer.close(); } finally { writer = null; } } } };
false
community_kernel_src_test_java_org_neo4j_test_docs_DocsIncludeFile.java
2,084
public class DocsIncludeFile implements TestRule { public static DocsIncludeFile inSection( String section ) { return new DocsIncludeFile( section ); } public void printf( String format, Object... parameters ) { writer.printf( format, parameters ); } public void println( String line ) { writer.println( line ); } public void println() { writer.println(); } private final String section; private PrintWriter writer; DocsIncludeFile( String section ) { this.section = section; } @Override public Statement apply( final Statement base, Description description ) { String methodName = description.getMethodName(); assertNotNull( DocsIncludeFile.class.getName() + " must be a non-static @Rule", methodName ); File dir = path( "target", "docs", section, "includes" ); assertTrue( dir + " must be a directory", dir.isDirectory() || dir.mkdirs() ); final File file = path( dir, methodName + ".asciidoc" ); return new Statement() { @Override public void evaluate() throws Throwable { if ( file.exists() ) { assertTrue( file + " should not exist", file.isFile() && file.delete() ); } writer = new PrintWriter( file ); try { base.evaluate(); } finally { try { writer.close(); } finally { writer = null; } } } }; } }
false
community_kernel_src_test_java_org_neo4j_test_docs_DocsIncludeFile.java
2,085
public class TestGraphDatabaseFactoryState extends GraphDatabaseFactoryState { private FileSystemAbstraction fileSystem; private boolean systemOutLogging; public TestGraphDatabaseFactoryState() { fileSystem = null; systemOutLogging = false; } public TestGraphDatabaseFactoryState( TestGraphDatabaseFactoryState previous ) { super( previous ); fileSystem = previous.fileSystem; systemOutLogging = previous.systemOutLogging; } public FileSystemAbstraction getFileSystem() { return fileSystem; } public void setFileSystem( FileSystemAbstraction fileSystem ) { this.fileSystem = fileSystem; } }
false
community_kernel_src_test_java_org_neo4j_test_TestGraphDatabaseFactoryState.java
2,086
{ @Override protected FileSystemAbstraction createFileSystemAbstraction() { FileSystemAbstraction fs = state.getFileSystem(); if ( fs != null ) { return fs; } else { return super.createFileSystemAbstraction(); } } };
false
community_kernel_src_test_java_org_neo4j_test_TestGraphDatabaseFactory.java
2,087
{ @Override @SuppressWarnings("deprecation") public GraphDatabaseService newDatabase( Map<String, String> config ) { return new ImpermanentGraphDatabase( storeDir, config, state.databaseDependencies() ) { @Override protected FileSystemAbstraction createFileSystemAbstraction() { FileSystemAbstraction fs = state.getFileSystem(); if ( fs != null ) { return fs; } else { return super.createFileSystemAbstraction(); } } }; } } );
false
community_kernel_src_test_java_org_neo4j_test_TestGraphDatabaseFactory.java
2,088
public class TestGraphDatabaseFactory extends GraphDatabaseFactory { public TestGraphDatabaseFactory() { super( new TestGraphDatabaseFactoryState() ); } public TestGraphDatabaseFactory( Logging logging ) { super( new TestGraphDatabaseFactoryState() ); setLogging( logging ); } public GraphDatabaseService newImpermanentDatabase() { return newImpermanentDatabaseBuilder().newGraphDatabase(); } public GraphDatabaseService newImpermanentDatabase( String storeDir ) { return newImpermanentDatabaseBuilder( storeDir ).newGraphDatabase(); } public GraphDatabaseBuilder newImpermanentDatabaseBuilder() { return newImpermanentDatabaseBuilder( ImpermanentGraphDatabase.PATH ); } @Override protected TestGraphDatabaseFactoryState getCurrentState() { return (TestGraphDatabaseFactoryState) super.getCurrentState(); } @Override protected TestGraphDatabaseFactoryState getStateCopy() { return new TestGraphDatabaseFactoryState( getCurrentState() ); } public FileSystemAbstraction getFileSystem() { return getCurrentState().getFileSystem(); } public TestGraphDatabaseFactory setFileSystem( FileSystemAbstraction fileSystem ) { getCurrentState().setFileSystem( fileSystem ); return this; } public TestGraphDatabaseFactory setLogging( Logging logging ) { getCurrentState().setLogging( logging ); return this; } @Override public TestGraphDatabaseFactory addKernelExtensions( Iterable<KernelExtensionFactory<?>> newKernelExtensions ) { return (TestGraphDatabaseFactory) super.addKernelExtensions( newKernelExtensions ); } @Override public TestGraphDatabaseFactory addKernelExtension( KernelExtensionFactory<?> newKernelExtension ) { return (TestGraphDatabaseFactory) super.addKernelExtension( newKernelExtension ); } public GraphDatabaseBuilder newImpermanentDatabaseBuilder( final String storeDir ) { final TestGraphDatabaseFactoryState state = getStateCopy(); return new TestGraphDatabaseBuilder( new GraphDatabaseBuilder.DatabaseCreator() { @Override @SuppressWarnings("deprecation") public GraphDatabaseService newDatabase( Map<String, String> config ) { return new ImpermanentGraphDatabase( storeDir, config, state.databaseDependencies() ) { @Override protected FileSystemAbstraction createFileSystemAbstraction() { FileSystemAbstraction fs = state.getFileSystem(); if ( fs != null ) { return fs; } else { return super.createFileSystemAbstraction(); } } }; } } ); } }
false
community_kernel_src_test_java_org_neo4j_test_TestGraphDatabaseFactory.java
2,089
public class TestGraphDatabaseBuilder extends GraphDatabaseBuilder { public TestGraphDatabaseBuilder( DatabaseCreator creator ) { super( creator ); } }
false
community_kernel_src_test_java_org_neo4j_test_TestGraphDatabaseBuilder.java
2,090
private static final class Lazy { private volatile Object productOrFactory; Lazy( GraphDefinition graph, String title, String documentation ) { productOrFactory = new Factory( graph, title, documentation ); } @SuppressWarnings( "unchecked"/*cast to T*/) <T> T get( Producer<T> producer, boolean create ) { Object result = productOrFactory; if ( result instanceof Factory ) { synchronized ( this ) { if ( ( result = productOrFactory ) instanceof Factory ) { productOrFactory = result = ( (Factory) result ).create( producer, create ); } } } return (T) result; } }
false
community_kernel_src_test_java_org_neo4j_test_TestData.java
2,091
private static final class Factory { private final GraphDefinition graph; private final String title; private final String documentation; Factory( GraphDefinition graph, String title, String documentation ) { this.graph = graph; this.title = title; this.documentation = documentation; } Object create( Producer<?> producer, boolean create ) { return create ? producer.create( graph, title, documentation ) : null; } }
false
community_kernel_src_test_java_org_neo4j_test_TestData.java
2,092
{ @Override public void evaluate() throws Throwable { product.set( create( graph, title == null ? null : title.value(), doc == null ? null : doc.value(), description.getMethodName() ) ); try { try { base.evaluate(); } catch ( Throwable err ) { try { destroy( get( false ), false ); } catch ( Throwable sub ) { List<Throwable> failures = new ArrayList<Throwable>(); if ( err instanceof MultipleFailureException ) { failures.addAll( ( (MultipleFailureException) err ).getFailures() ); } else { failures.add( err ); } failures.add( sub ); throw new MultipleFailureException( failures ); } throw err; } destroy( get( false ), false ); } finally { product.set( null ); } } };
false
community_kernel_src_test_java_org_neo4j_test_TestData.java
2,093
@Ignore( "this is not a test, it is a testing utility" ) public class TestData<T> implements TestRule { @Target( ElementType.METHOD ) @Retention( RetentionPolicy.RUNTIME ) public @interface Title { String value(); } public interface Producer<T> { T create( GraphDefinition graph, String title, String documentation ); void destroy( T product, boolean successful ); } public static <T> TestData<T> producedThrough( Producer<T> transformation ) { transformation.getClass(); // null check return new TestData<T>( transformation ); } public T get() { return get( true ); } private static final class Lazy { private volatile Object productOrFactory; Lazy( GraphDefinition graph, String title, String documentation ) { productOrFactory = new Factory( graph, title, documentation ); } @SuppressWarnings( "unchecked"/*cast to T*/) <T> T get( Producer<T> producer, boolean create ) { Object result = productOrFactory; if ( result instanceof Factory ) { synchronized ( this ) { if ( ( result = productOrFactory ) instanceof Factory ) { productOrFactory = result = ( (Factory) result ).create( producer, create ); } } } return (T) result; } } private static final class Factory { private final GraphDefinition graph; private final String title; private final String documentation; Factory( GraphDefinition graph, String title, String documentation ) { this.graph = graph; this.title = title; this.documentation = documentation; } Object create( Producer<?> producer, boolean create ) { return create ? producer.create( graph, title, documentation ) : null; } } private final Producer<T> producer; private final ThreadLocal<Lazy> product = new InheritableThreadLocal<Lazy>(); private TestData( Producer<T> producer ) { this.producer = producer; } @Override public Statement apply( final Statement base, final Description description ) { final Title title = description.getAnnotation( Title.class ); final Documented doc = description.getAnnotation( Documented.class ); GraphDescription.Graph g = description.getAnnotation( GraphDescription.Graph.class ); if ( g == null ) g = description.getTestClass().getAnnotation( GraphDescription.Graph.class ); final GraphDescription graph = GraphDescription.create( g ); return new Statement() { @Override public void evaluate() throws Throwable { product.set( create( graph, title == null ? null : title.value(), doc == null ? null : doc.value(), description.getMethodName() ) ); try { try { base.evaluate(); } catch ( Throwable err ) { try { destroy( get( false ), false ); } catch ( Throwable sub ) { List<Throwable> failures = new ArrayList<Throwable>(); if ( err instanceof MultipleFailureException ) { failures.addAll( ( (MultipleFailureException) err ).getFailures() ); } else { failures.add( err ); } failures.add( sub ); throw new MultipleFailureException( failures ); } throw err; } destroy( get( false ), false ); } finally { product.set( null ); } } }; } private void destroy( @SuppressWarnings( "hiding" ) T product, boolean successful ) { if ( product != null ) producer.destroy( product, successful ); } private T get( boolean create ) { Lazy lazy = product.get(); if ( lazy == null ) { if ( create ) throw new IllegalStateException( "Not in test case" ); return null; } return lazy.get( producer, create ); } private static final String EMPTY = ""; private static Lazy create( GraphDescription graph, String title, String doc, String methodName ) { if ( doc != null ) { if ( title == null ) { // standard javadoc means of finding a title int dot = doc.indexOf( '.' ); if ( dot > 0 ) { title = doc.substring( 0, dot ); if ( title.contains( "\n" ) ) { title = null; } else { title = title.trim(); doc = doc.substring( dot + 1 ); } } } String[] lines = doc.split( "\n" ); int indent = Integer.MAX_VALUE; int start = 0, end = 0; for ( int i = 0; i < lines.length; i++ ) { if ( EMPTY.equals( lines[i].trim() ) ) { lines[i] = EMPTY; if ( start == i ) end = ++start; // skip initial blank lines } else { for ( int j = 0; j < lines[i].length(); j++ ) { if ( !Character.isWhitespace( lines[i].charAt( j ) ) ) { indent = Math.min( indent, j ); break; } } end = i; // skip blank lines at the end } } if ( end == lines.length ) end--; // all lines were empty // If there still is no title, and the first line looks like a // title, take the first line as title if ( title == null && start < end && EMPTY.equals( lines[start + 1] ) ) { title = lines[start].trim(); start += 2; } StringBuilder documentation = new StringBuilder(); for ( int i = start; i <= end; i++ ) { documentation.append( EMPTY.equals( lines[i] ) ? EMPTY : lines[i].substring( indent ) ).append( "\n" ); } doc = documentation.toString(); } else { doc = EMPTY; } if ( title == null ) { title = methodName.replace( "_", " " ); } return new Lazy( graph, title, doc ); } }
false
community_kernel_src_test_java_org_neo4j_test_TestData.java
2,094
{ @Override public void evaluate() throws Throwable { base.evaluate(); } };
false
community_kernel_src_test_java_org_neo4j_test_TargetDirectory.java
2,095
public class TestDirectory implements TestRule { private File subdir = null; private TestDirectory() { } public String absolutePath() { return directory().getAbsolutePath(); } public File directory() { if ( subdir == null ) throw new IllegalStateException( "Not initialized" ); return subdir; } @Override public Statement apply( final Statement base, Description description ) { subdir = directoryForDescription( description ); return new Statement() { @Override public void evaluate() throws Throwable { base.evaluate(); } }; } @Override public String toString() { String subdirName = subdir == null ? "<uninitialized>" : subdir.toString(); return format( "%s[%s]", getClass().getSimpleName(), subdirName ); } }
false
community_kernel_src_test_java_org_neo4j_test_TargetDirectory.java
2,096
public class TargetDirectory { public class TestDirectory implements TestRule { private File subdir = null; private TestDirectory() { } public String absolutePath() { return directory().getAbsolutePath(); } public File directory() { if ( subdir == null ) throw new IllegalStateException( "Not initialized" ); return subdir; } @Override public Statement apply( final Statement base, Description description ) { subdir = directoryForDescription( description ); return new Statement() { @Override public void evaluate() throws Throwable { base.evaluate(); } }; } @Override public String toString() { String subdirName = subdir == null ? "<uninitialized>" : subdir.toString(); return format( "%s[%s]", getClass().getSimpleName(), subdirName ); } } private final FileSystemAbstraction fileSystem; private final File base; public static TargetDirectory forTest( Class<?> owningTest ) { //noinspection deprecation return forTest( new DefaultFileSystemAbstraction(), owningTest ); } public static TargetDirectory forTest( FileSystemAbstraction fileSystem, Class<?> owningTest ) { return new TargetDirectory( fileSystem, new File( new File( locateTarget( owningTest ), "test-data" ), owningTest.getName() ) ); } public static TestDirectory testDirForTest( Class<?> owningTest ) { //noinspection deprecation return forTest( new DefaultFileSystemAbstraction(), owningTest ).testDirectory(); } private TargetDirectory( FileSystemAbstraction fileSystem, File base ) { this.fileSystem = fileSystem; this.base = base.getAbsoluteFile(); } public File cacheDirectory( String name ) { File dir = new File( ensureBase(), name ); if ( ! fileSystem.fileExists( dir ) ) { fileSystem.mkdir( dir ); } return dir; } public File existingDirectory( String name ) { return new File( base, name ); } public File cleanDirectory( String name ) { File dir = new File( ensureBase(), name ); if ( fileSystem.fileExists( dir ) ) { recursiveDelete( dir ); } fileSystem.mkdir( dir ); return dir; } public File directoryForDescription( Description description ) { String test = description.getMethodName(); String dir = DigestUtils.md5Hex( test ); register( test, dir ); return cleanDirectory( dir ); } public File file( String name ) { return new File( ensureBase(), name ); } public TestDirectory testDirectory() { return new TestDirectory(); } public File makeGraphDbDir() { return cleanDirectory( "graph-db" ); } public void cleanup() throws IOException { fileSystem.deleteRecursively( base ); fileSystem.mkdirs( base ); } private void recursiveDelete( File file ) { try { fileSystem.deleteRecursively( file ); } catch ( IOException e ) { throw new RuntimeException( e ); } } private void register( String test, String dir ) { try { FileUtils.writeToFile( new File( ensureBase(), ".register" ), format( "%s=%s\n", dir, test ), true ); } catch ( IOException e ) { throw new RuntimeException( e ); } } private File ensureBase() { if ( fileSystem.fileExists( base ) && !fileSystem.isDirectory( base ) ) throw new IllegalStateException( base + " exists and is not a directory!" ); try { fileSystem.mkdirs( base ); } catch ( IOException e ) { throw new RuntimeException( e ); } return base; } private static File locateTarget( Class<?> owningTest ) { try { File codeSource = new File( owningTest.getProtectionDomain().getCodeSource().getLocation().toURI() ); if ( codeSource.isDirectory() ) { // code loaded from a directory return codeSource.getParentFile(); } } catch ( URISyntaxException e ) { // ignored } return new File( "target" ); } }
false
community_kernel_src_test_java_org_neo4j_test_TargetDirectory.java
2,097
{ @Override public void handle( IOException failure ) { } };
false
community_kernel_src_test_java_org_neo4j_test_StreamConsumer.java
2,098
out { @Override PrintStream replace( PrintStream replacement ) { PrintStream old = java.lang.System.out; java.lang.System.setOut( replacement ); return old; } },
false
community_kernel_src_test_java_org_neo4j_test_Mute.java
2,099
{ @Override void restore( boolean failure ) throws IOException { for ( Handler handler : handlers ) { logger.addHandler( handler ); } logger.setLevel( level ); if ( replacement != null ) { logger.removeHandler( replacement ); } } };
false
community_kernel_src_test_java_org_neo4j_test_Mute.java