Unnamed: 0
int64 0
6.7k
| func
stringlengths 12
89.6k
| target
bool 2
classes | project
stringlengths 45
151
|
|---|---|---|---|
2,100
|
public class GenerateConfigDocumentation
{
public static void main( String[] args ) throws Exception
{
File output = null;
String bundleName = null;
if(args.length > 0)
{
bundleName = args[0];
if(args.length > 1)
{
output = new File(args[1]);
}
} else
{
System.out.println("Usage: GenerateConfigDocumentation CONFIG_BUNDLE_CLASS [output file]");
System.exit(0);
}
ConfigAsciiDocGenerator generator = new ConfigAsciiDocGenerator();
String doc = generator.generateDocsFor(bundleName);
if(output != null)
{
System.out.println("Saving docs for '"+bundleName+"' in '" + output.getAbsolutePath() + "'.");
FileUtils.writeToFile(output, doc, false);
} else
{
System.out.println(doc);
}
}
}
| false
|
community_kernel_src_main_java_org_neo4j_tooling_GenerateConfigDocumentation.java
|
2,101
|
public class InputStreamAwaiter
{
private final InputStream input;
private final byte[] bytes = new byte[1024];
private final Clock clock;
private static final String NEW_LINE = System.getProperty( "line.separator" );
public InputStreamAwaiter( InputStream input )
{
this( Clock.SYSTEM_CLOCK, input );
}
public InputStreamAwaiter( Clock clock, InputStream input )
{
this.clock = clock;
this.input = input;
}
public void awaitLine( String expectedLine, long timeout, TimeUnit unit ) throws IOException,
TimeoutException, InterruptedException
{
long deadline = clock.currentTimeMillis() + unit.toMillis( timeout );
StringBuilder buffer = new StringBuilder();
do
{
while ( input.available() > 0 )
{
buffer.append( new String( bytes, 0, input.read( bytes ) ) );
}
String[] lines = buffer.toString().split( NEW_LINE );
for ( String line : lines )
{
if ( expectedLine.equals( line ) )
{
return;
}
}
Thread.sleep( 10 );
}
while ( clock.currentTimeMillis() < deadline );
throw new TimeoutException( "Timed out waiting to read line: [" + expectedLine + "]. Seen input:\n\t"
+ buffer.toString().replaceAll( "\n", "\n\t" ) );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_InputStreamAwaiter.java
|
2,102
|
public class ImpermanentDatabaseRule extends DatabaseRule
{
private Logging logging;
public ImpermanentDatabaseRule()
{
}
public ImpermanentDatabaseRule( Logging logging )
{
this.logging = logging;
}
@Override
protected GraphDatabaseFactory newFactory()
{
return new TestGraphDatabaseFactory( logging );
}
@Override
protected GraphDatabaseBuilder newBuilder( GraphDatabaseFactory factory )
{
return ((TestGraphDatabaseFactory) factory).newImpermanentDatabaseBuilder();
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_ImpermanentDatabaseRule.java
|
2,103
|
public class GraphTransactionRule
extends ExternalResource
{
private final DatabaseRule database;
private Transaction tx;
public GraphTransactionRule( DatabaseRule database )
{
this.database = database;
}
@Override
protected void before()
throws Throwable
{
begin();
}
@Override
protected void after()
{
success();
}
public void begin()
{
tx = database.getGraphDatabaseService().beginTx();
}
public void success()
{
tx.success();
tx.finish();
}
public void failure()
{
tx.failure();
tx.finish();
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_GraphTransactionRule.java
|
2,104
|
ERROR{
};
| false
|
community_kernel_src_test_java_org_neo4j_test_GraphDescription.java
|
2,105
|
BOOLEAN
{
@Override
Boolean convert( String value )
{
return Boolean.parseBoolean( value );
}
@Override Class<?> componentClass()
{
return Boolean.class;
}
},
| false
|
community_kernel_src_test_java_org_neo4j_test_GraphDescription.java
|
2,106
|
DOUBLE
{
@Override
Double convert( String value )
{
return Double.parseDouble( value );
}
@Override Class<?> componentClass()
{
return Double.class;
}
},
| false
|
community_kernel_src_test_java_org_neo4j_test_GraphDescription.java
|
2,107
|
INTEGER
{
@Override
Long convert( String value )
{
return Long.parseLong( value );
}
@Override Class<?> componentClass()
{
return Long.class;
}
},
| false
|
community_kernel_src_test_java_org_neo4j_test_GraphDescription.java
|
2,108
|
STRING
{
@Override
String convert( String value )
{
return value;
}
@Override Class<?> componentClass()
{
return String.class;
}
},
| false
|
community_kernel_src_test_java_org_neo4j_test_GraphDescription.java
|
2,109
|
ARRAY
{
@Override Object convert( PropType componentType, String value )
{
String[] items = value.split( " *, *" );
Object[] result = (Object[]) Array.newInstance( componentType.componentClass(), items.length );
for ( int i =0 ; i < items.length; i++ )
{
result[i] = componentType.convert( items[i] );
}
return result;
}
},
| false
|
community_kernel_src_test_java_org_neo4j_test_GraphDescription.java
|
2,110
|
private static class NodeWithAddedLabels implements NODE
{
private final LABEL[] labels;
private final NODE inner;
NodeWithAddedLabels( NODE inner, String[] labelNames )
{
this.inner = inner;
labels = new LABEL[labelNames.length];
for(int i=0;i<labelNames.length;i++)
{
labels[i] = new DefaultLabel(labelNames[i]);
}
}
@Override
public String name()
{
return inner.name();
}
@Override
public PROP[] properties()
{
return inner.properties();
}
@Override
public LABEL[] labels()
{
return labels;
}
@Override
public boolean setNameProperty()
{
return inner.setNameProperty();
}
@Override
public Class<? extends Annotation> annotationType()
{
return inner.annotationType();
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_GraphDescription.java
|
2,111
|
private static class DefaultRel extends Default implements REL
{
private final String start, type, end;
DefaultRel( String start, String type, String end )
{
super( null );
this.type = type;
this.start = defined( start );
this.end = defined( end );
}
@Override
public String start()
{
return start;
}
@Override
public String end()
{
return end;
}
@Override
public String type()
{
return type;
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_GraphDescription.java
|
2,112
|
private static class DefaultNode extends Default implements NODE
{
private final LABEL[] labels;
DefaultNode( String name, String[] labelNames )
{
super( name );
labels = new LABEL[labelNames.length];
for(int i=0;i<labelNames.length;i++)
{
labels[i] = new DefaultLabel(labelNames[i]);
}
}
@Override
public LABEL[] labels()
{
return labels;
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_GraphDescription.java
|
2,113
|
private static class DefaultLabel implements LABEL
{
private final String name;
public DefaultLabel( String name )
{
this.name = name;
}
@Override
public Class<? extends Annotation> annotationType()
{
throw new UnsupportedOperationException( "this is not a real annotation" );
}
@Override
public String value()
{
return name;
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_GraphDescription.java
|
2,114
|
private static class Default
{
private final String name;
Default( String name )
{
this.name = "".equals( name ) ? null : name;
}
public String name()
{
return name;
}
public Class<? extends Annotation> annotationType()
{
throw new UnsupportedOperationException( "this is not a real annotation" );
}
public PROP[] properties()
{
return NO_PROPS;
}
public boolean setNameProperty()
{
return true;
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_GraphDescription.java
|
2,115
|
{
@Override
public Map<String, Node> create( GraphDatabaseService graphdb )
{
// don't bother with creating a transaction
return new HashMap<String, Node>();
}
};
| false
|
community_kernel_src_test_java_org_neo4j_test_GraphDescription.java
|
2,116
|
{
@Override
public Map<String, Node> create( GraphDefinition graph, String title, String documentation )
{
return graph.create( holder.graphdb() );
}
@Override
public void destroy( Map<String, Node> product, boolean successful )
{
if ( destroy )
{
GraphDescription.destroy( product );
}
}
};
| false
|
community_kernel_src_test_java_org_neo4j_test_GraphDescription.java
|
2,117
|
public class GraphDescription implements GraphDefinition
{
@Inherited
@Target( { ElementType.METHOD, ElementType.TYPE } )
@Retention( RetentionPolicy.RUNTIME )
public @interface Graph
{
String[] value() default {};
NODE[] nodes() default {};
REL[] relationships() default {};
boolean autoIndexNodes() default false;
boolean autoIndexRelationships() default false;
}
@Target( {} )
public @interface NODE
{
String name();
PROP[] properties() default {};
LABEL[] labels() default {};
boolean setNameProperty() default false;
}
@Target( {} )
public @interface REL
{
String name() default "";
String type();
String start();
String end();
PROP[] properties() default {};
boolean setNameProperty() default false;
}
@Target( {} )
public @interface PROP
{
String key();
String value();
PropType type() default STRING;
PropType componentType() default ERROR;
}
@Target( {} )
public @interface LABEL
{
String value();
}
@SuppressWarnings( "boxing" )
public enum PropType
{
ARRAY
{
@Override Object convert( PropType componentType, String value )
{
String[] items = value.split( " *, *" );
Object[] result = (Object[]) Array.newInstance( componentType.componentClass(), items.length );
for ( int i =0 ; i < items.length; i++ )
{
result[i] = componentType.convert( items[i] );
}
return result;
}
},
STRING
{
@Override
String convert( String value )
{
return value;
}
@Override Class<?> componentClass()
{
return String.class;
}
},
INTEGER
{
@Override
Long convert( String value )
{
return Long.parseLong( value );
}
@Override Class<?> componentClass()
{
return Long.class;
}
},
DOUBLE
{
@Override
Double convert( String value )
{
return Double.parseDouble( value );
}
@Override Class<?> componentClass()
{
return Double.class;
}
},
BOOLEAN
{
@Override
Boolean convert( String value )
{
return Boolean.parseBoolean( value );
}
@Override Class<?> componentClass()
{
return Boolean.class;
}
},
ERROR{
};
Class<?> componentClass() {
throw new UnsupportedOperationException( "Not implemented for property type" + name() );
}
Object convert( String value ) {
throw new UnsupportedOperationException( "Not implemented for property type" + name() );
}
Object convert( PropType componentType, String value ) {
throw new UnsupportedOperationException( "Not implemented for property type" + name() );
}
}
public static TestData.Producer<Map<String, Node>> createGraphFor( final GraphHolder holder, final boolean destroy )
{
return new TestData.Producer<Map<String, Node>>()
{
@Override
public Map<String, Node> create( GraphDefinition graph, String title, String documentation )
{
return graph.create( holder.graphdb() );
}
@Override
public void destroy( Map<String, Node> product, boolean successful )
{
if ( destroy )
{
GraphDescription.destroy( product );
}
}
};
}
@Override
public Map<String, Node> create( GraphDatabaseService graphdb )
{
Map<String, Node> result = new HashMap<String, Node>();
Transaction tx = graphdb.beginTx();
try
{
graphdb.index().getRelationshipAutoIndexer().setEnabled( autoIndexRelationships );
for ( NODE def : nodes )
{
Node node = init( graphdb.createNode(), def.setNameProperty() ? def.name() : null, def.properties(), graphdb.index().getNodeAutoIndexer(), autoIndexNodes );
for ( LABEL label : def.labels() )
{
node.addLabel( label( label.value() ) );
}
result.put( def.name(), node );
}
for ( REL def : rels )
{
init( result.get( def.start() ).createRelationshipTo( result.get( def.end() ),
DynamicRelationshipType.withName( def.type() ) ), def.setNameProperty() ? def.name() : null,
def.properties(), graphdb.index().getRelationshipAutoIndexer(), autoIndexRelationships );
}
tx.success();
}
finally
{
tx.finish();
}
return result;
}
private static <T extends PropertyContainer> T init( T entity, String name, PROP[] properties, AutoIndexer<T> autoindex, boolean auto )
{
autoindex.setEnabled( auto );
for ( PROP prop : properties )
{
if(auto)
{
autoindex.startAutoIndexingProperty( prop.key() );
}
PropType tpe = prop.type();
switch(tpe) {
case ARRAY:
entity.setProperty( prop.key(), tpe.convert( prop.componentType(), prop.value() ) );
break;
default:
entity.setProperty( prop.key(), prop.type().convert( prop.value() ) );
}
}
if ( name != null )
{
if(auto)
{
autoindex.startAutoIndexingProperty( "name" );
}
entity.setProperty( "name", name );
}
return entity;
}
private static final PROP[] NO_PROPS = {};
private static final NODE[] NO_NODES = {};
private static final REL[] NO_RELS = {};
private static final GraphDescription EMPTY = new GraphDescription( NO_NODES, NO_RELS, false, false )
{
@Override
public Map<String, Node> create( GraphDatabaseService graphdb )
{
// don't bother with creating a transaction
return new HashMap<String, Node>();
}
};
private final NODE[] nodes;
private final REL[] rels;
private final boolean autoIndexRelationships;
private final boolean autoIndexNodes;
public static GraphDescription create( String... definition )
{
Map<String, NODE> nodes = new HashMap<String, NODE>();
List<REL> relationships = new ArrayList<REL>();
parse( definition, nodes, relationships );
return new GraphDescription( nodes.values().toArray( NO_NODES ), relationships.toArray( NO_RELS ), false, false );
}
public static void destroy( Map<String, Node> nodes )
{
if ( nodes.isEmpty() ) return;
GraphDatabaseService db = nodes.values().iterator().next().getGraphDatabase();
Transaction tx = db.beginTx();
try
{
for ( Node node : GlobalGraphOperations.at( db ).getAllNodes() )
{
for ( Relationship rel : node.getRelationships() )
rel.delete();
node.delete();
}
tx.success();
}
finally
{
tx.finish();
}
}
public static GraphDescription create( Graph graph )
{
if ( graph == null )
{
return EMPTY;
}
Map<String, NODE> nodes = new HashMap<String, NODE>();
for ( NODE node : graph.nodes() )
{
if ( nodes.put( defined( node.name() ), node ) != null )
{
throw new IllegalArgumentException( "Node \"" + node.name() + "\" defined more than once" );
}
}
Map<String, REL> rels = new HashMap<String, REL>();
List<REL> relationships = new ArrayList<REL>();
for ( REL rel : graph.relationships() )
{
createIfAbsent( nodes, rel.start() );
createIfAbsent( nodes, rel.end() );
String name = rel.name();
if ( !name.equals( "" ) )
{
if ( rels.put( name, rel ) != null )
{
throw new IllegalArgumentException( "Relationship \"" + name + "\" defined more than once" );
}
}
relationships.add( rel );
}
parse( graph.value(), nodes, relationships );
return new GraphDescription( nodes.values().toArray( NO_NODES ), relationships.toArray( NO_RELS ), graph.autoIndexNodes(), graph.autoIndexRelationships() );
}
private static void createIfAbsent( Map<String, NODE> nodes, String name, String ... labels )
{
if ( !nodes.containsKey( name ) )
{
nodes.put( name, new DefaultNode( name, labels ) );
}
else
{
NODE preexistingNode = nodes.get( name );
// Join with any new labels
HashSet<String> joinedLabels = new HashSet<String>( asList( labels ));
for ( LABEL label : preexistingNode.labels() )
{
joinedLabels.add( label.value() );
}
String[] labelNameArray = joinedLabels.toArray(new String[joinedLabels.size()]);
nodes.put( name, new NodeWithAddedLabels(preexistingNode, labelNameArray));
}
}
private static String parseAndCreateNodeIfAbsent( Map<String, NODE> nodes, String descriptionToParse )
{
String[] parts = descriptionToParse.split( ":" );
if ( parts.length == 0 )
{
throw new IllegalArgumentException( "Empty node names are not allowed." );
}
createIfAbsent( nodes, parts[0], copyOfRange( parts, 1, parts.length ) );
return parts[0];
}
private static void parse( String[] description, Map<String, NODE> nodes, List<REL> relationships )
{
for ( String part : description )
{
for ( String line : part.split( "\n" ) )
{
String[] components = line.split( " " );
if ( components.length != 3 )
{
throw new IllegalArgumentException( "syntax error: \"" + line + "\"" );
}
String startName = parseAndCreateNodeIfAbsent( nodes, defined( components[0] ) );
String endName = parseAndCreateNodeIfAbsent( nodes, defined( components[2] ) );
relationships.add( new DefaultRel( startName, components[1], endName ) );
}
}
}
private GraphDescription( NODE[] nodes, REL[] rels, boolean autoIndexNodes, boolean autoIndexRelationships )
{
this.nodes = nodes;
this.rels = rels;
this.autoIndexNodes = autoIndexNodes;
this.autoIndexRelationships = autoIndexRelationships;
}
static String defined( String name )
{
if ( name == null || name.equals( "" ) )
{
throw new IllegalArgumentException( "Node name not provided" );
}
return name;
}
private static class Default
{
private final String name;
Default( String name )
{
this.name = "".equals( name ) ? null : name;
}
public String name()
{
return name;
}
public Class<? extends Annotation> annotationType()
{
throw new UnsupportedOperationException( "this is not a real annotation" );
}
public PROP[] properties()
{
return NO_PROPS;
}
public boolean setNameProperty()
{
return true;
}
}
private static class DefaultNode extends Default implements NODE
{
private final LABEL[] labels;
DefaultNode( String name, String[] labelNames )
{
super( name );
labels = new LABEL[labelNames.length];
for(int i=0;i<labelNames.length;i++)
{
labels[i] = new DefaultLabel(labelNames[i]);
}
}
@Override
public LABEL[] labels()
{
return labels;
}
}
/*
* Used if the user has defined the same node twice, with different labels, this combines
* all labels the user has added.
*/
private static class NodeWithAddedLabels implements NODE
{
private final LABEL[] labels;
private final NODE inner;
NodeWithAddedLabels( NODE inner, String[] labelNames )
{
this.inner = inner;
labels = new LABEL[labelNames.length];
for(int i=0;i<labelNames.length;i++)
{
labels[i] = new DefaultLabel(labelNames[i]);
}
}
@Override
public String name()
{
return inner.name();
}
@Override
public PROP[] properties()
{
return inner.properties();
}
@Override
public LABEL[] labels()
{
return labels;
}
@Override
public boolean setNameProperty()
{
return inner.setNameProperty();
}
@Override
public Class<? extends Annotation> annotationType()
{
return inner.annotationType();
}
}
private static class DefaultRel extends Default implements REL
{
private final String start, type, end;
DefaultRel( String start, String type, String end )
{
super( null );
this.type = type;
this.start = defined( start );
this.end = defined( end );
}
@Override
public String start()
{
return start;
}
@Override
public String end()
{
return end;
}
@Override
public String type()
{
return type;
}
}
private static class DefaultLabel implements LABEL
{
private final String name;
public DefaultLabel( String name )
{
this.name = name;
}
@Override
public Class<? extends Annotation> annotationType()
{
throw new UnsupportedOperationException( "this is not a real annotation" );
}
@Override
public String value()
{
return name;
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_GraphDescription.java
|
2,118
|
public class GraphDatabaseServiceCleaner
{
private GraphDatabaseServiceCleaner()
{
throw new UnsupportedOperationException();
}
public static void cleanDatabaseContent( GraphDatabaseService db )
{
try ( Transaction tx = db.beginTx() )
{
for ( ConstraintDefinition constraint : db.schema().getConstraints() )
{
constraint.drop();
}
for ( IndexDefinition index : db.schema().getIndexes() )
{
index.drop();
}
tx.success();
}
try ( Transaction tx = db.beginTx() )
{
for ( Relationship relationship : GlobalGraphOperations.at( db ).getAllRelationships() )
{
relationship.delete();
}
for ( Node node : GlobalGraphOperations.at( db ).getAllNodes() )
{
node.delete();
}
tx.success();
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_GraphDatabaseServiceCleaner.java
|
2,119
|
{
@Override
public void evaluate() throws Throwable
{
try
{
base.evaluate();
}
catch ( Throwable failure )
{
printOutput();
throw failure;
}
}
};
| false
|
community_kernel_src_test_java_org_neo4j_test_FailureOutput.java
|
2,120
|
public class FailureOutput implements TestRule
{
private final ByteArrayOutputStream output = new ByteArrayOutputStream();
private final PrintStream stream = new PrintStream( output );
private final PrintStream target;
public FailureOutput()
{
this( System.out );
}
public FailureOutput( PrintStream target )
{
this.target = target;
}
@Override
public Statement apply( final Statement base, Description description )
{
return new Statement()
{
@Override
public void evaluate() throws Throwable
{
try
{
base.evaluate();
}
catch ( Throwable failure )
{
printOutput();
throw failure;
}
}
};
}
private void printOutput() throws IOException
{
target.write( output.toByteArray() );
target.flush();
}
public PrintStream stream()
{
return stream;
}
public PrintWriter writer()
{
return new PrintWriter( stream );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_FailureOutput.java
|
2,121
|
public class ImpermanentGraphDatabase extends EmbeddedGraphDatabase
{
/**
* If enabled will track unclosed database instances in tests. The place of instantiation
* will get printed in an exception with the message "Unclosed database instance".
*/
private static boolean TRACK_UNCLOSED_DATABASE_INSTANCES = false;
private static final Map<File, Exception> startedButNotYetClosed = new ConcurrentHashMap<>();
protected static final String PATH = "target/test-data/impermanent-db";
/**
* This is deprecated. Use {@link TestGraphDatabaseFactory} instead
*/
@Deprecated
public ImpermanentGraphDatabase()
{
this( new HashMap<String, String>() );
}
/*
* TODO this shouldn't be here. It so happens however that some tests may use the database
* directory as the path to store stuff and in this case we need to define the path explicitly,
* otherwise we end up writing outside the workspace and hence leave stuff behind.
* The other option is to explicitly remove all files present on startup. Either way,
* the fact that this discussion takes place is indication that things are inconsistent,
* since an ImpermanentGraphDatabase should not have any mention of a store directory in
* any case.
*/
public ImpermanentGraphDatabase( String storeDir )
{
this( storeDir, withForcedInMemoryConfiguration( new HashMap<String, String>() ) );
}
/**
* This is deprecated. Use {@link TestGraphDatabaseFactory} instead
*/
@Deprecated
public ImpermanentGraphDatabase( Map<String, String> params )
{
this( PATH, withForcedInMemoryConfiguration( params ) );
}
/**
* This is deprecated. Use {@link TestGraphDatabaseFactory} instead
*/
@Deprecated
public ImpermanentGraphDatabase( String storeDir, Map<String, String> params )
{
this( storeDir, withForcedInMemoryConfiguration( params ),
Iterables.<KernelExtensionFactory<?>, KernelExtensionFactory>cast( Service.load(
KernelExtensionFactory.class ) ),
Service.load( CacheProvider.class ),
Service.load( TransactionInterceptorProvider.class )
);
}
/**
* This is deprecated. Use {@link TestGraphDatabaseFactory} instead
*/
@Deprecated
public ImpermanentGraphDatabase( Map<String, String> params,
Iterable<KernelExtensionFactory<?>> kernelExtensions,
Iterable<CacheProvider> cacheProviders,
Iterable<TransactionInterceptorProvider> transactionInterceptorProviders )
{
this( PATH, params, kernelExtensions, cacheProviders, transactionInterceptorProviders );
}
/**
* This is deprecated. Use {@link TestGraphDatabaseFactory} instead
*/
@Deprecated
public ImpermanentGraphDatabase( String storeDir, Map<String, String> params,
Iterable<KernelExtensionFactory<?>> kernelExtensions,
Iterable<CacheProvider> cacheProviders,
Iterable<TransactionInterceptorProvider> transactionInterceptorProviders )
{
this( storeDir, withForcedInMemoryConfiguration( params ),
getDependencies( kernelExtensions, cacheProviders, transactionInterceptorProviders ) );
}
private static Dependencies getDependencies(
Iterable<KernelExtensionFactory<?>> kernelExtensions,
Iterable<CacheProvider> cacheProviders,
Iterable<TransactionInterceptorProvider> transactionInterceptorProviders )
{
GraphDatabaseFactoryState state = new GraphDatabaseFactoryState();
state.setKernelExtensions( kernelExtensions );
state.setCacheProviders( cacheProviders );
state.setTransactionInterceptorProviders( transactionInterceptorProviders );
return state.databaseDependencies();
}
protected ImpermanentGraphDatabase( String storeDir, Map<String, String> params, Dependencies dependencies )
{
super( storeDir, withForcedInMemoryConfiguration( params ), dependencies );
trackUnclosedUse( storeDir );
}
private void trackUnclosedUse( String path )
{
if ( TRACK_UNCLOSED_DATABASE_INSTANCES )
{
Exception testThatDidNotCloseDb = startedButNotYetClosed.put( new File( path ),
new Exception( "Unclosed database instance" ) );
if ( testThatDidNotCloseDb != null )
{
testThatDidNotCloseDb.printStackTrace();
}
}
}
@Override
public void shutdown()
{
if ( TRACK_UNCLOSED_DATABASE_INSTANCES )
{
startedButNotYetClosed.remove( new File( getStoreDir() ) );
}
super.shutdown();
}
@Override
protected FileSystemAbstraction createFileSystemAbstraction()
{
return life.add( new EphemeralFileSystemAbstraction() );
}
private static Map<String, String> withForcedInMemoryConfiguration( Map<String, String> params )
{
// Because EphemeralFileChannel doesn't support memory mapping
Map<String, String> result = new HashMap<>( params );
result.put( use_memory_mapped_buffers.name(), FALSE );
// To signal to index provides that we should be in-memory
result.put( ephemeral.name(), TRUE );
return result;
}
@Override
protected Logging createLogging()
{
return life.add( new SingleLoggingService( StringLogger.loggerDirectory( fileSystem, storeDir ) ) );
}
public void cleanContent()
{
cleanDatabaseContent( this );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_ImpermanentGraphDatabase.java
|
2,122
|
public class InputStreamAwaiterTest
{
@Test
public void shouldWaitForALineWithoutBlocking() throws Exception
{
// given
ArtificialClock clock = new ArtificialClock();
InputStream inputStream = spy( new MockInputStream( clock.progressor( 5, TimeUnit.MILLISECONDS ),
lines( "important message" ) ) );
InputStreamAwaiter awaiter = new InputStreamAwaiter( clock, inputStream );
// when
awaiter.awaitLine( "important message", 5, TimeUnit.SECONDS );
}
@Test
public void shouldTimeoutWhenDifferentContentProvided() throws Exception
{
// given
ArtificialClock clock = new ArtificialClock();
InputStream inputStream = spy( new MockInputStream( clock.progressor( 1, TimeUnit.SECONDS ),
lines( "different content" ),
lines( "different message" ) ) );
InputStreamAwaiter awaiter = new InputStreamAwaiter( clock, inputStream );
// when
try
{
awaiter.awaitLine( "important message", 5, TimeUnit.SECONDS );
fail( "should have thrown exception" );
}
// then
catch ( TimeoutException e )
{
// ok
}
}
@Test
public void shouldTimeoutWhenNoContentProvided() throws Exception
{
// given
ArtificialClock clock = new ArtificialClock();
InputStream inputStream = spy( new MockInputStream( clock.progressor( 1, TimeUnit.SECONDS ) ) );
InputStreamAwaiter awaiter = new InputStreamAwaiter( clock, inputStream );
// when
try
{
awaiter.awaitLine( "important message", 5, TimeUnit.SECONDS );
fail( "should have thrown exception" );
}
// then
catch ( TimeoutException e )
{
// ok
}
}
private static String lines( String... lines )
{
StringBuilder result = new StringBuilder();
for ( String line : lines )
{
result.append( line ).append( System.getProperty( "line.separator" ) );
}
return result.toString();
}
private static class MockInputStream extends InputStream
{
private final byte[][] chunks;
private final ArtificialClock.Progressor progressor;
private int chunk = 0;
MockInputStream( ArtificialClock.Progressor progressor, String... chunks )
{
this.progressor = progressor;
this.chunks = new byte[chunks.length][];
for ( int i = 0; i < chunks.length; i++ )
{
this.chunks[i] = chunks[i].getBytes();
}
}
@Override
public int available() throws IOException
{
progressor.tick();
if ( chunk >= chunks.length )
{
return 0;
}
return chunks[chunk].length;
}
@Override
public int read( byte[] target ) throws IOException
{
if ( chunk >= chunks.length )
{
return 0;
}
byte[] source = chunks[chunk++];
System.arraycopy( source, 0, target, 0, source.length );
return source.length;
}
@Override
public int read() throws IOException
{
throw new UnsupportedOperationException();
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_InputStreamAwaiterTest.java
|
2,123
|
{
@Override
public Voice mute()
{
final Logger logger = LogManager.getLogManager().getLogger( "" );
final Level level = logger.getLevel();
final Handler[] handlers = logger.getHandlers();
for ( Handler handler : handlers )
{
logger.removeHandler( handler );
}
if ( replacement != null )
{
logger.addHandler( replacement );
logger.setLevel( Level.ALL );
}
return new Voice()
{
@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
|
2,124
|
private static class MockInputStream extends InputStream
{
private final byte[][] chunks;
private final ArtificialClock.Progressor progressor;
private int chunk = 0;
MockInputStream( ArtificialClock.Progressor progressor, String... chunks )
{
this.progressor = progressor;
this.chunks = new byte[chunks.length][];
for ( int i = 0; i < chunks.length; i++ )
{
this.chunks[i] = chunks[i].getBytes();
}
}
@Override
public int available() throws IOException
{
progressor.tick();
if ( chunk >= chunks.length )
{
return 0;
}
return chunks[chunk].length;
}
@Override
public int read( byte[] target ) throws IOException
{
if ( chunk >= chunks.length )
{
return 0;
}
byte[] source = chunks[chunk++];
System.arraycopy( source, 0, target, 0, source.length );
return source.length;
}
@Override
public int read() throws IOException
{
throw new UnsupportedOperationException();
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_InputStreamAwaiterTest.java
|
2,125
|
public final class Mute implements TestRule
{
public static Mute mute( Mutable... mutables )
{
return new Mute( mutables );
}
public static Mute muteAll()
{
return mute( System.out, System.err, java_util_logging );
}
public enum System implements Mutable
{
out
{
@Override
PrintStream replace( PrintStream replacement )
{
PrintStream old = java.lang.System.out;
java.lang.System.setOut( replacement );
return old;
}
},
err
{
@Override
PrintStream replace( PrintStream replacement )
{
PrintStream old = java.lang.System.err;
java.lang.System.setErr( replacement );
return old;
}
};
@Override
public Voice mute()
{
final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
final PrintStream old = replace( new PrintStream( buffer ) );
return new Voice()
{
@Override
void restore( boolean failure ) throws IOException
{
replace( old ).flush();
if ( failure )
{
old.write( buffer.toByteArray() );
}
}
};
}
abstract PrintStream replace( PrintStream replacement );
}
public static final Mutable java_util_logging = java_util_logging( null, null );
public static Mutable java_util_logging( OutputStream redirectTo, Level level )
{
final Handler replacement = redirectTo == null ? null : new StreamHandler( redirectTo, new SimpleFormatter() );
if ( replacement != null && level != null )
{
replacement.setLevel( level );
}
return new Mutable()
{
@Override
public Voice mute()
{
final Logger logger = LogManager.getLogManager().getLogger( "" );
final Level level = logger.getLevel();
final Handler[] handlers = logger.getHandlers();
for ( Handler handler : handlers )
{
logger.removeHandler( handler );
}
if ( replacement != null )
{
logger.addHandler( replacement );
logger.setLevel( Level.ALL );
}
return new Voice()
{
@Override
void restore( boolean failure ) throws IOException
{
for ( Handler handler : handlers )
{
logger.addHandler( handler );
}
logger.setLevel( level );
if ( replacement != null )
{
logger.removeHandler( replacement );
}
}
};
}
};
}
public <T> T call( Callable<T> callable ) throws Exception
{
Voice[] voices = captureVoices();
boolean failure = true;
try
{
T result = callable.call();
failure = false;
return result;
}
finally
{
releaseVoices( voices, failure );
}
}
private final Mutable[] mutables;
private Mute( Mutable[] mutables )
{
this.mutables = mutables;
}
@Override
public Statement apply( final Statement base, Description description )
{
return new Statement()
{
@Override
public void evaluate() throws Throwable
{
Voice[] voices = captureVoices();
boolean failure = true;
try
{
base.evaluate();
failure = false;
}
finally
{
releaseVoices( voices, failure );
}
}
};
}
public interface Mutable
{
Voice mute();
}
private static abstract class Voice
{
abstract void restore( boolean failure ) throws IOException;
}
Voice[] captureVoices()
{
Voice[] voices = new Voice[mutables.length];
boolean ok = false;
try
{
for ( int i = 0; i < voices.length; i++ )
{
voices[i] = mutables[i].mute();
}
ok = true;
}
finally
{
if ( !ok )
{
releaseVoices( voices, false );
}
}
return voices;
}
void releaseVoices( Voice[] voices, boolean failure )
{
List<Throwable> failures = null;
try
{
failures = new ArrayList<Throwable>( voices.length );
}
catch ( Throwable oom )
{
// nothing we can do...
}
for ( Voice voice : voices )
{
if ( voice != null )
{
try
{
voice.restore( failure );
}
catch ( Throwable exception )
{
if ( failures != null )
{
failures.add( exception );
}
}
}
}
if ( failures != null && !failures.isEmpty() )
{
for ( Throwable exception : failures )
{
exception.printStackTrace();
}
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_Mute.java
|
2,126
|
{
@Override
public void evaluate() throws Throwable
{
resource = createResource( dir );
try
{
base.evaluate();
}
finally
{
R waste = resource;
resource = null;
disposeResource( waste );
}
}
}, description );
| false
|
enterprise_ha_src_test_java_org_neo4j_test_ManagedResource.java
|
2,127
|
public abstract class ManagedResource<R> implements TestRule
{
private R resource;
public final R getResource()
{
R result = this.resource;
if ( result == null )
{
throw new IllegalStateException( "Resource is not started." );
}
return result;
}
protected abstract R createResource( TargetDirectory.TestDirectory dir ) throws Exception;
protected abstract void disposeResource( R resource );
@Override
public final Statement apply( final Statement base, Description description )
{
final TargetDirectory.TestDirectory dir = TargetDirectory.forTest( description.getTestClass() ).testDirectory();
return dir.apply( new Statement()
{
@Override
public void evaluate() throws Throwable
{
resource = createResource( dir );
try
{
base.evaluate();
}
finally
{
R waste = resource;
resource = null;
disposeResource( waste );
}
}
}, description );
}
}
| false
|
enterprise_ha_src_test_java_org_neo4j_test_ManagedResource.java
|
2,128
|
public class LoggerRule
extends ExternalResource
{
private Logger logger;
private String testName;
@Override
protected void before()
throws Throwable
{
logger.info( "Begin test:" + testName );
super.before();
}
@Override
protected void after()
{
super.after();
logger.info( "Finished test:" + testName );
}
@Override
public Statement apply( Statement base, Description description )
{
testName = description.getDisplayName();
logger = LoggerFactory.getLogger( description.getTestClass() );
return super.apply( base, description );
}
public Logger getLogger()
{
return logger;
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_LoggerRule.java
|
2,129
|
public static class NonCleanLogCopy
{
private final FileBackup[] backups;
NonCleanLogCopy( FileBackup... backups )
{
this.backups = backups;
}
public void reinstate() throws IOException
{
for ( FileBackup backup : backups )
{
backup.restore();
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_LogTestUtils.java
|
2,130
|
public static abstract class LogHookAdapter<RECORD> implements LogHook<RECORD>
{
@Override
public void file( File file )
{ // Do nothing
}
@Override
public void done( File file )
{ // Do nothing
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_LogTestUtils.java
|
2,131
|
private static class FileBackup
{
private final File file, backup;
private final FileSystemAbstraction fileSystem;
FileBackup( File file, File backup, FileSystemAbstraction fileSystem )
{
this.file = file;
this.backup = backup;
this.fileSystem = fileSystem;
}
public void restore() throws IOException
{
fileSystem.deleteFile( file );
fileSystem.renameFile( backup, file );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_LogTestUtils.java
|
2,132
|
public static class CountingLogHook<RECORD> extends LogHookAdapter<RECORD>
{
private int count;
@Override
public boolean accept( RECORD item )
{
count++;
return true;
}
public int getCount()
{
return count;
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_LogTestUtils.java
|
2,133
|
private static class ByteArray
{
private final byte[] bytes;
public ByteArray( byte[] bytes )
{
this.bytes = bytes;
}
@Override
public boolean equals( Object obj )
{
return Arrays.equals( bytes, ((ByteArray)obj).bytes );
}
@Override
public int hashCode()
{
return Arrays.hashCode( bytes );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_LogTestUtils.java
|
2,134
|
{
@Override
public boolean accept( LogEntry item )
{
target.set( max( target.get(), item.getIdentifier() ) );
return true;
}
};
| false
|
community_kernel_src_test_java_org_neo4j_test_LogTestUtils.java
|
2,135
|
{
private int recordCount = 0;
@Override
public boolean accept( Pair<Byte, List<byte[]>> item )
{
System.out.println( stringifyTxLogType( item.first().byteValue() ) + ": " +
stringifyTxLogBody( item.other() ) );
recordCount++;
return true;
}
@Override
public void file( File file )
{
System.out.println( "=== File:" + file + " ===" );
recordCount = 0;
}
@Override
public void done( File file )
{
System.out.println( "===> Read " + recordCount + " records from " + file );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_test_LogTestUtils.java
|
2,136
|
{
private final Map<ByteArray,List<Xid>> xids = new HashMap<>();
@Override
public boolean accept( Pair<Byte, List<byte[]>> item )
{
if ( item.first().byteValue() == TxLog.BRANCH_ADD )
{
ByteArray key = new ByteArray( item.other().get( 0 ) );
List<Xid> list = xids.get( key );
if ( list == null )
{
list = new ArrayList<>();
xids.put( key, list );
}
Xid xid = new XidImpl( item.other().get( 0 ), item.other().get( 1 ) );
list.add( xid );
}
else if ( item.first().byteValue() == TxLog.TX_DONE )
{
List<Xid> removed = xids.remove( new ByteArray( item.other().get( 0 ) ) );
if ( removed == null )
{
throw new IllegalArgumentException( "Not found" );
}
}
return true;
}
@Override
public void file( File file )
{
xids.clear();
System.out.println( "=== " + file + " ===" );
}
@Override
public void done( File file )
{
for ( List<Xid> xid : xids.values() )
{
System.out.println( "dangling " + xid );
}
}
};
| false
|
community_kernel_src_test_java_org_neo4j_test_LogTestUtils.java
|
2,137
|
{
@Override
public boolean accept( Pair<Byte, List<byte[]>> item )
{
return true;
}
};
| false
|
community_kernel_src_test_java_org_neo4j_test_LogTestUtils.java
|
2,138
|
{
@Override
public boolean accept( Pair<Byte, List<byte[]>> item )
{
return item.first().byteValue() != TxLog.TX_DONE;
}
};
| false
|
community_kernel_src_test_java_org_neo4j_test_LogTestUtils.java
|
2,139
|
public class LogTestUtils
{
public static interface LogHook<RECORD> extends Predicate<RECORD>
{
void file( File file );
void done( File file );
}
public static abstract class LogHookAdapter<RECORD> implements LogHook<RECORD>
{
@Override
public void file( File file )
{ // Do nothing
}
@Override
public void done( File file )
{ // Do nothing
}
}
public static final LogHook<Pair<Byte, List<byte[]>>> EVERYTHING_BUT_DONE_RECORDS =
new LogHookAdapter<Pair<Byte,List<byte[]>>>()
{
@Override
public boolean accept( Pair<Byte, List<byte[]>> item )
{
return item.first().byteValue() != TxLog.TX_DONE;
}
};
public static final LogHook<Pair<Byte, List<byte[]>>> NO_FILTER = new LogHookAdapter<Pair<Byte,List<byte[]>>>()
{
@Override
public boolean accept( Pair<Byte, List<byte[]>> item )
{
return true;
}
};
public static final LogHook<Pair<Byte, List<byte[]>>> PRINT_DANGLING = new LogHook<Pair<Byte,List<byte[]>>>()
{
private final Map<ByteArray,List<Xid>> xids = new HashMap<>();
@Override
public boolean accept( Pair<Byte, List<byte[]>> item )
{
if ( item.first().byteValue() == TxLog.BRANCH_ADD )
{
ByteArray key = new ByteArray( item.other().get( 0 ) );
List<Xid> list = xids.get( key );
if ( list == null )
{
list = new ArrayList<>();
xids.put( key, list );
}
Xid xid = new XidImpl( item.other().get( 0 ), item.other().get( 1 ) );
list.add( xid );
}
else if ( item.first().byteValue() == TxLog.TX_DONE )
{
List<Xid> removed = xids.remove( new ByteArray( item.other().get( 0 ) ) );
if ( removed == null )
{
throw new IllegalArgumentException( "Not found" );
}
}
return true;
}
@Override
public void file( File file )
{
xids.clear();
System.out.println( "=== " + file + " ===" );
}
@Override
public void done( File file )
{
for ( List<Xid> xid : xids.values() )
{
System.out.println( "dangling " + xid );
}
}
};
public static final LogHook<Pair<Byte, List<byte[]>>> DUMP = new LogHook<Pair<Byte,List<byte[]>>>()
{
private int recordCount = 0;
@Override
public boolean accept( Pair<Byte, List<byte[]>> item )
{
System.out.println( stringifyTxLogType( item.first().byteValue() ) + ": " +
stringifyTxLogBody( item.other() ) );
recordCount++;
return true;
}
@Override
public void file( File file )
{
System.out.println( "=== File:" + file + " ===" );
recordCount = 0;
}
@Override
public void done( File file )
{
System.out.println( "===> Read " + recordCount + " records from " + file );
}
};
public static LogHook<LogEntry> findLastTransactionIdentifier( final AtomicInteger target )
{
return new LogHookAdapter<LogEntry>()
{
@Override
public boolean accept( LogEntry item )
{
target.set( max( target.get(), item.getIdentifier() ) );
return true;
}
};
}
private static String stringifyTxLogType( byte recordType )
{
switch ( recordType )
{
case TxLog.TX_START: return "TX_START";
case TxLog.BRANCH_ADD: return "BRANCH_ADD";
case TxLog.MARK_COMMIT: return "MARK_COMMIT";
case TxLog.TX_DONE: return "TX_DONE";
default: return "Unknown " + recordType;
}
}
private static String stringifyTxLogBody( List<byte[]> list )
{
if ( list.size() == 2 )
{
return new XidImpl( list.get( 0 ), list.get( 1 ) ).toString();
}
else if ( list.size() == 1 )
{
return stripFromBranch( new XidImpl( list.get( 0 ), new byte[0] ).toString() );
}
throw new RuntimeException( list.toString() );
}
private static String stripFromBranch( String xidToString )
{
int index = xidToString.lastIndexOf( ", BranchId" );
return xidToString.substring( 0, index );
}
private static class ByteArray
{
private final byte[] bytes;
public ByteArray( byte[] bytes )
{
this.bytes = bytes;
}
@Override
public boolean equals( Object obj )
{
return Arrays.equals( bytes, ((ByteArray)obj).bytes );
}
@Override
public int hashCode()
{
return Arrays.hashCode( bytes );
}
}
public static class CountingLogHook<RECORD> extends LogHookAdapter<RECORD>
{
private int count;
@Override
public boolean accept( RECORD item )
{
count++;
return true;
}
public int getCount()
{
return count;
}
}
public static void filterTxLog( FileSystemAbstraction fileSystem, String storeDir,
LogHook<Pair<Byte, List<byte[]>>> filter ) throws IOException
{
filterTxLog( fileSystem, storeDir, filter, 0 );
}
public static void filterTxLog( FileSystemAbstraction fileSystem, String storeDir,
LogHook<Pair<Byte, List<byte[]>>> filter, long startPosition ) throws IOException
{
for ( File file : oneOrTwo( fileSystem, new File( storeDir, "tm_tx_log" ) ) )
{
filterTxLog( fileSystem, file, filter, startPosition );
}
}
public static void filterTxLog( FileSystemAbstraction fileSystem, File file,
LogHook<Pair<Byte, List<byte[]>>> filter ) throws IOException
{
filterTxLog( fileSystem, file, filter, 0 );
}
public static void filterTxLog( FileSystemAbstraction fileSystem, File file,
LogHook<Pair<Byte, List<byte[]>>> filter, long startPosition ) throws IOException
{
File tempFile = new File( file.getPath() + ".tmp" );
fileSystem.deleteFile( tempFile );
StoreChannel in = fileSystem.open( file, "r" );
in.position( startPosition );
StoreChannel out = fileSystem.open( tempFile, "rw" );
LogBuffer outBuffer = new DirectMappedLogBuffer( out, new Monitors().newMonitor( ByteCounterMonitor.class ) );
ByteBuffer buffer = ByteBuffer.allocate( 1024*1024 );
boolean changed = false;
try
{
filter.file( file );
in.read( buffer );
buffer.flip();
while ( buffer.hasRemaining() )
{
byte type = buffer.get();
List<byte[]> xids = null;
if ( type == TxLog.TX_START )
{
xids = readXids( buffer, 1 );
}
else if ( type == TxLog.BRANCH_ADD )
{
xids = readXids( buffer, 2 );
}
else if ( type == TxLog.MARK_COMMIT )
{
xids = readXids( buffer, 1 );
}
else if ( type == TxLog.TX_DONE )
{
xids = readXids( buffer, 1 );
}
else
{
throw new IllegalArgumentException( "Unknown type:" + type + ", position:" +
(in.position()-buffer.remaining()) );
}
if ( filter.accept( Pair.of( type, xids ) ) )
{
outBuffer.put( type );
writeXids( xids, outBuffer );
}
else
{
changed = true;
}
}
}
finally
{
safeClose( in );
outBuffer.force();
safeClose( out );
filter.done( file );
}
if ( changed )
{
replace( tempFile, file );
}
else
{
tempFile.delete();
}
}
public static void assertLogContains( FileSystemAbstraction fileSystem, String logPath,
LogEntry ... expectedEntries ) throws IOException
{
ByteBuffer buffer = ByteBuffer.allocateDirect( 9 + Xid.MAXGTRIDSIZE
+ Xid.MAXBQUALSIZE * 10 );
try ( StoreChannel fileChannel = fileSystem.open( new File( logPath ), "r" ) )
{
// Always a header
LogIoUtils.readLogHeader( buffer, fileChannel, true );
// Read all log entries
List<LogEntry> entries = new ArrayList<>( );
CommandFactory cmdFactory = new CommandFactory();
LogEntry entry;
while ( (entry = LogIoUtils.readEntry( buffer, fileChannel, cmdFactory )) != null )
{
entries.add( entry );
}
// Assert entries are what we expected
for(int entryNo=0;entryNo < expectedEntries.length; entryNo++)
{
LogEntry expectedEntry = expectedEntries[entryNo];
if(entries.size() <= entryNo)
{
fail("Log ended prematurely. Expected to find '" + expectedEntry.toString() + "' as log entry number "+entryNo+", instead there were no more log entries." );
}
LogEntry actualEntry = entries.get( entryNo );
assertThat( "Unexpected entry at entry number " + entryNo, actualEntry, is( expectedEntry ) );
}
// And assert log does not contain more entries
assertThat( "The log contained more entries than we expected!", entries.size(), is( expectedEntries.length ) );
}
}
private static void replace( File tempFile, File file )
{
file.renameTo( new File( file.getAbsolutePath() + "." + System.currentTimeMillis() ) );
tempFile.renameTo( file );
}
public static File[] filterNeostoreLogicalLog( FileSystemAbstraction fileSystem,
String storeDir, LogHook<LogEntry> filter ) throws IOException
{
List<File> files = new ArrayList<>( asList(
oneOrTwo( fileSystem, new File( storeDir, LOGICAL_LOG_DEFAULT_NAME ) ) ) );
gatherHistoricalLogicalLogFiles( fileSystem, storeDir, files );
for ( File file : files )
{
File filteredLog = filterNeostoreLogicalLog( fileSystem, file, filter );
replace( filteredLog, file );
}
return files.toArray( new File[files.size()] );
}
private static void gatherHistoricalLogicalLogFiles( FileSystemAbstraction fileSystem, String storeDir,
List<File> files )
{
long highestVersion = getHighestHistoryLogVersion( fileSystem, new File( storeDir ), LOGICAL_LOG_DEFAULT_NAME );
for ( long version = 0; version <= highestVersion; version++ )
{
File versionFile = getHistoryFileName( new File( storeDir, LOGICAL_LOG_DEFAULT_NAME ), version );
if ( fileSystem.fileExists( versionFile ) )
{
files.add( versionFile );
}
}
}
public static File filterNeostoreLogicalLog( FileSystemAbstraction fileSystem, File file, LogHook<LogEntry> filter )
throws IOException
{
filter.file( file );
File tempFile = new File( file.getAbsolutePath() + ".tmp" );
fileSystem.deleteFile( tempFile );
StoreChannel in = fileSystem.open( file, "r" );
StoreChannel out = fileSystem.open( tempFile, "rw" );
LogBuffer outBuffer = new DirectMappedLogBuffer( out, new Monitors().newMonitor( ByteCounterMonitor.class ) );
ByteBuffer buffer = ByteBuffer.allocate( 1024*1024 );
transferLogicalLogHeader( in, outBuffer, buffer );
CommandFactory cf = new CommandFactory();
try
{
LogEntry entry = null;
while ( (entry = readEntry( buffer, in, cf ) ) != null )
{
if ( !filter.accept( entry ) )
{
continue;
}
writeLogEntry( entry, outBuffer );
}
}
finally
{
safeClose( in );
outBuffer.force();
safeClose( out );
filter.done( file );
}
return tempFile;
}
private static void transferLogicalLogHeader( StoreChannel in, LogBuffer outBuffer,
ByteBuffer buffer ) throws IOException
{
long[] header = LogIoUtils.readLogHeader( buffer, in, true );
LogIoUtils.writeLogHeader( buffer, header[0], header[1] );
byte[] headerBytes = new byte[buffer.limit()];
buffer.get( headerBytes );
outBuffer.put( headerBytes );
}
private static void safeClose( StoreChannel channel )
{
try
{
if ( channel != null )
{
channel.close();
}
}
catch ( IOException e )
{ // OK
}
}
private static void writeXids( List<byte[]> xids, LogBuffer outBuffer ) throws IOException
{
for ( byte[] xid : xids )
{
outBuffer.put( (byte)xid.length );
}
for ( byte[] xid : xids )
{
outBuffer.put( xid );
}
}
private static List<byte[]> readXids( ByteBuffer buffer, int count )
{
byte[] counts = new byte[count];
for ( int i = 0; i < count; i++ )
{
counts[i] = buffer.get();
}
List<byte[]> xids = new ArrayList<>();
for ( int i = 0; i < count; i++ )
{
xids.add( readXid( buffer, counts[i] ) );
}
return xids;
}
private static byte[] readXid( ByteBuffer buffer, byte length )
{
byte[] bytes = new byte[length];
buffer.get( bytes );
return bytes;
}
public static File[] oneOrTwo( FileSystemAbstraction fileSystem, File file )
{
List<File> files = new ArrayList<>();
File one = new File( file.getPath() + ".1" );
if ( fileSystem.fileExists( one ) )
{
files.add( one );
}
File two = new File( file.getPath() + ".2" );
if ( fileSystem.fileExists( two ) )
{
files.add( two );
}
return files.toArray( new File[files.size()] );
}
public static NonCleanLogCopy copyLogicalLog( FileSystemAbstraction fileSystem,
File logBaseFileName ) throws IOException
{
char active = '1';
File activeLog = new File( logBaseFileName.getPath() + ".active" );
ByteBuffer buffer = ByteBuffer.allocate( 1024 );
File activeLogBackup;
try ( StoreChannel af = fileSystem.open( activeLog, "r" ) )
{
af.read( buffer );
buffer.flip();
activeLogBackup = new File( logBaseFileName.getPath() + ".bak.active" );
try ( StoreChannel activeCopy = fileSystem.open( activeLogBackup, "rw" ) )
{
activeCopy.write( buffer );
}
}
buffer.flip();
active = buffer.asCharBuffer().get();
buffer.clear();
File currentLog = new File( logBaseFileName.getPath() + "." + active );
File currentLogBackup = new File( logBaseFileName.getPath() + ".bak." + active );
try ( StoreChannel source = fileSystem.open( currentLog, "r" );
StoreChannel dest = fileSystem.open( currentLogBackup, "rw" ) )
{
int read = -1;
do
{
read = source.read( buffer );
buffer.flip();
dest.write( buffer );
buffer.clear();
}
while ( read == 1024 );
}
return new NonCleanLogCopy(
new FileBackup( activeLog, activeLogBackup, fileSystem ),
new FileBackup( currentLog, currentLogBackup, fileSystem ) );
}
private static class FileBackup
{
private final File file, backup;
private final FileSystemAbstraction fileSystem;
FileBackup( File file, File backup, FileSystemAbstraction fileSystem )
{
this.file = file;
this.backup = backup;
this.fileSystem = fileSystem;
}
public void restore() throws IOException
{
fileSystem.deleteFile( file );
fileSystem.renameFile( backup, file );
}
}
public static class NonCleanLogCopy
{
private final FileBackup[] backups;
NonCleanLogCopy( FileBackup... backups )
{
this.backups = backups;
}
public void reinstate() throws IOException
{
for ( FileBackup backup : backups )
{
backup.restore();
}
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_LogTestUtils.java
|
2,140
|
{
@Override
public JavaTestDocsGenerator create( GraphDefinition graph,
String title, String documentation )
{
return (JavaTestDocsGenerator) new JavaTestDocsGenerator( title ).description( documentation );
}
@Override
public void destroy( JavaTestDocsGenerator product, boolean successful )
{
// TODO: invoke some complete method here?
}
};
| false
|
community_kernel_src_test_java_org_neo4j_test_JavaTestDocsGenerator.java
|
2,141
|
public class JavaTestDocsGenerator extends AsciiDocGenerator
{
public static final Producer<JavaTestDocsGenerator> PRODUCER = new Producer<JavaTestDocsGenerator>()
{
@Override
public JavaTestDocsGenerator create( GraphDefinition graph,
String title, String documentation )
{
return (JavaTestDocsGenerator) new JavaTestDocsGenerator( title ).description( documentation );
}
@Override
public void destroy( JavaTestDocsGenerator product, boolean successful )
{
// TODO: invoke some complete method here?
}
};
public JavaTestDocsGenerator( String title )
{
super( title, "docs" );
}
public void document( String directory, String sectionName )
{
this.setSection( sectionName );
String name = title.replace( " ", "-" ).toLowerCase();
File dir = new File( new File( directory ), section );
String filename = name + ".asciidoc";
Writer fw = getFW( dir, filename );
description = replaceSnippets( description, dir, name );
try
{
line( fw,
"[[" + sectionName + "-" + name.replaceAll( "\\(|\\)", "" )
+ "]]" );
String firstChar = title.substring( 0, 1 ).toUpperCase();
line( fw, firstChar + title.substring( 1 ) );
for ( int i = 0; i < title.length(); i++ )
{
fw.append( "=" );
}
fw.append( "\n" );
line( fw, "" );
line( fw, description );
line( fw, "" );
fw.flush();
fw.close();
}
catch ( IOException e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void addImageSnippet( String tagName, String imageName, String title )
{
this.addSnippet( tagName, "\nimage:" + imageName + "[" + title
+ "scaledwidth=75%]\n" );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_JavaTestDocsGenerator.java
|
2,142
|
public class JavaDocsGenerator extends AsciiDocGenerator
{
private final static String DIRECTORY = "target" + File.separator + "docs";
public JavaDocsGenerator( String title, String section )
{
super( title, section );
}
public void saveToFile( String identifier, String text )
{
Writer fw = getFW( DIRECTORY + File.separator + this.section,
getTitle() + "-" + identifier );
try
{
line( fw, text );
fw.flush();
fw.close();
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_JavaDocsGenerator.java
|
2,143
|
public class IterableMatcher<T> extends TypeSafeMatcher<Iterable<T>>
{
private final Iterable<T> toMatch;
private IterableMatcher( Iterable<T> toMatch )
{
this.toMatch = toMatch;
}
@Override
protected boolean matchesSafely( Iterable<T> objects )
{
if ( Iterables.count( toMatch ) != Iterables.count( objects ))
{
return false;
}
Iterator<T> original = toMatch.iterator();
Iterator<T> matched = objects.iterator();
T fromOriginal;
T fromToMatch;
for ( ; original.hasNext() && matched.hasNext(); )
{
fromOriginal = original.next();
fromToMatch = matched.next();
if ( !fromOriginal.equals( fromToMatch ) )
{
return false;
}
}
return true;
}
@Override
public void describeTo( Description description )
{
description.appendValueList( "Iterable [", ",", "]", toMatch );
}
public static <T> IterableMatcher<T> matchesIterable( Iterable<T> toMatch )
{
return new IterableMatcher<T>( toMatch );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_IterableMatcher.java
|
2,144
|
{
@Override
public boolean accept( ManagedCluster cluster )
{
for ( HighlyAvailableGraphDatabase graphDatabaseService : cluster.getAllMembers() )
{
if ( !exceptSet.contains( graphDatabaseService ))
{
if ( graphDatabaseService.isMaster() )
{
return true;
}
}
}
return false;
}
@Override
public String toString()
{
return "There's an available master";
}
};
| false
|
enterprise_ha_src_test_java_org_neo4j_test_ha_ClusterManager.java
|
2,145
|
{
@Override
public boolean accept( ManagedCluster cluster )
{
ClusterMembers members = cluster.getMaster().getDependencyResolver().resolveDependency( ClusterMembers.class );
return Iterables.count(members.getMembers()) == count;
}
@Override
public String toString()
{
return "Master should see " + count + " members";
}
};
| false
|
enterprise_ha_src_test_java_org_neo4j_test_ha_ClusterManager.java
|
2,146
|
{
@Override
public boolean accept( ManagedCluster cluster )
{
if (!allSeesAllAsJoined().accept( cluster ))
return false;
for ( HighlyAvailableGraphDatabase database : cluster.getAllMembers() )
{
ClusterMembers members = database.getDependencyResolver().resolveDependency( ClusterMembers.class );
for ( ClusterMember clusterMember : members.getMembers() )
{
if ( clusterMember.getHARole().equals( "UNKNOWN" ) )
{
return false;
}
}
}
// Everyone sees everyone else as available!
return true;
}
@Override
public String toString()
{
return "All instances should see all others as available";
}
};
| false
|
enterprise_ha_src_test_java_org_neo4j_test_ha_ClusterManager.java
|
2,147
|
{
@Override
public void deadlock( DebuggedThread thread )
{
throw new DeadlockDetectedError();
}
};
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_SubProcess.java
|
2,148
|
static class DeadlockDetectedError extends Error
{
@Override
public Throwable fillInStackTrace()
{
return this;
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_SubProcess.java
|
2,149
|
{
@Override
public void run()
{
killAll( handlers );
}
} );
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_SubProcess.java
|
2,150
|
@SuppressWarnings( "serial" )
public abstract class SubProcess<T, P> implements Serializable
{
private interface NoInterface
{
// Used when no interface is declared
}
private final Class<T> t;
private final transient Predicate<String> classPathFilter;
@SuppressWarnings( { "unchecked", "rawtypes" } )
public SubProcess( Predicate<String> classPathFilter )
{
if ( getClass().getSuperclass() != SubProcess.class )
{
throw new ClassCastException( SubProcess.class.getName() + " may only be extended one level " );
}
Class<?> me = getClass();
while ( me.getSuperclass() != SubProcess.class )
{
me = me.getSuperclass();
}
Type type = ( (ParameterizedType) me.getGenericSuperclass() ).getActualTypeArguments()[0];
@SuppressWarnings( { "hiding" } ) Class<T> t;
if ( type instanceof Class<?> )
{
t = (Class<T>) type;
}
else if ( type instanceof ParameterizedType )
{
t = (Class<T>) ( (ParameterizedType) type ).getRawType();
}
else
{
throw new ClassCastException( "Illegal type parameter " + type );
}
if ( t == Object.class )
{
t = (Class) NoInterface.class;
}
if ( !t.isInterface() )
{
throw new ClassCastException( t + " is not an interface" );
}
if ( t.isAssignableFrom( getClass() ) || t == NoInterface.class )
{
this.t = t;
}
else
{
throw new ClassCastException( getClass().getName() + " must implement declared interface " + t );
}
this.classPathFilter = classPathFilter;
}
public SubProcess()
{
this( null );
}
public T start( P parameter, BreakPoint... breakpoints )
{
DebuggerConnector debugger = null;
if ( breakpoints != null && breakpoints.length != 0 )
{
debugger = new DebuggerConnector( breakpoints );
}
DispatcherTrapImpl callback;
try
{
callback = new DispatcherTrapImpl( this, parameter );
}
catch ( RemoteException e )
{
throw new RuntimeException( "Failed to create local RMI endpoint.", e );
}
Process process;
String pid;
DebugDispatch debugDispatch = null;
Dispatcher dispatcher;
try
{
synchronized ( debugger != null ? DebuggerConnector.class : new Object() )
{
if ( debugger != null )
{
process = start( "java", "-Xmx1G", debugger.listen(), "-cp",
classPath( System.getProperty( "java.class.path" ) ), SubProcess.class.getName(),
serialize( callback ) );
}
else
{
process = start( "java", "-Xmx1G", "-cp", classPath( System.getProperty( "java.class.path" ) ),
SubProcess.class.getName(), serialize( callback ) );
}
pid = getPid( process );
pipe( "[" + toString() + ":" + pid + "] ", process.getErrorStream(), errorStreamTarget() );
pipe( "[" + toString() + ":" + pid + "] ", process.getInputStream(), inputStreamTarget() );
if ( debugger != null )
{
debugDispatch = debugger.connect( toString() + ":" + pid );
}
}
dispatcher = callback.get( process );
}
finally
{
try
{
UnicastRemoteObject.unexportObject( callback, true );
}
catch ( RemoteException e )
{
e.printStackTrace();
}
}
if ( dispatcher == null )
{
throw new IllegalStateException( "failed to start sub process" );
}
Handler handler = new Handler( t, dispatcher, process, "<" + toString() + ":" + pid + ">", debugDispatch );
if ( debugDispatch != null )
{
debugDispatch.handler = handler;
}
return t.cast( Proxy.newProxyInstance( t.getClassLoader(), new Class[] { t }, live( handler ) ) );
}
protected PrintStream errorStreamTarget()
{
return System.err;
}
protected PrintStream inputStreamTarget()
{
return System.out;
}
private String classPath( String parentClasspath )
{
if ( classPathFilter == null )
{
return parentClasspath;
}
StringBuilder result = new StringBuilder();
for ( String part : parentClasspath.split( File.pathSeparator ) )
{
if ( classPathFilter.accept( part ) )
{
result.append( result.length() > 0 ? File.pathSeparator : "" ).append( part );
}
}
return result.toString();
}
private static Process start( String... args )
{
ProcessBuilder builder = new ProcessBuilder( args );
try
{
return builder.start();
}
catch ( IOException e )
{
throw new RuntimeException( "Failed to start sub process", e );
}
}
@SuppressWarnings( "restriction" )
private static class DebuggerConnector
{
private static final com.sun.jdi.connect.ListeningConnector connector;
static
{
com.sun.jdi.connect.ListeningConnector first = null;
for ( com.sun.jdi.connect.ListeningConnector conn : com.sun.jdi.Bootstrap.virtualMachineManager().listeningConnectors() )
{
first = conn;
break;
}
connector = first;
}
private final Map<String, List<BreakPoint>> breakpoints = new HashMap<>();
private final Map<String, ? extends com.sun.jdi.connect.Connector.Argument> args;
DebuggerConnector( BreakPoint[] breakpoints )
{
this.args = connector.defaultArguments();
for ( BreakPoint breakpoint : breakpoints )
{
List<BreakPoint> list = this.breakpoints.get( breakpoint.type );
if ( list == null )
{
this.breakpoints.put( breakpoint.type, list = new ArrayList<>() );
}
list.add( breakpoint );
}
}
String listen()
{
try
{
return String.format( "-agentlib:jdwp=transport=%s,address=%s", connector.transport().name(),
connector.startListening( args ) );
}
catch ( Exception e )
{
throw new UnsupportedOperationException( "Debugger not supported", e );
}
}
DebugDispatch connect( String string )
{
final com.sun.jdi.VirtualMachine vm;
try
{
vm = connector.accept( args );
connector.stopListening( args );
}
catch ( Exception e )
{
throw new RuntimeException( "Debugger connection failure", e );
}
com.sun.jdi.request.EventRequestManager erm = vm.eventRequestManager();
TYPES: for ( Map.Entry<String, List<BreakPoint>> entry : breakpoints.entrySet() )
{
for ( com.sun.jdi.ReferenceType type : vm.classesByName( entry.getKey() ) )
{
if ( type.name().equals( entry.getKey() ) )
{
for ( BreakPoint breakpoint : entry.getValue() )
{
breakpoint.setup( type );
}
continue TYPES;
}
}
com.sun.jdi.request.ClassPrepareRequest prepare = erm.createClassPrepareRequest();
prepare.addClassFilter( entry.getKey() );
prepare.enable();
}
if ( vm.canRequestMonitorEvents() )
{
erm.createMonitorContendedEnterRequest().enable();
}
DebugDispatch dispatch = new DebugDispatch( vm.eventQueue(), breakpoints );
new Thread( dispatch, "Debugger: [" + string + "]" ).start();
return dispatch;
}
}
@SuppressWarnings( "restriction" )
static class DebugDispatch implements Runnable
{
static DebugDispatch get( Object o )
{
if ( Proxy.isProxyClass( o.getClass() ) )
{
InvocationHandler handler = Proxy.getInvocationHandler( o );
if ( handler instanceof Handler )
{
return ( (Handler) handler ).debugDispatch;
}
}
throw new IllegalArgumentException( "Not a sub process: " + o );
}
volatile Handler handler;
private final com.sun.jdi.event.EventQueue queue;
private final Map<String, List<BreakPoint>> breakpoints;
private final Map<com.sun.jdi.ThreadReference, DebuggerDeadlockCallback> suspended = new HashMap<>();
static final DebuggerDeadlockCallback defaultCallback = new DebuggerDeadlockCallback()
{
@Override
public void deadlock( DebuggedThread thread )
{
throw new DeadlockDetectedError();
}
};
DebugDispatch( com.sun.jdi.event.EventQueue queue, Map<String, List<BreakPoint>> breakpoints )
{
this.queue = queue;
this.breakpoints = breakpoints;
}
@Override
public void run()
{
for ( ;; )
{
final com.sun.jdi.event.EventSet events;
try
{
events = queue.remove();
}
catch ( InterruptedException e )
{
return;
}
Integer exitCode = null;
try
{
for ( com.sun.jdi.event.Event event : events )
{
if ( event instanceof com.sun.jdi.event.MonitorContendedEnterEvent )
{
com.sun.jdi.event.MonitorContendedEnterEvent monitor = (com.sun.jdi.event.MonitorContendedEnterEvent) event;
final com.sun.jdi.ThreadReference thread;
try
{
thread = monitor.monitor().owningThread();
}
catch ( com.sun.jdi.IncompatibleThreadStateException e )
{
e.printStackTrace();
continue;
}
if ( thread != null && thread.isSuspended() )
{
DebuggerDeadlockCallback callback = suspended.get( thread );
try
{
if ( callback != null )
{
callback.deadlock( new DebuggedThread( this, thread ) );
}
}
catch ( DeadlockDetectedError deadlock )
{
@SuppressWarnings( "hiding" ) Handler handler = this.handler;
if ( handler != null )
{
handler.kill( false );
}
}
}
}
else if ( event instanceof com.sun.jdi.event.LocatableEvent )
{
callback( (com.sun.jdi.event.LocatableEvent) event );
}
else if ( event instanceof com.sun.jdi.event.ClassPrepareEvent )
{
setup( ( (com.sun.jdi.event.ClassPrepareEvent) event ).referenceType() );
}
else if ( event instanceof com.sun.jdi.event.VMDisconnectEvent
|| event instanceof com.sun.jdi.event.VMDeathEvent )
{
return;
}
}
}
catch ( KillSubProcess kill )
{
exitCode = kill.exitCode;
}
finally
{
if ( exitCode != null )
{
events.virtualMachine().exit( exitCode );
}
else
{
events.resume();
}
}
}
}
private void setup( com.sun.jdi.ReferenceType type )
{
List<BreakPoint> list = breakpoints.get( type.name() );
if ( list == null )
{
return;
}
for ( BreakPoint breakpoint : list )
{
breakpoint.setup( type );
}
}
private void callback( com.sun.jdi.event.LocatableEvent event ) throws KillSubProcess
{
List<BreakPoint> list = breakpoints.get( event.location().declaringType().name() );
if ( list == null )
{
return;
}
com.sun.jdi.Method method = event.location().method();
for ( BreakPoint breakpoint : list )
{
if ( breakpoint.matches( method.name(), method.argumentTypeNames() ) )
{
if ( breakpoint.enabled )
{
breakpoint.invoke( new DebugInterface( this, event ) );
}
}
}
}
void suspended( com.sun.jdi.ThreadReference thread, DebuggerDeadlockCallback callback )
{
if ( callback == null )
{
callback = defaultCallback;
}
suspended.put( thread, callback );
}
void resume( com.sun.jdi.ThreadReference thread )
{
suspended.remove( thread );
}
DebuggedThread[] suspendedThreads()
{
if ( suspended.isEmpty() )
{
return new DebuggedThread[0];
}
List<DebuggedThread> threads = new ArrayList<>();
for ( com.sun.jdi.ThreadReference thread : suspended.keySet() )
{
threads.add( new DebuggedThread( this, thread ) );
}
return threads.toArray( new DebuggedThread[threads.size()] );
}
}
static class DeadlockDetectedError extends Error
{
@Override
public Throwable fillInStackTrace()
{
return this;
}
}
protected abstract void startup( P parameter ) throws Throwable;
public final void shutdown()
{
shutdown( true );
}
protected void shutdown( boolean normal )
{
System.exit( 0 );
}
public static void stop( Object subprocess )
{
( (Handler) Proxy.getInvocationHandler( subprocess ) ).stop( null, 0 );
}
public static void stop( Object subprocess, long timeout, TimeUnit unit )
{
( (Handler) Proxy.getInvocationHandler( subprocess ) ).stop( unit, timeout );
}
public static void kill( Object subprocess )
{
( (Handler) Proxy.getInvocationHandler( subprocess ) ).kill( true );
}
@Override
public String toString()
{
return getClass().getSimpleName();
}
public static void main( String[] args ) throws Throwable
{
if ( args.length != 1 )
{
throw new IllegalArgumentException( "Needs to be started from " + SubProcess.class.getName() );
}
DispatcherTrap trap = deserialize( args[0] );
SubProcess<?, Object> subProcess = trap.getSubProcess();
subProcess.doStart( trap.trap( new DispatcherImpl( subProcess ) ) );
}
private transient volatile boolean alive;
private void doStart( P parameter ) throws Throwable
{
alive = true;
startup( parameter );
liveLoop();
}
private void doStop( boolean normal )
{
alive = false;
shutdown( normal );
}
private void liveLoop() throws Exception
{
while ( alive )
{
for ( int i = System.in.available(); i >= 0; i-- )
{
if ( System.in.read() == -1 )
{
// Parent process exited, die with it
doStop( false );
}
Thread.sleep( 1 );
}
}
}
private static final Field PID;
static
{
Field pid;
try
{
pid = Class.forName( "java.lang.UNIXProcess" ).getDeclaredField( "pid" );
pid.setAccessible( true );
}
catch ( Throwable ex )
{
pid = null;
}
PID = pid;
}
private int lastPid = 0;
private String getPid( Process process )
{
if ( PID != null )
{
try
{
return PID.get( process ).toString();
}
catch ( Exception ok )
{
// handled by lastPid++
}
}
return Integer.toString( lastPid++ );
}
private static class PipeTask
{
private final String prefix;
private final InputStream source;
private final PrintStream target;
private StringBuilder line;
PipeTask( String prefix, InputStream source, PrintStream target )
{
this.prefix = prefix;
this.source = source;
this.target = target;
line = new StringBuilder();
}
boolean pipe()
{
try
{
byte[] data = new byte[Math.max( 1, source.available() )];
int bytesRead = source.read( data );
if ( bytesRead == -1 )
{
printLastLine();
return false;
}
if ( bytesRead < data.length )
{
data = Arrays.copyOf( data, bytesRead );
}
ByteBuffer chars = ByteBuffer.wrap( data );
while ( chars.hasRemaining() )
{
char c = (char) chars.get();
line.append( c );
if ( c == '\n' )
{
print();
}
}
}
catch ( IOException e )
{
printLastLine();
return false;
}
return true;
}
private void printLastLine()
{
if ( line.length() > 0 )
{
line.append( '\n' );
print();
}
}
private void print()
{
target.print( prefix + line.toString() );
line = new StringBuilder();
}
}
private static class PipeThread extends Thread
{
{
setName( getClass().getSimpleName() );
}
final CopyOnWriteArrayList<PipeTask> tasks = new CopyOnWriteArrayList<>();
@Override
public void run()
{
while ( true )
{
List<PipeTask> done = new ArrayList<>();
for ( PipeTask task : tasks )
{
if ( !task.pipe() )
{
done.add( task );
}
}
if ( !done.isEmpty() )
{
tasks.removeAll( done );
}
if ( tasks.isEmpty() )
{
synchronized ( PipeThread.class )
{
if ( tasks.isEmpty() )
{
piper = null;
return;
}
}
}
try
{
Thread.sleep( 10 );
}
catch ( InterruptedException e )
{
Thread.interrupted();
}
}
}
}
private static PipeThread piper;
private static void pipe( final String prefix, final InputStream source, final PrintStream target )
{
synchronized ( PipeThread.class )
{
if ( piper == null )
{
piper = new PipeThread();
piper.start();
}
piper.tasks.add( new PipeTask( prefix, source, target ) );
}
}
private interface DispatcherTrap extends Remote
{
Object trap( Dispatcher dispatcher ) throws RemoteException;
SubProcess<?, Object> getSubProcess() throws RemoteException;
}
private static class DispatcherTrapImpl extends UnicastRemoteObject implements DispatcherTrap
{
private final Object parameter;
private volatile Dispatcher dispatcher;
private final SubProcess<?, ?> process;
DispatcherTrapImpl( SubProcess<?, ?> process, Object parameter ) throws RemoteException
{
super();
this.process = process;
this.parameter = parameter;
}
Dispatcher get( @SuppressWarnings( "hiding" ) Process process )
{
while ( dispatcher == null )
{
try
{
Thread.sleep( 10 );
}
catch ( InterruptedException e )
{
Thread.currentThread().interrupt();
}
try
{
process.exitValue();
}
catch ( IllegalThreadStateException e )
{
continue;
}
return null;
}
return dispatcher;
}
@Override
public synchronized Object trap( @SuppressWarnings( "hiding" ) Dispatcher dispatcher )
{
if ( this.dispatcher != null )
{
throw new IllegalStateException( "Dispatcher already trapped!" );
}
this.dispatcher = dispatcher;
return parameter;
}
@Override
@SuppressWarnings( "unchecked" )
public SubProcess<?, Object> getSubProcess()
{
return (SubProcess<?, Object>) process;
}
}
@SuppressWarnings( "restriction" )
private static String serialize( DispatcherTrapImpl obj )
{
ByteArrayOutputStream os = new ByteArrayOutputStream();
try
{
ObjectOutputStream oos = new ObjectOutputStream( os );
oos.writeObject( RemoteObject.toStub( obj ) );
oos.close();
}
catch ( IOException e )
{
throw new RuntimeException( "Broken implementation!", e );
}
return new sun.misc.BASE64Encoder().encode( os.toByteArray() );
}
@SuppressWarnings( "restriction" )
private static DispatcherTrap deserialize( String data )
{
try
{
return (DispatcherTrap) new ObjectInputStream( new ByteArrayInputStream(
new sun.misc.BASE64Decoder().decodeBuffer( data ) ) ).readObject();
}
catch ( Exception e )
{
return null;
}
}
private interface Dispatcher extends Remote
{
void stop() throws RemoteException;
Object dispatch( String name, String[] types, Object[] args ) throws RemoteException, Throwable;
}
private static InvocationHandler live( Handler handler )
{
try
{
synchronized ( Handler.class )
{
if ( live == null )
{
final Set<Handler> handlers = live = new HashSet<>();
Runtime.getRuntime().addShutdownHook( new Thread()
{
@Override
public void run()
{
killAll( handlers );
}
} );
}
live.add( handler );
}
}
catch ( UnsupportedOperationException e )
{
handler.kill( false );
throw new IllegalStateException( "JVM is shutting down!" );
}
return handler;
}
private static void dead( Handler handler )
{
synchronized ( Handler.class )
{
try
{
if ( live != null )
{
live.remove( handler );
}
}
catch ( UnsupportedOperationException ok )
{
// ok, already dead
}
}
}
private static void killAll( Set<Handler> handlers )
{
synchronized ( Handler.class )
{
if ( !handlers.isEmpty() )
{
for ( Handler handler : handlers )
{
try
{
handler.process.exitValue();
}
catch ( IllegalThreadStateException e )
{
handler.kill( false );
}
}
}
live = Collections.emptySet();
}
}
private static Set<Handler> live;
private static class Handler implements InvocationHandler
{
private final Dispatcher dispatcher;
private final Process process;
private final Class<?> type;
private final String repr;
private final DebugDispatch debugDispatch;
Handler( Class<?> type, Dispatcher dispatcher, Process process, String repr, DebugDispatch debugDispatch )
{
this.type = type;
this.dispatcher = dispatcher;
this.process = process;
this.repr = repr;
this.debugDispatch = debugDispatch;
}
@Override
public String toString()
{
return repr;
}
void kill( boolean wait )
{
process.destroy();
if ( wait )
{
dead( this );
await( process );
}
}
int stop( TimeUnit unit, long timeout )
{
final CountDownLatch latch = new CountDownLatch( unit == null ? 0 : 1 );
Thread stopper = new Thread()
{
@Override
public void run()
{
latch.countDown();
try
{
dispatcher.stop();
}
catch ( RemoteException e )
{
process.destroy();
}
}
};
stopper.start();
try
{
latch.await();
timeout = System.currentTimeMillis() + ( unit == null ? 0 : unit.toMillis( timeout ) );
while ( stopper.isAlive() && System.currentTimeMillis() < timeout )
{
Thread.sleep( 1 );
}
}
catch ( InterruptedException e )
{
// handled by exit
}
if ( stopper.isAlive() )
{
stopper.interrupt();
}
dead( this );
return await( process );
}
private static int await( Process process )
{
return new ProcessStreamHandler( process, true ).waitForResult();
}
@Override
public Object invoke( Object proxy, Method method, Object[] args ) throws Throwable
{
try
{
if ( method.getDeclaringClass() == type )
{
return dispatch( method, args );
}
else if ( method.getDeclaringClass() == Object.class )
{
return method.invoke( this, args );
}
else
{
throw new UnsupportedOperationException( method.toString() );
}
}
catch ( ServerError ex )
{
throw ex.detail;
}
catch ( RemoteException ex )
{
throw new ConnectionDisruptedException( ex );
}
}
private Object dispatch( Method method, Object[] args ) throws Throwable
{
Class<?>[] params = method.getParameterTypes();
String[] types = new String[params.length];
for ( int i = 0; i < types.length; i++ )
{
types[i] = params[i].getName();
}
return dispatcher.dispatch( method.getName(), types, args );
}
}
private static class DispatcherImpl extends UnicastRemoteObject implements Dispatcher
{
private transient final SubProcess<?, ?> subprocess;
protected DispatcherImpl( SubProcess<?, ?> subprocess ) throws RemoteException
{
super();
this.subprocess = subprocess;
}
@Override
public Object dispatch( String name, String[] types, Object[] args ) throws Throwable
{
Class<?>[] params = new Class<?>[types.length];
for ( int i = 0; i < params.length; i++ )
{
params[i] = Class.forName( types[i] );
}
try
{
return subprocess.t.getMethod( name, params ).invoke( subprocess, args );
}
catch ( IllegalAccessException e )
{
throw new IllegalStateException( e );
}
catch ( InvocationTargetException e )
{
throw e.getTargetException();
}
}
@Override
public void stop() throws RemoteException
{
subprocess.doStop( true );
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_SubProcess.java
|
2,151
|
@SuppressWarnings( "serial" )
public final class KillSubProcess extends Exception
{
public static KillSubProcess withExitCode( int exitCode )
{
return new KillSubProcess( exitCode );
}
final int exitCode;
private KillSubProcess( int exitCode )
{
this.exitCode = exitCode;
}
@Override
public synchronized Throwable fillInStackTrace()
{
return this;
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_KillSubProcess.java
|
2,152
|
{
@Override
public void deadlock( DebuggedThread thread )
{
thread.resume();
}
};
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_DebuggerDeadlockCallback.java
|
2,153
|
public class DebuggedThread
{
private final com.sun.jdi.ThreadReference thread;
private final SubProcess.DebugDispatch debug;
DebuggedThread( SubProcess.DebugDispatch debug, com.sun.jdi.ThreadReference thread )
{
this.debug = debug;
this.thread = thread;
}
@Override
public String toString()
{
return "DebuggedThread[" + debug.handler + " " + thread.name() + "]";
}
public DebuggedThread suspend( DebuggerDeadlockCallback callback )
{
thread.suspend();
debug.suspended( thread, callback );
return this;
}
// TODO Make it possible to define the type of exception to terminate the thread with
public DebuggedThread stop()
{
/*
* To kill a thread requires an Exception. But it is not a local thread so it has to be an exception
* object on the remote VM. So grab hold of a reference to the RuntimeException class, get its constructor,
* create an instance on the remote VM and use that to stop the thread.
*/
ClassType threadDeathClass = (ClassType)
thread.virtualMachine().classesByName( "java.lang.RuntimeException" ).get(0);
Method constructor = threadDeathClass.concreteMethodByName( "<init>", "()V" );
try
{
ObjectReference toKillWith = threadDeathClass.newInstance( thread, constructor, new LinkedList(), ClassType.INVOKE_SINGLE_THREADED );
thread.stop( toKillWith );
}
catch (Exception e)
{
/*
* Can be one of {InvalidType, ClassNotLoaded, IncompatibleThreadState, Invocation}Exception. We cannot
* recover on any of those, just rethrow it.
*/
throw new RuntimeException( e );
}
return this;
}
public DebuggedThread resume()
{
thread.resume();
debug.resume( thread );
return this;
}
public String getLocal( int offset, String name )
{
try
{
com.sun.jdi.StackFrame frame = thread.frames().get( offset );
com.sun.jdi.LocalVariable variable = frame.visibleVariableByName( name );
return frame.getValue( variable ).toString();
}
catch ( Exception e )
{
return null;
}
}
public StackTraceElement[] getStackTrace()
{
try
{
List<com.sun.jdi.StackFrame> frames = thread.frames();
StackTraceElement[] trace = new StackTraceElement[frames.size()];
Iterator<com.sun.jdi.StackFrame> iter = frames.iterator();
for ( int i = 0; iter.hasNext(); i++ )
{
com.sun.jdi.Location loc = iter.next().location();
com.sun.jdi.Method method = loc.method();
String fileName;
try
{
fileName = loc.sourceName();
}
catch ( com.sun.jdi.AbsentInformationException e )
{
fileName = null;
}
trace[i] = new StackTraceElement( method.declaringType().name(), method.name(), fileName,
loc.lineNumber() );
}
return trace;
}
catch ( com.sun.jdi.IncompatibleThreadStateException e )
{
return new StackTraceElement[0];
}
}
public String name()
{
return thread.name();
}
public void printStackTrace( PrintStream out )
{
out.println( name() );
for ( StackTraceElement trace : getStackTrace() )
{
out.println( "\tat " + trace );
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_DebuggedThread.java
|
2,154
|
@SuppressWarnings( "restriction" )
public class DebugInterface
{
private final com.sun.jdi.event.LocatableEvent event;
private final SubProcess.DebugDispatch debug;
DebugInterface( SubProcess.DebugDispatch debug, com.sun.jdi.event.LocatableEvent event )
{
this.debug = debug;
this.event = event;
}
public boolean matchCallingMethod( int offset, Class<?> owner, String method )
{
try
{
com.sun.jdi.Location location = event.thread().frame( offset ).location();
if ( owner != null )
{
if ( !owner.getName().equals( location.declaringType().name() ) ) return false;
}
if ( method != null )
{
if ( !method.equals( location.method().name() ) ) return false;
}
return true;
}
catch ( com.sun.jdi.IncompatibleThreadStateException e )
{
return false;
}
}
public DebuggedThread thread()
{
return new DebuggedThread( debug, event.thread() );
}
public void printStackTrace( PrintStream out )
{
thread().printStackTrace(out);
}
public Object getLocalVariable( String name )
{
try
{
StackFrame frame = event.thread().frame( 0 );
return fromMirror( frame.getValue( frame.visibleVariableByName( name ) ) );
}
catch ( IncompatibleThreadStateException e )
{
throw new IllegalStateException( e );
}
catch ( AbsentInformationException e )
{
throw new IllegalStateException( e );
}
}
public void setLocalVariable( String name, Object value )
{
try
{
StackFrame frame = event.thread().frame( 0 );
LocalVariable local = frame.visibleVariableByName( name );
frame.setValue( local, mirror( value ) );
}
catch ( IncompatibleThreadStateException e )
{
throw new IllegalStateException( e );
}
catch ( AbsentInformationException e )
{
throw new IllegalStateException( e );
}
catch ( InvalidTypeException e )
{
throw new IllegalStateException( e );
}
catch ( ClassNotLoadedException e )
{
throw new IllegalStateException( e );
}
}
@SuppressWarnings( "boxing" )
private Value mirror( Object value )
{
VirtualMachine vm = event.virtualMachine();
if ( value == null )
{
return vm.mirrorOfVoid();
}
if ( value instanceof String )
{
return vm.mirrorOf( (String) value );
}
if ( value instanceof Integer )
{
return vm.mirrorOf( (Integer) value );
}
if ( value instanceof Long )
{
return vm.mirrorOf( (Long) value );
}
if ( value instanceof Double )
{
return vm.mirrorOf( (Double) value );
}
if ( value instanceof Boolean )
{
return vm.mirrorOf( (Boolean) value );
}
if ( value instanceof Byte )
{
return vm.mirrorOf( (Byte) value );
}
if ( value instanceof Character )
{
return vm.mirrorOf( (Character) value );
}
if ( value instanceof Short )
{
return vm.mirrorOf( (Short) value );
}
if ( value instanceof Float )
{
return vm.mirrorOf( (Float) value );
}
throw new IllegalArgumentException( "Cannot mirror: " + value );
}
@SuppressWarnings( "boxing" )
private Object fromMirror( Value value )
{
if ( value instanceof com.sun.jdi.VoidValue )
{
return null;
}
if ( value instanceof com.sun.jdi.StringReference )
{
return ( (com.sun.jdi.StringReference) value).value();
}
if ( value instanceof com.sun.jdi.IntegerValue )
{
return ( (com.sun.jdi.IntegerValue) value ).intValue();
}
if ( value instanceof com.sun.jdi.LongValue )
{
return ( (com.sun.jdi.LongValue) value ).longValue();
}
if ( value instanceof com.sun.jdi.DoubleValue )
{
return ( (com.sun.jdi.DoubleValue) value ).doubleValue();
}
if ( value instanceof com.sun.jdi.BooleanValue )
{
return ( (com.sun.jdi.BooleanValue) value ).booleanValue();
}
if ( value instanceof com.sun.jdi.ByteValue )
{
return ( (com.sun.jdi.ByteValue) value ).byteValue();
}
if ( value instanceof com.sun.jdi.CharValue )
{
return ( (com.sun.jdi.CharValue) value ).charValue();
}
if ( value instanceof com.sun.jdi.ShortValue )
{
return ( (com.sun.jdi.ShortValue) value ).shortValue();
}
if ( value instanceof com.sun.jdi.FloatValue )
{
return ( (com.sun.jdi.FloatValue) value ).floatValue();
}
return value.toString();
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_DebugInterface.java
|
2,155
|
public class ConnectionDisruptedException extends IllegalStateException
{
public ConnectionDisruptedException( Throwable cause )
{
super( "Subprocess connection disrupted", cause );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_ConnectionDisruptedException.java
|
2,156
|
{
private volatile int numberOfCalls;
@Override
protected void callback( DebugInterface debug ) throws KillSubProcess
{
if ( ++numberOfCalls <= letNumberOfCallsPass )
return;
if ( !stackTraceMustContain.accept( debug.thread().getStackTrace() ) )
return;
debug.thread().suspend( null );
this.disable();
crashNotification.countDown();
throw KillSubProcess.withExitCode( -1 );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_BreakPoint.java
|
2,157
|
{
@Override
public boolean accept( StackTraceElement[] item )
{
for ( StackTraceElement element : item )
if ( element.getClassName().equals( cls.getName() ) )
return true;
return false;
}
};
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_BreakPoint.java
|
2,158
|
{
@Override
public boolean accept( StackTraceElement[] item )
{
return !predicate.accept( item );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_BreakPoint.java
|
2,159
|
{
@Override
public boolean accept( StackTraceElement[] item )
{
return true;
}
};
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_BreakPoint.java
|
2,160
|
{
@Override
protected void callback( DebugInterface debug )
{
out.println( "Debugger stacktrace" );
debug.printStackTrace( out );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_BreakPoint.java
|
2,161
|
public abstract class BreakPoint implements DebuggerDeadlockCallback
{
public enum Event
{
ENTRY,
EXIT
}
public BreakPoint( Class<?> type, String method, Class<?>... args )
{
this(Event.ENTRY,type,method,args);
}
public BreakPoint( Event event, Class<?> type, String method, Class<?>... args )
{
this.event = event;
this.type = type.getName();
this.method = method;
this.args = new String[args.length];
for ( int i = 0; i < args.length; i++ )
{
this.args[i] = args[i].getName();
}
}
@Override
public String toString()
{
StringBuilder result = new StringBuilder( "BreakPoint[" );
result.append( type ).append( '#' ).append( method ).append( '(' );
for ( int i = 0; i < args.length; i++ )
{
if ( i > 0 ) result.append( ',' );
result.append( args[i] );
}
return result.append( ")]" ).toString();
}
public final int invocationCount()
{
return count.get();
}
public int invocationCount( int value )
{
return count.getAndSet( value );
}
public final int resetInvocationCount()
{
return invocationCount( 0 );
}
final void invoke( DebugInterface debug ) throws KillSubProcess
{
count.incrementAndGet();
callback( debug );
}
protected abstract void callback( DebugInterface debug ) throws KillSubProcess;
@Override
public void deadlock( DebuggedThread thread )
{
SubProcess.DebugDispatch.defaultCallback.deadlock( thread );
}
final Event event;
final String type;
private final String method;
private final String[] args;
private final AtomicInteger count = new AtomicInteger();
volatile boolean enabled = false;
private @SuppressWarnings( "restriction" )
com.sun.jdi.request.EventRequest request = null;
@SuppressWarnings( "restriction" )
public synchronized boolean isEnabled()
{
if ( request != null ) return request.isEnabled();
return enabled;
}
@SuppressWarnings( "restriction" )
public synchronized BreakPoint enable()
{
this.enabled = true;
if ( request != null ) request.enable();
return this;
}
@SuppressWarnings( "restriction" )
public synchronized BreakPoint disable()
{
this.enabled = false;
if ( request != null ) request.disable();
return this;
}
@SuppressWarnings( "restriction" )
synchronized void setRequest( com.sun.jdi.request.EventRequest request )
{
this.request = request;
this.request.setEnabled( enabled );
}
@SuppressWarnings( "restriction" )
void setup( com.sun.jdi.ReferenceType type )
{
com.sun.jdi.request.EventRequestManager erm = type.virtualMachine().eventRequestManager();
for ( @SuppressWarnings( "hiding" ) com.sun.jdi.Method method : type.methodsByName( this.method ) )
{
if ( matches( method.name(), method.argumentTypeNames() ) )
{
switch (event)
{
case ENTRY:
setRequest( erm.createBreakpointRequest( method.location() ) );
return;
case EXIT:
com.sun.jdi.request.MethodExitRequest request = erm.createMethodExitRequest();
request.addClassFilter( type );
setRequest( request );
}
return;
}
}
}
boolean matches( String name, List<String> argNames )
{
if ( !name.equals( method ) ) return false;
if ( argNames.size() != args.length ) return false;
Iterator<String> names = argNames.iterator();
for ( int i = 0; i < args.length; i++ )
{
if ( !args[i].equals( names.next() ) ) return false;
}
return true;
}
public static BreakPoint stacktrace( final PrintStream out, Class<?> type, String method, Class<?>... args )
{
return new BreakPoint( type, method, args )
{
@Override
protected void callback( DebugInterface debug )
{
out.println( "Debugger stacktrace" );
debug.printStackTrace( out );
}
};
}
public static final Predicate<StackTraceElement[]> ALL = new Predicate<StackTraceElement[]>()
{
@Override
public boolean accept( StackTraceElement[] item )
{
return true;
}
};
private static Predicate<StackTraceElement[]> reversed( final Predicate<StackTraceElement[]> predicate )
{
return new Predicate<StackTraceElement[]>()
{
@Override
public boolean accept( StackTraceElement[] item )
{
return !predicate.accept( item );
}
};
}
public static Predicate<StackTraceElement[]> stackTraceMustContainClass( final Class<?> cls )
{
return new Predicate<StackTraceElement[]>()
{
@Override
public boolean accept( StackTraceElement[] item )
{
for ( StackTraceElement element : item )
if ( element.getClassName().equals( cls.getName() ) )
return true;
return false;
}
};
}
public static Predicate<StackTraceElement[]> stackTraceMustNotContainClass( final Class<?> cls )
{
return reversed( stackTraceMustContainClass( cls ) );
}
public static BreakPoint thatCrashesTheProcess( final CountDownLatch crashNotification,
final int letNumberOfCallsPass, Class<?> type, String method, Class<?>... args )
{
return thatCrashesTheProcess( Event.ENTRY, crashNotification, letNumberOfCallsPass, ALL, type, method, args );
}
public static BreakPoint thatCrashesTheProcess( Event event, final CountDownLatch crashNotification,
final int letNumberOfCallsPass, final Predicate<StackTraceElement[]> stackTraceMustContain, Class<?> type,
String method, Class<?>... args )
{
return new BreakPoint( event, type, method, args )
{
private volatile int numberOfCalls;
@Override
protected void callback( DebugInterface debug ) throws KillSubProcess
{
if ( ++numberOfCalls <= letNumberOfCallsPass )
return;
if ( !stackTraceMustContain.accept( debug.thread().getStackTrace() ) )
return;
debug.thread().suspend( null );
this.disable();
crashNotification.countDown();
throw KillSubProcess.withExitCode( -1 );
}
};
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_BreakPoint.java
|
2,162
|
{
@Override
public void doWork()
{
deleteAllNodesAndRelationships( server );
deleteAllIndexes( server );
}
private void deleteAllNodesAndRelationships( final EnterpriseNeoServer server )
{
Iterable<Node> allNodes = GlobalGraphOperations.at( server.getDatabase().getGraph() ).getAllNodes();
for ( Node n : allNodes )
{
Iterable<Relationship> relationships = n.getRelationships();
for ( Relationship rel : relationships )
{
rel.delete();
}
if ( n.getId() != 0 )
{ // Don't delete the reference node - tests depend on it
// :-(
n.delete();
}
else
{ // Remove all state from the reference node instead
for ( String key : n.getPropertyKeys() )
{
n.removeProperty( key );
}
}
}
}
private void deleteAllIndexes( final EnterpriseNeoServer server )
{
IndexManager indexManager = server.getDatabase().getGraph().index();
for ( String indexName : indexManager.nodeIndexNames() )
{
try{
server.getDatabase().getGraph().index()
.forNodes( indexName )
.delete();
} catch(UnsupportedOperationException e) {
// Encountered a read-only index.
}
}
for ( String indexName : indexManager.relationshipIndexNames() )
{
try {
server.getDatabase().getGraph().index()
.forRelationships( indexName )
.delete();
} catch(UnsupportedOperationException e) {
// Encountered a read-only index.
}
}
for(String k : indexManager.getNodeAutoIndexer().getAutoIndexedProperties())
{
indexManager.getNodeAutoIndexer().stopAutoIndexingProperty(k);
}
indexManager.getNodeAutoIndexer().setEnabled(false);
for(String k : indexManager.getRelationshipAutoIndexer().getAutoIndexedProperties())
{
indexManager.getRelationshipAutoIndexer().stopAutoIndexingProperty(k);
}
indexManager.getRelationshipAutoIndexer().setEnabled(false);
}
} ).execute();
| false
|
enterprise_server-enterprise_src_test_java_org_neo4j_test_server_ha_EnterpriseServerHelper.java
|
2,163
|
public class EnterpriseServerHelper
{
public static void cleanTheDatabase( final EnterpriseNeoServer server )
{
if ( server == null )
{
return;
}
new Transactor( server.getDatabase().getGraph(), new UnitOfWork()
{
@Override
public void doWork()
{
deleteAllNodesAndRelationships( server );
deleteAllIndexes( server );
}
private void deleteAllNodesAndRelationships( final EnterpriseNeoServer server )
{
Iterable<Node> allNodes = GlobalGraphOperations.at( server.getDatabase().getGraph() ).getAllNodes();
for ( Node n : allNodes )
{
Iterable<Relationship> relationships = n.getRelationships();
for ( Relationship rel : relationships )
{
rel.delete();
}
if ( n.getId() != 0 )
{ // Don't delete the reference node - tests depend on it
// :-(
n.delete();
}
else
{ // Remove all state from the reference node instead
for ( String key : n.getPropertyKeys() )
{
n.removeProperty( key );
}
}
}
}
private void deleteAllIndexes( final EnterpriseNeoServer server )
{
IndexManager indexManager = server.getDatabase().getGraph().index();
for ( String indexName : indexManager.nodeIndexNames() )
{
try{
server.getDatabase().getGraph().index()
.forNodes( indexName )
.delete();
} catch(UnsupportedOperationException e) {
// Encountered a read-only index.
}
}
for ( String indexName : indexManager.relationshipIndexNames() )
{
try {
server.getDatabase().getGraph().index()
.forRelationships( indexName )
.delete();
} catch(UnsupportedOperationException e) {
// Encountered a read-only index.
}
}
for(String k : indexManager.getNodeAutoIndexer().getAutoIndexedProperties())
{
indexManager.getNodeAutoIndexer().stopAutoIndexingProperty(k);
}
indexManager.getNodeAutoIndexer().setEnabled(false);
for(String k : indexManager.getRelationshipAutoIndexer().getAutoIndexedProperties())
{
indexManager.getRelationshipAutoIndexer().stopAutoIndexingProperty(k);
}
indexManager.getRelationshipAutoIndexer().setEnabled(false);
}
} ).execute();
removeLogs( server );
}
private static void removeLogs( EnterpriseNeoServer server )
{
File logDir = new File( server.getDatabase().getLocation() + File.separator + ".." + File.separator + "log" );
try
{
FileUtils.deleteDirectory( logDir );
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
}
public static EnterpriseNeoServer createNonPersistentServer() throws IOException
{
return createServer( false );
}
public static EnterpriseNeoServer createPersistentServer() throws IOException
{
return createServer( true );
}
private static EnterpriseNeoServer createServer( boolean persistent ) throws IOException
{
EnterpriseServerBuilder builder = EnterpriseServerBuilder.server();
configureHostname( builder );
if ( persistent ) builder = (EnterpriseServerBuilder) builder.persistent();
EnterpriseNeoServer server = builder.build();
server.start();
return server;
}
private static void configureHostname( EnterpriseServerBuilder builder )
{
String hostName = System.getProperty( "neo-server.test.hostname" );
if (StringUtils.isNotEmpty( hostName )) {
builder.onHost( hostName );
}
}
}
| false
|
enterprise_server-enterprise_src_test_java_org_neo4j_test_server_ha_EnterpriseServerHelper.java
|
2,164
|
{
@Override
public Void call() throws Exception
{
ServerHolder.release( server );
return null;
}
} );
| false
|
community_server_src_test_java_org_neo4j_test_server_SharedServerTestBase.java
|
2,165
|
{
@Override
public Void call() throws Exception
{
server = ServerHolder.allocate();
serverUrl = server.baseUri().toString();
return null;
}
} );
| false
|
community_server_src_test_java_org_neo4j_test_server_SharedServerTestBase.java
|
2,166
|
public class SharedServerTestBase
{
private static boolean useExternal = Boolean.valueOf( System.getProperty( "neo-server.external", "false" ) );
private static String externalURL = System.getProperty( "neo-server.external.url", "http://localhost:7474" );
protected static NeoServer server()
{
return server;
}
protected final void cleanDatabase()
{
if ( useExternal )
{
// TODO
}
else
{
ServerHelper.cleanTheDatabase( server );
}
}
private static NeoServer server;
private static String serverUrl;
public static String getServerURL()
{
return serverUrl;
}
@Rule
public Mute mute = muteAll();
@BeforeClass
public static void allocateServer() throws Throwable
{
if ( useExternal )
{
serverUrl = externalURL;
}
else
{
muteAll().call( new Callable<Void>()
{
@Override
public Void call() throws Exception
{
server = ServerHolder.allocate();
serverUrl = server.baseUri().toString();
return null;
}
} );
}
}
@AfterClass
public static void releaseServer() throws Exception
{
if ( !useExternal )
{
try
{
muteAll().call( new Callable<Void>()
{
@Override
public Void call() throws Exception
{
ServerHolder.release( server );
return null;
}
} );
}
finally
{
server = null;
}
}
}
}
| false
|
community_server_src_test_java_org_neo4j_test_server_SharedServerTestBase.java
|
2,167
|
@SuppressWarnings( "restriction" )
static class DebugDispatch implements Runnable
{
static DebugDispatch get( Object o )
{
if ( Proxy.isProxyClass( o.getClass() ) )
{
InvocationHandler handler = Proxy.getInvocationHandler( o );
if ( handler instanceof Handler )
{
return ( (Handler) handler ).debugDispatch;
}
}
throw new IllegalArgumentException( "Not a sub process: " + o );
}
volatile Handler handler;
private final com.sun.jdi.event.EventQueue queue;
private final Map<String, List<BreakPoint>> breakpoints;
private final Map<com.sun.jdi.ThreadReference, DebuggerDeadlockCallback> suspended = new HashMap<>();
static final DebuggerDeadlockCallback defaultCallback = new DebuggerDeadlockCallback()
{
@Override
public void deadlock( DebuggedThread thread )
{
throw new DeadlockDetectedError();
}
};
DebugDispatch( com.sun.jdi.event.EventQueue queue, Map<String, List<BreakPoint>> breakpoints )
{
this.queue = queue;
this.breakpoints = breakpoints;
}
@Override
public void run()
{
for ( ;; )
{
final com.sun.jdi.event.EventSet events;
try
{
events = queue.remove();
}
catch ( InterruptedException e )
{
return;
}
Integer exitCode = null;
try
{
for ( com.sun.jdi.event.Event event : events )
{
if ( event instanceof com.sun.jdi.event.MonitorContendedEnterEvent )
{
com.sun.jdi.event.MonitorContendedEnterEvent monitor = (com.sun.jdi.event.MonitorContendedEnterEvent) event;
final com.sun.jdi.ThreadReference thread;
try
{
thread = monitor.monitor().owningThread();
}
catch ( com.sun.jdi.IncompatibleThreadStateException e )
{
e.printStackTrace();
continue;
}
if ( thread != null && thread.isSuspended() )
{
DebuggerDeadlockCallback callback = suspended.get( thread );
try
{
if ( callback != null )
{
callback.deadlock( new DebuggedThread( this, thread ) );
}
}
catch ( DeadlockDetectedError deadlock )
{
@SuppressWarnings( "hiding" ) Handler handler = this.handler;
if ( handler != null )
{
handler.kill( false );
}
}
}
}
else if ( event instanceof com.sun.jdi.event.LocatableEvent )
{
callback( (com.sun.jdi.event.LocatableEvent) event );
}
else if ( event instanceof com.sun.jdi.event.ClassPrepareEvent )
{
setup( ( (com.sun.jdi.event.ClassPrepareEvent) event ).referenceType() );
}
else if ( event instanceof com.sun.jdi.event.VMDisconnectEvent
|| event instanceof com.sun.jdi.event.VMDeathEvent )
{
return;
}
}
}
catch ( KillSubProcess kill )
{
exitCode = kill.exitCode;
}
finally
{
if ( exitCode != null )
{
events.virtualMachine().exit( exitCode );
}
else
{
events.resume();
}
}
}
}
private void setup( com.sun.jdi.ReferenceType type )
{
List<BreakPoint> list = breakpoints.get( type.name() );
if ( list == null )
{
return;
}
for ( BreakPoint breakpoint : list )
{
breakpoint.setup( type );
}
}
private void callback( com.sun.jdi.event.LocatableEvent event ) throws KillSubProcess
{
List<BreakPoint> list = breakpoints.get( event.location().declaringType().name() );
if ( list == null )
{
return;
}
com.sun.jdi.Method method = event.location().method();
for ( BreakPoint breakpoint : list )
{
if ( breakpoint.matches( method.name(), method.argumentTypeNames() ) )
{
if ( breakpoint.enabled )
{
breakpoint.invoke( new DebugInterface( this, event ) );
}
}
}
}
void suspended( com.sun.jdi.ThreadReference thread, DebuggerDeadlockCallback callback )
{
if ( callback == null )
{
callback = defaultCallback;
}
suspended.put( thread, callback );
}
void resume( com.sun.jdi.ThreadReference thread )
{
suspended.remove( thread );
}
DebuggedThread[] suspendedThreads()
{
if ( suspended.isEmpty() )
{
return new DebuggedThread[0];
}
List<DebuggedThread> threads = new ArrayList<>();
for ( com.sun.jdi.ThreadReference thread : suspended.keySet() )
{
threads.add( new DebuggedThread( this, thread ) );
}
return threads.toArray( new DebuggedThread[threads.size()] );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_SubProcess.java
|
2,168
|
@SuppressWarnings( "restriction" )
private static class DebuggerConnector
{
private static final com.sun.jdi.connect.ListeningConnector connector;
static
{
com.sun.jdi.connect.ListeningConnector first = null;
for ( com.sun.jdi.connect.ListeningConnector conn : com.sun.jdi.Bootstrap.virtualMachineManager().listeningConnectors() )
{
first = conn;
break;
}
connector = first;
}
private final Map<String, List<BreakPoint>> breakpoints = new HashMap<>();
private final Map<String, ? extends com.sun.jdi.connect.Connector.Argument> args;
DebuggerConnector( BreakPoint[] breakpoints )
{
this.args = connector.defaultArguments();
for ( BreakPoint breakpoint : breakpoints )
{
List<BreakPoint> list = this.breakpoints.get( breakpoint.type );
if ( list == null )
{
this.breakpoints.put( breakpoint.type, list = new ArrayList<>() );
}
list.add( breakpoint );
}
}
String listen()
{
try
{
return String.format( "-agentlib:jdwp=transport=%s,address=%s", connector.transport().name(),
connector.startListening( args ) );
}
catch ( Exception e )
{
throw new UnsupportedOperationException( "Debugger not supported", e );
}
}
DebugDispatch connect( String string )
{
final com.sun.jdi.VirtualMachine vm;
try
{
vm = connector.accept( args );
connector.stopListening( args );
}
catch ( Exception e )
{
throw new RuntimeException( "Debugger connection failure", e );
}
com.sun.jdi.request.EventRequestManager erm = vm.eventRequestManager();
TYPES: for ( Map.Entry<String, List<BreakPoint>> entry : breakpoints.entrySet() )
{
for ( com.sun.jdi.ReferenceType type : vm.classesByName( entry.getKey() ) )
{
if ( type.name().equals( entry.getKey() ) )
{
for ( BreakPoint breakpoint : entry.getValue() )
{
breakpoint.setup( type );
}
continue TYPES;
}
}
com.sun.jdi.request.ClassPrepareRequest prepare = erm.createClassPrepareRequest();
prepare.addClassFilter( entry.getKey() );
prepare.enable();
}
if ( vm.canRequestMonitorEvents() )
{
erm.createMonitorContendedEnterRequest().enable();
}
DebugDispatch dispatch = new DebugDispatch( vm.eventQueue(), breakpoints );
new Thread( dispatch, "Debugger: [" + string + "]" ).start();
return dispatch;
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_SubProcess.java
|
2,169
|
{
@Override
public boolean accept( ManagedCluster cluster )
{
int nrOfMembers = cluster.size();
for ( HighlyAvailableGraphDatabase database : cluster.getAllMembers() )
{
ClusterMembers members = database.getDependencyResolver().resolveDependency( ClusterMembers.class );
if (Iterables.count( members.getMembers() ) < nrOfMembers)
return false;
}
for ( ClusterMembers clusterMembers : cluster.getArbiters() )
{
if (Iterables.count(clusterMembers.getMembers()) < nrOfMembers)
{
return false;
}
}
// Everyone sees everyone else as joined!
return true;
}
@Override
public String toString()
{
return "All instances should see all others as joined";
}
};
| false
|
enterprise_ha_src_test_java_org_neo4j_test_ha_ClusterManager.java
|
2,170
|
private static class DispatcherImpl extends UnicastRemoteObject implements Dispatcher
{
private transient final SubProcess<?, ?> subprocess;
protected DispatcherImpl( SubProcess<?, ?> subprocess ) throws RemoteException
{
super();
this.subprocess = subprocess;
}
@Override
public Object dispatch( String name, String[] types, Object[] args ) throws Throwable
{
Class<?>[] params = new Class<?>[types.length];
for ( int i = 0; i < params.length; i++ )
{
params[i] = Class.forName( types[i] );
}
try
{
return subprocess.t.getMethod( name, params ).invoke( subprocess, args );
}
catch ( IllegalAccessException e )
{
throw new IllegalStateException( e );
}
catch ( InvocationTargetException e )
{
throw e.getTargetException();
}
}
@Override
public void stop() throws RemoteException
{
subprocess.doStop( true );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_SubProcess.java
|
2,171
|
public class SuspendedThreadsException extends Exception implements Iterable<String>
{
private final String[] threadNames;
SuspendedThreadsException( String... threadNames )
{
super( message( threadNames ) );
this.threadNames = threadNames.clone();
}
private static String message( String[] threadName )
{
if ( threadName == null || threadName.length == 0 )
throw new IllegalArgumentException( "No thread names given" );
if ( threadName.length == 1 )
{
return "The \"" + threadName[0] + "\" thread is still suspended.";
}
else
{
StringBuilder message = new StringBuilder( "The following threads are still suspended" );
String sep = ": ";
for ( String name : threadName )
{
message.append( sep ).append( '"' ).append( name ).append( '"' );
sep = ", ";
}
return message.toString();
}
}
@Override
public Iterator<String> iterator()
{
return Arrays.asList( threadNames ).iterator();
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_SuspendedThreadsException.java
|
2,172
|
private static class TestProcess extends SubProcess<TestRunnerDispatcher, RemoteRunNotifier> implements
TestRunnerDispatcher
{
private static final long serialVersionUID = 1L;
private final String className;
public TestProcess(String className)
{
this.className = className;
}
private volatile Object runner;
@Override
protected void startup( RemoteRunNotifier remote ) throws Throwable
{
try
{
RunNotifier notifier = new RunNotifier();
notifier.addListener( new RemoteRunListener( remote ) );
new RemoteTestRunner( this, remote, Class.forName( className ) ).run( notifier );
}
catch ( Throwable failure )
{
runner = failure;
throw failure;
}
}
@Override
public String toString()
{
return className.substring( className.lastIndexOf( '.' ) + 1);
}
@Override
protected void shutdown( boolean normal )
{
try
{
Object runner = this.runner;
if ( runner instanceof RemoteTestRunner ) ( (RemoteTestRunner) runner ).terminate();
}
finally
{
this.runner = new RunTerminatedException();
}
super.shutdown( normal );
}
@Override
public void run( String methodName ) throws Throwable
{
runner().run( methodName );
}
@Override
public void submit( Task<?> task ) throws Throwable
{
runner().run( task );
}
private RemoteTestRunner runner() throws Throwable
{
for ( Object runner = this.runner;; runner = this.runner )
{
if ( runner instanceof RemoteTestRunner )
{
return (RemoteTestRunner) runner;
}
else if ( runner instanceof Throwable )
{
throw (Throwable) runner;
}
Thread.sleep( 1 ); // yield
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_SubProcessTestRunner.java
|
2,173
|
public static class RunTerminatedException extends RuntimeException
{
private static final long serialVersionUID = 1L;
private RunTerminatedException()
{
// all instances are created here
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_SubProcessTestRunner.java
|
2,174
|
{
@Override
public void evaluate() throws Throwable
{
statement.evaluate();
host.checkPostConditions();
}
};
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_SubProcessTestRunner.java
|
2,175
|
{
@Override
public void evaluate()
{
testProcess.runner = RemoteTestRunner.this;
for ( Object test = testMethod;; test = testMethod )
{
if ( test == null || test instanceof Throwable )
{
try
{
Thread.sleep( 1 ); // yield
}
catch ( InterruptedException e )
{
testMethod = e;
break;
}
}
else if ( test instanceof FrameworkMethod )
{
try
{
methodBlock( (FrameworkMethod) test ).evaluate();
testMethod = null;
}
catch ( Throwable e )
{
testMethod = e;
}
}
else break; // received poison pill
}
}
};
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_SubProcessTestRunner.java
|
2,176
|
private static class RemoteTestRunner extends BlockJUnit4ClassRunner
{
private final TestProcess testProcess;
private final RemoteRunNotifier host;
private volatile Object testMethod;
private volatile Object test;
RemoteTestRunner( TestProcess testProcess, RemoteRunNotifier host, Class<?> test ) throws InitializationError
{
super( test );
this.testProcess = testProcess;
this.host = host;
}
void terminate()
{
testMethod = TERMINATED;
}
@Override
protected Statement childrenInvoker( RunNotifier notifier )
{
return new Statement()
{
@Override
public void evaluate()
{
testProcess.runner = RemoteTestRunner.this;
for ( Object test = testMethod;; test = testMethod )
{
if ( test == null || test instanceof Throwable )
{
try
{
Thread.sleep( 1 ); // yield
}
catch ( InterruptedException e )
{
testMethod = e;
break;
}
}
else if ( test instanceof FrameworkMethod )
{
try
{
methodBlock( (FrameworkMethod) test ).evaluate();
testMethod = null;
}
catch ( Throwable e )
{
testMethod = e;
}
}
else break; // received poison pill
}
}
};
}
@Override
protected Statement methodBlock( FrameworkMethod method )
{
final Statement statement = super.methodBlock( method );
return statement;
}
@Override
protected Statement methodInvoker( FrameworkMethod method, Object test )
{
this.test = test;
final Statement statement = super.methodInvoker( method, test );
return new Statement()
{
@Override
public void evaluate() throws Throwable
{
statement.evaluate();
host.checkPostConditions();
}
};
}
private Map<String, FrameworkMethod> methods;
void run( String methodName ) throws Throwable
{
if ( methods == null )
{
Map<String, FrameworkMethod> map = new HashMap<String, FrameworkMethod>();
for ( FrameworkMethod method : getChildren() )
{
map.put( method.getName(), method );
}
methods = map;
}
testMethod = methods.get( methodName );
for ( Object result = testMethod;; result = testMethod )
{
if ( result instanceof FrameworkMethod )
{
Thread.sleep( 1 ); // yield
}
else if ( result instanceof Throwable )
{
throw (Throwable) result;
}
else return; // success
}
}
<T> void run( Task<T> task )
{
task.run( inject( typeOf( task ) ) );
}
private <T> T inject( Class<T> type )
{
if ( type == null ) /*could not find concrete parameter type*/return null;
Object test = this.test;
if ( type.isInstance( test ) ) return type.cast( test );
return null; // TODO: what other things should we be able to inject into tasks?
}
@SuppressWarnings( "unchecked" )
private static <T> Class<T> typeOf( Task<T> task )
{
Class<?> taskType = task.getClass();
while ( taskType != Object.class )
{
for ( Type type : taskType.getGenericInterfaces() )
{
if ( type instanceof ParameterizedType )
{
ParameterizedType paramType = (ParameterizedType) type;
if ( paramType.getRawType() == Task.class )
{
Type param = paramType.getActualTypeArguments()[0];
if ( param.getClass() == Class.class ) return (Class<T>) param;
}
}
}
taskType = taskType.getSuperclass();
}
return null;
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_SubProcessTestRunner.java
|
2,177
|
private static class RemoteRunListener extends RunListener
{
private final RemoteRunNotifier remote;
public RemoteRunListener( RemoteRunNotifier remote )
{
this.remote = remote;
}
@Override
public void testFailure( Failure failure ) throws Exception
{
remote.failure( failure.getException() );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_SubProcessTestRunner.java
|
2,178
|
private class NotifierImpl extends UnicastRemoteObject implements RemoteRunNotifier
{
private static final long serialVersionUID = 1L;
private final EachTestNotifier notifier;
NotifierImpl( EachTestNotifier notifier ) throws RemoteException
{
super();
this.notifier = notifier;
}
@Override
public void failure( Throwable exception ) throws RemoteException
{
notifier.addFailure( exception );
}
@Override
public void checkPostConditions() throws Throwable
{
verifyBreakpointState();
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_SubProcessTestRunner.java
|
2,179
|
private class BreakpointDispatcher extends BreakPoint
{
private final FrameworkMethod handler;
BreakpointDispatcher( BreakPoint.Event event, Class<?> type, Method method, FrameworkMethod handler )
{
super( event, type, method.getName(), method.getParameterTypes() );
this.handler = handler;
}
@Override
protected void callback( DebugInterface debug ) throws KillSubProcess
{
Class<?>[] types = handler.getMethod().getParameterTypes();
Annotation[][] annotations = handler.getMethod().getParameterAnnotations();
Object[] params = new Object[types.length];
BUILD_PARAM_LIST: for ( int i = 0; i < types.length; i++ )
{
if ( types[i] == DebugInterface.class )
params[i] = debug;
else if ( types[i] == BreakPoint.class )
{
for ( Annotation annotation : annotations[i] )
{
if ( BreakpointHandler.class.isInstance( annotation ) )
{
String[] value = ( (BreakpointHandler) annotation ).value();
if ( value.length == 1 )
{
params[i] = breakpoints.get( value[0] );
continue BUILD_PARAM_LIST;
}
}
}
params[i] = this;
}
/*
else if ( types[i] == SequencingManager.class )
params[i] = seqManager;
*/
else if ( types[i] == Task.Executor.class )
params[i] = taskExecutor;
else
params[i] = null;
}
try
{
handler.invokeExplosively( null, params );
}
catch ( Throwable exception )
{
throw Exceptions.launderedException( KillSubProcess.class, exception );
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_SubProcessTestRunner.java
|
2,180
|
{
@Override
public void evaluate() throws Throwable
{
enableBreakpoints( method.getAnnotation( EnabledBreakpoints.class ) );
dispatcher.run( method.getName() );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_SubProcessTestRunner.java
|
2,181
|
{
@Override
public void evaluate() throws Throwable
{
startSubProcess( notifier );
try
{
children.evaluate();
}
finally
{
stopSubProcess();
}
}
};
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_SubProcessTestRunner.java
|
2,182
|
{
@Override
public void run()
{
try
{
dispatcher.submit( task );
}
catch ( Throwable e )
{
e.printStackTrace();
}
}
}.start();
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_SubProcessTestRunner.java
|
2,183
|
{
@Override
public void submit( final Task<?> task )
{
new Thread()
{
@Override
public void run()
{
try
{
dispatcher.submit( task );
}
catch ( Throwable e )
{
e.printStackTrace();
}
}
}.start();
}
};
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_SubProcessTestRunner.java
|
2,184
|
public class SubProcessTestRunner extends BlockJUnit4ClassRunner
{
public SubProcessTestRunner( Class<?> test ) throws InitializationError
{
super( test );
}
private final Map<String, BreakPoint> breakpoints = new HashMap<String, BreakPoint>();
private volatile TestRunnerDispatcher dispatcher;
//private final SequencingManager seqManager = null;
private final Task.Executor taskExecutor = new Task.Executor()
{
@Override
public void submit( final Task<?> task )
{
new Thread()
{
@Override
public void run()
{
try
{
dispatcher.submit( task );
}
catch ( Throwable e )
{
e.printStackTrace();
}
}
}.start();
}
};
@Override
protected void collectInitializationErrors( java.util.List<Throwable> errors )
{
super.collectInitializationErrors( errors );
for ( FrameworkMethod handler : getTestClass().getAnnotatedMethods( BreakpointHandler.class ) )
{
handler.validatePublicVoid( /*static:*/true, errors );
}
for ( FrameworkMethod beforeDebugged : getTestClass().getAnnotatedMethods( BeforeDebuggedTest.class ) )
{
beforeDebugged.validatePublicVoidNoArg( /*static:*/true, errors );
}
}
private void startSubProcess( RunNotifier notifier ) throws Throwable
{
EachTestNotifier eachNotifier = new EachTestNotifier( notifier, getDescription() );
NotifierImpl remoteNotifier = new NotifierImpl( eachNotifier );
this.dispatcher = new TestProcess( getTestClass().getJavaClass().getName() ).start( remoteNotifier,
breakpoints() );
}
private void stopSubProcess()
{
try
{
SubProcess.stop( dispatcher );
}
finally
{
dispatcher = null;
}
}
@Override
protected Statement classBlock( final RunNotifier notifier )
{
final Statement children = childrenInvoker( notifier );
return new Statement()
{
@Override
public void evaluate() throws Throwable
{
startSubProcess( notifier );
try
{
children.evaluate();
}
finally
{
stopSubProcess();
}
}
};
}
private BreakPoint[] breakpoints() throws Throwable
{
if ( breakpoints.isEmpty() )
{
synchronized ( breakpoints )
{
if ( breakpoints.isEmpty() )
{
List<Throwable> failures = new ArrayList<Throwable>();
final Object CLAIMED = new Object();
Map<String, Object> bpDefs = new HashMap<String, Object>();
ForeignBreakpoints foreign = getTestClass().getJavaClass().getAnnotation( ForeignBreakpoints.class );
if ( foreign != null ) for ( BreakpointDef def : foreign.value() )
{
String name = def.name();
if ( name.isEmpty() ) name = def.method();
if ( null != bpDefs.put( name, def ) )
failures.add( new Exception( "Multiple definitions of the breakpoint \"" + name + "\"" ) );
}
for ( FrameworkMethod method : getTestClass().getAnnotatedMethods( BreakpointTrigger.class ) )
{
String name = method.getAnnotation( BreakpointTrigger.class ).value();
if ( name.isEmpty() ) name = method.getName();
if ( null != bpDefs.put( name, method ) )
failures.add( new Exception( "Multiple definitions of the breakpoint \"" + name + "\"" ) );
}
for ( FrameworkMethod handler : getTestClass().getAnnotatedMethods( BreakpointHandler.class ) )
{
for ( String name : handler.getAnnotation( BreakpointHandler.class ).value() )
{
Object bp = bpDefs.get( name );
if ( bp == null )
{
failures.add( new Exception( "No such breakpoint: \"" + name + "\", referenced from: "
+ handler ) );
}
else if ( bp == CLAIMED )
{
failures.add( new Exception( "Multiple handlers for breakpoint: \"" + name
+ "\", referenced from: " + handler ) );
}
else if ( bp instanceof BreakpointDef )
{
try
{
for ( BreakpointDispatcher dispatch : createForeignBreakpoints( (BreakpointDef) bp,
handler ) )
{
breakpoints.put( name, dispatch );
}
}
catch ( Exception exc )
{
failures.add( exc );
}
}
else if ( bp instanceof FrameworkMethod )
{
breakpoints.put( name, new BreakpointDispatcher(
( (FrameworkMethod) bp ).getAnnotation( BreakpointTrigger.class ).on(),
( (FrameworkMethod) bp ).getMethod().getDeclaringClass(),
( (FrameworkMethod) bp ).getMethod(), handler ) );
}
else
{
failures.add( new Exception( "Internal error, unknown breakpoint def: " + bp ) );
}
bpDefs.put( name, CLAIMED );
}
}
if ( bpDefs.size() != breakpoints.size() ) for ( Object bp : bpDefs.values() )
{
if ( bp != CLAIMED ) failures.add( new Exception( "Unhandled breakpoint: " + bp ) );
}
if ( !failures.isEmpty() )
{
if ( failures.size() == 1 ) throw failures.get( 0 );
throw new MultipleFailureException( failures );
}
}
}
}
return breakpoints.values().toArray( new BreakPoint[breakpoints.size()] );
}
Iterable<BreakpointDispatcher> createForeignBreakpoints( BreakpointDef def, FrameworkMethod handler ) throws Exception
{
Class<?> type = Class.forName( def.type() );
List<BreakpointDispatcher> result = new ArrayList<BreakpointDispatcher>( 1 );
for ( Method method : type.getDeclaredMethods() ) if ( method.getName().equals( def.method() ) )
{
result.add( new BreakpointDispatcher( def.on(), type, method, handler ) );
}
if ( result.isEmpty() ) throw new Exception( "No such method: " + def );
return result;
}
private class BreakpointDispatcher extends BreakPoint
{
private final FrameworkMethod handler;
BreakpointDispatcher( BreakPoint.Event event, Class<?> type, Method method, FrameworkMethod handler )
{
super( event, type, method.getName(), method.getParameterTypes() );
this.handler = handler;
}
@Override
protected void callback( DebugInterface debug ) throws KillSubProcess
{
Class<?>[] types = handler.getMethod().getParameterTypes();
Annotation[][] annotations = handler.getMethod().getParameterAnnotations();
Object[] params = new Object[types.length];
BUILD_PARAM_LIST: for ( int i = 0; i < types.length; i++ )
{
if ( types[i] == DebugInterface.class )
params[i] = debug;
else if ( types[i] == BreakPoint.class )
{
for ( Annotation annotation : annotations[i] )
{
if ( BreakpointHandler.class.isInstance( annotation ) )
{
String[] value = ( (BreakpointHandler) annotation ).value();
if ( value.length == 1 )
{
params[i] = breakpoints.get( value[0] );
continue BUILD_PARAM_LIST;
}
}
}
params[i] = this;
}
/*
else if ( types[i] == SequencingManager.class )
params[i] = seqManager;
*/
else if ( types[i] == Task.Executor.class )
params[i] = taskExecutor;
else
params[i] = null;
}
try
{
handler.invokeExplosively( null, params );
}
catch ( Throwable exception )
{
throw Exceptions.launderedException( KillSubProcess.class, exception );
}
}
}
@Override
protected Statement methodBlock( final FrameworkMethod method )
{
Statement statement = new Statement()
{
@Override
public void evaluate() throws Throwable
{
enableBreakpoints( method.getAnnotation( EnabledBreakpoints.class ) );
dispatcher.run( method.getName() );
}
};
List<FrameworkMethod> befores = getTestClass().getAnnotatedMethods( BeforeDebuggedTest.class );
if ( !befores.isEmpty() ) statement = new RunBefores( statement, befores, null );
return statement;
}
private void enableBreakpoints( EnabledBreakpoints breakpoints )
{
Set<String> enabled = new HashSet<String>();
if ( breakpoints != null ) for ( String name : breakpoints.value() )
{
enabled.add( name );
}
for ( Map.Entry<String, BreakPoint> entry : this.breakpoints.entrySet() )
{
BreakPoint bp = entry.getValue();
( enabled.remove( entry.getKey() ) ? bp.enable() : bp.disable() ).resetInvocationCount();
}
if ( !enabled.isEmpty() ) throw new IllegalArgumentException( "Unknown breakpoints: " + enabled );
}
private void verifyBreakpointState() throws SuspendedThreadsException
{
DebugDispatch debugger = SubProcess.DebugDispatch.get( dispatcher );
// if there are no breakpoints we will have no debugger
DebuggedThread[] threads = (debugger == null) ? new DebuggedThread[0] : debugger.suspendedThreads();
if ( threads.length != 0 )
{
String[] names = new String[threads.length];
for ( int i = 0; i < threads.length; i++ )
{
names[i] = threads[i].name();
threads[i].resume();
}
throw new SuspendedThreadsException( names );
}
}
interface TestRunnerDispatcher
{
void submit( Task<?> task ) throws Throwable;
void run( String methodName ) throws Throwable;
}
private interface RemoteRunNotifier extends Remote
{
void failure( Throwable exception ) throws RemoteException;
void checkPostConditions() throws RemoteException, Throwable;
}
private class NotifierImpl extends UnicastRemoteObject implements RemoteRunNotifier
{
private static final long serialVersionUID = 1L;
private final EachTestNotifier notifier;
NotifierImpl( EachTestNotifier notifier ) throws RemoteException
{
super();
this.notifier = notifier;
}
@Override
public void failure( Throwable exception ) throws RemoteException
{
notifier.addFailure( exception );
}
@Override
public void checkPostConditions() throws Throwable
{
verifyBreakpointState();
}
}
private static class RemoteRunListener extends RunListener
{
private final RemoteRunNotifier remote;
public RemoteRunListener( RemoteRunNotifier remote )
{
this.remote = remote;
}
@Override
public void testFailure( Failure failure ) throws Exception
{
remote.failure( failure.getException() );
}
}
public static class RunTerminatedException extends RuntimeException
{
private static final long serialVersionUID = 1L;
private RunTerminatedException()
{
// all instances are created here
}
}
private static final Object TERMINATED = new Object();
private static class TestProcess extends SubProcess<TestRunnerDispatcher, RemoteRunNotifier> implements
TestRunnerDispatcher
{
private static final long serialVersionUID = 1L;
private final String className;
public TestProcess(String className)
{
this.className = className;
}
private volatile Object runner;
@Override
protected void startup( RemoteRunNotifier remote ) throws Throwable
{
try
{
RunNotifier notifier = new RunNotifier();
notifier.addListener( new RemoteRunListener( remote ) );
new RemoteTestRunner( this, remote, Class.forName( className ) ).run( notifier );
}
catch ( Throwable failure )
{
runner = failure;
throw failure;
}
}
@Override
public String toString()
{
return className.substring( className.lastIndexOf( '.' ) + 1);
}
@Override
protected void shutdown( boolean normal )
{
try
{
Object runner = this.runner;
if ( runner instanceof RemoteTestRunner ) ( (RemoteTestRunner) runner ).terminate();
}
finally
{
this.runner = new RunTerminatedException();
}
super.shutdown( normal );
}
@Override
public void run( String methodName ) throws Throwable
{
runner().run( methodName );
}
@Override
public void submit( Task<?> task ) throws Throwable
{
runner().run( task );
}
private RemoteTestRunner runner() throws Throwable
{
for ( Object runner = this.runner;; runner = this.runner )
{
if ( runner instanceof RemoteTestRunner )
{
return (RemoteTestRunner) runner;
}
else if ( runner instanceof Throwable )
{
throw (Throwable) runner;
}
Thread.sleep( 1 ); // yield
}
}
}
private static class RemoteTestRunner extends BlockJUnit4ClassRunner
{
private final TestProcess testProcess;
private final RemoteRunNotifier host;
private volatile Object testMethod;
private volatile Object test;
RemoteTestRunner( TestProcess testProcess, RemoteRunNotifier host, Class<?> test ) throws InitializationError
{
super( test );
this.testProcess = testProcess;
this.host = host;
}
void terminate()
{
testMethod = TERMINATED;
}
@Override
protected Statement childrenInvoker( RunNotifier notifier )
{
return new Statement()
{
@Override
public void evaluate()
{
testProcess.runner = RemoteTestRunner.this;
for ( Object test = testMethod;; test = testMethod )
{
if ( test == null || test instanceof Throwable )
{
try
{
Thread.sleep( 1 ); // yield
}
catch ( InterruptedException e )
{
testMethod = e;
break;
}
}
else if ( test instanceof FrameworkMethod )
{
try
{
methodBlock( (FrameworkMethod) test ).evaluate();
testMethod = null;
}
catch ( Throwable e )
{
testMethod = e;
}
}
else break; // received poison pill
}
}
};
}
@Override
protected Statement methodBlock( FrameworkMethod method )
{
final Statement statement = super.methodBlock( method );
return statement;
}
@Override
protected Statement methodInvoker( FrameworkMethod method, Object test )
{
this.test = test;
final Statement statement = super.methodInvoker( method, test );
return new Statement()
{
@Override
public void evaluate() throws Throwable
{
statement.evaluate();
host.checkPostConditions();
}
};
}
private Map<String, FrameworkMethod> methods;
void run( String methodName ) throws Throwable
{
if ( methods == null )
{
Map<String, FrameworkMethod> map = new HashMap<String, FrameworkMethod>();
for ( FrameworkMethod method : getChildren() )
{
map.put( method.getName(), method );
}
methods = map;
}
testMethod = methods.get( methodName );
for ( Object result = testMethod;; result = testMethod )
{
if ( result instanceof FrameworkMethod )
{
Thread.sleep( 1 ); // yield
}
else if ( result instanceof Throwable )
{
throw (Throwable) result;
}
else return; // success
}
}
<T> void run( Task<T> task )
{
task.run( inject( typeOf( task ) ) );
}
private <T> T inject( Class<T> type )
{
if ( type == null ) /*could not find concrete parameter type*/return null;
Object test = this.test;
if ( type.isInstance( test ) ) return type.cast( test );
return null; // TODO: what other things should we be able to inject into tasks?
}
@SuppressWarnings( "unchecked" )
private static <T> Class<T> typeOf( Task<T> task )
{
Class<?> taskType = task.getClass();
while ( taskType != Object.class )
{
for ( Type type : taskType.getGenericInterfaces() )
{
if ( type instanceof ParameterizedType )
{
ParameterizedType paramType = (ParameterizedType) type;
if ( paramType.getRawType() == Task.class )
{
Type param = paramType.getActualTypeArguments()[0];
if ( param.getClass() == Class.class ) return (Class<T>) param;
}
}
}
taskType = taskType.getSuperclass();
}
return null;
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_SubProcessTestRunner.java
|
2,185
|
private static class PipeThread extends Thread
{
{
setName( getClass().getSimpleName() );
}
final CopyOnWriteArrayList<PipeTask> tasks = new CopyOnWriteArrayList<>();
@Override
public void run()
{
while ( true )
{
List<PipeTask> done = new ArrayList<>();
for ( PipeTask task : tasks )
{
if ( !task.pipe() )
{
done.add( task );
}
}
if ( !done.isEmpty() )
{
tasks.removeAll( done );
}
if ( tasks.isEmpty() )
{
synchronized ( PipeThread.class )
{
if ( tasks.isEmpty() )
{
piper = null;
return;
}
}
}
try
{
Thread.sleep( 10 );
}
catch ( InterruptedException e )
{
Thread.interrupted();
}
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_SubProcess.java
|
2,186
|
private static class PipeTask
{
private final String prefix;
private final InputStream source;
private final PrintStream target;
private StringBuilder line;
PipeTask( String prefix, InputStream source, PrintStream target )
{
this.prefix = prefix;
this.source = source;
this.target = target;
line = new StringBuilder();
}
boolean pipe()
{
try
{
byte[] data = new byte[Math.max( 1, source.available() )];
int bytesRead = source.read( data );
if ( bytesRead == -1 )
{
printLastLine();
return false;
}
if ( bytesRead < data.length )
{
data = Arrays.copyOf( data, bytesRead );
}
ByteBuffer chars = ByteBuffer.wrap( data );
while ( chars.hasRemaining() )
{
char c = (char) chars.get();
line.append( c );
if ( c == '\n' )
{
print();
}
}
}
catch ( IOException e )
{
printLastLine();
return false;
}
return true;
}
private void printLastLine()
{
if ( line.length() > 0 )
{
line.append( '\n' );
print();
}
}
private void print()
{
target.print( prefix + line.toString() );
line = new StringBuilder();
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_SubProcess.java
|
2,187
|
{
@Override
public void run()
{
latch.countDown();
try
{
dispatcher.stop();
}
catch ( RemoteException e )
{
process.destroy();
}
}
};
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_SubProcess.java
|
2,188
|
private static class Handler implements InvocationHandler
{
private final Dispatcher dispatcher;
private final Process process;
private final Class<?> type;
private final String repr;
private final DebugDispatch debugDispatch;
Handler( Class<?> type, Dispatcher dispatcher, Process process, String repr, DebugDispatch debugDispatch )
{
this.type = type;
this.dispatcher = dispatcher;
this.process = process;
this.repr = repr;
this.debugDispatch = debugDispatch;
}
@Override
public String toString()
{
return repr;
}
void kill( boolean wait )
{
process.destroy();
if ( wait )
{
dead( this );
await( process );
}
}
int stop( TimeUnit unit, long timeout )
{
final CountDownLatch latch = new CountDownLatch( unit == null ? 0 : 1 );
Thread stopper = new Thread()
{
@Override
public void run()
{
latch.countDown();
try
{
dispatcher.stop();
}
catch ( RemoteException e )
{
process.destroy();
}
}
};
stopper.start();
try
{
latch.await();
timeout = System.currentTimeMillis() + ( unit == null ? 0 : unit.toMillis( timeout ) );
while ( stopper.isAlive() && System.currentTimeMillis() < timeout )
{
Thread.sleep( 1 );
}
}
catch ( InterruptedException e )
{
// handled by exit
}
if ( stopper.isAlive() )
{
stopper.interrupt();
}
dead( this );
return await( process );
}
private static int await( Process process )
{
return new ProcessStreamHandler( process, true ).waitForResult();
}
@Override
public Object invoke( Object proxy, Method method, Object[] args ) throws Throwable
{
try
{
if ( method.getDeclaringClass() == type )
{
return dispatch( method, args );
}
else if ( method.getDeclaringClass() == Object.class )
{
return method.invoke( this, args );
}
else
{
throw new UnsupportedOperationException( method.toString() );
}
}
catch ( ServerError ex )
{
throw ex.detail;
}
catch ( RemoteException ex )
{
throw new ConnectionDisruptedException( ex );
}
}
private Object dispatch( Method method, Object[] args ) throws Throwable
{
Class<?>[] params = method.getParameterTypes();
String[] types = new String[params.length];
for ( int i = 0; i < types.length; i++ )
{
types[i] = params[i].getName();
}
return dispatcher.dispatch( method.getName(), types, args );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_SubProcess.java
|
2,189
|
private static class DispatcherTrapImpl extends UnicastRemoteObject implements DispatcherTrap
{
private final Object parameter;
private volatile Dispatcher dispatcher;
private final SubProcess<?, ?> process;
DispatcherTrapImpl( SubProcess<?, ?> process, Object parameter ) throws RemoteException
{
super();
this.process = process;
this.parameter = parameter;
}
Dispatcher get( @SuppressWarnings( "hiding" ) Process process )
{
while ( dispatcher == null )
{
try
{
Thread.sleep( 10 );
}
catch ( InterruptedException e )
{
Thread.currentThread().interrupt();
}
try
{
process.exitValue();
}
catch ( IllegalThreadStateException e )
{
continue;
}
return null;
}
return dispatcher;
}
@Override
public synchronized Object trap( @SuppressWarnings( "hiding" ) Dispatcher dispatcher )
{
if ( this.dispatcher != null )
{
throw new IllegalStateException( "Dispatcher already trapped!" );
}
this.dispatcher = dispatcher;
return parameter;
}
@Override
@SuppressWarnings( "unchecked" )
public SubProcess<?, Object> getSubProcess()
{
return (SubProcess<?, Object>) process;
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_subprocess_SubProcess.java
|
2,190
|
final class ServerHolder extends Thread
{
private static AssertionError allocation;
private static NeoServer server;
static synchronized NeoServer allocate() throws IOException
{
if ( allocation != null ) throw allocation;
if ( server == null ) server = startServer();
allocation = new AssertionError( "The server was allocated from here but not released properly" );
return server;
}
static synchronized void release( NeoServer server )
{
if ( server == null ) return;
if ( server != ServerHolder.server )
throw new AssertionError( "trying to suspend a server not allocated from here" );
if ( allocation == null ) throw new AssertionError( "releasing the server although it is not allocated" );
allocation = null;
}
static synchronized void ensureNotRunning()
{
if ( allocation != null ) throw allocation;
shutdown();
}
private static NeoServer startServer() throws IOException
{
NeoServer server = ServerHelper.createNonPersistentServer();
return server;
}
private static synchronized void shutdown()
{
allocation = null;
try
{
if ( server != null ) server.stop();
}
finally
{
server = null;
}
}
@Override
public void run()
{
shutdown();
}
static
{
Runtime.getRuntime().addShutdownHook( new ServerHolder() );
}
private ServerHolder()
{
super( ServerHolder.class.getName() );
}
}
| false
|
community_server_src_test_java_org_neo4j_test_server_ServerHolder.java
|
2,191
|
public static class Response
{
private final ClientResponse response;
private final String entity;
public Response( ClientResponse response )
{
this.response = sanityCheck( response );
this.entity = response.getEntity( String.class );
}
public int status()
{
return response.getStatus();
}
public String location()
{
if ( response.getLocation() != null )
{
return response.getLocation().toString();
}
throw new RuntimeException( "The request did not contain a location header, " +
"unable to provide location. Status code was: " + status() );
}
@SuppressWarnings("unchecked")
public <T> T content()
{
try
{
return (T) JsonHelper.readJson( entity );
}
catch ( JsonParseException e )
{
throw new RuntimeException( "Unable to deserialize: " + entity, e );
}
}
public String rawContent()
{
return entity;
}
public String stringFromContent( String key ) throws JsonParseException
{
return get(key).asText();
}
public JsonNode get(String fieldName) throws JsonParseException
{
return JsonHelper.jsonNode( entity ).get( fieldName );
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append( "HTTP " ).append( response.getStatus() ).append( "\n" );
for ( Map.Entry<String, List<String>> header : response.getHeaders().entrySet() )
{
for ( String headerEntry : header.getValue() )
{
sb.append( header.getKey() + ": " ).append( headerEntry ).append( "\n" );
}
}
sb.append( "\n" );
sb.append( entity ).append( "\n" );
return sb.toString();
}
}
| false
|
community_server_src_test_java_org_neo4j_test_server_HTTP.java
|
2,192
|
public static class RawPayload
{
private final String payload;
public static RawPayload rawPayload( String payload )
{
return new RawPayload( payload );
}
public static RawPayload quotedJson( String json )
{
return new RawPayload( json.replaceAll( "'", "\"" ) );
}
private RawPayload( String payload )
{
this.payload = payload;
}
public String get()
{
return payload;
}
}
| false
|
community_server_src_test_java_org_neo4j_test_server_HTTP.java
|
2,193
|
public static class Builder
{
private final Map<String, String> headers;
private final String baseUri;
private Builder()
{
this( Collections.<String, String>emptyMap(), "" );
}
private Builder( Map<String, String> headers, String baseUri )
{
this.baseUri = baseUri;
this.headers = unmodifiableMap( headers );
}
public Builder withHeaders( String... kvPairs )
{
return withHeaders( stringMap( kvPairs ) );
}
public Builder withHeaders( Map<String, String> newHeaders )
{
HashMap<String, String> combined = new HashMap<>();
combined.putAll( newHeaders );
combined.putAll( headers );
return new Builder( combined, baseUri );
}
public Builder withBaseUri( String baseUri )
{
return new Builder( headers, baseUri );
}
public Response POST( String uri )
{
return exec( "POST", uri );
}
public Response POST( String uri, Object payload )
{
return exec( "POST", uri, payload );
}
public Response POST( String uri, RawPayload payload )
{
return exec( "POST", uri, payload );
}
public Response PUT( String uri )
{
return exec( "PUT", uri );
}
public Response PUT( String uri, Object payload )
{
return exec( "PUT", uri, payload );
}
public Response PUT( String uri, RawPayload payload )
{
return exec( "PUT", uri, payload );
}
public Response DELETE( String uri )
{
return exec( "DELETE", uri );
}
public Response GET( String uri )
{
return exec( "GET", uri );
}
public Response exec( String method, String uri )
{
return new Response( CLIENT.handle( build().build( buildUri( uri ), method ) ) );
}
public Response exec( String method, String uri, Object payload )
{
String jsonPayload = payload instanceof RawPayload ? ((RawPayload) payload).get() : createJsonFrom(
payload );
ClientRequest.Builder lastBuilder = build().entity( jsonPayload, MediaType.APPLICATION_JSON_TYPE );
return new Response( CLIENT.handle( lastBuilder.build( buildUri( uri ), method ) ) );
}
private URI buildUri( String uri )
{
URI unprefixedUri = URI.create( uri );
if ( unprefixedUri.isAbsolute() )
{
return unprefixedUri;
}
else
{
return URI.create( baseUri + uri );
}
}
private ClientRequest.Builder build()
{
ClientRequest.Builder builder = ClientRequest.create();
for ( Map.Entry<String, String> header : headers.entrySet() )
{
builder = builder.header( header.getKey(), header.getValue() );
}
return builder;
}
}
| false
|
community_server_src_test_java_org_neo4j_test_server_HTTP.java
|
2,194
|
public class EphemeralFileSystemAbstraction extends LifecycleAdapter implements FileSystemAbstraction
{
private final Set<File> directories = Collections.newSetFromMap( new ConcurrentHashMap<File, Boolean>() );
private final Map<File, EphemeralFileData> files;
public EphemeralFileSystemAbstraction()
{
this.files = new ConcurrentHashMap<>();
}
private EphemeralFileSystemAbstraction( Set<File> directories, Map<File, EphemeralFileData> files )
{
this.files = new ConcurrentHashMap<>( files );
this.directories.addAll( directories );
this.files.putAll( files );
}
@Override
public synchronized void shutdown()
{
for ( EphemeralFileData file : files.values() )
free( file );
files.clear();
for ( ThirdPartyFileSystem thirdPartyFileSystem : thirdPartyFileSystems.values() )
{
thirdPartyFileSystem.close();
}
thirdPartyFileSystems.clear();
}
@Override
protected void finalize() throws Throwable
{
shutdown();
super.finalize();
}
public void assertNoOpenFiles() throws Exception
{
List<FileStillOpenException> open = new ArrayList<>();
for ( EphemeralFileData file : files.values() )
{
for ( EphemeralFileChannel channel : loop( file.getOpenChannels() ) )
{
open.add( channel.openedAt );
}
}
MultipleExceptionsStrategy.assertEmptyExceptions( open );
}
public void dumpZip( OutputStream output ) throws IOException
{
try ( ZipOutputStream zip = new ZipOutputStream( output ) )
{
String prefix = null;
for ( Map.Entry<File, EphemeralFileData> entry : files.entrySet() )
{
File file = entry.getKey();
String parent = file.getParentFile().getAbsolutePath();
if ( prefix == null || prefix.startsWith( parent ) )
{
prefix = parent;
}
zip.putNextEntry( new ZipEntry( file.getAbsolutePath() ) );
entry.getValue().dumpTo( zip );
zip.closeEntry();
}
for ( ThirdPartyFileSystem fs : thirdPartyFileSystems.values() )
{
fs.dumpToZip( zip, EphemeralFileData.SCRATCH_PAD.get() );
}
if ( prefix != null )
{
File directory = new File( prefix );
if ( directory.exists() ) // things ended up on the file system...
{
addRecursively( zip, directory );
}
}
}
}
private void addRecursively( ZipOutputStream output, File input ) throws IOException
{
if ( input.isFile() )
{
output.putNextEntry( new ZipEntry( input.getAbsolutePath() ) );
byte[] scratchPad = EphemeralFileData.SCRATCH_PAD.get();
try ( FileInputStream source = new FileInputStream( input ) )
{
for ( int read; 0 <= (read = source.read( scratchPad )); )
{
output.write( scratchPad, 0, read );
}
}
output.closeEntry();
}
else
{
File[] children = input.listFiles();
if ( children != null )
{
for ( File child : children )
{
addRecursively( output, child );
}
}
}
}
@SuppressWarnings( "serial" )
private static class FileStillOpenException extends Exception
{
private final String filename;
FileStillOpenException( String filename )
{
super( "File still open: [" + filename + "]" );
this.filename = filename;
}
}
private void free(EphemeralFileData file)
{
if (file != null) file.fileAsBuffer.free();
}
@Override
public synchronized StoreChannel open( File fileName, String mode ) throws IOException
{
EphemeralFileData data = files.get( fileName );
if ( data != null )
{
return new StoreFileChannel( new EphemeralFileChannel(
data, new FileStillOpenException( fileName.getPath() ) ) );
}
return create( fileName );
}
@Override
public OutputStream openAsOutputStream( File fileName, boolean append ) throws IOException
{
return new ChannelOutputStream( open( fileName, "rw" ), append );
}
@Override
public InputStream openAsInputStream( File fileName ) throws IOException
{
return new ChannelInputStream( open( fileName, "r" ) );
}
@Override
public Reader openAsReader( File fileName, String encoding ) throws IOException
{
return new InputStreamReader( openAsInputStream( fileName ), encoding );
}
@Override
public Writer openAsWriter( File fileName, String encoding, boolean append ) throws IOException
{
return new OutputStreamWriter( openAsOutputStream( fileName, append ), encoding );
}
@Override
public FileLock tryLock(File fileName, StoreChannel channel) throws IOException
{
final java.nio.channels.FileLock lock = channel.tryLock();
return new FileLock()
{
@Override
public void release() throws IOException
{
lock.release();
}
};
}
@Override
public synchronized StoreChannel create( File fileName ) throws IOException
{
File parentFile = fileName.getParentFile();
if ( parentFile != null /*means that this is the 'default location'*/ && !fileExists( parentFile ) )
{
throw new FileNotFoundException( "'" + fileName
+ "' (The system cannot find the path specified)" );
}
EphemeralFileData data = new EphemeralFileData();
free( files.put( fileName, data ) );
return new StoreFileChannel(
new EphemeralFileChannel( data, new FileStillOpenException( fileName.getPath() ) ) );
}
@Override
public long getFileSize(File fileName)
{
EphemeralFileData file = files.get(fileName);
return file == null ? 0 : file.size();
}
@Override
public boolean fileExists( File file )
{
return directories.contains( file.getAbsoluteFile() ) || files.containsKey( file );
}
@Override
public boolean isDirectory( File file )
{
return directories.contains( file.getAbsoluteFile() );
}
@Override
public boolean mkdir( File directory )
{
if ( fileExists( directory ) )
{
return false;
}
directories.add( directory.getAbsoluteFile() );
return true;
}
@Override
public void mkdirs( File directory )
{
File currentDirectory = directory.getAbsoluteFile();
while ( currentDirectory != null )
{
mkdir( currentDirectory );
currentDirectory = currentDirectory.getParentFile();
}
}
@Override
public boolean deleteFile(File fileName)
{
EphemeralFileData removed = files.remove( fileName );
free( removed );
return removed != null;
}
@Override
public void deleteRecursively( File directory ) throws IOException
{
List<String> directoryPathItems = splitPath( directory );
for ( Map.Entry<File, EphemeralFileData> file : files.entrySet() )
{
File fileName = file.getKey();
List<String> fileNamePathItems = splitPath( fileName );
if ( directoryMatches( directoryPathItems, fileNamePathItems ) )
deleteFile( fileName );
}
}
@Override
public boolean renameFile(File from, File to) throws IOException
{
if (!files.containsKey( from )) throw new IOException("'" + from + "' doesn't exist");
if (files.containsKey(to)) throw new IOException("'" + to + "' already exists");
files.put(to, files.remove(from));
return true;
}
@Override
public File[] listFiles( File directory )
{
if ( files.containsKey( directory ) )
// This means that you're trying to list files on a file, not a directory.
return null;
List<String> directoryPathItems = splitPath( directory );
List<File> found = new ArrayList<>();
for ( Map.Entry<File, EphemeralFileData> file : files.entrySet() )
{
File fileName = file.getKey();
List<String> fileNamePathItems = splitPath( fileName );
if ( directoryMatches( directoryPathItems, fileNamePathItems ) )
found.add( constructPath( fileNamePathItems, directoryPathItems.size()+1 ) );
}
return found.toArray( new File[found.size()] );
}
private File constructPath( List<String> pathItems, int count )
{
File file = null;
for ( String pathItem : pathItems.subList( 0, count ) )
file = file == null ? new File( pathItem ) : new File( file, pathItem );
return file;
}
private boolean directoryMatches( List<String> directoryPathItems, List<String> fileNamePathItems )
{
return fileNamePathItems.size() > directoryPathItems.size() &&
fileNamePathItems.subList( 0, directoryPathItems.size() ).equals( directoryPathItems );
}
private List<String> splitPath( File path )
{
return asList( path.getPath().replaceAll( "\\\\", "/" ).split( "/" ) );
}
@Override
public void moveToDirectory( File file, File toDirectory ) throws IOException
{
EphemeralFileData fileToMove = files.remove( file );
if ( fileToMove == null )
throw new FileNotFoundException( file.getPath() );
files.put( new File( toDirectory, file.getName() ), fileToMove );
}
@Override
public void copyFile( File from, File to ) throws IOException
{
EphemeralFileData data = files.get( from );
if ( data == null )
throw new FileNotFoundException( "File " + from + " not found" );
copyFile( from, this, to, newCopyBuffer() );
}
@Override
public void copyRecursively( File fromDirectory, File toDirectory ) throws IOException
{
copyRecursivelyFromOtherFs( fromDirectory, this, toDirectory, newCopyBuffer() );
}
interface Positionable
{
long pos();
void pos( long position );
}
static class LocalPosition implements Positionable
{
private long position;
public LocalPosition( long position )
{
this.position = position;
}
@Override
public long pos()
{
return position;
}
@Override
public void pos( long position )
{
this.position = position;
}
}
private static class EphemeralFileChannel extends FileChannel implements Positionable
{
final FileStillOpenException openedAt;
private final EphemeralFileData data;
private long position = 0;
EphemeralFileChannel( EphemeralFileData data, FileStillOpenException opened )
{
this.data = data;
this.openedAt = opened;
data.open( this );
}
@Override
public String toString()
{
return String.format( "%s[%s]", getClass().getSimpleName(), openedAt.filename );
}
@Override
public int read( ByteBuffer dst )
{
return data.read( this, dst );
}
@Override
public long read( ByteBuffer[] dsts, int offset, int length )
{
throw new UnsupportedOperationException();
}
@Override
public int write( ByteBuffer src ) throws IOException
{
return data.write( this, src );
}
@Override
public long write( ByteBuffer[] srcs, int offset, int length )
{
throw new UnsupportedOperationException();
}
@Override
public long position() throws IOException
{
return position;
}
@Override
public FileChannel position( long newPosition ) throws IOException
{
this.position = newPosition;
return this;
}
@Override
public long size() throws IOException
{
return data.size();
}
@Override
public FileChannel truncate( long size ) throws IOException
{
data.truncate( size );
return this;
}
@Override
public void force(boolean metaData)
{
// NO-OP
}
@Override
public long transferTo(long position, long count, WritableByteChannel target)
{
throw new UnsupportedOperationException();
}
@Override
public long transferFrom( ReadableByteChannel src, long position, long count ) throws IOException
{
long previousPos = position();
position( position );
try
{
long transferred = 0;
ByteBuffer intermediary = ByteBuffer.allocateDirect( 8096 );
while ( transferred < count )
{
intermediary.clear();
intermediary.limit( (int) min( intermediary.capacity(), count-transferred ) );
int read = src.read( intermediary );
if ( read == -1 )
break;
transferred += read;
intermediary.flip();
}
return transferred;
}
finally
{
position( previousPos );
}
}
@Override
public int read( ByteBuffer dst, long position ) throws IOException
{
return data.read( new LocalPosition( position ), dst );
}
@Override
public int write( ByteBuffer src, long position ) throws IOException
{
return data.write( new LocalPosition( position ), src );
}
@Override
public MappedByteBuffer map( FileChannel.MapMode mode, long position, long size ) throws IOException
{
throw new IOException("Not supported");
}
@Override
public java.nio.channels.FileLock lock( long position, long size, boolean shared ) throws IOException
{
synchronized ( data.channels )
{
if ( !data.lock() )
{
return null;
}
return new EphemeralFileLock( this, data );
}
}
@Override
public java.nio.channels.FileLock tryLock( long position, long size, boolean shared ) throws IOException
{
synchronized ( data.channels )
{
if ( !data.lock() )
{
throw new IOException( "Locked" );
}
return new EphemeralFileLock( this, data );
}
}
@Override
protected void implCloseChannel() throws IOException
{
data.close( this );
}
@Override
public long pos()
{
return position;
}
@Override
public void pos( long position )
{
this.position = position;
}
}
private static class EphemeralFileData
{
private static final ThreadLocal<byte[]> SCRATCH_PAD = new ThreadLocal<byte[]>()
{
@Override
protected byte[] initialValue()
{
return new byte[1024];
}
};
private final DynamicByteBuffer fileAsBuffer;
private final Collection<WeakReference<EphemeralFileChannel>> channels = new LinkedList<>();
private int size;
private int locked;
public EphemeralFileData()
{
this( new DynamicByteBuffer() );
}
private EphemeralFileData( DynamicByteBuffer data )
{
this.fileAsBuffer = data;
}
int read( Positionable fc, ByteBuffer dst )
{
int wanted = dst.limit();
int available = min(wanted, (int) (size() - fc.pos()));
if ( available == 0 ) return -1; // EOF
int pending = available;
// Read up until our internal size
byte[] scratchPad = SCRATCH_PAD.get();
while (pending > 0)
{
int howMuchToReadThisTime = min(pending, scratchPad.length);
long pos = fc.pos();
fileAsBuffer.get((int) pos, scratchPad, 0, howMuchToReadThisTime);
fc.pos( pos + howMuchToReadThisTime );
dst.put(scratchPad, 0, howMuchToReadThisTime);
pending -= howMuchToReadThisTime;
}
return available; // return how much data was read
}
int write( Positionable fc, ByteBuffer src )
{
int wanted = src.limit();
int pending = wanted;
byte[] scratchPad = SCRATCH_PAD.get();
while ( pending > 0 )
{
int howMuchToWriteThisTime = min( pending, scratchPad.length );
src.get( scratchPad, 0, howMuchToWriteThisTime );
long pos = fc.pos();
fileAsBuffer.put( (int) pos, scratchPad, 0, howMuchToWriteThisTime );
fc.pos( pos += howMuchToWriteThisTime );
pending -= howMuchToWriteThisTime;
}
synchronized ( fileAsBuffer )
{
// If we just made a jump in the file fill the rest of the gap with zeros
int newSize = max( size, (int) fc.pos() );
int intermediaryBytes = newSize - wanted - size;
if ( intermediaryBytes > 0 )
{
fileAsBuffer.fillWithZeros( size, intermediaryBytes );
}
size = newSize;
}
return wanted;
}
EphemeralFileData copy()
{
synchronized ( fileAsBuffer )
{
EphemeralFileData copy = new EphemeralFileData( fileAsBuffer.copy() );
copy.size = size;
return copy;
}
}
void open( EphemeralFileChannel channel )
{
synchronized ( channels )
{
channels.add( new WeakReference<>( channel ) );
}
}
void close( EphemeralFileChannel channel )
{
synchronized ( channels )
{
locked = 0; // Regular file systems seems to release all file locks when closed...
for ( Iterator<EphemeralFileChannel> iter = getOpenChannels(); iter.hasNext(); )
{
if ( iter.next() == channel )
{
iter.remove();
}
}
}
}
Iterator<EphemeralFileChannel> getOpenChannels()
{
final Iterator<WeakReference<EphemeralFileChannel>> refs = channels.iterator();
return new PrefetchingIterator<EphemeralFileChannel>()
{
@Override
protected EphemeralFileChannel fetchNextOrNull()
{
while ( refs.hasNext() )
{
EphemeralFileChannel channel = refs.next().get();
if ( channel != null ) return channel;
refs.remove();
}
return null;
}
@Override
public void remove()
{
refs.remove();
}
};
}
long size()
{
synchronized ( fileAsBuffer )
{
return size;
}
}
void truncate( long newSize )
{
synchronized ( fileAsBuffer )
{
this.size = (int) newSize;
}
}
boolean lock()
{
return locked == 0;
}
void dumpTo( OutputStream target ) throws IOException
{
byte[] scratchPad = SCRATCH_PAD.get();
synchronized ( fileAsBuffer )
{
fileAsBuffer.dump( target, scratchPad, size );
}
}
}
private static class EphemeralFileLock extends java.nio.channels.FileLock
{
private EphemeralFileData file;
EphemeralFileLock(EphemeralFileChannel channel, EphemeralFileData file)
{
super(channel, 0, Long.MAX_VALUE, false);
this.file = file;
file.locked++;
}
@Override
public boolean isValid()
{
return file != null;
}
@Override
public void release() throws IOException
{
synchronized ( file.channels )
{
if ( file == null || file.locked == 0 )
{
return;
}
file.locked--;
file = null;
}
}
}
/**
* Dynamically expanding ByteBuffer substitute/wrapper. This will allocate ByteBuffers on the go
* so that we don't have to allocate too big of a buffer up-front.
*/
private static class DynamicByteBuffer
{
private static final int[] SIZES;
/**
* Holds a set of pools of unused BytBuffers, where pools are implemented by {@link Queue}s.
* Each pool contains only {@link ByteBuffer} of the same size. This way, we have pools for
* different sized {@link ByteBuffer}, and can pick an available byte buffer that suits what
* we want to store quickly.
*/
private static volatile AtomicReferenceArray<Queue<Reference<ByteBuffer>>> POOLS;
private static final byte[] zeroBuffer = new byte[1024];
synchronized DynamicByteBuffer copy()
{
return new DynamicByteBuffer( buf ); // invoke "copy constructor"
}
static
{
int K = 1024;
SIZES = new int[] { 64 * K, 128 * K, 256 * K, 512 * K, 1024 * K };
POOLS = new AtomicReferenceArray<>( SIZES.length );
for ( int sizeIndex = 0; sizeIndex < SIZES.length; sizeIndex++ )
POOLS.set( sizeIndex, new ConcurrentLinkedQueue<Reference<ByteBuffer>>() );
}
private ByteBuffer buf;
public DynamicByteBuffer()
{
buf = allocate( 0 );
}
/** This is a copying constructor, the input buffer is just read from, never stored in 'this'. */
private DynamicByteBuffer( ByteBuffer toClone )
{
int sizeIndex = sizeIndexFor( toClone.capacity() );
buf = allocate( sizeIndex );
copyByteBufferContents( toClone, buf );
}
private void copyByteBufferContents( ByteBuffer from, ByteBuffer to )
{
int positionBefore = from.position();
try
{
from.position( 0 );
to.put( from );
}
finally
{
from.position( positionBefore );
to.position( 0 );
}
}
/**
* Tries to allocate a buffer of at least the specified size.
* If no free buffers are available of the available capacity, we
* check for buffers up to two sizes larger. If still no buffers
* are found we allocate a new buffer of the specified size.
*/
private ByteBuffer allocate( int sizeIndex )
{
for (int enlargement = 0; enlargement < 2; enlargement++) {
AtomicReferenceArray<Queue<Reference<ByteBuffer>>> pools = POOLS;
if (sizeIndex + enlargement < pools.length()) {
Queue<Reference<ByteBuffer>> queue = pools.get( sizeIndex+enlargement );
if ( queue != null )
{
for (;;)
{
Reference<ByteBuffer> ref = queue.poll();
if ( ref == null ) break;
ByteBuffer buffer = ref.get();
if ( buffer != null ) return buffer;
}
}
}
}
return ByteBuffer.allocateDirect( ( sizeIndex < SIZES.length ) ? SIZES[sizeIndex]
: ( ( sizeIndex - SIZES.length + 1 ) * SIZES[SIZES.length - 1] ) );
}
void free()
{
try
{
clear();
int sizeIndex = buf.capacity() / SIZES[SIZES.length - 1];
if (sizeIndex == 0) for ( ; sizeIndex < SIZES.length; sizeIndex++ )
{
if (buf.capacity() == SIZES[sizeIndex]) break;
}
else
{
sizeIndex += SIZES.length - 1;
}
AtomicReferenceArray<Queue<Reference<ByteBuffer>>> pools = POOLS;
// Use soft references to the buffers to allow the GC to reclaim
// unused buffers if memory gets scarce.
SoftReference<ByteBuffer> ref = new SoftReference<>( buf );
// Put our buffer into a pool, create a pool for the buffer size if one does not exist
( sizeIndex < pools.length() ? pools.get( sizeIndex ) : getOrCreatePoolForSize( sizeIndex ) ).add( ref );
}
finally
{
buf = null;
}
}
private static synchronized Queue<Reference<ByteBuffer>> getOrCreatePoolForSize( int sizeIndex )
{
AtomicReferenceArray<Queue<Reference<ByteBuffer>>> pools = POOLS;
if ( sizeIndex >= pools.length() )
{
int newSize = pools.length();
while ( sizeIndex >= newSize )
newSize <<= 1;
AtomicReferenceArray<Queue<Reference<ByteBuffer>>> newPool = new AtomicReferenceArray<>( newSize );
for ( int i = 0; i < pools.length(); i++ )
newPool.set( i, pools.get( i ) );
for ( int i = pools.length(); i < newPool.length(); i++ )
newPool.set( i, new ConcurrentLinkedQueue<Reference<ByteBuffer>>() );
POOLS = pools = newPool;
}
return pools.get( sizeIndex );
}
synchronized void put( int pos, byte[] bytes, int offset, int length )
{
verifySize( pos+length );
try
{
buf.position( pos );
}
catch ( IllegalArgumentException e )
{
throw new IllegalArgumentException( buf + ", " + pos, e );
}
buf.put( bytes, offset, length );
}
synchronized void get( int pos, byte[] scratchPad, int i, int howMuchToReadThisTime )
{
buf.position( pos );
buf.get( scratchPad, i, howMuchToReadThisTime );
}
synchronized void fillWithZeros( int pos, int bytes )
{
buf.position( pos );
while ( bytes > 0 )
{
int howMuchToReadThisTime = min( bytes, zeroBuffer.length );
buf.put( zeroBuffer, 0, howMuchToReadThisTime );
bytes -= howMuchToReadThisTime;
}
buf.position( pos );
}
/**
* Checks if more space needs to be allocated.
*/
private void verifySize( int totalAmount )
{
if ( buf.capacity() >= totalAmount )
{
return;
}
// Double size each time, but after 1M only increase by 1M at a time, until required amount is reached.
int newSize = buf.capacity();
int sizeIndex = sizeIndexFor( newSize );
while ( newSize < totalAmount )
{
newSize += Math.min( newSize, 1024 * 1024 );
sizeIndex++;
}
int oldPosition = this.buf.position();
ByteBuffer buf = allocate( sizeIndex );
this.buf.position( 0 );
buf.put( this.buf );
this.buf = buf;
this.buf.position( oldPosition );
}
private static int sizeIndexFor( int capacity )
{
// Double size each time, but after 1M only increase by 1M at a time, until required amount is reached.
int sizeIndex = capacity / SIZES[SIZES.length - 1];
if (sizeIndex == 0) for ( ; sizeIndex < SIZES.length; sizeIndex++ )
{
if ( capacity == SIZES[sizeIndex] )
break;
}
else
{
sizeIndex += SIZES.length - 1;
}
return sizeIndex;
}
public void clear()
{
this.buf.clear();
}
void dump( OutputStream target, byte[] scratchPad, int size ) throws IOException
{
buf.position( 0 );
while ( size > 0 )
{
int read = min( size, scratchPad.length );
buf.get( scratchPad, 0, read );
size -= read;
target.write( scratchPad, 0, read );
}
}
}
public EphemeralFileSystemAbstraction snapshot()
{
Map<File, EphemeralFileData> copiedFiles = new HashMap<>();
for ( Map.Entry<File, EphemeralFileData> file : files.entrySet() )
{
copiedFiles.put( file.getKey(), file.getValue().copy() );
}
return new EphemeralFileSystemAbstraction( directories, copiedFiles );
}
public void copyRecursivelyFromOtherFs( File from, FileSystemAbstraction fromFs, File to ) throws IOException
{
copyRecursivelyFromOtherFs( from, fromFs, to, newCopyBuffer() );
}
private ByteBuffer newCopyBuffer()
{
return ByteBuffer.allocate( 1024*1024 );
}
private void copyRecursivelyFromOtherFs( File from, FileSystemAbstraction fromFs, File to, ByteBuffer buffer )
throws IOException
{
this.mkdirs( to );
for ( File fromFile : fromFs.listFiles( from ) )
{
File toFile = new File( to, fromFile.getName() );
if ( fromFs.isDirectory( fromFile ) )
copyRecursivelyFromOtherFs( fromFile, fromFs, toFile );
else
copyFile( fromFile, fromFs, toFile, buffer );
}
}
private void copyFile( File from, FileSystemAbstraction fromFs, File to, ByteBuffer buffer ) throws IOException
{
StoreChannel source = fromFs.open( from, "r" );
StoreChannel sink = this.open( to, "rw" );
try
{
for ( int available; (available = (int) (source.size() - source.position())) > 0; )
{
buffer.clear();
buffer.limit( min( available, buffer.capacity() ) );
source.read( buffer );
buffer.flip();
sink.write( buffer );
}
}
finally
{
if ( source != null )
source.close();
if ( sink != null )
sink.close();
}
}
private final Map<Class<? extends ThirdPartyFileSystem>, ThirdPartyFileSystem> thirdPartyFileSystems =
new HashMap<>();
@Override
public synchronized <K extends ThirdPartyFileSystem> K getOrCreateThirdPartyFileSystem(
Class<K> clazz, Function<Class<K>, K> creator )
{
ThirdPartyFileSystem fileSystem = thirdPartyFileSystems.get( clazz );
if (fileSystem == null)
{
thirdPartyFileSystems.put( clazz, fileSystem = creator.apply( clazz ) );
}
return clazz.cast( fileSystem );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_impl_EphemeralFileSystemAbstraction.java
|
2,195
|
public class ChannelOutputStream extends OutputStream
{
private final StoreChannel channel;
private final ByteBuffer buffer = ByteBuffer.allocateDirect( 8096 );
public ChannelOutputStream( StoreChannel channel, boolean append ) throws IOException
{
this.channel = channel;
if ( append )
this.channel.position( this.channel.size() );
}
@Override
public void write( int b ) throws IOException
{
buffer.clear();
buffer.put( (byte) b );
buffer.flip();
channel.write( buffer );
}
@Override
public void write( byte[] b ) throws IOException
{
write( b, 0, b.length );
}
@Override
public void write( byte[] b, int off, int len ) throws IOException
{
int written = 0, index = off;
while ( written < len )
{
buffer.clear();
buffer.put( b, index, Math.min( len-written, buffer.capacity() ) );
buffer.flip();
written += channel.write( buffer );
}
}
@Override
public void close() throws IOException
{
channel.close();
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_impl_ChannelOutputStream.java
|
2,196
|
public class ChannelInputStream extends InputStream
{
private final StoreChannel channel;
private final ByteBuffer buffer = ByteBuffer.allocateDirect( 8096 );
private int position;
public ChannelInputStream( StoreChannel channel )
{
this.channel = channel;
}
@Override
public int read() throws IOException
{
if ( !readAndFlip( channel, buffer, 1 ) )
return -1;
position++;
return buffer.get();
}
@Override
public int read( byte[] b, int off, int len ) throws IOException
{
// TODO implement properly
return super.read( b, off, len );
}
@Override
public int available() throws IOException
{
return (int) (position - channel.size());
}
@Override
public void close() throws IOException
{
channel.close();
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_impl_ChannelInputStream.java
|
2,197
|
public class ClusterTest
{
@Rule
public LoggerRule logging = new LoggerRule();
@Test
public void testCluster() throws Throwable
{
ClusterManager clusterManager = new ClusterManager( fromXml( getClass().getResource( "/threeinstances.xml" ).toURI() ),
TargetDirectory.forTest( getClass() ).cleanDirectory( "testCluster" ),
MapUtil.stringMap(HaSettings.ha_server.name(), ":6001-6005",
HaSettings.tx_push_factor.name(), "2"));
try
{
clusterManager.start();
clusterManager.getDefaultCluster().await( allSeesAllAsAvailable() );
GraphDatabaseAPI master = clusterManager.getDefaultCluster().getMaster();
Transaction tx = master.beginTx();
Node node = master.createNode();
long nodeId = node.getId();
node.setProperty( "foo", "bar" );
tx.success();
tx.finish();
HighlyAvailableGraphDatabase slave = clusterManager.getDefaultCluster().getAnySlave();
Transaction transaction = slave.beginTx();
try
{
node = slave.getNodeById( nodeId );
assertThat( node.getProperty( "foo" ).toString(), CoreMatchers.equalTo( "bar" ) );
}
finally
{
transaction.finish();
}
}
finally
{
clusterManager.stop();
}
}
@Test
public void testClusterWithHostnames() throws Throwable
{
String hostName = InetAddress.getLocalHost().getHostName();
Clusters.Cluster cluster = new Clusters.Cluster( "neo4j.ha" );
for ( int i = 0; i < 3; i++ )
{
cluster.getMembers().add( new Clusters.Member( hostName +":"+(5001 + i), true ) );
}
final Clusters clusters = new Clusters();
clusters.getClusters().add( cluster );
ClusterManager clusterManager = new ClusterManager( ClusterManager.provided( clusters ),
TargetDirectory.forTest( getClass() ).cleanDirectory( "testCluster" ),
MapUtil.stringMap( HaSettings.ha_server.name(), hostName+":6001-6005",
HaSettings.tx_push_factor.name(), "2" ));
try
{
clusterManager.start();
clusterManager.getDefaultCluster().await( allSeesAllAsAvailable() );
GraphDatabaseAPI master = clusterManager.getDefaultCluster().getMaster();
Transaction tx = master.beginTx();
Node node = master.createNode();
long nodeId = node.getId();
node.setProperty( "foo", "bar" );
tx.success();
tx.finish();
HighlyAvailableGraphDatabase anySlave = clusterManager.getDefaultCluster().getAnySlave();
try(Transaction ignore = anySlave.beginTx())
{
node = anySlave.getNodeById( nodeId );
assertThat( node.getProperty( "foo" ).toString(), CoreMatchers.equalTo( "bar" ) );
}
}
finally
{
clusterManager.stop();
}
}
@Test
public void testClusterWithWildcardIP() throws Throwable
{
Clusters.Cluster cluster = new Clusters.Cluster( "neo4j.ha" );
for ( int i = 0; i < 3; i++ )
{
cluster.getMembers().add( new Clusters.Member( (5001 + i), true ) );
}
final Clusters clusters = new Clusters();
clusters.getClusters().add( cluster );
ClusterManager clusterManager = new ClusterManager( ClusterManager.provided( clusters ),
TargetDirectory.forTest( getClass() ).cleanDirectory( "testCluster" ),
MapUtil.stringMap( HaSettings.ha_server.name(), "0.0.0.0:6001-6005",
HaSettings.tx_push_factor.name(), "2" ));
try
{
clusterManager.start();
clusterManager.getDefaultCluster().await( allSeesAllAsAvailable() );
GraphDatabaseAPI master = clusterManager.getDefaultCluster().getMaster();
Transaction tx = master.beginTx();
Node node = master.createNode();
long nodeId = node.getId();
node.setProperty( "foo", "bar" );
tx.success();
tx.finish();
HighlyAvailableGraphDatabase anySlave = clusterManager.getDefaultCluster().getAnySlave();
try(Transaction ignore = anySlave.beginTx())
{
node = anySlave.getNodeById( nodeId );
assertThat( node.getProperty( "foo" ).toString(), CoreMatchers.equalTo( "bar" ) );
}
}
finally
{
clusterManager.stop();
}
}
@Test @Ignore("JH: Ignored for by CG in March 2013, needs revisit. I added @ignore instead of commenting out to list this in static analysis.")
public void testArbiterStartsFirstAndThenTwoInstancesJoin() throws Throwable
{
ClusterManager clusterManager = new ClusterManager( ClusterManager.clusterWithAdditionalArbiters( 2, 1 ),
TargetDirectory.forTest( getClass() ).cleanDirectory( "testCluster" ), MapUtil.stringMap());
try
{
clusterManager.start();
clusterManager.getDefaultCluster().await( allSeesAllAsAvailable() );
GraphDatabaseAPI master = clusterManager.getDefaultCluster().getMaster();
Transaction tx = master.beginTx();
master.createNode();
tx.success();
tx.finish();
}
finally
{
clusterManager.stop();
}
}
@Test
public void testInstancesWithConflictingClusterPorts() throws Throwable
{
HighlyAvailableGraphDatabase first = null;
try
{
String masterStoreDir =
TargetDirectory.forTest( getClass() ).cleanDirectory( "testConflictingClusterPortsMaster" ).getAbsolutePath();
first = (HighlyAvailableGraphDatabase) new HighlyAvailableGraphDatabaseFactory().
newHighlyAvailableDatabaseBuilder( masterStoreDir )
.setConfig( ClusterSettings.initial_hosts, "127.0.0.1:5001" )
.setConfig( ClusterSettings.cluster_server, "127.0.0.1:5001" )
.setConfig( ClusterSettings.server_id, "1" )
.setConfig( HaSettings.ha_server, "127.0.0.1:6666" )
.newGraphDatabase();
try
{
String slaveStoreDir =
TargetDirectory.forTest( getClass() ).cleanDirectory( "testConflictingClusterPortsSlave" ).getAbsolutePath();
HighlyAvailableGraphDatabase failed = (HighlyAvailableGraphDatabase) new HighlyAvailableGraphDatabaseFactory().
newHighlyAvailableDatabaseBuilder( slaveStoreDir )
.setConfig( ClusterSettings.initial_hosts, "127.0.0.1:5001" )
.setConfig( ClusterSettings.cluster_server, "127.0.0.1:5001" )
.setConfig( ClusterSettings.server_id, "2" )
.setConfig( HaSettings.ha_server, "127.0.0.1:6667" )
.newGraphDatabase();
failed.shutdown();
fail("Should not start when ports conflict");
}
catch ( Exception e )
{
// good
}
}
finally
{
if ( first != null )
{
first.shutdown();
}
}
}
@Test
public void testInstancesWithConflictingHaPorts() throws Throwable
{
HighlyAvailableGraphDatabase first = null;
try
{
String storeDir =
TargetDirectory.forTest( getClass() ).cleanDirectory( "testConflictingHaPorts" ).getAbsolutePath();
first = (HighlyAvailableGraphDatabase) new HighlyAvailableGraphDatabaseFactory().
newHighlyAvailableDatabaseBuilder( storeDir )
.setConfig( ClusterSettings.initial_hosts, "127.0.0.1:5001" )
.setConfig( ClusterSettings.cluster_server, "127.0.0.1:5001" )
.setConfig( ClusterSettings.server_id, "1" )
.setConfig( HaSettings.ha_server, "127.0.0.1:6666" )
.newGraphDatabase();
try
{
HighlyAvailableGraphDatabase failed = (HighlyAvailableGraphDatabase) new HighlyAvailableGraphDatabaseFactory().
newHighlyAvailableDatabaseBuilder( storeDir )
.setConfig( ClusterSettings.initial_hosts, "127.0.0.1:5001" )
.setConfig( ClusterSettings.cluster_server, "127.0.0.1:5002" )
.setConfig( ClusterSettings.server_id, "2" )
.setConfig( HaSettings.ha_server, "127.0.0.1:6666" )
.newGraphDatabase();
failed.shutdown();
fail( "Should not start when ports conflict" );
}
catch ( Exception e )
{
// good
}
}
finally
{
if ( first != null )
{
first.shutdown();
}
}
}
@Test
public void given4instanceClusterWhenMasterGoesDownThenElectNewMaster() throws Throwable
{
ClusterManager clusterManager = new ClusterManager( fromXml( getClass().getResource( "/fourinstances.xml" ).toURI() ),
TargetDirectory.forTest( getClass() ).cleanDirectory( "4instances" ), MapUtil.stringMap() );
try
{
clusterManager.start();
ClusterManager.ManagedCluster cluster = clusterManager.getDefaultCluster();
cluster.await( allSeesAllAsAvailable() );
logging.getLogger().info( "STOPPING MASTER" );
cluster.shutdown( cluster.getMaster() );
logging.getLogger().info( "STOPPED MASTER" );
cluster.await( ClusterManager.masterAvailable() );
GraphDatabaseService master = cluster.getMaster();
logging.getLogger().info( "CREATE NODE" );
Transaction tx = master.beginTx();
master.createNode();
logging.getLogger().info( "CREATED NODE" );
tx.success();
tx.finish();
logging.getLogger().info( "STOPPING CLUSTER" );
}
finally
{
clusterManager.stop();
}
}
@Test
public void givenEmptyHostListWhenClusterStartupThenFormClusterWithSingleInstance() throws Exception
{
HighlyAvailableGraphDatabase db = (HighlyAvailableGraphDatabase) new HighlyAvailableGraphDatabaseFactory().
newHighlyAvailableDatabaseBuilder( TargetDirectory.forTest( getClass() ).cleanDirectory(
"singleinstance" ).getAbsolutePath() ).
setConfig( ClusterSettings.server_id, "1" ).
setConfig( ClusterSettings.initial_hosts, "" ).
newGraphDatabase();
try
{
System.out.println(db.isAvailable( 10 ));
}
finally
{
db.shutdown();
}
}
}
| false
|
enterprise_ha_src_test_java_org_neo4j_test_ha_ClusterTest.java
|
2,198
|
public class ClusterRule extends ExternalResource
{
private final Class<?> testClass;
private ClusterManager clusterManager;
private File storeDirectory;
private Description description;
public ClusterRule( Class<?> testClass )
{
this.testClass = testClass;
}
public ClusterManager.ManagedCluster startCluster() throws Exception
{
return startCluster( new HighlyAvailableGraphDatabaseFactory(), stringMap() );
}
public ClusterManager.ManagedCluster startCluster(Map<String, String> config) throws Exception
{
return startCluster( new HighlyAvailableGraphDatabaseFactory(), config );
}
public ClusterManager.ManagedCluster startCluster( HighlyAvailableGraphDatabaseFactory databaseFactory )
throws Exception
{
return startCluster( databaseFactory, stringMap() );
}
public ClusterManager.ManagedCluster startCluster( HighlyAvailableGraphDatabaseFactory databaseFactory,
Map<String, String> config ) throws Exception
{
config.putAll(stringMap(
default_timeout.name(), "1s",
tx_push_factor.name(), "0"));
clusterManager = new ClusterManager.Builder( storeDirectory )
.withDbFactory(databaseFactory).build();
try
{
clusterManager.start();
}
catch ( Throwable throwable )
{
throw new RuntimeException( throwable );
}
ClusterManager.ManagedCluster cluster = clusterManager.getDefaultCluster();
cluster.await( masterAvailable() );
return cluster;
}
@Override
public Statement apply( Statement base, Description description )
{
this.description = description;
return super.apply( base, description );
}
@Override
protected void before() throws Throwable
{
this.storeDirectory = TargetDirectory.forTest( testClass ).directoryForDescription( description );
}
@Override
protected void after()
{
try
{
if ( clusterManager != null )
{
clusterManager.stop();
}
}
catch ( Throwable throwable )
{
throwable.printStackTrace();
}
}
}
| false
|
enterprise_ha_src_test_java_org_neo4j_test_ha_ClusterRule.java
|
2,199
|
private class StartNetworkAgainKit implements RepairKit
{
private final HighlyAvailableGraphDatabase db;
private final Iterable<Lifecycle> stoppedServices;
StartNetworkAgainKit( HighlyAvailableGraphDatabase db, Iterable<Lifecycle> stoppedServices )
{
this.db = db;
this.stoppedServices = stoppedServices;
}
@Override
public HighlyAvailableGraphDatabase repair() throws Throwable
{
for ( Lifecycle stoppedService : stoppedServices )
{
stoppedService.start();
}
return db;
}
}
| false
|
enterprise_ha_src_test_java_org_neo4j_test_ha_ClusterManager.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.