Unnamed: 0
int64 0
6.7k
| func
stringlengths 12
89.6k
| target
bool 2
classes | project
stringlengths 45
151
|
|---|---|---|---|
5,500
|
{
@Override
public String apply( StateMachine stateMachine )
{
return stateMachine.getState().toString();
}
}, server.getStateMachines().getStateMachines() );
| false
|
enterprise_ha_src_test_java_org_neo4j_ha_correctness_ClusterInstance.java
|
5,501
|
{
@Override
public void execute( Runnable command )
{
command.run();
}
};
| false
|
enterprise_ha_src_test_java_org_neo4j_ha_correctness_ClusterInstance.java
|
5,502
|
public class UniquenessConstraintValidationHAIT
{
public final @Rule LifeRule life = new LifeRule();
public final @Rule TargetDirectory.TestDirectory targetDir =
testDirForTest( UniquenessConstraintValidationHAIT.class );
public final @Rule OtherThreadRule<Void> otherThread = new OtherThreadRule<>();
@Before
public void startLife()
{
life.start();
}
@Test
public void shouldAllowCreationOfNonConflictingDataOnSeparateHosts() throws Exception
{
// given
ClusterManager.ManagedCluster cluster = startClusterSeededWith(
databaseWithUniquenessConstraint( "Label1", "key1" ) );
HighlyAvailableGraphDatabase slave1 = cluster.getAnySlave();
HighlyAvailableGraphDatabase slave2 = cluster.getAnySlave( /*except:*/slave1 );
// when
Future<Boolean> created;
Transaction tx = slave1.beginTx();
try
{
slave1.createNode( label( "Label1" ) ).setProperty( "key1", "value1" );
created = otherThread.execute( createNode( slave2, "Label1", "key1", "value2" ) );
tx.success();
}
finally
{
tx.finish();
}
// then
assertTrue( "creating non-conflicting data should pass", created.get() );
}
@Test
public void shouldPreventConcurrentCreationOfConflictingDataOnSeparateHosts() throws Exception
{
// given
ClusterManager.ManagedCluster cluster = startClusterSeededWith(
databaseWithUniquenessConstraint( "Label1", "key1" ) );
HighlyAvailableGraphDatabase slave1 = cluster.getAnySlave();
HighlyAvailableGraphDatabase slave2 = cluster.getAnySlave( /*except:*/slave1 );
// when
Future<Boolean> created;
Transaction tx = slave1.beginTx();
try
{
slave1.createNode( label( "Label1" ) ).setProperty( "key1", "value1" );
created = otherThread.execute( createNode( slave2, "Label1", "key1", "value1" ) );
assertThat( otherThread, isWaiting() );
tx.success();
}
finally
{
tx.finish();
}
// then
assertFalse( "creating violating data should fail", created.get() );
}
@Test
public void shouldPreventConcurrentCreationOfConflictingNonStringPropertyOnMasterAndSlave() throws Exception
{
// given
ClusterManager.ManagedCluster cluster = startClusterSeededWith(
databaseWithUniquenessConstraint( "Label1", "key1" ) );
HighlyAvailableGraphDatabase master = cluster.getMaster();
HighlyAvailableGraphDatabase slave = cluster.getAnySlave();
// when
Future<Boolean> created;
Transaction tx = master.beginTx();
try
{
master.createNode( label( "Label1" ) ).setProperty( "key1", 0x0099CC );
created = otherThread.execute( createNode( slave, "Label1", "key1", 0x0099CC ) );
assertThat( otherThread, isWaiting() );
tx.success();
}
finally
{
tx.finish();
}
// then
assertFalse( "creating violating data should fail", created.get() );
}
@Test
public void shouldAllowOtherHostToCompleteIfFirstHostRollsBackTransaction() throws Exception
{
// given
ClusterManager.ManagedCluster cluster = startClusterSeededWith(
databaseWithUniquenessConstraint( "Label1", "key1" ) );
HighlyAvailableGraphDatabase slave1 = cluster.getAnySlave();
HighlyAvailableGraphDatabase slave2 = cluster.getAnySlave( /*except:*/slave1 );
// when
Future<Boolean> created;
Transaction tx = slave1.beginTx();
try
{
slave1.createNode( label( "Label1" ) ).setProperty( "key1", "value1" );
created = otherThread.execute( createNode( slave2, "Label1", "key1", "value1" ) );
assertThat( otherThread, isWaiting() );
tx.failure();
}
finally
{
tx.finish();
}
// then
assertTrue( "creating data that conflicts only with rolled back data should pass", created.get() );
}
private ClusterManager.ManagedCluster startClusterSeededWith( File seedDir )
{
ClusterManager.ManagedCluster cluster = life
.add( new ClusterManager.Builder( targetDir.directory() ).withSeedDir( seedDir ).build() )
.getDefaultCluster();
cluster.await( allSeesAllAsAvailable() );
return cluster;
}
private File databaseWithUniquenessConstraint( String label, String propertyKey )
{
File storeDir = new File( targetDir.directory(), "seed" );
GraphDatabaseService graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( storeDir.getAbsolutePath() );
try
{
Transaction tx = graphDb.beginTx();
try
{
graphDb.schema().constraintFor( label( label ) ).assertPropertyIsUnique( propertyKey ).create();
tx.success();
}
finally
{
tx.finish();
}
}
finally
{
graphDb.shutdown();
}
return storeDir;
}
}
| false
|
enterprise_ha_src_test_java_org_neo4j_ha_UniquenessConstraintValidationHAIT.java
|
5,503
|
public class TransactionMonitoringIT
{
@Test
public void injectedTransactionCountShouldBeMonitored() throws Throwable
{
// GIVEN
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" ) );
EideticTransactionMonitor masterMonitor = new EideticTransactionMonitor();
EideticTransactionMonitor firstSlaveMonitor = new EideticTransactionMonitor();
EideticTransactionMonitor secondSlaveMonitor = new EideticTransactionMonitor();
try
{
clusterManager.start();
clusterManager.getDefaultCluster().await( allSeesAllAsAvailable() );
GraphDatabaseAPI master = clusterManager.getDefaultCluster().getMaster();
master.getDependencyResolver().resolveDependency( Monitors.class ).addMonitorListener(
masterMonitor, XaResourceManager.class.getName(), NeoStoreXaDataSource.DEFAULT_DATA_SOURCE_NAME );
HighlyAvailableGraphDatabase firstSlave = clusterManager.getDefaultCluster().getAnySlave();
firstSlave.getDependencyResolver().resolveDependency( Monitors.class ).addMonitorListener(
firstSlaveMonitor, XaResourceManager.class.getName(), NeoStoreXaDataSource.DEFAULT_DATA_SOURCE_NAME );
HighlyAvailableGraphDatabase secondSlave = clusterManager.getDefaultCluster().getAnySlave( firstSlave );
secondSlave.getDependencyResolver().resolveDependency( Monitors.class ).addMonitorListener(
secondSlaveMonitor, XaResourceManager.class.getName(), NeoStoreXaDataSource.DEFAULT_DATA_SOURCE_NAME );
// WHEN
Transaction tx = master.beginTx();
master.createNode();
tx.success();
tx.finish();
tx = firstSlave.beginTx();
firstSlave.createNode();
tx.success();
tx.finish();
tx = secondSlave.beginTx();
secondSlave.createNode();
tx.success();
tx.finish();
}
finally
{
clusterManager.stop();
}
// THEN
assertEquals( 3, masterMonitor.getCommitCount() );
assertEquals( 0, masterMonitor.getInjectOnePhaseCommitCount() );
assertEquals( 0, masterMonitor.getInjectTwoPhaseCommitCount() );
assertEquals( 1, firstSlaveMonitor.getCommitCount() );
assertEquals( 2, firstSlaveMonitor.getInjectOnePhaseCommitCount() );
assertEquals( 0, firstSlaveMonitor.getInjectTwoPhaseCommitCount() );
assertEquals( 1, secondSlaveMonitor.getCommitCount() );
assertEquals( 2, secondSlaveMonitor.getInjectOnePhaseCommitCount() );
assertEquals( 0, secondSlaveMonitor.getInjectTwoPhaseCommitCount() );
}
@Test
public void pullUpdatesShouldUpdateCounters() throws Throwable
{
// GIVEN
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(), "0" ) );
EideticTransactionMonitor masterMonitor = new EideticTransactionMonitor();
EideticTransactionMonitor firstSlaveMonitor = new EideticTransactionMonitor();
try
{
clusterManager.start();
clusterManager.getDefaultCluster().await( allSeesAllAsAvailable() );
GraphDatabaseAPI master = clusterManager.getDefaultCluster().getMaster();
master.getDependencyResolver().resolveDependency( Monitors.class ).addMonitorListener(
masterMonitor, XaResourceManager.class.getName(), NeoStoreXaDataSource.DEFAULT_DATA_SOURCE_NAME );
HighlyAvailableGraphDatabase firstSlave = clusterManager.getDefaultCluster().getAnySlave();
firstSlave.getDependencyResolver().resolveDependency( Monitors.class ).addMonitorListener(
firstSlaveMonitor, XaResourceManager.class.getName(), NeoStoreXaDataSource.DEFAULT_DATA_SOURCE_NAME );
// WHEN
for ( int i = 0; i < 10; i++ )
{
Transaction tx = master.beginTx();
master.createNode();
tx.success();
tx.finish();
}
firstSlave.getDependencyResolver().resolveDependency( UpdatePuller.class ).pullUpdates();
}
finally
{
clusterManager.stop();
}
// THEN
assertEquals( 0, firstSlaveMonitor.getCommitCount() );
assertEquals( 10, firstSlaveMonitor.getInjectOnePhaseCommitCount() );
assertEquals( 0, firstSlaveMonitor.getInjectTwoPhaseCommitCount() );
}
}
| false
|
enterprise_ha_src_test_java_org_neo4j_ha_TransactionMonitoringIT.java
|
5,504
|
private static class AcquireWriteLock implements WorkerCommand<HighlyAvailableGraphDatabase, Lock>
{
private final Transaction tx;
private final Callable<Node> callable;
public AcquireWriteLock( Transaction tx, Callable<Node> callable )
{
this.tx = tx;
this.callable = callable;
}
@Override
public Lock doWork( HighlyAvailableGraphDatabase state ) throws Exception
{
return tx.acquireWriteLock( callable.call() );
}
}
| false
|
enterprise_ha_src_test_java_org_neo4j_ha_TransactionConstraintsIT.java
|
5,505
|
private static class AcquireReadLockOnReferenceNode implements WorkerCommand<HighlyAvailableGraphDatabase, Lock>
{
private final Transaction tx;
private final Node commonNode;
public AcquireReadLockOnReferenceNode( Transaction tx, Node commonNode )
{
this.tx = tx;
this.commonNode = commonNode;
}
@Override
public Lock doWork( HighlyAvailableGraphDatabase state )
{
return tx.acquireReadLock( commonNode );
}
}
| false
|
enterprise_ha_src_test_java_org_neo4j_ha_TransactionConstraintsIT.java
|
5,506
|
{
@Override
public Node call() throws Exception
{
return node;
}
} ), 1, SECONDS );
| false
|
enterprise_ha_src_test_java_org_neo4j_ha_TransactionConstraintsIT.java
|
5,507
|
Future<Lock> writeLockFuture = thread2.executeDontWait( new AcquireWriteLock( tx2, new Callable<Node>(){
@Override
public Node call() throws Exception
{
return commonNode;
}
} ) );
| false
|
enterprise_ha_src_test_java_org_neo4j_ha_TransactionConstraintsIT.java
|
5,508
|
public class TransactionConstraintsIT extends AbstractClusterTest
{
@Before
public void stableCluster()
{
// Ensure a stable cluster before starting tests
cluster.await( ClusterManager.allSeesAllAsAvailable() );
}
@Test
public void start_tx_as_slave_and_finish_it_after_having_switched_to_master_should_not_succeed() throws Exception
{
// GIVEN
GraphDatabaseService db = cluster.getAnySlave();
takeTheLeadInAnEventualMasterSwitch( db );
// WHEN
Transaction tx = db.beginTx();
try
{
db.createNode().setProperty( "name", "slave" );
tx.success();
}
finally
{
cluster.shutdown( cluster.getMaster() );
assertFinishGetsTransactionFailure( tx );
}
cluster.await( masterAvailable() );
// THEN
assertEquals( db, cluster.getMaster() );
// to prevent a deadlock scenario which occurs if this test exists (and @After starts)
// before the db has recovered from its KERNEL_PANIC
awaitFullyOperational( db );
}
@Test
public void start_tx_as_slave_and_finish_it_after_another_master_being_available_should_not_succeed() throws Exception
{
// GIVEN
HighlyAvailableGraphDatabase db = cluster.getAnySlave();
// WHEN
HighlyAvailableGraphDatabase theOtherSlave;
Transaction tx = db.beginTx();
try
{
db.createNode().setProperty( "name", "slave" );
tx.success();
}
finally
{
theOtherSlave = cluster.getAnySlave( db );
takeTheLeadInAnEventualMasterSwitch( theOtherSlave );
cluster.shutdown( cluster.getMaster() );
assertFinishGetsTransactionFailure( tx );
}
cluster.await( ClusterManager.masterAvailable() );
// THEN
assertFalse( db.isMaster() );
assertTrue( theOtherSlave.isMaster() );
// to prevent a deadlock scenario which occurs if this test exists (and @After starts)
// before the db has recovered from its KERNEL_PANIC
awaitFullyOperational( db );
}
@Test
public void slave_should_not_be_able_to_produce_an_invalid_transaction() throws Exception
{
// GIVEN
HighlyAvailableGraphDatabase aSlave = cluster.getAnySlave();
Node node = createMiniTree( aSlave );
// WHEN
Transaction tx = aSlave.beginTx();
try
{
// Deleting this node isn't allowed since it still has relationships
node.delete();
tx.success();
}
finally
{
// THEN
assertFinishGetsTransactionFailure( tx );
}
}
@Test
public void master_should_not_be_able_to_produce_an_invalid_transaction() throws Exception
{
// GIVEN
HighlyAvailableGraphDatabase master = cluster.getMaster();
Node node = createMiniTree( master );
// WHEN
Transaction tx = master.beginTx();
try
{
// Deleting this node isn't allowed since it still has relationships
node.delete();
tx.success();
}
finally
{
// THEN
assertFinishGetsTransactionFailure( tx );
}
}
@Test
public void write_operation_on_slave_has_to_be_performed_within_a_transaction() throws Exception
{
// GIVEN
HighlyAvailableGraphDatabase aSlave = cluster.getAnySlave();
// WHEN
try
{
aSlave.createNode();
fail( "Shouldn't be able to do a write operation outside a transaction" );
}
catch ( NotInTransactionException e )
{
// THEN
}
}
@Test
public void write_operation_on_master_has_to_be_performed_within_a_transaction() throws Exception
{
// GIVEN
HighlyAvailableGraphDatabase master = cluster.getMaster();
// WHEN
try
{
master.createNode();
fail( "Shouldn't be able to do a write operation outside a transaction" );
}
catch ( NotInTransactionException e )
{
// THEN
}
}
@Test
public void slave_should_not_be_able_to_modify_node_deleted_on_master() throws Exception
{
// GIVEN
// -- node created on slave
HighlyAvailableGraphDatabase aSlave = cluster.getAnySlave();
Node node = createNode( aSlave );
// -- that node delete on master, but the slave doesn't see it yet
deleteNode( cluster.getMaster(), node.getId() );
// WHEN
Transaction tx = aSlave.beginTx();
try
{
node.setProperty( "name", "test" );
fail( "Shouldn't be able to modify a node deleted on master" );
}
catch ( NotFoundException e )
{
// THEN
// -- the transactions gotten back in the response should delete that node
}
finally
{
tx.finish();
}
}
@Test
public void deadlock_detection_involving_two_slaves() throws Exception
{
HighlyAvailableGraphDatabase slave1 = cluster.getAnySlave();
deadlockDetectionBetween( slave1, cluster.getAnySlave( slave1 ) );
}
@Test
public void deadlock_detection_involving_slave_and_master() throws Exception
{
deadlockDetectionBetween( cluster.getAnySlave(), cluster.getMaster() );
}
private void deadlockDetectionBetween( HighlyAvailableGraphDatabase slave1, final HighlyAvailableGraphDatabase slave2 ) throws Exception
{
// GIVEN
// -- two members acquiring a read lock on the same entity
final Node commonNode;
try(Transaction tx = slave1.beginTx())
{
commonNode = slave1.createNode();
tx.success();
}
OtherThreadExecutor<HighlyAvailableGraphDatabase> thread2 = new OtherThreadExecutor<>( "T2", slave2 );
Transaction tx1 = slave1.beginTx();
Transaction tx2 = thread2.execute( new BeginTx() );
tx1.acquireReadLock( commonNode );
thread2.execute( new AcquireReadLockOnReferenceNode( tx2, commonNode ) );
// -- and one of them wanting (and awaiting) to upgrade its read lock to a write lock
Future<Lock> writeLockFuture = thread2.executeDontWait( new AcquireWriteLock( tx2, new Callable<Node>(){
@Override
public Node call() throws Exception
{
return commonNode;
}
} ) );
for ( int i = 0; i < 10; i++ )
{
thread2.waitUntilThreadState( Thread.State.TIMED_WAITING, Thread.State.WAITING );
Thread.sleep(2);
}
try
{
// WHEN
tx1.acquireWriteLock( commonNode );
fail( "Deadlock exception should have been thrown" );
}
catch ( DeadlockDetectedException e )
{
// THEN -- deadlock should be avoided with this exception
}
finally
{
tx1.close();
}
assertNotNull( writeLockFuture.get() );
thread2.execute( new FinishTx( tx2, true ) );
thread2.close();
}
@Ignore( "Known issue where locks acquired from Transaction#acquireXXXLock() methods doesn't get properly released when calling Lock#release() method" )
@Test
public void manually_acquire_and_release_transaction_lock() throws Exception
{
// GIVEN
// -- a slave acquiring a lock on an ubiquitous node
HighlyAvailableGraphDatabase master = cluster.getMaster();
OtherThreadExecutor<HighlyAvailableGraphDatabase> masterWorker = new OtherThreadExecutor<>( "master worker", master );
final Node node = createNode( master );
cluster.sync();
HighlyAvailableGraphDatabase slave = cluster.getAnySlave();
Transaction slaveTx = slave.beginTx();
try
{
Lock lock = slaveTx.acquireWriteLock( slave.getNodeById( node.getId() ) );
// WHEN
// -- the lock is manually released (tx still running)
lock.release();
// THEN
// -- that entity should be able to be locked from another member
Transaction masterTx = masterWorker.execute( new BeginTx() );
masterWorker.execute( new AcquireWriteLock( masterTx, new Callable<Node>()
{
@Override
public Node call() throws Exception
{
return node;
}
} ), 1, SECONDS );
}
finally
{
slaveTx.finish();
masterWorker.close();
}
}
private void takeTheLeadInAnEventualMasterSwitch( GraphDatabaseService db )
{
createNode( db );
}
private Node createNode( GraphDatabaseService db )
{
Transaction tx = db.beginTx();
try
{
Node node = db.createNode();
node.setProperty( "name", "yo" );
tx.success();
return node;
}
finally
{
tx.finish();
}
}
private Node createMiniTree( GraphDatabaseService db )
{
Transaction tx = db.beginTx();
try
{
Node root = db.createNode();
root.createRelationshipTo( db.createNode(), MyRelTypes.TEST );
root.createRelationshipTo( db.createNode(), MyRelTypes.TEST );
tx.success();
return root;
}
finally
{
tx.finish();
}
}
private void deleteNode( HighlyAvailableGraphDatabase db, long id )
{
Transaction tx = db.beginTx();
try
{
db.getNodeById( id ).delete();
tx.success();
}
finally
{
tx.finish();
}
}
@Override
protected void configureClusterMember( GraphDatabaseBuilder builder, String clusterName, int serverId )
{
super.configureClusterMember( builder, clusterName, serverId );
builder.setConfig( HaSettings.tx_push_factor, "0" );
builder.setConfig( HaSettings.pull_interval, "0" );
}
private void assertFinishGetsTransactionFailure( Transaction tx )
{
try
{
tx.finish();
fail( "Transaction shouldn't be able to finish" );
}
catch ( TransactionFailureException e )
{ // Good
}
}
private static class AcquireReadLockOnReferenceNode implements WorkerCommand<HighlyAvailableGraphDatabase, Lock>
{
private final Transaction tx;
private final Node commonNode;
public AcquireReadLockOnReferenceNode( Transaction tx, Node commonNode )
{
this.tx = tx;
this.commonNode = commonNode;
}
@Override
public Lock doWork( HighlyAvailableGraphDatabase state )
{
return tx.acquireReadLock( commonNode );
}
}
private static class AcquireWriteLock implements WorkerCommand<HighlyAvailableGraphDatabase, Lock>
{
private final Transaction tx;
private final Callable<Node> callable;
public AcquireWriteLock( Transaction tx, Callable<Node> callable )
{
this.tx = tx;
this.callable = callable;
}
@Override
public Lock doWork( HighlyAvailableGraphDatabase state ) throws Exception
{
return tx.acquireWriteLock( callable.call() );
}
}
@Rule
public DumpProcessInformationRule dumpInfo = new DumpProcessInformationRule( 1, MINUTES, localVm( System.out ) );
private void awaitFullyOperational( GraphDatabaseService db ) throws InterruptedException
{
long endTime = currentTimeMillis() + MINUTES.toMillis( 1 );
for ( int i = 0; currentTimeMillis() < endTime; i++ )
{
try
{
doABogusTransaction( db );
break;
}
catch ( Exception e )
{
if ( i > 0 && i%10 == 0 )
{
e.printStackTrace();
}
Thread.sleep( 1000 );
}
}
}
private void doABogusTransaction( GraphDatabaseService db ) throws Exception
{
Transaction tx = db.beginTx();
try
{
db.createNode();
}
finally
{
tx.finish();
}
}
}
| false
|
enterprise_ha_src_test_java_org_neo4j_ha_TransactionConstraintsIT.java
|
5,509
|
{
@Override
public void elected( String role, InstanceId electedMember, URI availableAtUri )
{
electedLatch.countDown();
}
} );
| false
|
enterprise_ha_src_test_java_org_neo4j_ha_TestSlaveOnlyCluster.java
|
5,510
|
{
@Override
public ClusterAction apply( Message message )
{
return new MessageDeliveryAction( message );
}
};
| false
|
enterprise_ha_src_test_java_org_neo4j_ha_correctness_MessageDeliveryAction.java
|
5,511
|
public class ProofDatabase
{
private final GraphDatabaseService gds;
private final Map<ClusterState, Node> stateNodes = new HashMap<>();
public ProofDatabase( String location )
{
File dbDir = new File( location );
cleanDbDir( dbDir );
this.gds = new GraphDatabaseFactory().newEmbeddedDatabase( dbDir.getPath() );
}
public Node newState( ClusterState state )
{
try( Transaction tx = gds.beginTx() )
{
Node node = gds.createNode( label( "State" ) );
node.setProperty( "description", state.toString() );
tx.success();
stateNodes.put( state, node );
return node;
}
}
public void newStateTransition( ClusterState originalState,
Pair<ClusterAction, ClusterState> transition )
{
try( Transaction tx = gds.beginTx() )
{
Node stateNode = stateNodes.get( originalState );
if(stateNode == null)
{
System.out.println(originalState);
}
Node subStateNode = newState( transition.other() );
Relationship msg = stateNode.createRelationshipTo( subStateNode, DynamicRelationshipType
.withName( "MESSAGE" ) );
msg.setProperty( "description", transition.first().toString() );
tx.success();
}
}
private void cleanDbDir( File dbDir )
{
if( dbDir.exists())
{
try
{
FileUtils.deleteRecursively( dbDir );
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
} else
{
dbDir.getParentFile().mkdirs();
}
}
public void shutdown()
{
gds.shutdown();
}
public boolean isKnownState( ClusterState state )
{
return stateNodes.containsKey( state );
}
public long numberOfKnownStates()
{
return stateNodes.size();
}
public long id( ClusterState nextState )
{
return stateNodes.get(nextState).getId();
}
public void export( GraphVizExporter graphVizExporter ) throws IOException
{
graphVizExporter.export( gds );
}
}
| false
|
enterprise_ha_src_test_java_org_neo4j_ha_correctness_ProofDatabase.java
|
5,512
|
class ProverTimeouts extends Timeouts
{
private final Map<Object, Pair<ProverTimeout, Long>> timeouts;
private final URI to;
private long time = 0;
public ProverTimeouts( URI to )
{
super(new FixedTimeoutStrategy(1));
this.to = to;
timeouts = new LinkedHashMap<>();
}
private ProverTimeouts( URI to, Map<Object, Pair<ProverTimeout, Long>> timeouts )
{
super( new FixedTimeoutStrategy( 0 ) );
this.to = to;
this.timeouts = new LinkedHashMap<>(timeouts);
}
@Override
public void addMessageProcessor( MessageProcessor messageProcessor )
{
}
@Override
public void setTimeout( Object key, Message<? extends MessageType> timeoutMessage )
{
// Should we add support for using timeout strategies to order the timeouts here?
long timeout = time++;
timeouts.put( key, Pair.of( new ProverTimeout( timeout, timeoutMessage
.setHeader( Message.TO, to.toASCIIString() )
.setHeader( Message.FROM, to.toASCIIString() ) ), timeout ) );
}
@Override
public void cancelTimeout( Object key )
{
timeouts.remove( key );
}
@Override
public void cancelAllTimeouts()
{
timeouts.clear();
}
@Override
public Map<Object, Timeout> getTimeouts()
{
throw new UnsupportedOperationException();
}
@Override
public void tick( long time )
{
// Don't pass this on to the parent class.
}
public ProverTimeouts snapshot()
{
return new ProverTimeouts(to, timeouts);
}
@Override
public boolean equals( Object o )
{
if ( this == o )
{
return true;
}
if ( o == null || getClass() != o.getClass() )
{
return false;
}
ProverTimeouts that = (ProverTimeouts) o;
Iterator<Pair<ProverTimeout,Long>> those = that.timeouts.values().iterator();
Iterator<Pair<ProverTimeout,Long>> mine = timeouts.values().iterator();
while(mine.hasNext())
{
if(!those.hasNext() || !those.next().first().equals( mine.next().first() ))
{
return false;
}
}
if(those.hasNext())
{
return false;
}
return true;
}
@Override
public int hashCode()
{
return timeouts.hashCode();
}
public boolean hasTimeouts()
{
return timeouts.size() > 0;
}
public ClusterAction pop()
{
Map.Entry<Object, Pair<ProverTimeout, Long>> lowestTimeout = nextTimeout();
timeouts.remove( lowestTimeout.getKey() );
return new MessageDeliveryAction( lowestTimeout.getValue().first().getTimeoutMessage() );
}
public ClusterAction peek()
{
Map.Entry<Object, Pair<ProverTimeout, Long>> next = nextTimeout();
if(next != null)
{
return new MessageDeliveryAction( next.getValue().first().getTimeoutMessage() );
}
else
{
return null;
}
}
private Map.Entry<Object, Pair<ProverTimeout, Long>> nextTimeout()
{
Map.Entry<Object, Pair<ProverTimeout, Long>> lowestTimeout = null;
for ( Map.Entry<Object, Pair<ProverTimeout, Long>> current : timeouts.entrySet() )
{
if(lowestTimeout == null || lowestTimeout.getValue().other() > current.getValue().other())
{
lowestTimeout = current;
}
}
return lowestTimeout;
}
class ProverTimeout extends Timeout
{
public ProverTimeout( long timeout, Message<? extends MessageType> timeoutMessage )
{
super( timeout, timeoutMessage );
}
@Override
public int hashCode()
{
return getTimeoutMessage().hashCode();
}
@Override
public boolean equals( Object obj )
{
if(obj.getClass() != getClass())
{
return false;
}
ProverTimeout that = (ProverTimeout)obj;
return getTimeoutMessage().toString().equals( that.getTimeoutMessage().toString() );
}
}
}
| false
|
enterprise_ha_src_test_java_org_neo4j_ha_correctness_ProverTimeouts.java
|
5,513
|
{
@Override
public boolean typeEquals( Class<?> firstType, Class<?> otherType )
{
return firstType == otherType;
}
@Override
public boolean itemEquals( Object lhs, Object rhs )
{
return lhs == rhs || lhs != null && lhs.equals( rhs );
}
};
| false
|
community_kernel_src_main_java_org_neo4j_helpers_ArrayUtil.java
|
5,514
|
{
@Override
public boolean accept( Throwable item )
{
return item.getMessage() != null && item.getMessage().contains( containsMessage ) &&
anyOfClasses.accept( item );
}
} );
| false
|
community_kernel_src_main_java_org_neo4j_helpers_Exceptions.java
|
5,515
|
{
@Override
public boolean accept( Throwable item )
{
for ( Class<? extends Throwable> type : types )
{
if ( type.isAssignableFrom( item.getClass() ) )
{
return true;
}
}
return false;
}
};
| false
|
community_kernel_src_main_java_org_neo4j_helpers_Exceptions.java
|
5,516
|
public class Exceptions
{
private static final String UNEXPECTED_MESSAGE = "Unexpected Exception";
public static <T extends Throwable> T withCause( T exception, Throwable cause )
{
try
{
exception.initCause( cause );
}
catch ( Exception failure )
{
// OK, we did our best, guess there will be no cause
}
return exception;
}
public static RuntimeException launderedException( Throwable exception )
{
return launderedException( UNEXPECTED_MESSAGE, exception );
}
public static RuntimeException launderedException( String messageForUnexpected, Throwable exception )
{
return launderedException( RuntimeException.class, messageForUnexpected, exception );
}
public static <T extends Throwable> T launderedException( Class<T> type, Throwable exception )
{
return launderedException( type, UNEXPECTED_MESSAGE, exception );
}
public static <T extends Throwable> T launderedException( Class<T> type, String messageForUnexpected,
Throwable exception )
{
if ( type.isInstance( exception ) )
{
return type.cast( exception );
}
else if ( exception instanceof Error )
{
throw (Error) exception;
}
else if ( exception instanceof InvocationTargetException )
{
return launderedException( type, messageForUnexpected,
( (InvocationTargetException) exception ).getTargetException() );
}
else if ( exception instanceof RuntimeException )
{
throw (RuntimeException) exception;
}
else
{
throw new RuntimeException( messageForUnexpected, exception );
}
}
/**
* Peels off layers of causes. For example:
*
* MyFarOuterException
* cause: MyOuterException
* cause: MyInnerException
* cause: MyException
* and a toPeel predicate returning true for MyFarOuterException and MyOuterException
* will return MyInnerException. If the predicate peels all exceptions null is returned.
*
* @param exception the outer exception to peel to get to an delegate cause.
* @param toPeel {@link Predicate} for deciding what to peel. {@code true} means
* to peel (i.e. remove), whereas the first {@code false} means stop and return.
* @return the delegate cause of an exception, dictated by the predicate.
*/
public static Throwable peel( Throwable exception, Predicate<Throwable> toPeel )
{
while ( exception != null )
{
if ( !toPeel.accept( exception ) )
{
break;
}
exception = exception.getCause();
}
return exception;
}
public static Predicate<Throwable> exceptionsOfType( final Class<? extends Throwable>... types )
{
return new Predicate<Throwable>()
{
@Override
public boolean accept( Throwable item )
{
for ( Class<? extends Throwable> type : types )
{
if ( type.isAssignableFrom( item.getClass() ) )
{
return true;
}
}
return false;
}
};
}
private Exceptions()
{
// no instances
}
public static Throwable rootCause( Throwable caughtException )
{
if ( null == caughtException )
{
throw new IllegalArgumentException( "Cannot obtain rootCause from (null)" );
}
Throwable root = caughtException;
Throwable cause = root.getCause();
while ( null != cause )
{
root = cause;
cause = cause.getCause();
}
return root;
}
public static String stringify( Throwable cause )
{
try
{
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
PrintStream target = new PrintStream( bytes, true, "UTF-8" );
cause.printStackTrace( target );
target.flush();
return bytes.toString("UTF-8");
}
catch(UnsupportedEncodingException e)
{
cause.printStackTrace(System.err);
return "[ERROR: Unable to serialize stacktrace, UTF-8 not supported.]";
}
}
public static String stringify( Thread thread, StackTraceElement[] elements )
{
StringBuilder builder = new StringBuilder(
"\"" + thread.getName() + "\"" + (thread.isDaemon() ? " daemon": "") +
" prio=" + thread.getPriority() +
" tid=" + thread.getId() +
" " + thread.getState().name().toLowerCase() + "\n" );
builder.append( " " + State.class.getName() + ": " + thread.getState().name().toUpperCase() + "\n" );
for ( StackTraceElement element : elements )
{
builder.append( " at " + element.getClassName() + "." + element.getMethodName() );
if ( element.isNativeMethod() )
{
builder.append( "(Native method)" );
}
else if ( element.getFileName() == null )
{
builder.append( "(Unknown source)" );
}
else
{
builder.append( "(" + element.getFileName() + ":" + element.getLineNumber() + ")" );
}
builder.append( "\n" );
}
return builder.toString();
}
@SuppressWarnings( "rawtypes" )
public static boolean contains( final Throwable cause, final String containsMessage, final Class... anyOfTheseClasses )
{
final Predicate<Throwable> anyOfClasses = isAnyOfClasses( anyOfTheseClasses );
return contains( cause, new Predicate<Throwable>()
{
@Override
public boolean accept( Throwable item )
{
return item.getMessage() != null && item.getMessage().contains( containsMessage ) &&
anyOfClasses.accept( item );
}
} );
}
@SuppressWarnings( "rawtypes" )
public static boolean contains( Throwable cause, Class... anyOfTheseClasses )
{
return contains( cause, isAnyOfClasses( anyOfTheseClasses ) );
}
public static boolean contains( Throwable cause, Predicate<Throwable> toLookFor )
{
while ( cause != null )
{
if ( toLookFor.accept( cause ) )
{
return true;
}
cause = cause.getCause();
}
return false;
}
public static Predicate<Throwable> isAnyOfClasses( final Class... anyOfTheseClasses )
{
return new Predicate<Throwable>()
{
@Override
public boolean accept( Throwable item )
{
for ( Class cls : anyOfTheseClasses )
{
if ( cls.isInstance( item ) )
{
return true;
}
}
return false;
}
};
}
public static <E extends Throwable> E combine( E first, E second )
{
if ( first == null )
{
return second;
}
if ( second == null )
{
return first;
}
Throwable current = first;
while ( current.getCause() != null )
{
current = current.getCause();
}
current.initCause( second );
return first;
}
}
| false
|
community_kernel_src_main_java_org_neo4j_helpers_Exceptions.java
|
5,517
|
public class DaemonThreadFactory
implements ThreadFactory
{
static final AtomicInteger poolNumber = new AtomicInteger( 1 );
final ThreadGroup group;
final AtomicInteger threadNumber = new AtomicInteger( 1 );
final String namePrefix;
public DaemonThreadFactory(String name)
{
SecurityManager s = System.getSecurityManager();
group = ( s != null ) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
namePrefix = name+"-" +
poolNumber.getAndIncrement() +
"-thread-";
}
public Thread newThread( Runnable r )
{
Thread t = new Thread( group, r,
namePrefix + threadNumber.getAndIncrement(),
0 );
if( !t.isDaemon() )
{
t.setDaemon( true );
}
if( t.getPriority() != Thread.NORM_PRIORITY )
{
t.setPriority( Thread.NORM_PRIORITY );
}
return t;
}
}
| false
|
community_kernel_src_main_java_org_neo4j_helpers_DaemonThreadFactory.java
|
5,518
|
public class Counter
{
private volatile long count;
private static final AtomicLongFieldUpdater<Counter> COUNT = AtomicLongFieldUpdater.newUpdater(
Counter.class, "count" );
public void inc()
{
COUNT.incrementAndGet( this );
}
public long count()
{
return count;
}
}
| false
|
community_kernel_src_main_java_org_neo4j_helpers_Counter.java
|
5,519
|
{
@Override
public long currentTimeMillis()
{
return System.currentTimeMillis();
}
};
| false
|
community_kernel_src_main_java_org_neo4j_helpers_Clock.java
|
5,520
|
public class BazService extends FooService {
}
| false
|
community_kernel_src_test_java_org_neo4j_helpers_BazService.java
|
5,521
|
public class BarService extends FooService {
}
| false
|
community_kernel_src_test_java_org_neo4j_helpers_BarService.java
|
5,522
|
public abstract class ArrayUtil
{
/**
* I can't believe this method is missing from {@link Arrays}.
* @see Arrays#toString(byte[]) for similar functionality.
*/
public static String toString( Object array )
{
assert array.getClass().isArray() : array + " is not an array";
StringBuilder result = new StringBuilder();
String separator = "[";
for ( int size = Array.getLength( array ), i = 0; i < size; i++ )
{
result.append( separator ).append( Array.get( array, i ) );
separator = ", ";
}
return result.append( ']' ).toString();
}
public static int hashCode( Object array )
{
assert array.getClass().isArray() : array + " is not an array";
int length = Array.getLength( array ), result = length;
for ( int i = 0; i < length; i++ )
{
result = 31 * result + Array.get( array, i ).hashCode();
}
return result;
}
public interface ArrayEquality
{
boolean typeEquals( Class<?> firstType, Class<?> otherType );
boolean itemEquals( Object firstArray, Object otherArray );
}
public static final ArrayEquality DEFAULT_ARRAY_EQUALITY = new ArrayEquality()
{
@Override
public boolean typeEquals( Class<?> firstType, Class<?> otherType )
{
return firstType == otherType;
}
@Override
public boolean itemEquals( Object lhs, Object rhs )
{
return lhs == rhs || lhs != null && lhs.equals( rhs );
}
};
public static boolean equals( Object firstArray, Object otherArray )
{
return equals( firstArray, otherArray, DEFAULT_ARRAY_EQUALITY );
}
/**
* I also can't believe this method is missing from {@link Arrays}.
* Both arguments must be arrays of some type.
*
* @param firstArray value to compare to the other value
* @param otherArray value to compare to the first value
* @param equality equality logic
*
* @see Arrays#equals(byte[], byte[]) for similar functionality.
*/
public static boolean equals( Object firstArray, Object otherArray, ArrayEquality equality )
{
assert firstArray.getClass().isArray() : firstArray + " is not an array";
assert otherArray.getClass().isArray() : otherArray + " is not an array";
int length;
if ( equality.typeEquals( firstArray.getClass(), otherArray.getClass() )
&& (length = Array.getLength( firstArray )) == Array.getLength( otherArray ) )
{
for ( int i = 0; i < length; i++ )
{
if ( !equality.itemEquals( Array.get( firstArray, i ), Array.get( otherArray, i ) ) )
{
return false;
}
}
return true;
}
return false;
}
public static Object clone( Object array )
{
if ( array instanceof Object[] )
{
return ((Object[]) array).clone();
}
if ( array instanceof boolean[] )
{
return ((boolean[]) array).clone();
}
if ( array instanceof byte[] )
{
return ((byte[]) array).clone();
}
if ( array instanceof short[] )
{
return ((short[]) array).clone();
}
if ( array instanceof char[] )
{
return ((char[]) array).clone();
}
if ( array instanceof int[] )
{
return ((int[]) array).clone();
}
if ( array instanceof long[] )
{
return ((long[]) array).clone();
}
if ( array instanceof float[] )
{
return ((float[]) array).clone();
}
if ( array instanceof double[] )
{
return ((double[]) array).clone();
}
throw new IllegalArgumentException( "Not an array type: " + array.getClass() );
}
private ArrayUtil()
{ // No instances allowed
}
}
| false
|
community_kernel_src_main_java_org_neo4j_helpers_ArrayUtil.java
|
5,523
|
class ProverTimeout extends Timeout
{
public ProverTimeout( long timeout, Message<? extends MessageType> timeoutMessage )
{
super( timeout, timeoutMessage );
}
@Override
public int hashCode()
{
return getTimeoutMessage().hashCode();
}
@Override
public boolean equals( Object obj )
{
if(obj.getClass() != getClass())
{
return false;
}
ProverTimeout that = (ProverTimeout)obj;
return getTimeoutMessage().toString().equals( that.getTimeoutMessage().toString() );
}
}
| false
|
enterprise_ha_src_test_java_org_neo4j_ha_correctness_ProverTimeouts.java
|
5,524
|
public class Args
{
private final String[] args;
private final Map<String, String> map = new HashMap<String, String>();
private final List<String> orphans = new ArrayList<String>();
// private final Set<String> touchedParameters = new HashSet<String>();
// private final BitSet touchedOrphans = new BitSet();
/**
* Suitable for main( String[] args )
* @param args the arguments to parse.
*/
public Args( String... args )
{
this.args = args;
parseArgs( args );
}
public Args( Map<String, String> source )
{
this.args = null;
putAll( source );
}
public String[] source()
{
return this.args;
}
public Map<String, String> asMap()
{
return new HashMap<String, String>( this.map );
}
public boolean has( String key )
{
return this.map.containsKey( key );
}
public String get( String key, String defaultValue )
{
String value = this.map.get( key );
return value != null ? value : defaultValue;
}
public String get( String key, String defaultValueIfNotFound, String defaultValueIfNoValue )
{
String value = this.map.get( key );
if ( value != null )
{
return value;
}
return this.map.containsKey( key ) ? defaultValueIfNoValue : defaultValueIfNotFound;
}
public Number getNumber( String key, Number defaultValue )
{
String value = this.map.get( key );
return value != null ? Double.parseDouble( value ) : defaultValue;
}
public Boolean getBoolean( String key, Boolean defaultValue )
{
String value = this.map.get( key );
return value != null ? Boolean.parseBoolean( value ) : defaultValue;
}
public Boolean getBoolean( String key, Boolean defaultValueIfNotFound,
Boolean defaultValueIfNoValue )
{
String value = this.map.get( key );
if ( value != null )
{
return Boolean.parseBoolean( value );
}
return this.map.containsKey( key ) ? defaultValueIfNoValue : defaultValueIfNotFound;
}
public <T extends Enum<T>> T getEnum( Class<T> enumClass, String key, T defaultValue )
{
String raw = this.map.get( key );
if ( raw == null )
return defaultValue;
for ( T candidate : enumClass.getEnumConstants() )
if ( candidate.name().equals( raw ) )
return candidate;
throw new IllegalArgumentException( "No enum instance '" + raw + "' in " + enumClass.getName() );
}
public Object put( String key, String value )
{
return map.put( key, value );
}
public void putAll( Map<String, String> source )
{
this.map.putAll( source );
}
public List<String> orphans()
{
return new ArrayList<String>( this.orphans );
}
public String[] asArgs()
{
List<String> list = new ArrayList<String>();
for ( String orphan : orphans )
{
String quote = orphan.contains( " " ) ? " " : "";
list.add( quote + orphan + quote );
}
for ( Map.Entry<String, String> entry : map.entrySet() )
{
String quote = entry.getKey().contains( " " ) || entry.getValue().contains( " " ) ? " " : "";
list.add( quote + (entry.getKey().length() > 1 ? "--" : "-") + entry.getKey() + "=" + entry.getValue() + quote );
}
return list.toArray( new String[0] );
}
@Override
public String toString()
{
StringBuilder builder = new StringBuilder();
for ( String arg : asArgs() )
builder.append( builder.length() > 0 ? " " : "" ).append( arg );
return builder.toString();
}
private static boolean isOption( String arg )
{
return arg.startsWith( "-" ) && arg.length() > 1;
}
private static String stripOption( String arg )
{
while ( arg.length() > 0 && arg.charAt( 0 ) == '-' )
{
arg = arg.substring( 1 );
}
return arg;
}
private void parseArgs( String[] args )
{
for ( int i = 0; i < args.length; i++ )
{
String arg = args[ i ];
if ( isOption( arg ) )
{
arg = stripOption( arg );
int equalIndex = arg.indexOf( '=' );
if ( equalIndex != -1 )
{
String key = arg.substring( 0, equalIndex );
String value = arg.substring( equalIndex + 1 );
if ( value.length() > 0 )
{
map.put( key, value );
}
}
else
{
String key = arg;
int nextIndex = i+1;
String value = nextIndex < args.length ?
args[ nextIndex ] : null;
value = ( value == null || isOption( value ) ) ? null : value;
if ( value != null )
{
i = nextIndex;
}
map.put( key, value );
}
}
else
{
orphans.add( arg );
}
}
}
/* public void printUntouched( PrintStream out )
{
boolean first = true;
for ( Map.Entry<String, String> parameter : map.entrySet() )
{
if ( touchedParameters.contains( parameter ) ) continue;
if ( first )
{
first = false;
out.println( "Untouched parameters:" );
}
out.println( " " + parameter.getKey() + ":" + parameter.getValue() );
}
first = true;
for ( int i = 0; i < orphans.size(); i++ )
{
if ( touchedOrphans.get( i ) ) continue;
if ( first )
{
first = false;
out.println( "Untouched orphans:" );
}
out.println( "(" + i + "):" + orphans.get( i ) );
}
}
public Map<String, String> getUntouchedParameters()
{
return null;
}
public Iterable<String> getUntouchedOrphans()
{
return null;
}*/
public static String jarUsage( Class<?> main, String... params )
{
StringBuilder usage = new StringBuilder( "USAGE: java [-cp ...] " );
try
{
String jar = main.getProtectionDomain().getCodeSource().getLocation().getPath();
usage.append( "-jar " ).append( jar );
}
catch ( Exception ex )
{
// ignore
}
usage.append( ' ' ).append( main.getCanonicalName() );
for ( String param : params )
{
usage.append( ' ' ).append( param );
}
return usage.toString();
}
}
| false
|
community_kernel_src_main_java_org_neo4j_helpers_Args.java
|
5,525
|
{
@Override
public boolean accept( File file )
{
return file.isFile() && file.getName().endsWith( ".jar" );
}
};
| false
|
enterprise_ha_src_test_java_org_neo4j_ha_upgrade_Utils.java
|
5,526
|
public class Utils
{
private Utils()
{
}
public static String assembleClassPathFromPackage( File directory )
{
List<File> jarFiles = new ArrayList<File>();
FileFilter jarFilter = new FileFilter()
{
@Override
public boolean accept( File file )
{
return file.isFile() && file.getName().endsWith( ".jar" );
}
};
gatherFiles( jarFiles, directory, jarFilter );
StringBuilder classpath = new StringBuilder();
for ( File file : jarFiles )
classpath.append( classpath.length() > 0 ? File.pathSeparator : "" ).append( file.getAbsolutePath() );
return classpath.toString();
}
private static void gatherFiles( List<File> jarFiles, File directory, FileFilter filter )
{
for ( File file : directory.listFiles() )
{
if ( file.isDirectory() )
gatherFiles( jarFiles, file, filter );
else if ( filter.accept( file ) )
jarFiles.add( file );
}
}
public static File downloadAndUnpack( String url, File targetDirectory, String downloadedFileName ) throws IOException
{
URL website = new URL( url );
File downloaded = new File( targetDirectory, downloadedFileName + ".zip" );
if ( !downloaded.exists() )
{
File tmpDownload = new File( downloaded.getAbsolutePath() + ".tmp" );
deleteFile( tmpDownload );
copyURLToFile( website, tmpDownload );
moveFile( tmpDownload, downloaded );
}
File unpacked = new File( targetDirectory, downloadedFileName );
if ( !unpacked.exists() )
{
File tmpUnpack = new File( unpacked.getAbsolutePath() + "-tmp" );
deleteRecursively( tmpUnpack );
tmpUnpack.mkdirs();
unzip( downloaded, tmpUnpack );
FileUtils.moveFile( tmpUnpack, unpacked );
}
return unpacked;
}
public static List<File> unzip( File zipFile, File targetDir ) throws IOException
{
List<File> files = new ArrayList<File>();
ZipFile zip = new ZipFile( zipFile );
try
{
zip = new ZipFile( zipFile );
for ( ZipEntry entry : Collections.list( zip.entries() ) )
{
File target = new File( targetDir, entry.getName() );
target.getParentFile().mkdirs();
if ( !entry.isDirectory() )
{
InputStream input = zip.getInputStream( entry );
try
{
copyInputStreamToFile( input, target );
files.add( target );
}
finally
{
closeQuietly( input );
}
}
}
return files;
}
finally
{
zip.close();
}
}
public static void copyInputStreamToFile( InputStream stream, File target ) throws IOException
{
OutputStream out = null;
try
{
out = new FileOutputStream( target );
copy( stream, out );
}
finally
{
closeQuietly( out );
}
}
public static Process execJava( String classPath, String mainClass, String... args ) throws Exception
{
List<String> allArgs = new ArrayList<String>( asList( "java", "-cp", classPath, mainClass ) );
allArgs.addAll( asList( args ) );
return getRuntime().exec( allArgs.toArray( new String[0] ) );
}
}
| false
|
enterprise_ha_src_test_java_org_neo4j_ha_upgrade_Utils.java
|
5,527
|
@Ignore( "Keep this test around as it's a very simple and 'close' test to quickly verify rolling upgrades" )
public class RollingUpgradeIT
{
private static final String OLD_VERSION = "2.0.0";
private final TargetDirectory DIR = TargetDirectory.forTest( getClass() );
private final File DBS_DIR = DIR.cleanDirectory( "dbs" );
private LegacyDatabase[] legacyDbs;
private GraphDatabaseAPI[] newDbs;
@Test
public void doRollingUpgradeFromPreviousVersionWithMasterLast() throws Throwable
{
/* High level scenario:
* 1 Have a cluster of 3 instances running <old version>
* 1.1 Download a <old version> package
* 1.2 Unpack the <old version> package
* 1.4 Assembly classpath and start 3 JVMs running <old version>
* 1.5 Create some data in the cluster
* 2 Go over each one restarting into <this version>
* 2.1 Grab a JVM and kill it
* 2.2 Start that db inside this test JVM, which will run <this version>
* 2.3 Perform a write transaction to the current master and see that it picks it up
* 2.4 Perform a write transaction to to this instance and see that master picks it up
* 3 Make sure the cluster functions after each one has been restarted
* 3.1 Do basic transactions on master/slaves.
* 3.2 Do a master switch
* 3.3 Restart one slave
* 3.4 Take down the instances and do consistency check */
try
{
startOldVersionCluster();
rollOverToNewVersion();
verify();
}
catch ( Throwable e )
{
e.printStackTrace();
throw e;
}
}
private void debug( String message )
{
debug( message, true );
}
private void debug( String message, boolean enter )
{
String string = "RUT " + message;
if ( enter )
{
System.out.println( string );
}
else
{
System.out.print( string );
}
}
@After
public void cleanUp() throws Exception
{
if ( legacyDbs != null )
{
for ( int i = 0; i < legacyDbs.length; i++ )
{
stop( i );
}
}
if ( newDbs != null )
{
for ( GraphDatabaseService db : newDbs )
{
db.shutdown();
}
}
}
private void startOldVersionCluster() throws Exception
{
debug( "Downloading " + OLD_VERSION + " package" );
File oldVersionPackage = downloadAndUnpack(
"http://download.neo4j.org/artifact?edition=enterprise&version=" + OLD_VERSION + "&distribution=zip",
DIR.cacheDirectory( "download" ), OLD_VERSION + "-enterprise" );
String classpath = assembleClassPathFromPackage( oldVersionPackage );
debug( "Starting " + OLD_VERSION + " cluster in separate jvms" );
@SuppressWarnings( "rawtypes" )
Future[] legacyDbFutures = new Future[3];
for ( int i = 0; i < legacyDbFutures.length; i++ )
{
legacyDbFutures[i] = LegacyDatabaseImpl.start( classpath, new File( DBS_DIR, "" + i ), config( i ) );
debug( " Started " + i );
}
legacyDbs = new LegacyDatabase[legacyDbFutures.length];
for ( int i = 0; i < legacyDbFutures.length; i++ )
{
legacyDbs[i] = (LegacyDatabase) legacyDbFutures[i].get();
}
for ( LegacyDatabase db : legacyDbs )
{
debug( " Awaiting " + db.getStoreDir() + " to start" );
db.awaitStarted( 10, TimeUnit.SECONDS );
debug( " " + db.getStoreDir() + " fully started" );
}
for ( int i = 0; i < legacyDbs.length; i++ )
{
String name = "initial-" + i;
long node = legacyDbs[i].createNode( name );
for ( LegacyDatabase db : legacyDbs )
{
db.verifyNodeExists( node, name );
}
}
debug( OLD_VERSION + " cluster fully operational" );
}
private Map<String, String> config( int serverId ) throws UnknownHostException
{
String localhost = InetAddress.getLocalHost().getHostAddress();
Map<String, String> result = MapUtil.stringMap(
server_id.name(), "" + serverId,
cluster_server.name(), localhost + ":" + ( 5000+serverId ),
ha_server.name(), localhost + ":" + ( 6000+serverId ),
initial_hosts.name(), localhost + ":" + 5000 + "," + localhost + ":" + 5001 + "," + localhost + ":" + 5002 );
return result;
}
private void rollOverToNewVersion() throws Exception
{
debug( "Starting to roll over to current version" );
Pair<LegacyDatabase, Integer> master = findOutWhoIsMaster();
newDbs = new GraphDatabaseAPI[legacyDbs.length];
for ( int i = 0; i < legacyDbs.length; i++ )
{
LegacyDatabase legacyDb = legacyDbs[i];
if ( legacyDb == master.first() )
{ // Roll over the master last
continue;
}
rollOver( legacyDb, i );
}
rollOver( master.first(), master.other() );
}
private void rollOver( LegacyDatabase legacyDb, int i ) throws Exception
{
String storeDir = legacyDb.getStoreDir();
stop( i );
Thread.sleep( 30000 );
debug( "Starting " + i + " as current version" );
// start that db up in this JVM
newDbs[i] = (GraphDatabaseAPI) new HighlyAvailableGraphDatabaseFactory()
.newHighlyAvailableDatabaseBuilder( storeDir )
.setConfig( config( i ) )
.newGraphDatabase();
debug( "Started " + i + " as current version" );
legacyDbs[i] = null;
// issue transaction and see that it propagates
String name = "upgraded-" + i;
long node = createNodeWithRetry( newDbs[i], name );
debug( "Node created on " + i );
for ( int j = 0; j < i; j++ )
{
if ( legacyDbs[i] != null )
{
legacyDbs[j].verifyNodeExists( node, name );
debug( "Verified on legacy db " + j );
}
}
for ( int j = 0; j < newDbs.length; j++ )
{
if ( newDbs[j] != null )
{
verifyNodeExists( newDbs[j], node, name );
debug( "Verified on new db " + j );
}
}
}
private Pair<LegacyDatabase,Integer> findOutWhoIsMaster()
{
try
{
for ( int i = 0; i < legacyDbs.length; i++ )
{
LegacyDatabase db = legacyDbs[i];
if ( db.isMaster() )
{
return Pair.of( db, i );
}
}
}
catch ( RemoteException e )
{
throw new RuntimeException( e );
}
throw new IllegalStateException( "No master" );
}
private void stop( int i )
{
try
{
LegacyDatabase legacyDb = legacyDbs[i];
if ( legacyDb != null )
{
legacyDb.stop();
legacyDbs[i] = null;
}
}
catch ( RemoteException e )
{
// OK
}
}
private void verify( )
{
// TODO Auto-generated method stub
}
private long createNodeWithRetry( GraphDatabaseService db, String name ) throws InterruptedException
{
long end = currentTimeMillis() + SECONDS.toMillis( 60*2 );
Exception exception = null;
while ( currentTimeMillis() < end )
{
try
{
return createNode( db, name );
}
catch ( Exception e )
{
// OK
exception = e;
// Jiffy is a less well known SI unit for time equal to 1024 millis, aka binary second
debug( "Master not switched yet, retrying in a jiffy (" + e + ")" );
sleep( 1024 ); // 1024, because why the hell not
}
}
throw launderedException( exception );
}
private long createNode( GraphDatabaseService db, String name )
{
Transaction tx = db.beginTx();
try
{
Node node = db.createNode();
node.setProperty( "name", name );
tx.success();
return node.getId();
}
finally
{
tx.finish();
}
}
private void verifyNodeExists( GraphDatabaseAPI db, long id, String name )
{
try ( Transaction tx = db.beginTx() )
{
db.getDependencyResolver().resolveDependency( UpdatePuller.class ).pullUpdates();
for ( Node node : at( db ).getAllNodes() )
{
if ( name.equals( node.getProperty( "name", null ) ) )
{
return;
}
}
tx.success();
}
fail( "Node " + id + " with name '" + name + "' not found" );
}
}
| false
|
enterprise_ha_src_test_java_org_neo4j_ha_upgrade_RollingUpgradeIT.java
|
5,528
|
{
@Override
public LegacyDatabase call() throws Exception
{
long endTime = currentTimeMillis() + SECONDS.toMillis( 10000 );
while ( currentTimeMillis() < endTime )
{
try
{
return (LegacyDatabase) rmiLocation.getBoundObject();
}
catch ( RemoteException e )
{
// OK
sleep( 100 );
}
}
process.destroy();
throw new IllegalStateException( "Couldn't get remote to legacy database" );
}
} );
| false
|
enterprise_ha_src_test_java_org_neo4j_ha_upgrade_LegacyDatabaseImpl.java
|
5,529
|
public class LegacyDatabaseImpl extends UnicastRemoteObject implements LegacyDatabase
{
// This has to be adapted to the way HA GDB is started in the specific old version it's used for.
public static void main( String[] args ) throws Exception
{
Args arguments = new Args( args );
String storeDir = arguments.orphans().get( 0 );
GraphDatabaseAPI db = (GraphDatabaseAPI) new HighlyAvailableGraphDatabaseFactory()
.newHighlyAvailableDatabaseBuilder( storeDir )
.setConfig( arguments.asMap() )
.newGraphDatabase();
LegacyDatabaseImpl legacyDb = new LegacyDatabaseImpl( storeDir, db );
rmiLocation( parseInt( arguments.orphans().get( 1 ) ) ).bind( legacyDb );
}
private final GraphDatabaseAPI db;
private final String storeDir;
public LegacyDatabaseImpl( String storeDir, GraphDatabaseAPI db ) throws RemoteException
{
super();
this.storeDir = storeDir;
this.db = db;
}
public static Future<LegacyDatabase> start( String classpath, File storeDir, Map<String, String> config )
throws Exception
{
List<String> args = new ArrayList<String>();
args.add( storeDir.getAbsolutePath() );
int rmiPort = 7000 + parseInt( config.get( "ha.server_id" ) );
args.add( "" + rmiPort );
args.addAll( asList( new Args( config ).asArgs() ) );
final Process process = execJava( appendNecessaryTestClasses( classpath ),
LegacyDatabaseImpl.class.getName(), args.toArray( new String[0] ) );
new ProcessStreamHandler( process, false ).launch();
final RmiLocation rmiLocation = rmiLocation( rmiPort );
ExecutorService executor = newSingleThreadExecutor();
Future<LegacyDatabase> future = executor.submit( new Callable<LegacyDatabase>()
{
@Override
public LegacyDatabase call() throws Exception
{
long endTime = currentTimeMillis() + SECONDS.toMillis( 10000 );
while ( currentTimeMillis() < endTime )
{
try
{
return (LegacyDatabase) rmiLocation.getBoundObject();
}
catch ( RemoteException e )
{
// OK
sleep( 100 );
}
}
process.destroy();
throw new IllegalStateException( "Couldn't get remote to legacy database" );
}
} );
executor.shutdown();
return future;
}
private static String appendNecessaryTestClasses( String classpath )
{
for ( String path : getProperty( "java.class.path" ).split( File.pathSeparator ) )
{
if ( path.contains( "test-classes" ) && !path.contains( File.separator + "kernel" + File.separator ) )
{
classpath = classpath + File.pathSeparator + path;
}
}
return classpath;
}
private static RmiLocation rmiLocation( int rmiPort )
{
return RmiLocation.location( "127.0.0.1", rmiPort, "remote" );
}
@Override
public int stop()
{
db.shutdown();
System.exit( 0 );
return 0;
}
@Override
public String getStoreDir()
{
return storeDir;
}
@Override
public void awaitStarted( long time, TimeUnit unit )
{
db.beginTx().finish();
}
@Override
public long createNode( String name )
{
Transaction tx = db.beginTx();
try
{
Node node = db.createNode();
node.setProperty( "name", name );
tx.success();
return node.getId();
}
finally
{
tx.finish();
}
}
@Override
public void verifyNodeExists( long id, String name )
{
try
{
db.getDependencyResolver().resolveDependency( UpdatePuller.class ).pullUpdates();
}
catch ( Exception e )
{
throw launderedException( e );
}
try ( Transaction tx = db.beginTx() )
{
for ( Node node : at( db ).getAllNodes() )
{
if ( name.equals( node.getProperty( "name", null ) ) )
{
return;
}
}
tx.success();
}
fail( "Node " + id + " with name '" + name + "' not found" );
}
@Override
public boolean isMaster() throws RemoteException
{
return ((HighlyAvailableGraphDatabase)db).isMaster();
}
}
| false
|
enterprise_ha_src_test_java_org_neo4j_ha_upgrade_LegacyDatabaseImpl.java
|
5,530
|
public class TestProverTimeouts
{
@Test
public void equalsShouldBeLogicalAndNotExact() throws Exception
{
// Given
ProverTimeouts timeouts1 = new ProverTimeouts( new URI("http://asd") );
ProverTimeouts timeouts2 = new ProverTimeouts( new URI("http://asd") );
timeouts1.setTimeout( "a", Message.internal( ProposerMessage.join ) );
timeouts1.setTimeout( "b", Message.internal( ProposerMessage.join ) );
timeouts1.setTimeout( "c", Message.internal( ProposerMessage.join ) );
timeouts2.setTimeout( "b", Message.internal( ProposerMessage.join ) );
timeouts2.setTimeout( "c", Message.internal( ProposerMessage.join ) );
// When
timeouts1.cancelTimeout( "a" );
// Then
assertEquals(timeouts1, timeouts2);
}
}
| false
|
enterprise_ha_src_test_java_org_neo4j_ha_correctness_TestProverTimeouts.java
|
5,531
|
public class TestProver
{
@Test
public void aClusterSnapshotShouldEqualItsOrigin() throws Exception
{
// Given
Logging logging = new TestLogging();
ClusterConfiguration config = new ClusterConfiguration( "default",
logging.getMessagesLog( ClusterConfiguration.class ),
"cluster://localhost:5001",
"cluster://localhost:5002",
"cluster://localhost:5003" );
ClusterState state = new ClusterState(
asList(
newClusterInstance( new InstanceId( 1 ), new URI("cluster://localhost:5001"), config, logging ),
newClusterInstance( new InstanceId( 2 ), new URI("cluster://localhost:5002"), config, logging ),
newClusterInstance( new InstanceId( 3 ), new URI("cluster://localhost:5003"), config, logging )),
emptySetOf( ClusterAction.class ));
// When
ClusterState snapshot = state.snapshot();
// Then
assertEquals(state, snapshot);
assertEquals(state.hashCode(), snapshot.hashCode());
}
@Test
public void twoStatesWithSameSetupAndPendingMessagesShouldBeEqual() throws Exception
{
// Given
Logging logging = new TestLogging();
ClusterConfiguration config = new ClusterConfiguration( "default",
logging.getMessagesLog( ClusterConfiguration.class ),
"cluster://localhost:5001",
"cluster://localhost:5002",
"cluster://localhost:5003" );
ClusterState state = new ClusterState(
asList(
newClusterInstance( new InstanceId( 1 ), new URI("cluster://localhost:5001"), config, logging ),
newClusterInstance( new InstanceId( 2 ), new URI("cluster://localhost:5002"), config, logging ),
newClusterInstance( new InstanceId( 3 ), new URI("cluster://localhost:5003"), config, logging )),
emptySetOf( ClusterAction.class ));
// When
ClusterState firstState = state.performAction( new MessageDeliveryAction( Message.to( ClusterMessage.join,
new URI( "cluster://localhost:5002" ), new Object[]{"defaultcluster", new URI[]{new URI( "cluster://localhost:5003" )}} ).setHeader( Message.CONVERSATION_ID, "-1" ).setHeader( Message.FROM, "cluster://localhost:5002" ) ) );
ClusterState secondState = state.performAction( new MessageDeliveryAction( Message.to( ClusterMessage.join, new URI( "cluster://localhost:5002" ), new Object[]{"defaultcluster", new URI[]{new URI( "cluster://localhost:5003" )}} ).setHeader( Message.CONVERSATION_ID, "-1" ).setHeader( Message.FROM, "cluster://localhost:5002" ) ) );
// Then
assertEquals(firstState, secondState);
assertEquals(firstState.hashCode(), secondState.hashCode());
}
}
| false
|
enterprise_ha_src_test_java_org_neo4j_ha_correctness_TestProver.java
|
5,532
|
static final class OpenEndedProgressListener extends SinglePartProgressListener
{
private int lastReported = 0;
OpenEndedProgressListener( Indicator indicator )
{
super( indicator, 0 );
}
@Override
public void done()
{
indicator.completeProcess();
}
@Override
void update( long progress )
{
started();
int current = (int) (progress / indicator.reportResolution());
if ( current > lastReported )
{
indicator.progress( lastReported, current );
lastReported = current;
}
}
}
| false
|
community_kernel_src_main_java_org_neo4j_helpers_progress_ProgressListener.java
|
5,533
|
public abstract class ProgressMonitorFactory
{
public static final ProgressMonitorFactory NONE = new ProgressMonitorFactory()
{
@Override
protected Indicator newIndicator( String process )
{
return Indicator.NONE;
}
@Override
protected Indicator.OpenEnded newOpenEndedIndicator( String process, int resolution )
{
return Indicator.NONE;
}
};
public static ProgressMonitorFactory textual( final OutputStream out )
{
try
{
return textual( new OutputStreamWriter( out, "UTF-8" ) );
}
catch ( UnsupportedEncodingException e )
{
throw new RuntimeException( e );
}
}
public static ProgressMonitorFactory textual( final Writer out )
{
return new ProgressMonitorFactory()
{
@Override
protected Indicator newIndicator( String process )
{
return new Indicator.Textual( process, writer() );
}
@Override
protected Indicator.OpenEnded newOpenEndedIndicator( String process, int resolution )
{
return new Indicator.OpenEndedTextual( process, writer(), resolution );
}
private PrintWriter writer()
{
return out instanceof PrintWriter ? (PrintWriter) out : new PrintWriter( out );
}
};
}
public final MultiPartBuilder multipleParts( String process )
{
return new MultiPartBuilder( this, process );
}
public final ProgressListener singlePart( String process, long totalCount )
{
return new ProgressListener.SinglePartProgressListener( newIndicator( process ), totalCount );
}
public final ProgressListener openEnded( String process, int resolution )
{
return new ProgressListener.OpenEndedProgressListener( newOpenEndedIndicator( process, resolution ) );
}
protected abstract Indicator newIndicator( String process );
protected abstract Indicator.OpenEnded newOpenEndedIndicator( String process, int resolution );
public static class MultiPartBuilder
{
private Aggregator aggregator;
private Set<String> parts = new HashSet<String>();
private Completion completion = null;
private MultiPartBuilder( ProgressMonitorFactory factory, String process )
{
this.aggregator = new Aggregator(factory.newIndicator( process ));
}
public ProgressListener progressForPart( String part, long totalCount )
{
if ( aggregator == null )
{
throw new IllegalStateException( "Builder has been completed." );
}
if ( !parts.add( part ) )
{
throw new IllegalArgumentException( String.format( "Part '%s' has already been defined.", part ) );
}
ProgressListener.MultiPartProgressListener progress = new ProgressListener.MultiPartProgressListener( aggregator, part, totalCount );
aggregator.add( progress );
return progress;
}
public Completion build()
{
if ( aggregator != null )
{
completion = aggregator.initialize();
}
aggregator = null;
parts = null;
return completion;
}
}
}
| false
|
community_kernel_src_main_java_org_neo4j_helpers_progress_ProgressMonitorFactory.java
|
5,534
|
public class IndexActivationFailedKernelException extends KernelException
{
public IndexActivationFailedKernelException( Throwable cause, String message )
{
super( Status.Schema.IndexCreationFailure, cause, message );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_api_exceptions_index_IndexActivationFailedKernelException.java
|
5,535
|
public class LevelSelectorOrderer extends
AbstractSelectorOrderer<Pair<AtomicInteger, TraversalBranch[]>>
{
private final boolean stopDescentOnResult;
private final TotalDepth totalDepth = new TotalDepth();
private final int maxDepth;
public LevelSelectorOrderer( BranchSelector startSelector, BranchSelector endSelector,
boolean stopDescentOnResult, int maxDepth )
{
super( startSelector, endSelector );
this.stopDescentOnResult = stopDescentOnResult;
this.maxDepth = maxDepth;
}
protected Pair<AtomicInteger, TraversalBranch[]> initialState()
{
return Pair.<AtomicInteger, TraversalBranch[]> of( new AtomicInteger(),
new TraversalBranch[] {null} );
}
@Override
public TraversalBranch next( TraversalContext metadata )
{
TraversalBranch branch = nextBranchFromCurrentSelector( metadata, false );
Pair<AtomicInteger, TraversalBranch[]> state = getStateForCurrentSelector();
AtomicInteger previousDepth = state.first();
if ( branch != null && branch.length() == previousDepth.get() )
{ // Same depth as previous branch returned from this side.
return branch;
}
else
{ // A different depth than previous branch
if ( branch != null )
totalDepth.set( currentSide(), branch.length() );
if ( (stopDescentOnResult && metadata.getNumberOfPathsReturned() > 0) ||
totalDepth.get() > maxDepth+1 )
{
nextSelector();
// return getStateForCurrentSelector().other().poll();
return null;
}
if ( branch != null )
{
previousDepth.set( branch.length() );
state.other()[0] = branch;
}
BranchSelector otherSelector = nextSelector();
Pair<AtomicInteger, TraversalBranch[]> otherState = getStateForCurrentSelector();
TraversalBranch otherBranch = otherState.other()[0];
if ( otherBranch != null )
{
otherState.other()[0] = null;
return otherBranch;
}
otherBranch = otherSelector.next( metadata );
return otherBranch != null ? otherBranch : branch;
}
}
private static class TotalDepth
{
private int out;
private int in;
void set( Direction side, int depth )
{
switch ( side )
{
case OUTGOING: out = depth; break;
case INCOMING: in = depth; break;
}
}
int get()
{
return out+in;
}
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_LevelSelectorOrderer.java
|
5,536
|
public class LabelIT
{
@Test
public void creatingIndexOnMasterShouldHaveSlavesBuildItAsWell() throws Throwable
{
// GIVEN
ClusterManager.ManagedCluster cluster = startCluster( clusterOfSize( 3 ) );
org.neo4j.kernel.ha.HighlyAvailableGraphDatabase slave1 = cluster.getAnySlave();
org.neo4j.kernel.ha.HighlyAvailableGraphDatabase slave2 = cluster.getAnySlave(/*except*/slave1);
Label label = label( "Person" );
// WHEN
TransactionContinuation txOnSlave1 = createNodeAndKeepTxOpen( slave1, label );
TransactionContinuation txOnSlave2 = createNodeAndKeepTxOpen( slave2, label );
commit(slave1, txOnSlave1);
commit(slave2, txOnSlave2);
// THEN
assertEquals( getLabelId( slave1, label ), getLabelId( slave2, label ) );
}
private long getLabelId( HighlyAvailableGraphDatabase db, Label label ) throws LabelNotFoundKernelException
{
try ( Transaction ignore = db.beginTx() )
{
ThreadToStatementContextBridge bridge = db.getDependencyResolver().resolveDependency(
ThreadToStatementContextBridge.class );
return bridge.instance().readOperations().labelGetForName( label.name() );
}
}
private void commit( HighlyAvailableGraphDatabase db, TransactionContinuation txc ) throws Exception
{
txc.resume();
txc.commit();
}
private TransactionContinuation createNodeAndKeepTxOpen( HighlyAvailableGraphDatabase db, Label label )
throws SystemException
{
TransactionContinuation txc = new TransactionContinuation( db );
txc.begin();
db.createNode( label );
txc.suspend();
return txc;
}
private final File storeDir = TargetDirectory.forTest( getClass() ).makeGraphDbDir();
private ClusterManager clusterManager;
private ClusterManager.ManagedCluster startCluster( ClusterManager.Provider provider ) throws Throwable
{
return startCluster( provider, new HighlyAvailableGraphDatabaseFactory() );
}
private ClusterManager.ManagedCluster startCluster( ClusterManager.Provider provider,
HighlyAvailableGraphDatabaseFactory dbFactory ) throws Throwable
{
clusterManager = new ClusterManager( provider, storeDir, stringMap(
default_timeout.name(), "1s", tx_push_factor.name(), "0" ),
new HashMap<Integer, Map<String,String>>(), dbFactory );
clusterManager.start();
ClusterManager.ManagedCluster cluster = clusterManager.getDefaultCluster();
cluster.await( allSeesAllAsAvailable() );
return cluster;
}
@After
public void after() throws Throwable
{
if ( clusterManager != null )
clusterManager.stop();
}
private static class TransactionContinuation
{
private final HighlyAvailableGraphDatabase db;
private final TransactionManager txManager;
private Transaction graphDbTx;
private javax.transaction.Transaction jtaTx;
private TransactionContinuation( HighlyAvailableGraphDatabase db ) {
this.db = db;
txManager = db.getDependencyResolver().resolveDependency( TransactionManager.class );
}
public void begin()
{
graphDbTx = db.beginTx();
}
public void suspend() throws SystemException
{
jtaTx = txManager.suspend();
}
public void resume() throws Exception
{
txManager.resume( jtaTx );
}
public void commit()
{
graphDbTx.close();
}
}
}
| false
|
enterprise_ha_src_test_java_org_neo4j_kernel_LabelIT.java
|
5,537
|
@Deprecated
public class KernelEventHandlers
implements Lifecycle
{
private final List<KernelEventHandler> kernelEventHandlers = new CopyOnWriteArrayList<>();
private final StringLogger log;
public KernelEventHandlers(StringLogger log)
{
this.log = log;
}
@Override
public void init()
throws Throwable
{
}
@Override
public void start()
throws Throwable
{
}
@Override
public void stop()
throws Throwable
{
}
@Override
public void shutdown()
throws Throwable
{
for( KernelEventHandler kernelEventHandler : kernelEventHandlers )
{
kernelEventHandler.beforeShutdown();
}
}
public KernelEventHandler registerKernelEventHandler( KernelEventHandler handler )
{
if( this.kernelEventHandlers.contains( handler ) )
{
return handler;
}
// Some algo for putting it in the right place
for( KernelEventHandler registeredHandler : this.kernelEventHandlers )
{
KernelEventHandler.ExecutionOrder order =
handler.orderComparedTo( registeredHandler );
int index = this.kernelEventHandlers.indexOf( registeredHandler );
if( order == KernelEventHandler.ExecutionOrder.BEFORE )
{
this.kernelEventHandlers.add( index, handler );
return handler;
}
else if( order == KernelEventHandler.ExecutionOrder.AFTER )
{
this.kernelEventHandlers.add( index + 1, handler );
return handler;
}
}
this.kernelEventHandlers.add( handler );
return handler;
}
public KernelEventHandler unregisterKernelEventHandler( KernelEventHandler handler )
{
if( !kernelEventHandlers.remove( handler ) )
{
throw new IllegalStateException( handler + " isn't registered" );
}
return handler;
}
public void kernelPanic( ErrorState error, Throwable cause )
{
for( KernelEventHandler handler : kernelEventHandlers )
{
try
{
handler.kernelPanic( error );
} catch( Throwable e )
{
if(cause != null)
{
log.error( "FATAL: Error while handling kernel panic.", new MultipleCauseException( "This " +
"exception combines the error from the kernel event handler with the reason the event " +
"was triggered in the first place.", asList( e, cause ) ) );
}
else
{
log.error( "FATAL: Error while handling kernel panic.", e );
}
}
}
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_KernelEventHandlers.java
|
5,538
|
private static class Versions extends KernelDiagnostics
{
private final Class<? extends GraphDatabaseService> graphDb;
private final StoreId storeId;
public Versions( Class<? extends GraphDatabaseService> graphDb, NeoStoreXaDataSource ds )
{
this.graphDb = graphDb;
this.storeId = ds.getStoreId();
}
@Override
void dump( StringLogger logger )
{
logger.logMessage( "Graph Database: " + graphDb.getName() + " " + storeId );
logger.logMessage( "Kernel version: " + Version.getKernel() );
logger.logMessage( "Neo4j component versions:" );
for ( Version componentVersion : Service.load( Version.class ) )
{
logger.logMessage( " " + componentVersion + "; revision: " + componentVersion.getRevision() );
}
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_KernelDiagnostics.java
|
5,539
|
private static class StoreFiles extends KernelDiagnostics implements Visitor<StringLogger.LineLogger,
RuntimeException>
{
private final File storeDir;
private static String FORMAT_DATE_ISO = "yyyy-MM-dd'T'HH:mm:ssZ";
final private SimpleDateFormat dateFormat;
private StoreFiles( String storeDir )
{
this.storeDir = new File( storeDir );
TimeZone tz = TimeZone.getDefault();
dateFormat = new SimpleDateFormat( FORMAT_DATE_ISO );
dateFormat.setTimeZone( tz );
}
@Override
void dump( StringLogger logger )
{
logger.logLongMessage( getDiskSpace( storeDir ) + "\nStorage files: (filename : modification date - size)", this, true );
}
@Override
public boolean visit( StringLogger.LineLogger logger )
{
logStoreFiles( logger, " ", storeDir );
return false;
}
private long logStoreFiles( StringLogger.LineLogger logger, String prefix, File dir )
{
if ( !dir.isDirectory() )
{
return 0;
}
File[] files = dir.listFiles();
if ( files == null )
{
logger.logLine( prefix + "<INACCESSIBLE>" );
return 0;
}
long total = 0;
for ( File file : files )
{
long size;
String filename = file.getName();
if ( file.isDirectory() )
{
logger.logLine( prefix + filename + ":" );
size = logStoreFiles( logger, prefix + " ", file );
filename = "- Total";
} else
{
size = file.length();
}
String fileModificationDate = getFileModificationDate( file );
String bytes = Format.bytes( size );
String fileInformation = String.format( "%s%s: %s - %s", prefix, filename, fileModificationDate, bytes );
logger.logLine( fileInformation );
total += size;
}
return total;
}
private String getFileModificationDate( File file )
{
Date modifiedDate = new Date( file.lastModified() );
return dateFormat.format( modifiedDate );
}
private String getDiskSpace( File storeDir )
{
long free = storeDir.getFreeSpace();
long total = storeDir.getTotalSpace();
long percentage = total != 0 ? (free * 100 / total) : 0;
return String.format( "Disk space on partition (Total / Free / Free %%): %s / %s / %s", total, free, percentage );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_KernelDiagnostics.java
|
5,540
|
@Deprecated
abstract class KernelDiagnostics implements DiagnosticsProvider
{
static void register( DiagnosticsManager manager, InternalAbstractGraphDatabase graphdb, NeoStoreXaDataSource ds )
{
manager.prependProvider( new Versions( graphdb.getClass(), ds ) );
ds.registerDiagnosticsWith( manager );
manager.appendProvider( new StoreFiles( graphdb.getStoreDir() ) );
}
private static class Versions extends KernelDiagnostics
{
private final Class<? extends GraphDatabaseService> graphDb;
private final StoreId storeId;
public Versions( Class<? extends GraphDatabaseService> graphDb, NeoStoreXaDataSource ds )
{
this.graphDb = graphDb;
this.storeId = ds.getStoreId();
}
@Override
void dump( StringLogger logger )
{
logger.logMessage( "Graph Database: " + graphDb.getName() + " " + storeId );
logger.logMessage( "Kernel version: " + Version.getKernel() );
logger.logMessage( "Neo4j component versions:" );
for ( Version componentVersion : Service.load( Version.class ) )
{
logger.logMessage( " " + componentVersion + "; revision: " + componentVersion.getRevision() );
}
}
}
private static class StoreFiles extends KernelDiagnostics implements Visitor<StringLogger.LineLogger,
RuntimeException>
{
private final File storeDir;
private static String FORMAT_DATE_ISO = "yyyy-MM-dd'T'HH:mm:ssZ";
final private SimpleDateFormat dateFormat;
private StoreFiles( String storeDir )
{
this.storeDir = new File( storeDir );
TimeZone tz = TimeZone.getDefault();
dateFormat = new SimpleDateFormat( FORMAT_DATE_ISO );
dateFormat.setTimeZone( tz );
}
@Override
void dump( StringLogger logger )
{
logger.logLongMessage( getDiskSpace( storeDir ) + "\nStorage files: (filename : modification date - size)", this, true );
}
@Override
public boolean visit( StringLogger.LineLogger logger )
{
logStoreFiles( logger, " ", storeDir );
return false;
}
private long logStoreFiles( StringLogger.LineLogger logger, String prefix, File dir )
{
if ( !dir.isDirectory() )
{
return 0;
}
File[] files = dir.listFiles();
if ( files == null )
{
logger.logLine( prefix + "<INACCESSIBLE>" );
return 0;
}
long total = 0;
for ( File file : files )
{
long size;
String filename = file.getName();
if ( file.isDirectory() )
{
logger.logLine( prefix + filename + ":" );
size = logStoreFiles( logger, prefix + " ", file );
filename = "- Total";
} else
{
size = file.length();
}
String fileModificationDate = getFileModificationDate( file );
String bytes = Format.bytes( size );
String fileInformation = String.format( "%s%s: %s - %s", prefix, filename, fileModificationDate, bytes );
logger.logLine( fileInformation );
total += size;
}
return total;
}
private String getFileModificationDate( File file )
{
Date modifiedDate = new Date( file.lastModified() );
return dateFormat.format( modifiedDate );
}
private String getDiskSpace( File storeDir )
{
long free = storeDir.getFreeSpace();
long total = storeDir.getTotalSpace();
long percentage = total != 0 ? (free * 100 / total) : 0;
return String.format( "Disk space on partition (Total / Free / Free %%): %s / %s / %s", total, free, percentage );
}
}
@Override
public String getDiagnosticsIdentifier()
{
return getClass().getDeclaringClass().getSimpleName() + ":" + getClass().getSimpleName();
}
@Override
public void acceptDiagnosticsVisitor( Object visitor )
{
// nothing visits ConfigurationLogging
}
@Override
public void dump( DiagnosticsPhase phase, StringLogger log )
{
if ( phase.isInitialization() || phase.isExplicitlyRequested() )
{
dump( log );
}
}
abstract void dump( StringLogger logger );
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_KernelDiagnostics.java
|
5,541
|
private class Kernel extends KernelData
{
Kernel( String desiredId )
{
super( new Config( config( desiredId ) ) );
kernels.add( this );
}
@Override
public Version version()
{
throw new UnsupportedOperationException();
}
@Override
public GraphDatabaseAPI graphDatabase()
{
throw new UnsupportedOperationException();
}
@Override
public void shutdown()
{
super.shutdown();
kernels.remove( this );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_KernelDataTest.java
|
5,542
|
{
@Override
public void evaluate() throws Throwable
{
try
{
base.evaluate();
}
finally
{
for ( Kernel kernel : kernels.toArray( new Kernel[kernels.size()] ) )
{
kernel.shutdown();
}
kernels.clear();
}
}
};
| false
|
community_kernel_src_test_java_org_neo4j_kernel_KernelDataTest.java
|
5,543
|
{
@Override
public Statement apply( final Statement base, Description description )
{
return new Statement()
{
@Override
public void evaluate() throws Throwable
{
try
{
base.evaluate();
}
finally
{
for ( Kernel kernel : kernels.toArray( new Kernel[kernels.size()] ) )
{
kernel.shutdown();
}
kernels.clear();
}
}
};
}
};
| false
|
community_kernel_src_test_java_org_neo4j_kernel_KernelDataTest.java
|
5,544
|
public class KernelDataTest
{
@Test
public void shouldGenerateUniqueInstanceIdentifiers() throws Exception
{
// given
Kernel kernel1 = new Kernel( null );
// when
Kernel kernel2 = new Kernel( null );
// then
assertNotNull( kernel1.instanceId() );
assertNotNull( kernel2.instanceId() );
assertFalse( kernel1.instanceId().equals( kernel2.instanceId() ) );
}
@Test
public void shouldReuseInstanceIdentifiers() throws Exception
{
// given
Kernel kernel = new Kernel( null );
String instanceId = kernel.instanceId();
kernel.shutdown();
// when
kernel = new Kernel( null );
// then
assertEquals( instanceId, kernel.instanceId() );
}
@Test
public void shouldAllowConfigurationOfInstanceId() throws Exception
{
// when
Kernel kernel = new Kernel( "myInstance" );
// then
assertEquals( "myInstance", kernel.instanceId() );
}
@Test
public void shouldGenerateInstanceIdentifierWhenNullConfigured() throws Exception
{
// when
Kernel kernel = new Kernel( null );
// then
assertEquals( kernel.instanceId(), kernel.instanceId().trim() );
assertTrue( kernel.instanceId().length() > 0 );
}
@Test
public void shouldGenerateInstanceIdentifierWhenEmptyStringConfigured() throws Exception
{
// when
Kernel kernel = new Kernel( "" );
// then
assertEquals( kernel.instanceId(), kernel.instanceId().trim() );
assertTrue( kernel.instanceId().length() > 0 );
}
@Test
public void shouldNotAllowMultipleInstancesWithTheSameConfiguredInstanceId() throws Exception
{
// given
new Kernel( "myInstance" );
// when
try
{
new Kernel( "myInstance" );
fail( "should have thrown exception" );
}
// then
catch ( IllegalStateException e )
{
assertEquals( "There is already a kernel started with forced_kernel_id='myInstance'.", e.getMessage() );
}
}
@Test
public void shouldAllowReuseOfConfiguredInstanceIdAfterShutdown() throws Exception
{
// given
new Kernel( "myInstance" ).shutdown();
// when
Kernel kernel = new Kernel( "myInstance" );
// then
assertEquals( "myInstance", kernel.instanceId() );
}
private class Kernel extends KernelData
{
Kernel( String desiredId )
{
super( new Config( config( desiredId ) ) );
kernels.add( this );
}
@Override
public Version version()
{
throw new UnsupportedOperationException();
}
@Override
public GraphDatabaseAPI graphDatabase()
{
throw new UnsupportedOperationException();
}
@Override
public void shutdown()
{
super.shutdown();
kernels.remove( this );
}
}
private final Collection<Kernel> kernels = new HashSet<Kernel>();
private static Map<String, String> config( String desiredId )
{
HashMap<String, String> config = new HashMap<String, String>();
if ( desiredId != null )
{
config.put( KernelData.forced_id.name(), desiredId );
}
return config;
}
@Rule
public final TestRule shutDownRemainingKernels = new TestRule()
{
@Override
public Statement apply( final Statement base, Description description )
{
return new Statement()
{
@Override
public void evaluate() throws Throwable
{
try
{
base.evaluate();
}
finally
{
for ( Kernel kernel : kernels.toArray( new Kernel[kernels.size()] ) )
{
kernel.shutdown();
}
kernels.clear();
}
}
};
}
};
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_KernelDataTest.java
|
5,545
|
@Deprecated
public abstract class KernelData
{
public static final Setting<String> forced_id = GraphDatabaseSettings.forced_kernel_id;
private static final Map<String, KernelData> instances = new ConcurrentHashMap<String, KernelData>();
private static synchronized String newInstance( KernelData instance )
{
String instanceId = instance.configuration.get( forced_id );
if ( instanceId == null || instanceId.equals( "" ) )
{
for ( int i = 0; i < instances.size() + 1; i++ )
{
instanceId = Integer.toString( i );
if ( !instances.containsKey( instanceId ) )
{
break;
}
}
}
if ( instances.containsKey( instanceId ) )
{
throw new IllegalStateException(
"There is already a kernel started with " + forced_id.name() + "='" + instanceId + "'." );
}
instances.put( instanceId, instance );
return instanceId;
}
private static synchronized void removeInstance( String instanceId )
{
if (instances.remove( instanceId ) == null)
throw new IllegalArgumentException( "No kernel found with instance id "+instanceId );
}
private final String instanceId;
private final Config configuration;
protected KernelData( Config configuration )
{
this.configuration = configuration;
this.instanceId = newInstance( this );
}
public final String instanceId()
{
return instanceId;
}
@Override
public final int hashCode()
{
return instanceId.hashCode();
}
@Override
public final boolean equals( Object obj )
{
return obj instanceof KernelData && instanceId.equals( ((KernelData) obj).instanceId );
}
public abstract Version version();
public Config getConfig()
{
return configuration;
}
public abstract GraphDatabaseAPI graphDatabase();
public void shutdown()
{
removeInstance( instanceId );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_KernelData.java
|
5,546
|
private static class PropertyValueFilteringNodeIdIterator extends AbstractPrimitiveLongIterator
{
private final PrimitiveLongIterator nodesWithLabel;
private final ReadOperations statement;
private final int propertyKeyId;
private final Object value;
PropertyValueFilteringNodeIdIterator( PrimitiveLongIterator nodesWithLabel, ReadOperations statement,
int propertyKeyId, Object value )
{
this.nodesWithLabel = nodesWithLabel;
this.statement = statement;
this.propertyKeyId = propertyKeyId;
this.value = value;
computeNext();
}
@Override
protected void computeNext()
{
for ( boolean hasNext = nodesWithLabel.hasNext(); hasNext; hasNext = nodesWithLabel.hasNext() )
{
long nextValue = nodesWithLabel.next();
try
{
if ( statement.nodeGetProperty( nextValue, propertyKeyId ).valueEquals( value ) )
{
next( nextValue );
return;
}
}
catch ( EntityNotFoundException e )
{
// continue to the next node
}
}
endReached();
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_InternalAbstractGraphDatabase.java
|
5,547
|
class DependencyResolverImpl extends DependencyResolver.Adapter
{
private <T> T resolveKnownSingleDependency( Class<T> type )
{
if ( type.equals( Map.class ) )
{
return type.cast( getConfig().getParams() );
}
else if ( type.equals( Config.class ) )
{
return type.cast( getConfig() );
}
else if ( GraphDatabaseService.class.isAssignableFrom( type )
&& type.isInstance( InternalAbstractGraphDatabase.this ) )
{
return type.cast( InternalAbstractGraphDatabase.this );
}
else if ( TransactionManager.class.isAssignableFrom( type ) && type.isInstance( txManager ) )
{
return type.cast( txManager );
}
else if ( LockManager.class.isAssignableFrom( type ) && type.isInstance( lockManager ) )
{
// Locks used to ensure pessimistic concurrency control between transactions
return type.cast( lockManager );
}
else if ( LockService.class.isAssignableFrom( type )
&& type.isInstance( neoDataSource.getLockService() ) )
{
// Locks used to control concurrent access to the store files
return type.cast( neoDataSource.getLockService() );
}
else if( StoreFactory.class.isAssignableFrom( type ) && type.isInstance( storeFactory ) )
{
return type.cast( storeFactory );
}
else if ( StringLogger.class.isAssignableFrom( type ) && type.isInstance( msgLog ) )
{
return type.cast( msgLog );
}
else if ( Logging.class.isAssignableFrom( type ) && type.isInstance( logging ) )
{
return type.cast( logging );
}
else if ( IndexStore.class.isAssignableFrom( type ) && type.isInstance( indexStore ) )
{
return type.cast( indexStore );
}
else if ( XaFactory.class.isAssignableFrom( type ) && type.isInstance( xaFactory ) )
{
return type.cast( xaFactory );
}
else if ( XaDataSourceManager.class.isAssignableFrom( type ) && type.isInstance( xaDataSourceManager ) )
{
return type.cast( xaDataSourceManager );
}
else if ( FileSystemAbstraction.class.isAssignableFrom( type ) && type.isInstance( fileSystem ) )
{
return type.cast( fileSystem );
}
else if ( Guard.class.isAssignableFrom( type ) && type.isInstance( guard ) )
{
return type.cast( guard );
}
else if ( IndexProviders.class.isAssignableFrom( type ) && type.isInstance( indexManager ) )
{
return type.cast( indexManager );
}
else if ( KernelData.class.isAssignableFrom( type ) && type.isInstance( extensions ) )
{
return type.cast( extensions );
}
else if ( TransactionInterceptorProviders.class.isAssignableFrom( type )
&& type.isInstance( transactionInterceptorProviders ) )
{
return type.cast( transactionInterceptorProviders );
}
else if ( KernelExtensions.class.isAssignableFrom( type ) && type.isInstance( kernelExtensions ) )
{
return type.cast( kernelExtensions );
}
else if ( NodeManager.class.isAssignableFrom( type ) && type.isInstance( nodeManager ) )
{
return type.cast( nodeManager );
}
else if ( TransactionStateFactory.class.isAssignableFrom( type ) && type.isInstance( stateFactory ) )
{
return type.cast( stateFactory );
}
else if ( TxIdGenerator.class.isAssignableFrom( type ) && type.isInstance( txIdGenerator ) )
{
return type.cast( txIdGenerator );
}
else if ( DiagnosticsManager.class.isAssignableFrom( type ) && type.isInstance( diagnosticsManager ) )
{
return type.cast( diagnosticsManager );
}
else if ( RelationshipTypeTokenHolder.class.isAssignableFrom( type ) && type.isInstance( relationshipTypeTokenHolder ) )
{
return type.cast( relationshipTypeTokenHolder );
}
else if ( PropertyKeyTokenHolder.class.isAssignableFrom( type ) && type.isInstance( propertyKeyTokenHolder ) )
{
return type.cast( propertyKeyTokenHolder );
}
else if ( LabelTokenHolder.class.isAssignableFrom( type ) && type.isInstance( labelTokenHolder ) )
{
return type.cast( labelTokenHolder );
}
else if ( KernelPanicEventGenerator.class.isAssignableFrom( type ) )
{
return type.cast( kernelPanicEventGenerator );
}
else if ( LifeSupport.class.isAssignableFrom( type ) )
{
return type.cast( life );
}
else if ( Monitors.class.isAssignableFrom( type ) )
{
return type.cast( monitors );
}
else if ( PersistenceManager.class.isAssignableFrom( type ) && type.isInstance( persistenceManager ) )
{
return type.cast( persistenceManager );
}
else if ( ThreadToStatementContextBridge.class.isAssignableFrom( type )
&& type.isInstance( statementContextProvider ) )
{
return type.cast( statementContextProvider );
}
else if ( CacheAccessBackDoor.class.isAssignableFrom( type ) && type.isInstance( cacheBridge ) )
{
return type.cast( cacheBridge );
}
else if ( StoreLockerLifecycleAdapter.class.isAssignableFrom( type ) && type.isInstance( storeLocker ) )
{
return type.cast( storeLocker );
}
else if ( IndexManager.class.equals( type )&& type.isInstance( indexManager ) )
{
return type.cast( indexManager );
}
else if ( IndexingService.class.isAssignableFrom( type )
&& type.isInstance( neoDataSource.getIndexService() ) )
{
return type.cast( neoDataSource.getIndexService() );
}
else if ( JobScheduler.class.isAssignableFrom( type ) && type.isInstance( jobScheduler ) )
{
return type.cast( jobScheduler );
}
else if ( LabelScanStore.class.isAssignableFrom( type )
&& type.isInstance( neoDataSource.getLabelScanStore() ) )
{
return type.cast( neoDataSource.getLabelScanStore() );
}
else if ( NeoStoreProvider.class.isAssignableFrom( type ) )
{
return type.cast( neoDataSource );
}
else if ( IdGeneratorFactory.class.isAssignableFrom( type ) )
{
return type.cast( idGeneratorFactory );
}
else if ( Monitors.class.isAssignableFrom( type ) )
{
return type.cast( monitors );
}
else if ( RemoteTxHook.class.isAssignableFrom( type ) )
{
return type.cast( txHook );
}
else if ( DependencyResolver.class.equals( type ) )
{
return type.cast( DependencyResolverImpl.this );
}
else if ( KernelHealth.class.isAssignableFrom( type ) )
{
return (T) kernelHealth;
}
return null;
}
@Override
public <T> T resolveDependency( Class<T> type, SelectionStrategy selector )
{
// Try known single dependencies
T result = resolveKnownSingleDependency( type );
if ( result != null )
{
return selector.select( type, Iterables.option( result ) );
}
// Try with kernel extensions
return kernelExtensions.resolveDependency( type, selector );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_InternalAbstractGraphDatabase.java
|
5,548
|
private class DefaultTxEventSyncHookFactory implements TxEventSyncHookFactory
{
@Override
public TransactionEventsSyncHook create()
{
return transactionEventHandlers.hasHandlers() ?
new TransactionEventsSyncHook( transactionEventHandlers, txManager ) : null;
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_InternalAbstractGraphDatabase.java
|
5,549
|
protected final class DefaultKernelData extends KernelData implements Lifecycle
{
private final GraphDatabaseAPI graphDb;
public DefaultKernelData( Config config, GraphDatabaseAPI graphDb )
{
super( config );
this.graphDb = graphDb;
}
@Override
public Version version()
{
return Version.getKernel();
}
@Override
public GraphDatabaseAPI graphDatabase()
{
return graphDb;
}
@Override
public void init() throws Throwable
{
}
@Override
public void start() throws Throwable
{
}
@Override
public void stop() throws Throwable
{
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_InternalAbstractGraphDatabase.java
|
5,550
|
{
@Override
public void run()
{
// Restart
try
{
life.stop();
life.start();
msgLog.logMessage( "Database restarted with the following configuration changes:" +
change );
}
catch ( LifecycleException e )
{
msgLog.logMessage( "Could not restart database", e );
}
}
} );
| false
|
community_kernel_src_main_java_org_neo4j_kernel_InternalAbstractGraphDatabase.java
|
5,551
|
{
Executor executor = Executors.newSingleThreadExecutor( new DaemonThreadFactory( "Database configuration " +
"restart" ) );
@Override
public void notifyConfigurationChanges( final Iterable<ConfigurationChange> change )
{
executor.execute( new Runnable()
{
@Override
public void run()
{
// Restart
try
{
life.stop();
life.start();
msgLog.logMessage( "Database restarted with the following configuration changes:" +
change );
}
catch ( LifecycleException e )
{
msgLog.logMessage( "Could not restart database", e );
}
}
} );
}
};
| false
|
community_kernel_src_main_java_org_neo4j_kernel_InternalAbstractGraphDatabase.java
|
5,552
|
class ConfigurationChangedRestarter extends LifecycleAdapter
{
private final ConfigurationChangeListener listener = new ConfigurationChangeListener()
{
Executor executor = Executors.newSingleThreadExecutor( new DaemonThreadFactory( "Database configuration " +
"restart" ) );
@Override
public void notifyConfigurationChanges( final Iterable<ConfigurationChange> change )
{
executor.execute( new Runnable()
{
@Override
public void run()
{
// Restart
try
{
life.stop();
life.start();
msgLog.logMessage( "Database restarted with the following configuration changes:" +
change );
}
catch ( LifecycleException e )
{
msgLog.logMessage( "Could not restart database", e );
}
}
} );
}
};
@Override
public void start() throws Throwable
{
config.addConfigurationChangeListener( listener );
}
@Override
public void stop() throws Throwable
{
config.removeConfigurationChangeListener( listener );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_InternalAbstractGraphDatabase.java
|
5,553
|
public static class Configuration
{
public static final Setting<Boolean> read_only = GraphDatabaseSettings.read_only;
public static final Setting<Boolean> use_memory_mapped_buffers =
GraphDatabaseSettings.use_memory_mapped_buffers;
public static final Setting<Boolean> execution_guard_enabled = GraphDatabaseSettings.execution_guard_enabled;
public static final Setting<String> cache_type = GraphDatabaseSettings.cache_type;
public static final Setting<Boolean> ephemeral = setting( "ephemeral", Settings.BOOLEAN, Settings.FALSE );
public static final Setting<File> store_dir = GraphDatabaseSettings.store_dir;
public static final Setting<File> neo_store = GraphDatabaseSettings.neo_store;
public static final Setting<File> logical_log = GraphDatabaseSettings.logical_log;
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_InternalAbstractGraphDatabase.java
|
5,554
|
{
@Override
public Node apply( long id )
{
return getNodeById( id );
}
}, input ) );
| false
|
community_kernel_src_main_java_org_neo4j_kernel_InternalAbstractGraphDatabase.java
|
5,555
|
private static class TransactionContinuation
{
private final HighlyAvailableGraphDatabase db;
private final TransactionManager txManager;
private Transaction graphDbTx;
private javax.transaction.Transaction jtaTx;
private TransactionContinuation( HighlyAvailableGraphDatabase db ) {
this.db = db;
txManager = db.getDependencyResolver().resolveDependency( TransactionManager.class );
}
public void begin()
{
graphDbTx = db.beginTx();
}
public void suspend() throws SystemException
{
jtaTx = txManager.suspend();
}
public void resume() throws Exception
{
txManager.resume( jtaTx );
}
public void commit()
{
graphDbTx.close();
}
}
| false
|
enterprise_ha_src_test_java_org_neo4j_kernel_LabelIT.java
|
5,556
|
private static class TotalDepth
{
private int out;
private int in;
void set( Direction side, int depth )
{
switch ( side )
{
case OUTGOING: out = depth; break;
case INCOMING: in = depth; break;
}
}
int get()
{
return out+in;
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_LevelSelectorOrderer.java
|
5,557
|
{
@Override
public NodeImpl lookup( long nodeId )
{
assertDatabaseRunning();
return nodeManager.getNodeForProxy( nodeId, null );
}
@Override
public NodeImpl lookup( long nodeId, LockType lock )
{
assertDatabaseRunning();
return nodeManager.getNodeForProxy( nodeId, lock );
}
@Override
public GraphDatabaseService getGraphDatabase()
{
// TODO This should be wrapped as well
return InternalAbstractGraphDatabase.this;
}
@Override
public NodeManager getNodeManager()
{
return nodeManager;
}
};
| false
|
community_kernel_src_main_java_org_neo4j_kernel_InternalAbstractGraphDatabase.java
|
5,558
|
public final class OrderedByTypeExpander extends
StandardExpander.RegularExpander
{
private final Collection<Pair<RelationshipType, Direction>> orderedTypes;
public OrderedByTypeExpander()
{
this( Collections.<Pair<RelationshipType, Direction>>emptyList() );
}
OrderedByTypeExpander( Collection<Pair<RelationshipType, Direction>> orderedTypes )
{
super( Collections.<Direction, RelationshipType[]>emptyMap() );
this.orderedTypes = orderedTypes;
}
@Override
public StandardExpander add( RelationshipType type, Direction direction )
{
Collection<Pair<RelationshipType, Direction>> newTypes = new ArrayList<Pair<RelationshipType,Direction>>( orderedTypes );
newTypes.add( Pair.of( type, direction ) );
return new OrderedByTypeExpander( newTypes );
}
@Override
public StandardExpander remove( RelationshipType type )
{
Collection<Pair<RelationshipType, Direction>> newTypes = new ArrayList<Pair<RelationshipType,Direction>>();
for ( Pair<RelationshipType, Direction> pair : orderedTypes )
if ( !type.name().equals( pair.first().name() ) )
newTypes.add( pair );
return new OrderedByTypeExpander( newTypes );
}
@Override
void buildString( StringBuilder result )
{
result.append( orderedTypes.toString() );
}
@Override
public StandardExpander reverse()
{
Collection<Pair<RelationshipType, Direction>> newTypes = new ArrayList<Pair<RelationshipType,Direction>>();
for ( Pair<RelationshipType, Direction> pair : orderedTypes )
newTypes.add( Pair.of( pair.first(), pair.other().reverse() ) );
return new OrderedByTypeExpander( newTypes );
}
@Override
RegularExpander createNew( Map<Direction, RelationshipType[]> newTypes )
{
throw new UnsupportedOperationException();
}
@Override
Iterator<Relationship> doExpand( final Path path, BranchState state )
{
final Node node = path.endNode();
return new NestingIterator<Relationship, Pair<RelationshipType, Direction>>(
orderedTypes.iterator() )
{
@Override
protected Iterator<Relationship> createNestedIterator(
Pair<RelationshipType, Direction> entry )
{
RelationshipType type = entry.first();
Direction dir = entry.other();
return ( ( dir == Direction.BOTH ) ? node.getRelationships( type ) :
node.getRelationships( type, dir ) ).iterator();
}
};
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_OrderedByTypeExpander.java
|
5,559
|
private static final class ExcludingExpander extends StandardExpander
{
private final Exclusion defaultExclusion;
private final Map<String, Exclusion> exclusion;
ExcludingExpander( Exclusion defaultExclusion,
Map<String, Exclusion> exclusion )
{
this.defaultExclusion = defaultExclusion;
this.exclusion = exclusion;
}
@Override
void buildString( StringBuilder result )
{
// FIXME: not really correct
result.append( defaultExclusion );
result.append( "*" );
for ( Map.Entry<String, Exclusion> entry : exclusion.entrySet() )
{
result.append( "," );
result.append( entry.getValue() );
result.append( entry.getKey() );
}
}
@Override
Iterator<Relationship> doExpand( Path path, BranchState state )
{
final Node node = path.endNode();
return new FilteringIterator<Relationship>(
node.getRelationships().iterator(),
new Predicate<Relationship>()
{
public boolean accept( Relationship rel )
{
Exclusion exclude = exclusion.get( rel.getType().name() );
exclude = (exclude == null) ? defaultExclusion
: exclude;
return exclude.accept( node, rel );
}
} );
}
@Override
public StandardExpander add( RelationshipType type, Direction direction )
{
Exclusion excluded = exclusion.get( type.name() );
final Map<String, Exclusion> newExclusion;
if ( (excluded == null ? defaultExclusion : excluded).includes( direction ) )
{
return this;
}
else
{
excluded = Exclusion.include( direction );
if ( excluded == defaultExclusion )
{
if ( exclusion.size() == 1 )
{
return new AllExpander( defaultExclusion.direction );
}
else
{
newExclusion = new HashMap<String, Exclusion>(
exclusion );
newExclusion.remove( type.name() );
}
}
else
{
newExclusion = new HashMap<String, Exclusion>( exclusion );
newExclusion.put( type.name(), excluded );
}
}
return new ExcludingExpander( defaultExclusion, newExclusion );
}
@Override
public StandardExpander remove( RelationshipType type )
{
Exclusion excluded = exclusion.get( type.name() );
if ( excluded == Exclusion.ALL )
{
return this;
}
Map<String, Exclusion> newExclusion = new HashMap<String, Exclusion>(
exclusion );
newExclusion.put( type.name(), Exclusion.ALL );
return new ExcludingExpander( defaultExclusion, newExclusion );
}
@Override
public StandardExpander reversed()
{
return reverse();
}
@Override
public StandardExpander reverse()
{
Map<String, Exclusion> newExclusion = new HashMap<String, Exclusion>();
for ( Map.Entry<String, Exclusion> entry : exclusion.entrySet() )
{
newExclusion.put( entry.getKey(), entry.getValue().reversed() );
}
return new ExcludingExpander( defaultExclusion.reversed(), newExclusion );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_StandardExpander.java
|
5,560
|
private static class DirectionAndTypes
{
final Direction direction;
final RelationshipType[] types;
DirectionAndTypes( Direction direction, RelationshipType[] types )
{
this.direction = direction;
this.types = types;
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_StandardExpander.java
|
5,561
|
private static class AllExpander extends StandardExpander
{
private final Direction direction;
AllExpander( Direction direction )
{
this.direction = direction;
}
@Override
void buildString( StringBuilder result )
{
if ( direction != Direction.BOTH )
{
result.append( direction );
result.append( ":" );
}
result.append( "*" );
}
@Override
Iterator<Relationship> doExpand( Path path, BranchState state )
{
return path.endNode().getRelationships( direction ).iterator();
}
@Override
public StandardExpander add( RelationshipType type, Direction dir )
{
return this;
}
@Override
public StandardExpander remove( RelationshipType type )
{
Map<String, Exclusion> exclude = new HashMap<String, Exclusion>();
exclude.put( type.name(), Exclusion.ALL );
return new ExcludingExpander( Exclusion.include( direction ),
exclude );
}
@Override
public StandardExpander reversed()
{
return reverse();
}
@Override
public StandardExpander reverse()
{
return new AllExpander( direction.reverse() );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_StandardExpander.java
|
5,562
|
{
@Override
public StandardExpander add( RelationshipType type, Direction direction )
{
return create( type, direction );
}
};
| false
|
community_kernel_src_main_java_org_neo4j_kernel_StandardExpander.java
|
5,563
|
public abstract class StandardExpander implements Expander, PathExpander
{
private StandardExpander()
{
}
static abstract class StandardExpansion<T> implements Expansion<T>
{
final StandardExpander expander;
final Path path;
final BranchState state;
StandardExpansion( StandardExpander expander, Path path, BranchState state )
{
this.expander = expander;
this.path = path;
this.state = state;
}
String stringRepresentation( String nodesORrelationships )
{
return "Expansion[" + path + ".expand( " + expander + " )."
+ nodesORrelationships + "()]";
}
abstract StandardExpansion<T> createNew( StandardExpander expander );
public StandardExpansion<T> including( RelationshipType type )
{
return createNew( expander.add( type ) );
}
public StandardExpansion<T> including( RelationshipType type,
Direction direction )
{
return createNew( expander.add( type, direction ) );
}
public StandardExpansion<T> excluding( RelationshipType type )
{
return createNew( expander.remove( type ) );
}
public StandardExpander expander()
{
return expander;
}
public StandardExpansion<T> filterNodes( Predicate<? super Node> filter )
{
return createNew( expander.addNodeFilter( filter ) );
}
public StandardExpansion<T> filterRelationships(
Predicate<? super Relationship> filter )
{
return createNew( expander.addRelationshipFilter( filter ) );
}
public T getSingle()
{
final Iterator<T> expanded = iterator();
if ( expanded.hasNext() )
{
final T result = expanded.next();
if ( expanded.hasNext() )
{
throw new NotFoundException(
"More than one relationship found for " + this );
}
return result;
}
return null;
}
public boolean isEmpty()
{
return !expander.doExpand( path, state ).hasNext();
}
public StandardExpansion<Node> nodes()
{
return new NodeExpansion( expander, path, state );
}
public StandardExpansion<Relationship> relationships()
{
return new RelationshipExpansion( expander, path, state );
}
public StandardExpansion<Pair<Relationship, Node>> pairs()
{
return new PairExpansion( expander, path, state );
}
}
private static final class RelationshipExpansion extends
StandardExpansion<Relationship>
{
RelationshipExpansion( StandardExpander expander, Path path, BranchState state )
{
super( expander, path, state );
}
@Override
public String toString()
{
return stringRepresentation( "relationships" );
}
@Override
StandardExpansion<Relationship> createNew( StandardExpander expander )
{
return new RelationshipExpansion( expander, path, state );
}
@Override
public StandardExpansion<Relationship> relationships()
{
return this;
}
public Iterator<Relationship> iterator()
{
return expander.doExpand( path, state );
}
}
private static final class NodeExpansion extends StandardExpansion<Node>
{
NodeExpansion( StandardExpander expander, Path path, BranchState state )
{
super( expander, path, state );
}
@Override
public String toString()
{
return stringRepresentation( "nodes" );
}
@Override
StandardExpansion<Node> createNew( StandardExpander expander )
{
return new NodeExpansion( expander, path, state );
}
@Override
public StandardExpansion<Node> nodes()
{
return this;
}
public Iterator<Node> iterator()
{
final Node node = path.endNode();
return new IteratorWrapper<Node, Relationship>(
expander.doExpand( path, state ) )
{
@Override
protected Node underlyingObjectToObject( Relationship rel )
{
return rel.getOtherNode( node );
}
};
}
}
private static final class PairExpansion extends
StandardExpansion<Pair<Relationship, Node>>
{
PairExpansion( StandardExpander expander, Path path, BranchState state )
{
super( expander, path, state );
}
@Override
public String toString()
{
return stringRepresentation( "pairs" );
}
@Override
StandardExpansion<Pair<Relationship, Node>> createNew( StandardExpander expander )
{
return new PairExpansion( expander, path, state );
}
@Override
public StandardExpansion<Pair<Relationship, Node>> pairs()
{
return this;
}
public Iterator<Pair<Relationship, Node>> iterator()
{
final Node node = path.endNode();
return new IteratorWrapper<Pair<Relationship, Node>, Relationship>(
expander.doExpand( path, state ) )
{
@Override
protected Pair<Relationship, Node> underlyingObjectToObject(
Relationship rel )
{
return Pair.of( rel, rel.getOtherNode( node ) );
}
};
}
}
private static class AllExpander extends StandardExpander
{
private final Direction direction;
AllExpander( Direction direction )
{
this.direction = direction;
}
@Override
void buildString( StringBuilder result )
{
if ( direction != Direction.BOTH )
{
result.append( direction );
result.append( ":" );
}
result.append( "*" );
}
@Override
Iterator<Relationship> doExpand( Path path, BranchState state )
{
return path.endNode().getRelationships( direction ).iterator();
}
@Override
public StandardExpander add( RelationshipType type, Direction dir )
{
return this;
}
@Override
public StandardExpander remove( RelationshipType type )
{
Map<String, Exclusion> exclude = new HashMap<String, Exclusion>();
exclude.put( type.name(), Exclusion.ALL );
return new ExcludingExpander( Exclusion.include( direction ),
exclude );
}
@Override
public StandardExpander reversed()
{
return reverse();
}
@Override
public StandardExpander reverse()
{
return new AllExpander( direction.reverse() );
}
}
private enum Exclusion
{
ALL( null, "!" )
{
@Override
public boolean accept( Node start, Relationship rel )
{
return false;
}
},
INCOMING( Direction.OUTGOING )
{
@Override
Exclusion reversed()
{
return OUTGOING;
}
},
OUTGOING( Direction.INCOMING )
{
@Override
Exclusion reversed()
{
return INCOMING;
}
},
NONE( Direction.BOTH, "" )
{
@Override
boolean includes( Direction direction )
{
return true;
}
};
private final String string;
private final Direction direction;
private Exclusion( Direction direction, String string )
{
this.direction = direction;
this.string = string;
}
private Exclusion( Direction direction )
{
this.direction = direction;
this.string = "!" + name() + ":";
}
@Override
public final String toString()
{
return string;
}
boolean accept( Node start, Relationship rel )
{
return matchDirection( direction, start, rel );
}
Exclusion reversed()
{
return this;
}
boolean includes( Direction dir )
{
return this.direction == dir;
}
static Exclusion include( Direction direction )
{
switch ( direction )
{
case INCOMING:
return OUTGOING;
case OUTGOING:
return INCOMING;
default:
return NONE;
}
}
}
private static final class ExcludingExpander extends StandardExpander
{
private final Exclusion defaultExclusion;
private final Map<String, Exclusion> exclusion;
ExcludingExpander( Exclusion defaultExclusion,
Map<String, Exclusion> exclusion )
{
this.defaultExclusion = defaultExclusion;
this.exclusion = exclusion;
}
@Override
void buildString( StringBuilder result )
{
// FIXME: not really correct
result.append( defaultExclusion );
result.append( "*" );
for ( Map.Entry<String, Exclusion> entry : exclusion.entrySet() )
{
result.append( "," );
result.append( entry.getValue() );
result.append( entry.getKey() );
}
}
@Override
Iterator<Relationship> doExpand( Path path, BranchState state )
{
final Node node = path.endNode();
return new FilteringIterator<Relationship>(
node.getRelationships().iterator(),
new Predicate<Relationship>()
{
public boolean accept( Relationship rel )
{
Exclusion exclude = exclusion.get( rel.getType().name() );
exclude = (exclude == null) ? defaultExclusion
: exclude;
return exclude.accept( node, rel );
}
} );
}
@Override
public StandardExpander add( RelationshipType type, Direction direction )
{
Exclusion excluded = exclusion.get( type.name() );
final Map<String, Exclusion> newExclusion;
if ( (excluded == null ? defaultExclusion : excluded).includes( direction ) )
{
return this;
}
else
{
excluded = Exclusion.include( direction );
if ( excluded == defaultExclusion )
{
if ( exclusion.size() == 1 )
{
return new AllExpander( defaultExclusion.direction );
}
else
{
newExclusion = new HashMap<String, Exclusion>(
exclusion );
newExclusion.remove( type.name() );
}
}
else
{
newExclusion = new HashMap<String, Exclusion>( exclusion );
newExclusion.put( type.name(), excluded );
}
}
return new ExcludingExpander( defaultExclusion, newExclusion );
}
@Override
public StandardExpander remove( RelationshipType type )
{
Exclusion excluded = exclusion.get( type.name() );
if ( excluded == Exclusion.ALL )
{
return this;
}
Map<String, Exclusion> newExclusion = new HashMap<String, Exclusion>(
exclusion );
newExclusion.put( type.name(), Exclusion.ALL );
return new ExcludingExpander( defaultExclusion, newExclusion );
}
@Override
public StandardExpander reversed()
{
return reverse();
}
@Override
public StandardExpander reverse()
{
Map<String, Exclusion> newExclusion = new HashMap<String, Exclusion>();
for ( Map.Entry<String, Exclusion> entry : exclusion.entrySet() )
{
newExclusion.put( entry.getKey(), entry.getValue().reversed() );
}
return new ExcludingExpander( defaultExclusion.reversed(), newExclusion );
}
}
public static final StandardExpander DEFAULT = new AllExpander(
Direction.BOTH )
{
@Override
public StandardExpander add( RelationshipType type, Direction direction )
{
return create( type, direction );
}
};
public static final StandardExpander EMPTY =
new RegularExpander( Collections.<Direction, RelationshipType[]>emptyMap() );
private static class DirectionAndTypes
{
final Direction direction;
final RelationshipType[] types;
DirectionAndTypes( Direction direction, RelationshipType[] types )
{
this.direction = direction;
this.types = types;
}
}
static class RegularExpander extends StandardExpander
{
final Map<Direction, RelationshipType[]> typesMap;
final DirectionAndTypes[] directions;
RegularExpander( Map<Direction, RelationshipType[]> types )
{
this.typesMap = types;
this.directions = new DirectionAndTypes[types.size()];
int i = 0;
for ( Map.Entry<Direction, RelationshipType[]> entry : types.entrySet() )
{
this.directions[i++] = new DirectionAndTypes( entry.getKey(), entry.getValue() );
}
}
@Override
void buildString( StringBuilder result )
{
result.append( typesMap.toString() );
}
@Override
Iterator<Relationship> doExpand( Path path, BranchState state )
{
final Node node = path.endNode();
if ( directions.length == 1 )
{
DirectionAndTypes direction = directions[0];
return node.getRelationships( direction.direction, direction.types ).iterator();
}
else
{
return new NestingIterator<Relationship, DirectionAndTypes>( new ArrayIterator<DirectionAndTypes>(
directions ) )
{
@Override
protected Iterator<Relationship> createNestedIterator( DirectionAndTypes item )
{
return node.getRelationships( item.direction, item.types ).iterator();
}
};
}
}
StandardExpander createNew( Map<Direction, RelationshipType[]> types )
{
if ( types.isEmpty() )
{
return new AllExpander( Direction.BOTH );
}
return new RegularExpander( types );
}
@Override
public StandardExpander add( RelationshipType type, Direction direction )
{
Map<Direction, Collection<RelationshipType>> tempMap = temporaryTypeMapFrom( typesMap );
tempMap.get( direction ).add( type );
return createNew( toTypeMap( tempMap ) );
}
@Override
public StandardExpander remove( RelationshipType type )
{
Map<Direction, Collection<RelationshipType>> tempMap = temporaryTypeMapFrom( typesMap );
for ( Direction direction : Direction.values() )
{
tempMap.get( direction ).remove( type );
}
return createNew( toTypeMap( tempMap ) );
}
@Override
public StandardExpander reversed()
{
return reverse();
}
@Override
public StandardExpander reverse()
{
Map<Direction, Collection<RelationshipType>> tempMap = temporaryTypeMapFrom( typesMap );
Collection<RelationshipType> out = tempMap.get( Direction.OUTGOING );
Collection<RelationshipType> in = tempMap.get( Direction.INCOMING );
tempMap.put( Direction.OUTGOING, in );
tempMap.put( Direction.INCOMING, out );
return createNew( toTypeMap( tempMap ) );
}
}
private static final class FilteringExpander extends StandardExpander
{
private final StandardExpander expander;
private final Filter[] filters;
FilteringExpander( StandardExpander expander, Filter... filters )
{
this.expander = expander;
this.filters = filters;
}
@Override
void buildString( StringBuilder result )
{
expander.buildString( result );
result.append( "; filter:" );
for ( Filter filter : filters )
{
result.append( " " );
result.append( filter );
}
}
@Override
Iterator<Relationship> doExpand( final Path path, BranchState state )
{
return new FilteringIterator<Relationship>(
expander.doExpand( path, state ), new Predicate<Relationship>()
{
public boolean accept( Relationship item )
{
Path extendedPath = extend( path, item );
for ( Filter filter : filters )
{
if ( filter.exclude( extendedPath ) )
{
return false;
}
}
return true;
}
} );
}
@Override
public StandardExpander addNodeFilter( Predicate<? super Node> filter )
{
return new FilteringExpander( expander, append( filters,
new NodeFilter( filter ) ) );
}
@Override
public StandardExpander addRelationshipFilter(
Predicate<? super Relationship> filter )
{
return new FilteringExpander( expander, append( filters,
new RelationshipFilter( filter ) ) );
}
@Override
public StandardExpander add( RelationshipType type, Direction direction )
{
return new FilteringExpander( expander.add( type, direction ),
filters );
}
@Override
public StandardExpander remove( RelationshipType type )
{
return new FilteringExpander( expander.remove( type ), filters );
}
@Override
public StandardExpander reversed()
{
return reverse();
}
@Override
public StandardExpander reverse()
{
return new FilteringExpander( expander.reversed(), filters );
}
}
private static final class WrappingExpander extends StandardExpander
{
private static final String IMMUTABLE = "Immutable Expander ";
private final PathExpander expander;
WrappingExpander( PathExpander expander )
{
this.expander = expander;
}
@Override
void buildString( StringBuilder result )
{
result.append( expander );
}
@Override
Iterator<Relationship> doExpand( Path path, BranchState state )
{
return expander.expand( path, state ).iterator();
}
@Override
public StandardExpander add( RelationshipType type, Direction direction )
{
throw new UnsupportedOperationException( IMMUTABLE + expander );
}
@Override
public StandardExpander remove( RelationshipType type )
{
throw new UnsupportedOperationException( IMMUTABLE + expander );
}
@Override
public StandardExpander reversed()
{
return reverse();
}
@Override
public StandardExpander reverse()
{
throw new UnsupportedOperationException( IMMUTABLE + expander );
}
}
private static final class WrappingRelationshipExpander extends StandardExpander
{
private static final String IMMUTABLE = "Immutable Expander ";
private final RelationshipExpander expander;
WrappingRelationshipExpander( RelationshipExpander expander )
{
this.expander = expander;
}
@Override
void buildString( StringBuilder result )
{
result.append( expander );
}
@Override
Iterator<Relationship> doExpand( Path path, BranchState state )
{
return expander.expand( path.endNode() ).iterator();
}
@Override
public StandardExpander add( RelationshipType type, Direction direction )
{
throw new UnsupportedOperationException( IMMUTABLE + expander );
}
@Override
public StandardExpander remove( RelationshipType type )
{
throw new UnsupportedOperationException( IMMUTABLE + expander );
}
@Override
public StandardExpander reversed()
{
return reverse();
}
@Override
public StandardExpander reverse()
{
throw new UnsupportedOperationException( IMMUTABLE + expander );
}
}
private static abstract class Filter
{
abstract boolean exclude( Path path );
}
private static final class NodeFilter extends Filter
{
private final Predicate<? super Node> predicate;
NodeFilter( Predicate<? super Node> predicate )
{
this.predicate = predicate;
}
@Override
public String toString()
{
return predicate.toString();
}
@Override
boolean exclude( Path path )
{
return !predicate.accept( path.lastRelationship().getOtherNode( path.endNode() ) );
}
}
private static final class RelationshipFilter extends Filter
{
private final Predicate<? super Relationship> predicate;
RelationshipFilter( Predicate<? super Relationship> predicate )
{
this.predicate = predicate;
}
@Override
public String toString()
{
return predicate.toString();
}
@Override
boolean exclude( Path path )
{
return !predicate.accept( path.lastRelationship() );
}
}
private static final class PathFilter extends Filter
{
private final Predicate<? super Path> predicate;
PathFilter( Predicate<? super Path> predicate )
{
this.predicate = predicate;
}
@Override
public String toString()
{
return predicate.toString();
}
@Override
boolean exclude( Path path )
{
return !predicate.accept( path );
}
}
public final Expansion<Relationship> expand( Node node )
{
return new RelationshipExpansion( this, new SingleNodePath( node ), BranchState.NO_STATE );
}
public final Expansion<Relationship> expand( Path path, BranchState state )
{
return new RelationshipExpansion( this, path, state );
}
static <T> T[] append( T[] array, T item )
{
@SuppressWarnings("unchecked") T[] result = (T[]) Array.newInstance(
array.getClass().getComponentType(), array.length + 1 );
System.arraycopy( array, 0, result, 0, array.length );
result[array.length] = item;
return result;
}
static boolean matchDirection( Direction dir, Node start, Relationship rel )
{
switch ( dir )
{
case INCOMING:
return rel.getEndNode().equals( start );
case OUTGOING:
return rel.getStartNode().equals( start );
case BOTH:
return true;
}
return true;
}
abstract Iterator<Relationship> doExpand( Path path, BranchState state );
@Override
public final String toString()
{
StringBuilder result = new StringBuilder( "Expander[" );
buildString( result );
result.append( "]" );
return result.toString();
}
abstract void buildString( StringBuilder result );
public final StandardExpander add( RelationshipType type )
{
return add( type, Direction.BOTH );
}
public abstract StandardExpander add( RelationshipType type,
Direction direction );
public abstract StandardExpander remove( RelationshipType type );
public abstract StandardExpander reverse();
public abstract StandardExpander reversed();
public StandardExpander addNodeFilter( Predicate<? super Node> filter )
{
return new FilteringExpander( this, new NodeFilter( filter ) );
}
@Override
public final Expander addRelationsipFilter( Predicate<? super Relationship> filter )
{
return addRelationshipFilter( filter );
}
public StandardExpander addRelationshipFilter(
Predicate<? super Relationship> filter )
{
return new FilteringExpander( this, new RelationshipFilter( filter ) );
}
static StandardExpander wrap( RelationshipExpander expander )
{
return new WrappingRelationshipExpander( expander );
}
static StandardExpander wrap( PathExpander expander )
{
return new WrappingExpander( expander );
}
public static PathExpander toPathExpander( RelationshipExpander expander )
{
return expander instanceof PathExpander ? (PathExpander) expander : wrap( expander );
}
public static StandardExpander create( Direction direction )
{
return new AllExpander( direction );
}
public static StandardExpander create( RelationshipType type, Direction dir )
{
Map<Direction, RelationshipType[]> types =
new EnumMap<Direction, RelationshipType[]>( Direction.class );
types.put( dir, new RelationshipType[]{type} );
return new RegularExpander( types );
}
static StandardExpander create( RelationshipType type1, Direction dir1,
RelationshipType type2, Direction dir2 )
{
Map<Direction, Collection<RelationshipType>> tempMap = temporaryTypeMap();
tempMap.get( dir1 ).add( type1 );
tempMap.get( dir2 ).add( type2 );
return new RegularExpander( toTypeMap( tempMap ) );
}
private static Map<Direction, RelationshipType[]> toTypeMap(
Map<Direction, Collection<RelationshipType>> tempMap )
{
// Remove OUT/IN where there is a BOTH
Collection<RelationshipType> both = tempMap.get( Direction.BOTH );
tempMap.get( Direction.OUTGOING ).removeAll( both );
tempMap.get( Direction.INCOMING ).removeAll( both );
// Convert into a final map
Map<Direction, RelationshipType[]> map = new EnumMap<Direction, RelationshipType[]>( Direction.class );
for ( Map.Entry<Direction, Collection<RelationshipType>> entry : tempMap.entrySet() )
{
if ( !entry.getValue().isEmpty() )
{
map.put( entry.getKey(), entry.getValue().toArray( new RelationshipType[entry.getValue().size()] ) );
}
}
return map;
}
private static Map<Direction, Collection<RelationshipType>> temporaryTypeMap()
{
Map<Direction, Collection<RelationshipType>> map = new EnumMap<Direction,
Collection<RelationshipType>>( Direction.class );
for ( Direction direction : Direction.values() )
{
map.put( direction, new ArrayList<RelationshipType>() );
}
return map;
}
private static Map<Direction, Collection<RelationshipType>> temporaryTypeMapFrom( Map<Direction,
RelationshipType[]> typeMap )
{
Map<Direction, Collection<RelationshipType>> map = new EnumMap<Direction,
Collection<RelationshipType>>( Direction.class );
for ( Direction direction : Direction.values() )
{
ArrayList<RelationshipType> types = new ArrayList<RelationshipType>();
map.put( direction, types );
RelationshipType[] existing = typeMap.get( direction );
if ( existing != null )
{
types.addAll( asList( existing ) );
}
}
return map;
}
public static StandardExpander create( RelationshipType type1, Direction dir1,
RelationshipType type2, Direction dir2, Object... more )
{
Map<Direction, Collection<RelationshipType>> tempMap = temporaryTypeMap();
tempMap.get( dir1 ).add( type1 );
tempMap.get( dir2 ).add( type2 );
for ( int i = 0; i < more.length; i++ )
{
RelationshipType type = (RelationshipType) more[i++];
Direction direction = (Direction) more[i];
tempMap.get( direction ).add( type );
}
return new RegularExpander( toTypeMap( tempMap ) );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_StandardExpander.java
|
5,564
|
public class StandardBranchCollisionDetector implements BranchCollisionDetector
{
private final Map<Node, Collection<TraversalBranch>[]> paths =
new HashMap<Node, Collection<TraversalBranch>[]>( 1000 );
private final Evaluator evaluator;
private final Set<Path> returnedPaths = new HashSet<Path>();
public StandardBranchCollisionDetector( Evaluator evaluator )
{
this.evaluator = evaluator;
}
@SuppressWarnings( "unchecked" )
public Collection<Path> evaluate( TraversalBranch branch, Direction direction )
{
// [0] for paths from start, [1] for paths from end
Collection<TraversalBranch>[] pathsHere = paths.get( branch.endNode() );
int index = direction.ordinal();
if ( pathsHere == null )
{
pathsHere = new Collection[] { new ArrayList<TraversalBranch>(), new ArrayList<TraversalBranch>() };
paths.put( branch.endNode(), pathsHere );
}
pathsHere[index].add( branch );
// If there are paths from the other side then include all the
// combined paths
Collection<TraversalBranch> otherCollections = pathsHere[index == 0 ? 1 : 0];
if ( !otherCollections.isEmpty() )
{
Collection<Path> foundPaths = new ArrayList<Path>();
for ( TraversalBranch otherBranch : otherCollections )
{
TraversalBranch startPath = index == 0 ? branch : otherBranch;
TraversalBranch endPath = index == 0 ? otherBranch : branch;
BidirectionalTraversalBranchPath path = new BidirectionalTraversalBranchPath(
startPath, endPath );
if ( returnedPaths.add( path ) && includePath( path, startPath, endPath ) )
{
foundPaths.add( path );
}
}
if ( !foundPaths.isEmpty() )
{
return foundPaths;
}
}
return null;
}
protected boolean includePath( Path path, TraversalBranch startPath, TraversalBranch endPath )
{
Evaluation eval = evaluator.evaluate( path );
if ( !eval.continues() )
{
startPath.evaluation( eval );
endPath.evaluation( eval );
}
return eval.includes();
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_StandardBranchCollisionDetector.java
|
5,565
|
ALTERNATING
{
@Override
public SideSelector create( BranchSelector start, BranchSelector end, int maxDepth )
{
return org.neo4j.graphdb.traversal.SideSelectorPolicies.ALTERNATING.create( start, end, maxDepth );
}
};
| false
|
community_kernel_src_main_java_org_neo4j_kernel_SideSelectorPolicies.java
|
5,566
|
LEVEL_STOP_DESCENT_ON_RESULT
{
@Override
public SideSelector create( BranchSelector start, BranchSelector end, int maxDepth )
{
return org.neo4j.graphdb.traversal.SideSelectorPolicies.LEVEL_STOP_DESCENT_ON_RESULT
.create( start, end, maxDepth );
}
},
| false
|
community_kernel_src_main_java_org_neo4j_kernel_SideSelectorPolicies.java
|
5,567
|
LEVEL
{
@Override
public SideSelector create( BranchSelector start, BranchSelector end, int maxDepth )
{
return org.neo4j.graphdb.traversal.SideSelectorPolicies.LEVEL.create( start, end, maxDepth );
}
},
| false
|
community_kernel_src_main_java_org_neo4j_kernel_SideSelectorPolicies.java
|
5,568
|
public class ShortestPathsBranchCollisionDetector extends StandardBranchCollisionDetector
{
private int depth = -1;
public ShortestPathsBranchCollisionDetector( Evaluator evaluator )
{
super( evaluator );
}
@Override
protected boolean includePath( Path path, TraversalBranch startBranch, TraversalBranch endBranch )
{
if ( !super.includePath( path, startBranch, endBranch ) )
return false;
if ( depth == -1 )
{
depth = path.length();
return true;
}
return path.length() == depth;
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_ShortestPathsBranchCollisionDetector.java
|
5,569
|
private static abstract class Worker extends Thread
{
private final Exchanger<Throwable> error;
private volatile boolean done;
Worker( String name, Exchanger<Throwable> error )
{
super( name );
this.error = error;
start();
}
void done()
{
if ( done ) interrupt();
this.done = true;
}
@Override
public void run()
{
try
{
while ( !done )
{
perform();
}
}
catch ( Throwable err )
{
done = true;
try
{
error.exchange( err );
}
catch ( InterruptedException e )
{
// ignore - we know where it came from
}
}
}
abstract void perform();
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_RaceBetweenCommitAndGetMoreRelationshipsIT.java
|
5,570
|
{
@Override
void perform()
{
try
{
int count = 0;
for ( @SuppressWarnings( "unused" ) Relationship rel : graphdb.getNodeById(0)
.getRelationships() )
{
count++;
}
if ( count % 100 != 0 ) throw new IllegalStateException( "Not atomic!" );
if ( assertions() ) System.out.println( "counted relationships" );
}
catch ( InvalidRecordException ire )
{
if ( assertions() ) ire.printStackTrace();
else System.err.println( ire );
}
}
} };
| false
|
community_kernel_src_test_java_org_neo4j_kernel_RaceBetweenCommitAndGetMoreRelationshipsIT.java
|
5,571
|
{
@Override
void perform()
{
setup( 100 );
if ( assertions() ) System.out.println( "created 100" );
}
}, new Worker( "reader", error )
| false
|
community_kernel_src_test_java_org_neo4j_kernel_RaceBetweenCommitAndGetMoreRelationshipsIT.java
|
5,572
|
public class RaceBetweenCommitAndGetMoreRelationshipsIT extends TimerTask
{
private static final RelationshipType TYPE = DynamicRelationshipType.withName( "TYPE" );
private static RaceBetweenCommitAndGetMoreRelationshipsIT instance;
private final GraphDatabaseService graphdb;
private final NodeManager nodeManager;
private final Timer timer;
private final Exchanger<Throwable> error = new Exchanger<Throwable>();
/**
* A hack to transport the test to the main thread through the debugger
*/
public static boolean exception( Throwable err )
{
RaceBetweenCommitAndGetMoreRelationshipsIT race = instance;
if ( race != null ) try
{
race.error.exchange( err );
}
catch ( InterruptedException e )
{
// ignore
}
return false;
}
private RaceBetweenCommitAndGetMoreRelationshipsIT(GraphDatabaseService graphdb, NodeManager nodeManager)
{
this.graphdb = graphdb;
this.nodeManager = nodeManager;
this.timer = new Timer( /*daemon:*/true );
}
public static void main( String... args )
{
String path = "target/commit-getMore-race";
if ( args != null && args.length >= 1 )
{
path = args[0];
}
delete( new File( path ) );
GraphDatabaseAPI graphdb = (GraphDatabaseAPI) new GraphDatabaseFactory().newEmbeddedDatabase( path );
RaceBetweenCommitAndGetMoreRelationshipsIT race = instance = new RaceBetweenCommitAndGetMoreRelationshipsIT(
graphdb, graphdb.getDependencyResolver().resolveDependency( NodeManager.class ) );
try
{
race.execute();
}
catch ( Throwable e )
{
e.printStackTrace();
}
finally
{
graphdb.shutdown();
}
}
private static void delete( File file )
{
if ( file.isDirectory() )
{
for ( File child : file.listFiles() )
delete( child );
}
else if ( !file.exists() )
{
return;
}
file.delete();
}
private void execute() throws Throwable
{
try(Transaction tx = graphdb.beginTx())
{
graphdb.createNode(); // Create a node with id 0 (test was originally written to use the reference node)
tx.success();
}
setup( 1000 );
nodeManager.clearCache();
timer.schedule( this, 10, 10 );
Worker[] threads = { new Worker( "writer", error )
{
@Override
void perform()
{
setup( 100 );
if ( assertions() ) System.out.println( "created 100" );
}
}, new Worker( "reader", error )
{
@Override
void perform()
{
try
{
int count = 0;
for ( @SuppressWarnings( "unused" ) Relationship rel : graphdb.getNodeById(0)
.getRelationships() )
{
count++;
}
if ( count % 100 != 0 ) throw new IllegalStateException( "Not atomic!" );
if ( assertions() ) System.out.println( "counted relationships" );
}
catch ( InvalidRecordException ire )
{
if ( assertions() ) ire.printStackTrace();
else System.err.println( ire );
}
}
} };
try
{
throw error.exchange( new Error( "this should never see the light of day" ) );
}
finally
{
cancel();
for ( Worker worker : threads )
worker.done();
}
}
private static boolean assertions()
{
boolean assertions = false;
assert ( assertions = true ) == true;
return assertions;
}
protected Node setup( int relCount )
{
Transaction tx = graphdb.beginTx();
try
{
Node root = graphdb.getNodeById( 0 );
for ( int i = 0; i < relCount; i++ )
{
root.createRelationshipTo( graphdb.createNode(), TYPE );
}
tx.success();
return root;
}
finally
{
tx.finish();
}
}
@Override
public void run()
{
nodeManager.clearCache();
if ( assertions() ) System.out.println( "cleared cache" );
}
private static abstract class Worker extends Thread
{
private final Exchanger<Throwable> error;
private volatile boolean done;
Worker( String name, Exchanger<Throwable> error )
{
super( name );
this.error = error;
start();
}
void done()
{
if ( done ) interrupt();
this.done = true;
}
@Override
public void run()
{
try
{
while ( !done )
{
perform();
}
}
catch ( Throwable err )
{
done = true;
try
{
error.exchange( err );
}
catch ( InterruptedException e )
{
// ignore - we know where it came from
}
}
}
abstract void perform();
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_RaceBetweenCommitAndGetMoreRelationshipsIT.java
|
5,573
|
{
@Override
public void release()
{
}
};
| false
|
community_kernel_src_main_java_org_neo4j_kernel_PlaceboTransaction.java
|
5,574
|
@Deprecated
public class PlaceboTransaction extends TopLevelTransaction
{
public final static Lock NO_LOCK = new Lock()
{
@Override
public void release()
{
}
};
public PlaceboTransaction( PersistenceManager pm, AbstractTransactionManager transactionManager, TransactionState state )
{
super( pm, transactionManager, state );
}
@Override
public void close()
{
if ( !transactionOutcome.successCalled() && !transactionOutcome.failureCalled() )
{
markAsRollbackOnly();
}
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_PlaceboTransaction.java
|
5,575
|
private static class CrudeAggregatedExpander implements PathExpander
{
private final List<Expander> steps;
CrudeAggregatedExpander( List<Expander> steps )
{
this.steps = steps;
}
@Override
public Iterable<Relationship> expand( Path path, BranchState state )
{
Expander expansion;
try
{
expansion = steps.get( path.length() );
}
catch ( IndexOutOfBoundsException e )
{
return Collections.emptyList();
}
return expansion.expand( path.endNode() );
}
@Override
public PathExpander reverse()
{
List<Expander> reversedSteps = new ArrayList<Expander>();
for ( Expander step : steps )
reversedSteps.add( step.reversed() );
Collections.reverse( reversedSteps );
return new CrudeAggregatedExpander( reversedSteps );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_PathDescription.java
|
5,576
|
public class PathDescription
{
private final List<Expander> steps;
public PathDescription()
{
this( new ArrayList<Expander>() );
}
private PathDescription( List<Expander> steps )
{
this.steps = steps;
}
public PathDescription step( RelationshipType type )
{
return step( expanderForTypes( type ) );
}
public PathDescription step( RelationshipType type, Direction direction )
{
return step( expanderForTypes( type, direction ) );
}
public PathDescription step( Expander expander )
{
List<Expander> newSteps = new ArrayList<Expander>( steps );
newSteps.add( expander );
return new PathDescription( newSteps );
}
public PathExpander build()
{
return new CrudeAggregatedExpander( steps );
}
private static class CrudeAggregatedExpander implements PathExpander
{
private final List<Expander> steps;
CrudeAggregatedExpander( List<Expander> steps )
{
this.steps = steps;
}
@Override
public Iterable<Relationship> expand( Path path, BranchState state )
{
Expander expansion;
try
{
expansion = steps.get( path.length() );
}
catch ( IndexOutOfBoundsException e )
{
return Collections.emptyList();
}
return expansion.expand( path.endNode() );
}
@Override
public PathExpander reverse()
{
List<Expander> reversedSteps = new ArrayList<Expander>();
for ( Expander step : steps )
reversedSteps.add( step.reversed() );
Collections.reverse( reversedSteps );
return new CrudeAggregatedExpander( reversedSteps );
}
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_PathDescription.java
|
5,577
|
{
@Override
protected Iterator<Relationship> createNestedIterator(
Pair<RelationshipType, Direction> entry )
{
RelationshipType type = entry.first();
Direction dir = entry.other();
return ( ( dir == Direction.BOTH ) ? node.getRelationships( type ) :
node.getRelationships( type, dir ) ).iterator();
}
};
| false
|
community_kernel_src_main_java_org_neo4j_kernel_OrderedByTypeExpander.java
|
5,578
|
{
@Override
public ResourceIterator<Node> iterator()
{
return nodesByLabelAndProperty( myLabel, key, value );
}
};
| false
|
community_kernel_src_main_java_org_neo4j_kernel_InternalAbstractGraphDatabase.java
|
5,579
|
{
@Override
public RelationshipImpl lookupRelationship( long relationshipId )
{
assertDatabaseRunning();
return nodeManager.getRelationshipForProxy( relationshipId );
}
@Override
public GraphDatabaseService getGraphDatabaseService()
{
return InternalAbstractGraphDatabase.this;
}
@Override
public NodeManager getNodeManager()
{
return nodeManager;
}
@Override
public Node newNodeProxy( long nodeId )
{
// only used by relationship already checked as valid in cache
return nodeManager.newNodeProxyById( nodeId );
}
};
| false
|
community_kernel_src_main_java_org_neo4j_kernel_InternalAbstractGraphDatabase.java
|
5,580
|
{
@Override
public void run()
{
}
};
| false
|
community_kernel_src_test_java_org_neo4j_kernel_CannedFileSystemAbstraction.java
|
5,581
|
public class DummyExtensionFactory extends KernelExtensionFactory<DummyExtensionFactory.Dependencies>
{
public interface Dependencies
{
Config getConfig();
KernelData getKernel();
}
static final String EXTENSION_ID = "dummy";
public DummyExtensionFactory()
{
super( EXTENSION_ID );
}
@Override
public Lifecycle newKernelExtension( Dependencies dependencies ) throws Throwable
{
return new DummyExtension( dependencies );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_DummyExtensionFactory.java
|
5,582
|
{
@Override
public void logLine( String line )
{
appendLine( line );
}
} );
| false
|
community_kernel_src_test_java_org_neo4j_kernel_DiagnosticsLoggingTest.java
|
5,583
|
private class FakeLogger extends StringLogger implements Logging
{
private final StringBuilder messages = new StringBuilder();
public String getMessages()
{
return messages.toString();
}
private void appendLine( String mess )
{
messages.append( mess ).append( "\n" );
}
@Override
public void logLongMessage( String msg, Visitor<LineLogger, RuntimeException> source, boolean flush )
{
appendLine( msg );
source.visit( new LineLogger()
{
@Override
public void logLine( String line )
{
appendLine( line );
}
} );
}
@Override
public void logMessage( String msg, boolean flush )
{
appendLine( msg );
}
@Override
public void logMessage( String msg, LogMarker marker )
{
appendLine( msg );
}
@Override
public void logMessage( String msg, Throwable cause, boolean flush )
{
appendLine( msg );
}
@Override
public void addRotationListener( Runnable listener )
{
}
@Override
public void flush()
{
}
@Override
public void close()
{
}
@Override
protected void logLine( String line )
{
appendLine( line );
}
@Override
public StringLogger getMessagesLog( Class loggingClass )
{
if ( loggingClass.equals( DiagnosticsManager.class ) )
{
return this;
}
else
{
return StringLogger.DEV_NULL;
}
}
@Override
public ConsoleLogger getConsoleLog( Class loggingClass )
{
return new ConsoleLogger( StringLogger.SYSTEM );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_DiagnosticsLoggingTest.java
|
5,584
|
@SuppressWarnings("deprecation")
private class FakeDatabase extends ImpermanentGraphDatabase
{
@Override
protected Logging createLogging()
{
return new FakeLogger();
}
public FakeLogger getLogger()
{
return (FakeLogger) logging;
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_DiagnosticsLoggingTest.java
|
5,585
|
public class DiagnosticsLoggingTest
{
@Test
public void shouldSeeHelloWorld()
{
FakeDatabase db = new FakeDatabase();
FakeLogger logger = db.getLogger();
String messages = logger.getMessages();
assertThat( messages, containsString( "Network information" ) );
assertThat( messages, containsString( "Disk space on partition" ) );
assertThat( messages, containsString( "Local timezone" ) );
db.shutdown();
}
private class FakeLogger extends StringLogger implements Logging
{
private final StringBuilder messages = new StringBuilder();
public String getMessages()
{
return messages.toString();
}
private void appendLine( String mess )
{
messages.append( mess ).append( "\n" );
}
@Override
public void logLongMessage( String msg, Visitor<LineLogger, RuntimeException> source, boolean flush )
{
appendLine( msg );
source.visit( new LineLogger()
{
@Override
public void logLine( String line )
{
appendLine( line );
}
} );
}
@Override
public void logMessage( String msg, boolean flush )
{
appendLine( msg );
}
@Override
public void logMessage( String msg, LogMarker marker )
{
appendLine( msg );
}
@Override
public void logMessage( String msg, Throwable cause, boolean flush )
{
appendLine( msg );
}
@Override
public void addRotationListener( Runnable listener )
{
}
@Override
public void flush()
{
}
@Override
public void close()
{
}
@Override
protected void logLine( String line )
{
appendLine( line );
}
@Override
public StringLogger getMessagesLog( Class loggingClass )
{
if ( loggingClass.equals( DiagnosticsManager.class ) )
{
return this;
}
else
{
return StringLogger.DEV_NULL;
}
}
@Override
public ConsoleLogger getConsoleLog( Class loggingClass )
{
return new ConsoleLogger( StringLogger.SYSTEM );
}
}
@SuppressWarnings("deprecation")
private class FakeDatabase extends ImpermanentGraphDatabase
{
@Override
protected Logging createLogging()
{
return new FakeLogger();
}
public FakeLogger getLogger()
{
return (FakeLogger) logging;
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_DiagnosticsLoggingTest.java
|
5,586
|
@Deprecated
public class DefaultTxHook implements RemoteTxHook
{
@Override
public void remotelyInitializeTransaction( int eventIdentifier, TransactionState state )
{
// Do nothing from the ordinary here
}
@Override
public void remotelyFinishTransaction( int eventIdentifier, boolean success )
{
// Do nothing from the ordinary here
}
@Override
public boolean freeIdsDuringRollback()
{
return true;
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_DefaultTxHook.java
|
5,587
|
@Deprecated
public class DefaultIdGeneratorFactory
implements IdGeneratorFactory
{
private final Map<IdType, IdGenerator> generators = new HashMap<IdType, IdGenerator>();
public IdGenerator open( FileSystemAbstraction fs, File fileName, int grabSize, IdType idType, long highId )
{
IdGenerator generator = new IdGeneratorImpl( fs, fileName, grabSize, idType.getMaxValue(),
idType.allowAggressiveReuse(), highId );
generators.put( idType, generator );
return generator;
}
public IdGenerator get( IdType idType )
{
return generators.get( idType );
}
public void create( FileSystemAbstraction fs, File fileName, long highId )
{
IdGeneratorImpl.createGenerator( fs, fileName, highId );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_DefaultIdGeneratorFactory.java
|
5,588
|
public class DefaultGraphDatabaseDependencies extends GraphDatabaseDependencies
{
public DefaultGraphDatabaseDependencies()
{
this( GraphDatabaseSettings.class );
}
public DefaultGraphDatabaseDependencies( Logging logging )
{
this( logging, GraphDatabaseSettings.class );
}
public DefaultGraphDatabaseDependencies( Class<?>... settingsClasses )
{
this( null, settingsClasses );
}
public DefaultGraphDatabaseDependencies( Logging logging, Class<?>... settingsClasses )
{
super(
logging,
Arrays.asList( settingsClasses ),
Iterables.<KernelExtensionFactory<?>,KernelExtensionFactory>cast( Service.load( KernelExtensionFactory.class ) ),
Service.load( CacheProvider.class ),
Service.load( TransactionInterceptorProvider.class ) );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_DefaultGraphDatabaseDependencies.java
|
5,589
|
{
@Override
public boolean mkdirs()
{
return false;
}
};
| false
|
community_kernel_src_test_java_org_neo4j_kernel_DefaultFileSystemAbstractionTest.java
|
5,590
|
public class DefaultFileSystemAbstractionTest
{
private final DefaultFileSystemAbstraction defaultFileSystemAbstraction = new DefaultFileSystemAbstraction();
private File path;
@Before
public void before() throws Exception
{
path = new File( "target/" + UUID.randomUUID() );
}
@Test
public void shouldCreatePath() throws Exception
{
defaultFileSystemAbstraction.mkdirs( path );
assertThat( path.exists(), is( true ) );
}
@Test
public void shouldCreateDeepPath() throws Exception
{
path = new File( path, UUID.randomUUID() + "/" + UUID.randomUUID() );
defaultFileSystemAbstraction.mkdirs( path );
assertThat( path.exists(), is( true ) );
}
@Test
public void shouldCreatePathThatAlreadyExists() throws Exception
{
assertTrue( path.mkdir() );
defaultFileSystemAbstraction.mkdirs( path );
assertThat( path.exists(), is( true ) );
}
@Test
public void shouldCreatePathThatPointsToFile() throws Exception
{
assertTrue( path.mkdir() );
path = new File( path, "some_file" );
assertTrue( path.createNewFile() );
defaultFileSystemAbstraction.mkdirs( path );
assertThat( path.exists(), is( true ) );
}
@Test
public void shouldFailGracefullyWhenPathCannotBeCreated() throws Exception
{
path = new File( "target/" + UUID.randomUUID() )
{
@Override
public boolean mkdirs()
{
return false;
}
};
try
{
defaultFileSystemAbstraction.mkdirs( path );
fail();
}
catch ( IOException e )
{
assertThat( path.exists(), is( false ) );
assertThat( e.getMessage(), is( format( UNABLE_TO_CREATE_DIRECTORY_FORMAT, path ) ) );
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_DefaultFileSystemAbstractionTest.java
|
5,591
|
@Deprecated
public class DefaultFileSystemAbstraction
implements FileSystemAbstraction
{
static final String UNABLE_TO_CREATE_DIRECTORY_FORMAT = "Unable to create directory path [%s] for Neo4j store.";
@Override
public StoreFileChannel open( File fileName, String mode ) throws IOException
{
// Returning only the channel is ok, because the channel, when close()d will close its parent File.
FileChannel channel = new RandomAccessFile( fileName, mode ).getChannel();
return new StoreFileChannel( channel );
}
@Override
public OutputStream openAsOutputStream( File fileName, boolean append ) throws IOException
{
return new FileOutputStream( fileName, append );
}
@Override
public InputStream openAsInputStream( File fileName ) throws IOException
{
return new FileInputStream( fileName );
}
@Override
public Reader openAsReader( File fileName, String encoding ) throws IOException
{
return new InputStreamReader( new FileInputStream( fileName ), encoding );
}
@Override
public Writer openAsWriter( File fileName, String encoding, boolean append ) throws IOException
{
return new OutputStreamWriter( new FileOutputStream( fileName, append ), encoding );
}
@Override
public FileLock tryLock( File fileName, StoreChannel channel ) throws IOException
{
return FileLock.getOsSpecificFileLock( fileName, channel );
}
@Override
public StoreFileChannel create( File fileName ) throws IOException
{
return open( fileName, "rw" );
}
@Override
public boolean mkdir( File fileName )
{
return fileName.mkdir();
}
@Override
public void mkdirs( File path ) throws IOException
{
if (path.exists()) return;
boolean directoriesWereCreated = path.mkdirs();
if (directoriesWereCreated) return;
throw new IOException( format( UNABLE_TO_CREATE_DIRECTORY_FORMAT, path ) );
}
@Override
public boolean fileExists( File fileName )
{
return fileName.exists();
}
@Override
public long getFileSize( File fileName )
{
return fileName.length();
}
@Override
public boolean deleteFile( File fileName )
{
return FileUtils.deleteFile( fileName );
}
@Override
public void deleteRecursively( File directory ) throws IOException
{
FileUtils.deleteRecursively( directory );
}
@Override
public boolean renameFile( File from, File to ) throws IOException
{
return FileUtils.renameFile( from, to );
}
@Override
public File[] listFiles( File directory )
{
return directory.listFiles();
}
@Override
public boolean isDirectory( File file )
{
return file.isDirectory();
}
@Override
public void moveToDirectory( File file, File toDirectory ) throws IOException
{
FileUtils.moveFileToDirectory( file, toDirectory );
}
@Override
public void copyFile( File from, File to ) throws IOException
{
FileUtils.copyFile( from, to );
}
@Override
public void copyRecursively( File fromDirectory, File toDirectory ) throws IOException
{
FileUtils.copyRecursively( fromDirectory, toDirectory );
}
private final Map<Class<? extends ThirdPartyFileSystem>, ThirdPartyFileSystem> thirdPartyFileSystems =
new HashMap<Class<? extends ThirdPartyFileSystem>, ThirdPartyFileSystem>();
@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_main_java_org_neo4j_kernel_DefaultFileSystemAbstraction.java
|
5,592
|
public class DeadlockDetectedException extends RuntimeException
{
public DeadlockDetectedException( String message )
{
super( "Don't panic.\n" +
"\n" +
"A deadlock scenario has been detected and avoided. This means that two or more transactions, which were " +
"holding locks, were wanting to await locks held by one another, which would have resulted in a deadlock " +
"between these transactions. This exception was thrown instead of ending up in that deadlock.\n" +
"\n" +
"See the deadlock section in the Neo4j manual for how to avoid this: " +
"http://docs.neo4j.org/chunked/stable/transactions-deadlocks.html\n" +
"\n" +
"Details: '" + message + "'." );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_DeadlockDetectedException.java
|
5,593
|
public class DatabaseAvailability
implements Lifecycle, AvailabilityGuard.AvailabilityRequirement
{
private TransactionManager txManager;
private AvailabilityGuard availabilityGuard;
public DatabaseAvailability( TransactionManager txManager, AvailabilityGuard availabilityGuard )
{
this.txManager = txManager;
this.availabilityGuard = availabilityGuard;
}
@Override
public void init()
throws Throwable
{
}
@Override
public void start()
throws Throwable
{
availabilityGuard.grant(this);
}
@Override
public void stop()
throws Throwable
{
// Database is no longer available for use
// Deny beginning new transactions
availabilityGuard.deny(this);
// If possible, wait until current transactions finish before continuing the shutdown
if ( txManager instanceof TxManager )
{
// TODO make stop-deadline configurable
long deadline = Clock.SYSTEM_CLOCK.currentTimeMillis() + 20 * 1000;
TxManager realTxManager = (TxManager) txManager;
while ( realTxManager.getActiveTxCount() > 0 && Clock.SYSTEM_CLOCK.currentTimeMillis() < deadline)
{
Thread.yield();
}
}
}
@Override
public void shutdown()
throws Throwable
{
// TODO: Starting database. Make sure none can access it through lock or CAS
}
@Override
public String description()
{
return getClass().getSimpleName();
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_DatabaseAvailability.java
|
5,594
|
@Deprecated
public class CommonFactories
{
public static IdGeneratorFactory defaultIdGeneratorFactory()
{
return new DefaultIdGeneratorFactory();
}
public static FileSystemAbstraction defaultFileSystemAbstraction()
{
return new DefaultFileSystemAbstraction();
}
public static RemoteTxHook defaultTxHook()
{
return new DefaultTxHook();
}
public static RecoveryVerifier defaultRecoveryVerifier()
{
return RecoveryVerifier.ALWAYS_VALID;
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_CommonFactories.java
|
5,595
|
POSTORDER_BREADTH_FIRST
{
public BranchSelector create( TraversalBranch startSource, PathExpander expander )
{
return BranchOrderingPolicies.POSTORDER_BREADTH_FIRST.create( startSource, expander );
}
};
| false
|
community_kernel_src_main_java_org_neo4j_kernel_CommonBranchOrdering.java
|
5,596
|
PREORDER_BREADTH_FIRST
{
public BranchSelector create( TraversalBranch startSource, PathExpander expander )
{
return BranchOrderingPolicies.PREORDER_BREADTH_FIRST.create( startSource, expander );
}
},
| false
|
community_kernel_src_main_java_org_neo4j_kernel_CommonBranchOrdering.java
|
5,597
|
POSTORDER_DEPTH_FIRST
{
public BranchSelector create( TraversalBranch startSource, PathExpander expander )
{
return BranchOrderingPolicies.POSTORDER_DEPTH_FIRST.create( startSource, expander );
}
},
| false
|
community_kernel_src_main_java_org_neo4j_kernel_CommonBranchOrdering.java
|
5,598
|
PREORDER_DEPTH_FIRST
{
public BranchSelector create( TraversalBranch startSource, PathExpander expander )
{
return BranchOrderingPolicies.PREORDER_DEPTH_FIRST.create( startSource, expander );
}
},
| false
|
community_kernel_src_main_java_org_neo4j_kernel_CommonBranchOrdering.java
|
5,599
|
{
@Override
public void release() throws IOException
{
}
};
| false
|
community_kernel_src_test_java_org_neo4j_kernel_CannedFileSystemAbstraction.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.