Unnamed: 0
int64 0
6.7k
| func
stringlengths 12
89.6k
| target
bool 2
classes | project
stringlengths 45
151
|
|---|---|---|---|
4,900
|
{
@Override
public void process( NodePropertyUpdate update ) throws IOException, IndexEntryConflictException
{
delegate.process( update );
}
@Override
public void close() throws IOException, IndexEntryConflictException
{
try
{
delegate.close();
}
finally
{
closeCall();
}
}
};
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_index_ContractCheckingIndexProxy.java
|
4,901
|
public class ContractCheckingIndexProxy extends DelegatingIndexProxy
{
/**
* State machine for {@link IndexProxy proxies}
*
* The logic of {@link ContractCheckingIndexProxy} hinges on the fact that all states
* are always entered and checked in this order (States may be skipped though):
*
* INIT > STARTING > STARTED > CLOSED
*
* Valid state transitions are:
*
* INIT -[:start]-> STARTING -[:implicit]-> STARTED -[:close|:drop]-> CLOSED
* INIT -[:close] -> CLOSED
*
* Additionally, {@link ContractCheckingIndexProxy} keeps track of the number of open
* calls that started in STARTED state and are still running. This allows us
* to prevent calls to close() or drop() to go through while there are pending
* commits.
**/
private static enum State
{
INIT, STARTING, STARTED, CLOSED
}
private final AtomicReference<State> state;
private final AtomicInteger openCalls;
public ContractCheckingIndexProxy( IndexProxy delegate, boolean started )
{
super( delegate );
this.state = new AtomicReference<>( started ? State.STARTED : State.INIT );
this.openCalls = new AtomicInteger( 0 );
}
@Override
public void start() throws IOException
{
if ( state.compareAndSet( State.INIT, State.STARTING ) )
{
try
{
super.start();
}
finally
{
this.state.set( State.STARTED );
}
}
else
{
throw new IllegalStateException( "An IndexProxy can only be started once" );
}
}
@Override
public IndexUpdater newUpdater( IndexUpdateMode mode )
{
if ( IndexUpdateMode.ONLINE == mode )
{
openCall( "update" );
return new DelegatingIndexUpdater( super.newUpdater( mode ) )
{
@Override
public void process( NodePropertyUpdate update ) throws IOException, IndexEntryConflictException
{
delegate.process( update );
}
@Override
public void close() throws IOException, IndexEntryConflictException
{
try
{
delegate.close();
}
finally
{
closeCall();
}
}
};
}
else
{
return super.newUpdater( mode );
}
}
@Override
public void force() throws IOException
{
openCall( "force" );
try
{
super.force();
}
finally
{
closeCall();
}
}
@Override
public Future<Void> drop() throws IOException
{
if ( state.compareAndSet( State.INIT, State.CLOSED ) )
return super.drop();
if ( State.STARTING.equals( state.get() ) )
throw new IllegalStateException( "Concurrent drop while creating index" );
if ( state.compareAndSet( State.STARTED, State.CLOSED ) )
{
ensureNoOpenCalls( "drop" );
return super.drop();
}
throw new IllegalStateException( "IndexProxy already closed" );
}
@Override
public Future<Void> close() throws IOException
{
if ( state.compareAndSet( State.INIT, State.CLOSED ) )
return super.close();
if ( state.compareAndSet( State.STARTING, State.CLOSED ) )
throw new IllegalStateException( "Concurrent close while creating index" );
if ( state.compareAndSet( State.STARTED, State.CLOSED ) )
{
ensureNoOpenCalls( "close" );
return super.close();
}
throw new IllegalStateException( "IndexProxy already closed" );
}
private void openCall( String name )
{
// do not open call unless we are in STARTED
if ( State.STARTED.equals( state.get() ) )
{
// increment openCalls for closers to see
openCalls.incrementAndGet();
// ensure that the previous increment actually gets seen by closers
if ( State.CLOSED.equals( state.get() ) )
throw new IllegalStateException("Cannot call " + name + "() after index has been closed" );
}
else
throw new IllegalStateException("Cannot call " + name + "() before index has been started" );
}
private void ensureNoOpenCalls(String name)
{
if (openCalls.get() > 0)
throw new IllegalStateException( "Concurrent " + name + "() while updates have not completed" );
}
private void closeCall()
{
// rollback once the call finished or failed
openCalls.decrementAndGet();
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_index_ContractCheckingIndexProxy.java
|
4,902
|
public abstract class CollectingIndexUpdater implements IndexUpdater
{
protected final ArrayList<NodePropertyUpdate> updates = new ArrayList<>();
@Override
public void process( NodePropertyUpdate update )
{
if ( null != update )
{
updates.add( update );
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_CollectingIndexUpdater.java
|
4,903
|
public abstract class AbstractSwallowingIndexProxy implements IndexProxy
{
private final IndexDescriptor descriptor;
private final SchemaIndexProvider.Descriptor providerDescriptor;
private final IndexPopulationFailure populationFailure;
public AbstractSwallowingIndexProxy( IndexDescriptor descriptor, SchemaIndexProvider.Descriptor providerDescriptor,
IndexPopulationFailure populationFailure )
{
this.descriptor = descriptor;
this.providerDescriptor = providerDescriptor;
this.populationFailure = populationFailure;
}
@Override
public IndexPopulationFailure getPopulationFailure()
{
return populationFailure;
}
@Override
public void start()
{
String message = "Unable to start index, it is in a " + getState().name() + " state.";
throw new UnsupportedOperationException( message + ", caused by: " + getPopulationFailure() );
}
@Override
public IndexUpdater newUpdater( IndexUpdateMode mode )
{
return SwallowingIndexUpdater.INSTANCE;
}
@Override
public void force()
{
}
@Override
public IndexDescriptor getDescriptor()
{
return descriptor;
}
@Override
public SchemaIndexProvider.Descriptor getProviderDescriptor()
{
return providerDescriptor;
}
@Override
public Future<Void> close()
{
return VOID;
}
@Override
public IndexReader newReader()
{
throw new UnsupportedOperationException();
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_index_AbstractSwallowingIndexProxy.java
|
4,904
|
public abstract class AbstractDelegatingIndexProxy implements IndexProxy
{
protected abstract IndexProxy getDelegate();
@Override
public void start() throws IOException
{
getDelegate().start();
}
@Override
public IndexUpdater newUpdater( IndexUpdateMode mode )
{
return getDelegate().newUpdater( mode );
}
@Override
public Future<Void> drop() throws IOException
{
return getDelegate().drop();
}
@Override
public InternalIndexState getState()
{
return getDelegate().getState();
}
@Override
public IndexDescriptor getDescriptor()
{
return getDelegate().getDescriptor();
}
@Override
public SchemaIndexProvider.Descriptor getProviderDescriptor()
{
return getDelegate().getProviderDescriptor();
}
@Override
public void force() throws IOException
{
getDelegate().force();
}
@Override
public Future<Void> close() throws IOException
{
return getDelegate().close();
}
@Override
public IndexReader newReader() throws IndexNotFoundKernelException
{
return getDelegate().newReader();
}
@Override
public boolean awaitStoreScanCompleted() throws IndexPopulationFailedKernelException, InterruptedException
{
return getDelegate().awaitStoreScanCompleted();
}
@Override
public void activate() throws IndexActivationFailedKernelException
{
getDelegate().activate();
}
@Override
public void validate() throws ConstraintVerificationFailedKernelException, IndexPopulationFailedKernelException
{
getDelegate().validate();
}
@Override
public IndexPopulationFailure getPopulationFailure() throws IllegalStateException
{
return getDelegate().getPopulationFailure();
}
@Override
public String toString()
{
return String.format( "%s -> %s", getClass().getSimpleName(), getDelegate().toString() );
}
@Override
public ResourceIterator<File> snapshotFiles() throws IOException
{
return getDelegate().snapshotFiles();
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_index_AbstractDelegatingIndexProxy.java
|
4,905
|
private static class StubTransactor extends Transactor
{
final List<KernelStatement> transactions = new ArrayList<>();
StubTransactor()
{
super( null, null );
}
@Override
public <RESULT, FAILURE extends KernelException> RESULT execute(
Work<RESULT, FAILURE> work ) throws FAILURE
{
KernelStatement state = mockedState();
transactions.add( state );
return work.perform( state );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_constraints_ConstraintIndexCreatorTest.java
|
4,906
|
public class ConstraintIndexCreatorTest
{
@Test
public void shouldCreateIndexInAnotherTransaction() throws Exception
{
// given
StatementOperationParts constraintCreationContext = mockedParts();
StatementOperationParts indexCreationContext = mockedParts();
IndexDescriptor descriptor = new IndexDescriptor( 123, 456 );
KernelStatement state = mockedState();
IndexingService indexingService = mock( IndexingService.class );
StubTransactor transactor = new StubTransactor();
when( constraintCreationContext.schemaReadOperations().indexGetCommittedId( state, descriptor, CONSTRAINT ) )
.thenReturn( 2468l );
IndexProxy indexProxy = mock( IndexProxy.class );
when( indexingService.getProxyForRule( 2468l ) ).thenReturn( indexProxy );
ConstraintIndexCreator creator = new ConstraintIndexCreator( transactor, indexingService );
// when
long indexId = creator.createUniquenessConstraintIndex( state, constraintCreationContext.schemaReadOperations(), 123, 456 );
// then
assertEquals( 2468l, indexId );
assertEquals( 1, transactor.transactions.size() );
verify( transactor.transactions.get( 0 ).txState() ).constraintIndexRuleDoAdd( descriptor );
verifyNoMoreInteractions( indexCreationContext.schemaWriteOperations() );
verify( constraintCreationContext.schemaReadOperations() ).indexGetCommittedId( state, descriptor, CONSTRAINT );
verifyNoMoreInteractions( constraintCreationContext.schemaReadOperations() );
verify( indexProxy ).awaitStoreScanCompleted();
}
@Test
public void shouldDropIndexIfPopulationFails() throws Exception
{
// given
StatementOperationParts constraintCreationContext = mockedParts();
KernelStatement state = mockedState();
IndexDescriptor descriptor = new IndexDescriptor( 123, 456 );
IndexingService indexingService = mock( IndexingService.class );
StubTransactor transactor = new StubTransactor();
when( constraintCreationContext.schemaReadOperations().indexGetCommittedId( state, descriptor, CONSTRAINT ) )
.thenReturn( 2468l );
IndexProxy indexProxy = mock( IndexProxy.class );
when( indexingService.getProxyForRule( 2468l ) ).thenReturn( indexProxy );
PreexistingIndexEntryConflictException cause = new PreexistingIndexEntryConflictException("a", 2, 1);
doThrow( new IndexPopulationFailedKernelException( descriptor, "some index", cause) )
.when(indexProxy).awaitStoreScanCompleted();
ConstraintIndexCreator creator = new ConstraintIndexCreator( transactor, indexingService );
// when
try
{
creator.createUniquenessConstraintIndex( state, constraintCreationContext.schemaReadOperations(), 123, 456 );
fail( "expected exception" );
}
// then
catch ( ConstraintVerificationFailedKernelException e )
{
assertEquals( "Existing data does not satisfy CONSTRAINT ON ( n:label[123] ) ASSERT n.property[456] IS UNIQUE.",
e.getMessage() );
}
assertEquals( 2, transactor.transactions.size() );
TxState tx1 = transactor.transactions.get( 0 ).txState();
verify( tx1 ).constraintIndexRuleDoAdd( new IndexDescriptor( 123, 456 ) );
verifyNoMoreInteractions( tx1 );
verify( constraintCreationContext.schemaReadOperations() ).indexGetCommittedId( state, descriptor, CONSTRAINT );
verifyNoMoreInteractions( constraintCreationContext.schemaReadOperations() );
TxState tx2 = transactor.transactions.get( 1 ).txState();
verify( tx2 ).constraintIndexDoDrop( new IndexDescriptor( 123, 456 ) );
verifyNoMoreInteractions( tx2 );
}
@Test
public void shouldDropIndexInAnotherTransaction() throws Exception
{
// given
StubTransactor transactor = new StubTransactor();
IndexingService indexingService = mock( IndexingService.class );
IndexDescriptor descriptor = new IndexDescriptor( 123, 456 );
ConstraintIndexCreator creator = new ConstraintIndexCreator( transactor, indexingService );
// when
creator.dropUniquenessConstraintIndex( descriptor );
// then
assertEquals( 1, transactor.transactions.size() );
verify( transactor.transactions.get( 0 ).txState() ).constraintIndexDoDrop( descriptor );
verifyZeroInteractions( indexingService );
}
private static class StubTransactor extends Transactor
{
final List<KernelStatement> transactions = new ArrayList<>();
StubTransactor()
{
super( null, null );
}
@Override
public <RESULT, FAILURE extends KernelException> RESULT execute(
Work<RESULT, FAILURE> work ) throws FAILURE
{
KernelStatement state = mockedState();
transactions.add( state );
return work.perform( state );
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_constraints_ConstraintIndexCreatorTest.java
|
4,907
|
private static class SpecificKernelException extends KernelException
{
protected SpecificKernelException()
{
super( Status.General.UnknownFailure, "very specific" );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_TransactorTest.java
|
4,908
|
public class TransactorTest
{
private final AbstractTransactionManager txManager = mock( AbstractTransactionManager.class );
private final PersistenceManager pm = mock(PersistenceManager.class);
private final Statement statement = mock( Statement.class );
private final KernelTransaction kernelTransaction = mock( KernelTransaction.class );
@SuppressWarnings("unchecked")
private final Transactor.Work<Object, KernelException> work = mock( Transactor.Work.class );
private final Transactor transactor = new Transactor( txManager, pm );
@Test
public void shouldCommitSuccessfulStatement() throws Exception
{
// given
javax.transaction.Transaction existingTransaction = mock( javax.transaction.Transaction.class );
when( txManager.suspend() ).thenReturn( existingTransaction );
when( pm.currentKernelTransactionForWriting() ).thenReturn( kernelTransaction );
when( kernelTransaction.acquireStatement() ).thenReturn( statement );
Object expectedResult = new Object();
when( work.perform( statement ) ).thenReturn( expectedResult );
// when
Object result = transactor.execute( work );
// then
assertEquals( expectedResult, result );
InOrder order = inOrder( txManager, pm, kernelTransaction );
order.verify( txManager ).suspend();
order.verify( txManager ).begin();
order.verify( pm ).currentKernelTransactionForWriting();
order.verify( txManager ).commit();
order.verify( txManager ).resume( existingTransaction );
order.verifyNoMoreInteractions();
}
@Test
public void shouldRollbackFailingStatement() throws Exception
{
// given
javax.transaction.Transaction existingTransaction = mock( javax.transaction.Transaction.class );
when( txManager.suspend() ).thenReturn( existingTransaction );
when( pm.currentKernelTransactionForWriting() ).thenReturn( kernelTransaction );
when( kernelTransaction.acquireStatement() ).thenReturn( statement );
SpecificKernelException exception = new SpecificKernelException();
when( work.perform( any( KernelStatement.class ) ) ).thenThrow( exception );
// when
try
{
transactor.execute( work );
fail( "expected exception" );
}
// then
catch ( SpecificKernelException e )
{
assertSame( exception, e );
}
InOrder order = inOrder( txManager, pm, kernelTransaction, work );
order.verify( txManager ).suspend();
order.verify( txManager ).begin();
order.verify( pm ).currentKernelTransactionForWriting();
order.verify( txManager ).rollback();
order.verify( txManager ).resume( existingTransaction );
order.verifyNoMoreInteractions();
}
@Test
public void shouldNotResumeATransactionIfThereWasNoTransactionSuspended() throws Exception
{
// given
when( txManager.suspend() ).thenReturn( null );
when( pm.currentKernelTransactionForWriting() ).thenReturn( kernelTransaction );
when( kernelTransaction.acquireStatement() ).thenReturn( statement );
Object expectedResult = new Object();
when( work.perform( statement ) ).thenReturn( expectedResult );
// when
Object result = transactor.execute( work );
// then
assertEquals( expectedResult, result );
InOrder order = inOrder( txManager, pm, kernelTransaction, work );
order.verify( txManager ).suspend();
order.verify( txManager ).begin();
order.verify( pm ).currentKernelTransactionForWriting();
order.verify( work ).perform( statement );
order.verify( txManager ).commit();
order.verifyNoMoreInteractions();
}
@Test
public void shouldPropagateNotSupportedExceptionFromBegin() throws Exception
{
// given
when( txManager.suspend() ).thenReturn( mock( javax.transaction.Transaction.class ) );
NotSupportedException exception = new NotSupportedException();
doThrow( exception ).when( txManager ).begin();
// when
try
{
transactor.execute( work );
fail( "expected exception" );
}
// then
catch ( TransactionFailureException e )
{
assertSame( exception, e.getCause().getCause() );
}
verifyZeroInteractions( work );
verify( txManager ).suspend();
verify( txManager ).begin();
verifyNoMoreInteractions( txManager );
}
@Test
public void shouldPropagateSystemExceptionFromBegin() throws Exception
{
// given
when( txManager.suspend() ).thenReturn( mock( javax.transaction.Transaction.class ) );
SystemException exception = new SystemException();
doThrow( exception ).when( txManager ).begin();
// when
try
{
transactor.execute( work );
fail( "expected exception" );
}
// then
catch ( TransactionFailureException e )
{
assertSame( exception, e.getCause().getCause() );
}
verifyZeroInteractions( work );
verify( txManager ).suspend();
verify( txManager ).begin();
verifyNoMoreInteractions( txManager );
}
@Test
public void shouldPropagateSystemExceptionFromSuspendTransaction() throws Exception
{
// given
SystemException exception = new SystemException();
doThrow( exception ).when( txManager ).suspend();
// when
try
{
transactor.execute( work );
fail( "expected exception" );
}
// then
catch ( TransactionFailureException e )
{
assertSame( exception, e.getCause() );
}
verifyZeroInteractions( work );
verify( txManager ).suspend();
verifyNoMoreInteractions( txManager );
}
@Test
public void shouldPropagateSystemExceptionFromResumeTransaction() throws Exception
{
// given
SystemException exception = new SystemException();
doThrow( exception ).when( txManager ).suspend();
// when
try
{
transactor.execute( work );
fail( "expected exception" );
}
// then
catch ( TransactionFailureException e )
{
assertSame( exception, e.getCause() );
}
verifyZeroInteractions( work );
}
private static class SpecificKernelException extends KernelException
{
protected SpecificKernelException()
{
super( Status.General.UnknownFailure, "very specific" );
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_TransactorTest.java
|
4,909
|
when( state.hasTxStateWithChanges() ).thenAnswer( new Answer<Boolean>() {
@Override
public Boolean answer( InvocationOnMock invocation ) throws Throwable
{
return txState.hasChanges();
}
} );
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_StatementOperationsTestHelper.java
|
4,910
|
public abstract class StatementOperationsTestHelper
{
public static StatementOperationParts mockedParts()
{
return new StatementOperationParts(
mock( KeyReadOperations.class ),
mock( KeyWriteOperations.class ),
mock( EntityReadOperations.class ),
mock( EntityWriteOperations.class ),
mock( SchemaReadOperations.class ),
mock( SchemaWriteOperations.class ),
mock( SchemaStateOperations.class ));
}
public static KernelStatement mockedState()
{
return mockedState( mock( TxState.class ) );
}
public static KernelStatement mockedState( final TxState txState )
{
KernelStatement state = mock( KernelStatement.class );
LockHolder lockHolder = mock( LockHolder.class );
ReleasableLock lock = mock( ReleasableLock.class );
when( lockHolder.getReleasableIndexEntryReadLock( anyInt(), anyInt(), anyString() ) ).thenReturn( lock );
when( lockHolder.getReleasableIndexEntryWriteLock( anyInt(), anyInt(), anyString() ) ).thenReturn( lock );
try
{
IndexReader indexReader = mock( IndexReader.class );
when( indexReader.lookup( Matchers.any() ) ).thenReturn( IteratorUtil.emptyPrimitiveLongIterator() );
when( state.getIndexReader( anyLong() ) ).thenReturn( indexReader );
}
catch ( IndexNotFoundKernelException e )
{
throw new Error( e );
}
when( state.txState() ).thenReturn( txState );
when( state.hasTxState() ).thenReturn( true );
when( state.hasTxStateWithChanges() ).thenAnswer( new Answer<Boolean>() {
@Override
public Boolean answer( InvocationOnMock invocation ) throws Throwable
{
return txState.hasChanges();
}
} );
when( state.locks() ).thenReturn( lockHolder );
return state;
}
private StatementOperationsTestHelper()
{ // Singleton
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_StatementOperationsTestHelper.java
|
4,911
|
public class StatementOperationParts
{
private final KeyReadOperations keyReadOperations;
private final KeyWriteOperations keyWriteOperations;
private final EntityReadOperations entityReadOperations;
private final EntityWriteOperations entityWriteOperations;
private final SchemaReadOperations schemaReadOperations;
private final SchemaWriteOperations schemaWriteOperations;
private final SchemaStateOperations schemaStateOperations;
@SuppressWarnings( "rawtypes" )
private Map<Class,Object> additionalParts;
public StatementOperationParts(
KeyReadOperations keyReadOperations,
KeyWriteOperations keyWriteOperations,
EntityReadOperations entityReadOperations,
EntityWriteOperations entityWriteOperations,
SchemaReadOperations schemaReadOperations,
SchemaWriteOperations schemaWriteOperations,
SchemaStateOperations schemaStateOperations )
{
this.keyReadOperations = keyReadOperations;
this.keyWriteOperations = keyWriteOperations;
this.entityReadOperations = entityReadOperations;
this.entityWriteOperations = entityWriteOperations;
this.schemaReadOperations = schemaReadOperations;
this.schemaWriteOperations = schemaWriteOperations;
this.schemaStateOperations = schemaStateOperations;
}
public <T> StatementOperationParts additionalPart( Class<T> cls, T value )
{
if ( additionalParts == null )
{
additionalParts = new HashMap<>();
}
additionalParts.put( cls, value );
return this;
}
@SuppressWarnings( "unchecked" )
public <T> T resolve( Class<T> cls )
{
T part = additionalParts != null ? (T) additionalParts.get( cls ) : null;
if ( part == null )
{
throw new IllegalArgumentException( "No part " + cls.getName() );
}
return part;
}
public KeyReadOperations keyReadOperations()
{
return checkNotNull( keyReadOperations, KeyReadOperations.class );
}
public KeyWriteOperations keyWriteOperations()
{
return checkNotNull( keyWriteOperations, KeyWriteOperations.class );
}
public EntityReadOperations entityReadOperations()
{
return checkNotNull( entityReadOperations, EntityReadOperations.class );
}
public EntityWriteOperations entityWriteOperations()
{
return checkNotNull( entityWriteOperations, EntityWriteOperations.class );
}
public SchemaReadOperations schemaReadOperations()
{
return checkNotNull( schemaReadOperations, SchemaReadOperations.class );
}
public SchemaWriteOperations schemaWriteOperations()
{
return checkNotNull( schemaWriteOperations, SchemaWriteOperations.class );
}
public SchemaStateOperations schemaStateOperations()
{
return checkNotNull( schemaStateOperations, SchemaStateOperations.class );
}
@SuppressWarnings( { "unchecked", "rawtypes" } )
public StatementOperationParts override(
KeyReadOperations keyReadOperations,
KeyWriteOperations keyWriteOperations,
EntityReadOperations entityReadOperations,
EntityWriteOperations entityWriteOperations,
SchemaReadOperations schemaReadOperations,
SchemaWriteOperations schemaWriteOperations,
SchemaStateOperations schemaStateOperations,
Object... alternatingAdditionalClassAndObject )
{
StatementOperationParts parts = new StatementOperationParts(
eitherOr( keyReadOperations, this.keyReadOperations, KeyReadOperations.class ),
eitherOr( keyWriteOperations, this.keyWriteOperations, KeyWriteOperations.class ),
eitherOr( entityReadOperations, this.entityReadOperations, EntityReadOperations.class ),
eitherOr( entityWriteOperations, this.entityWriteOperations, EntityWriteOperations.class ),
eitherOr( schemaReadOperations, this.schemaReadOperations, SchemaReadOperations.class ),
eitherOr( schemaWriteOperations, this.schemaWriteOperations, SchemaWriteOperations.class ),
eitherOr( schemaStateOperations, this.schemaStateOperations, SchemaStateOperations.class ));
if ( additionalParts != null )
{
parts.additionalParts = new HashMap<>( additionalParts );
}
for ( int i = 0; i < alternatingAdditionalClassAndObject.length; i++ )
{
parts.additionalPart( (Class) alternatingAdditionalClassAndObject[i++],
alternatingAdditionalClassAndObject[i] );
}
return parts;
}
private <T> T checkNotNull( T object, Class<T> cls )
{
if ( object == null )
{
throw new IllegalStateException( "No part of type " + cls.getSimpleName() + " assigned" );
}
return object;
}
private <T> T eitherOr( T first, T other, @SuppressWarnings("UnusedParameters"/*used as type flag*/) Class<T> cls )
{
return first != null ? first : other;
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_StatementOperationParts.java
|
4,912
|
public class StatementLifecycleTest
{
@Test
public void shouldReleaseItselfWhenClosed() throws Exception
{
// given
KernelTransactionImplementation transaction = mock( KernelTransactionImplementation.class );
KernelStatement statement = new KernelStatement( transaction, mock( IndexReaderFactory.class ), null, null,
null, null, null, null );
statement.acquire();
// when
statement.close();
// then
verify( transaction ).releaseStatement( statement );
}
@Test
public void shouldReleaseWhenAllNestedStatementsClosed() throws Exception
{
// given
KernelTransactionImplementation transaction = mock( KernelTransactionImplementation.class );
KernelStatement statement = new KernelStatement( transaction, mock( IndexReaderFactory.class ), null, null,
null, null, null, null );
statement.acquire();
statement.acquire();
// when
statement.close();
statement.close();
// then
verify( transaction ).releaseStatement( statement );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_StatementLifecycleTest.java
|
4,913
|
private class HasPropertyFilter implements Predicate<Long>
{
private final Object value;
private final int propertyKeyId;
private final KernelStatement state;
public HasPropertyFilter( KernelStatement state, int propertyKeyId, Object value )
{
this.state = state;
this.value = value;
this.propertyKeyId = propertyKeyId;
}
@Override
public boolean accept( Long nodeId )
{
try
{
if ( state.hasTxStateWithChanges() && state.txState().nodeIsDeletedInThisTx( nodeId ) )
{
return false;
}
Property property = nodeGetProperty( state, nodeId, propertyKeyId );
return property.isDefined() && property.valueEquals( value );
}
catch ( EntityNotFoundException e )
{
return false;
}
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_StateHandlingStatementOperations.java
|
4,914
|
private class HasLabelFilter implements Predicate<Long>
{
private final int labelId;
private final KernelStatement state;
public HasLabelFilter( KernelStatement state, int labelId )
{
this.state = state;
this.labelId = labelId;
}
@Override
public boolean accept( Long nodeId )
{
try
{
return nodeHasLabel( state, nodeId, labelId );
}
catch ( EntityNotFoundException e )
{
return false;
}
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_StateHandlingStatementOperations.java
|
4,915
|
{
@Override
public void run() throws IOException
{
outer.start();
}
} );
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_ContractCheckingIndexProxyTest.java
|
4,916
|
{
@Override
public void run() throws IOException
{
try (IndexUpdater updater = outer.newUpdater( IndexUpdateMode.ONLINE ))
{
updater.process( null );
latch.startAndAwaitFinish();
}
catch ( IndexEntryConflictException e )
{
throw new RuntimeException( e );
}
}
} );
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_ContractCheckingIndexProxyTest.java
|
4,917
|
{
@Override
Void perform( GraphDatabaseService graphDb )
{
entity.setProperty( key, value );
return null;
}
};
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_DataAndSchemaTransactionSeparationIT.java
|
4,918
|
{
@Override
public void force()
{
latch.startAndAwaitFinish();
}
};
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_ContractCheckingIndexProxyTest.java
|
4,919
|
private class GatheringIndexWriter extends IndexAccessor.Adapter implements IndexPopulator
{
private final Set<NodePropertyUpdate> updatesCommitted = new HashSet<>();
private final String propertyKey;
public GatheringIndexWriter( String propertyKey )
{
this.propertyKey = propertyKey;
}
@Override
public void create()
{
}
@Override
public void add( long nodeId, Object propertyValue )
{
ReadOperations statement = ctxProvider.instance().readOperations();
updatesCommitted.add( NodePropertyUpdate.add(
nodeId, statement.propertyKeyGetForName( propertyKey ),
propertyValue, new long[]{statement.labelGetForName( myLabel.name() )} ) );
}
@Override
public void verifyDeferredConstraints( PropertyAccessor propertyAccessor ) throws IndexEntryConflictException, IOException
{
}
@Override
public IndexUpdater newPopulatingUpdater( PropertyAccessor propertyAccessor ) throws IOException
{
return newUpdater( IndexUpdateMode.ONLINE );
}
@Override
public IndexUpdater newUpdater( final IndexUpdateMode mode )
{
return new CollectingIndexUpdater()
{
@Override
public void close() throws IOException, IndexEntryConflictException
{
if ( IndexUpdateMode.ONLINE == mode )
{
updatesCommitted.addAll( updates );
}
}
@Override
public void remove( Iterable<Long> nodeIds ) throws IOException
{
throw new UnsupportedOperationException( "not expected" );
}
};
}
@Override
public void close( boolean populationCompletedSuccessfully )
{
}
@Override
public void markAsFailed( String failure )
{
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_IndexCRUDIT.java
|
4,920
|
public class IndexCRUDIT
{
@Test
public void addingANodeWithPropertyShouldGetIndexed() throws Exception
{
// Given
String indexProperty = "indexProperty";
GatheringIndexWriter writer = newWriter( indexProperty );
createIndex( db, myLabel, indexProperty );
// When
int value1 = 12;
String otherProperty = "otherProperty";
int otherValue = 17;
Node node = createNode( map( indexProperty, value1, otherProperty, otherValue ), myLabel );
// Then, for now, this should trigger two NodePropertyUpdates
try ( Transaction tx = db.beginTx() )
{
DataWriteOperations statement = ctxProvider.instance().dataWriteOperations();
int propertyKey1 = statement.propertyKeyGetForName( indexProperty );
long[] labels = new long[]{statement.labelGetForName( myLabel.name() )};
assertThat( writer.updatesCommitted, equalTo( asSet(
NodePropertyUpdate.add( node.getId(), propertyKey1, value1, labels ) ) ) );
tx.success();
}
// We get two updates because we both add a label and a property to be indexed
// in the same transaction, in the future, we should optimize this down to
// one NodePropertyUpdate.
}
@Test
public void addingALabelToPreExistingNodeShouldGetIndexed() throws Exception
{
// GIVEN
String indexProperty = "indexProperty";
GatheringIndexWriter writer = newWriter( indexProperty );
createIndex( db, myLabel, indexProperty );
// WHEN
String otherProperty = "otherProperty";
int value = 12;
int otherValue = 17;
Node node = createNode( map( indexProperty, value, otherProperty, otherValue ) );
// THEN
assertThat( writer.updatesCommitted.size(), equalTo( 0 ) );
// AND WHEN
try ( Transaction tx = db.beginTx() )
{
node.addLabel( myLabel );
tx.success();
}
// THEN
try ( Transaction tx = db.beginTx() )
{
DataWriteOperations statement = ctxProvider.instance().dataWriteOperations();
int propertyKey1 = statement.propertyKeyGetForName( indexProperty );
long[] labels = new long[]{statement.labelGetForName( myLabel.name() )};
assertThat( writer.updatesCommitted, equalTo( asSet(
NodePropertyUpdate.add( node.getId(), propertyKey1, value, labels ) ) ) );
tx.success();
}
}
@SuppressWarnings("deprecation") private GraphDatabaseAPI db;
@Rule public EphemeralFileSystemRule fs = new EphemeralFileSystemRule();
private final SchemaIndexProvider mockedIndexProvider = mock( SchemaIndexProvider.class );
private final KernelExtensionFactory<?> mockedIndexProviderFactory =
singleInstanceSchemaIndexProviderFactory( "none", mockedIndexProvider );
private ThreadToStatementContextBridge ctxProvider;
private final Label myLabel = label( "MYLABEL" );
private Node createNode( Map<String, Object> properties, Label ... labels )
{
try ( Transaction tx = db.beginTx() )
{
Node node = db.createNode( labels );
for ( Map.Entry<String, Object> prop : properties.entrySet() )
{
node.setProperty( prop.getKey(), prop.getValue() );
}
tx.success();
return node;
}
}
@SuppressWarnings("deprecation")
@Before
public void before() throws Exception
{
TestGraphDatabaseFactory factory = new TestGraphDatabaseFactory();
factory.setFileSystem( fs.get() );
factory.addKernelExtensions( Arrays.<KernelExtensionFactory<?>>asList( mockedIndexProviderFactory ) );
db = (GraphDatabaseAPI) factory.newImpermanentDatabase();
ctxProvider = db.getDependencyResolver().resolveDependency( ThreadToStatementContextBridge.class );
}
private GatheringIndexWriter newWriter( String propertyKey ) throws IOException
{
GatheringIndexWriter writer = new GatheringIndexWriter( propertyKey );
when( mockedIndexProvider.getPopulator(
anyLong(), any( IndexDescriptor.class ), any( IndexConfiguration.class ) ) ).thenReturn( writer );
when( mockedIndexProvider.getProviderDescriptor() ).thenReturn( PROVIDER_DESCRIPTOR );
when( mockedIndexProvider.getOnlineAccessor( anyLong(), any( IndexConfiguration.class ) ) ).thenReturn( writer );
when( mockedIndexProvider.compareTo( any( SchemaIndexProvider.class ) ) ).thenReturn( 1 ); // always pretend to have highest priority
return writer;
}
@After
public void after() throws Exception
{
db.shutdown();
}
private class GatheringIndexWriter extends IndexAccessor.Adapter implements IndexPopulator
{
private final Set<NodePropertyUpdate> updatesCommitted = new HashSet<>();
private final String propertyKey;
public GatheringIndexWriter( String propertyKey )
{
this.propertyKey = propertyKey;
}
@Override
public void create()
{
}
@Override
public void add( long nodeId, Object propertyValue )
{
ReadOperations statement = ctxProvider.instance().readOperations();
updatesCommitted.add( NodePropertyUpdate.add(
nodeId, statement.propertyKeyGetForName( propertyKey ),
propertyValue, new long[]{statement.labelGetForName( myLabel.name() )} ) );
}
@Override
public void verifyDeferredConstraints( PropertyAccessor propertyAccessor ) throws IndexEntryConflictException, IOException
{
}
@Override
public IndexUpdater newPopulatingUpdater( PropertyAccessor propertyAccessor ) throws IOException
{
return newUpdater( IndexUpdateMode.ONLINE );
}
@Override
public IndexUpdater newUpdater( final IndexUpdateMode mode )
{
return new CollectingIndexUpdater()
{
@Override
public void close() throws IOException, IndexEntryConflictException
{
if ( IndexUpdateMode.ONLINE == mode )
{
updatesCommitted.addAll( updates );
}
}
@Override
public void remove( Iterable<Long> nodeIds ) throws IOException
{
throw new UnsupportedOperationException( "not expected" );
}
};
}
@Override
public void close( boolean populationCompletedSuccessfully )
{
}
@Override
public void markAsFailed( String failure )
{
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_IndexCRUDIT.java
|
4,921
|
{
@Override
public IndexProxy create( Throwable failure )
{
return failed;
}
};
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_FlippableIndexProxyTest.java
|
4,922
|
{
@Override
public IndexProxy create()
{
return proxy;
}
};
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_FlippableIndexProxyTest.java
|
4,923
|
{
@Override
public Void call() throws Exception
{
return null;
}
};
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_FlippableIndexProxyTest.java
|
4,924
|
{
@Override
public Void call()
{
triggerExternalAccess.countDown();
awaitLatch( triggerFinishFlip );
return null;
}
}, null );
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_FlippableIndexProxyTest.java
|
4,925
|
{
@Override
public Void doWork( Void state ) throws FlipFailedKernelException
{
flippable.flip( new Callable<Void>()
{
@Override
public Void call()
{
triggerExternalAccess.countDown();
awaitLatch( triggerFinishFlip );
return null;
}
}, null );
return null;
}
};
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_FlippableIndexProxyTest.java
|
4,926
|
{
@Override
public Void doWork( Void state ) throws IOException
{
awaitFuture( flippable.drop() );
return null;
}
};
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_FlippableIndexProxyTest.java
|
4,927
|
public class FlippableIndexProxyTest
{
@Test
public void shouldBeAbleToSwitchDelegate() throws Exception
{
// GIVEN
IndexProxy actual = mockIndexProxy();
IndexProxy other = mockIndexProxy();
FlippableIndexProxy delegate = new FlippableIndexProxy(actual);
delegate.setFlipTarget( singleProxy( other ) );
// WHEN
delegate.flip( noOp(), null );
delegate.drop().get();
// THEN
verify( other ).drop();
}
@Test
public void shouldNotBeAbleToFlipAfterClosed() throws Exception
{
//GIVEN
IndexProxy actual = mockIndexProxy();
IndexProxyFactory indexContextFactory = mock( IndexProxyFactory.class );
FlippableIndexProxy delegate = new FlippableIndexProxy( actual );
//WHEN
delegate.close().get();
delegate.setFlipTarget( indexContextFactory );
//THEN
try
{
delegate.flip( noOp(), null );
fail("Expected IndexProxyAlreadyClosedKernelException to be thrown");
}
catch ( IndexProxyAlreadyClosedKernelException e )
{
// expected
}
}
@Test
public void shouldNotBeAbleToFlipAfterDrop() throws Exception
{
//GIVEN
IndexProxy actual = mockIndexProxy();
IndexProxy failed = mockIndexProxy();
IndexProxyFactory indexContextFactory = mock( IndexProxyFactory.class );
FlippableIndexProxy delegate = new FlippableIndexProxy( actual );
delegate.setFlipTarget( indexContextFactory );
//WHEN
delegate.drop().get();
//THEN
try
{
delegate.flip( noOp(), singleFailedDelegate( failed ) );
fail("Expected IndexProxyAlreadyClosedKernelException to be thrown");
}
catch ( IndexProxyAlreadyClosedKernelException e )
{
// expected
}
}
@Test
public void shouldBlockAccessDuringFlipAndThenDelegateToCorrectContext() throws Exception
{
// GIVEN
final IndexProxy contextBeforeFlip = mockIndexProxy();
final IndexProxy contextAfterFlip = mockIndexProxy();
final FlippableIndexProxy flippable = new FlippableIndexProxy( contextBeforeFlip );
flippable.setFlipTarget( singleProxy( contextAfterFlip ) );
// And given complicated thread race condition tools
final CountDownLatch triggerFinishFlip = new CountDownLatch( 1 );
final CountDownLatch triggerExternalAccess = new CountDownLatch( 1 );
OtherThreadExecutor<Void> flippingThread = new OtherThreadExecutor<Void>( "Flipping thread", null );
OtherThreadExecutor<Void> dropIndexThread = new OtherThreadExecutor<Void>( "Drop index thread", null );
// WHEN one thread starts flipping to another context
Future<Void> flipContextFuture = flippingThread.executeDontWait( startFlipAndWaitForLatchBeforeFinishing(
flippable,
triggerFinishFlip, triggerExternalAccess ) );
// And I wait until the flipping thread is in the middle of "the flip"
triggerExternalAccess.await( 10, SECONDS );
// And another thread comes along and drops the index
Future<Void> dropIndexFuture = dropIndexThread.executeDontWait( dropTheIndex( flippable ) );
dropIndexThread.waitUntilWaiting();
// And the flipping thread finishes the flip
triggerFinishFlip.countDown();
// And both threads get to finish up and return
dropIndexFuture.get( 10, SECONDS );
flipContextFuture.get( 10, SECONDS );
// THEN the thread wanting to drop the index should not have interacted with the original context
// eg. it should have waited for the flip to finish
verifyNoMoreInteractions( contextBeforeFlip );
// But it should have gotten to drop the new index context, after the flip happened.
verify( contextAfterFlip ).drop();
}
private OtherThreadExecutor.WorkerCommand<Void, Void> dropTheIndex( final FlippableIndexProxy flippable )
{
return new OtherThreadExecutor.WorkerCommand<Void, Void>()
{
@Override
public Void doWork( Void state ) throws IOException
{
awaitFuture( flippable.drop() );
return null;
}
};
}
private OtherThreadExecutor.WorkerCommand<Void, Void> startFlipAndWaitForLatchBeforeFinishing(
final FlippableIndexProxy flippable, final CountDownLatch triggerFinishFlip,
final CountDownLatch triggerExternalAccess )
{
return new OtherThreadExecutor.WorkerCommand<Void, Void>()
{
@Override
public Void doWork( Void state ) throws FlipFailedKernelException
{
flippable.flip( new Callable<Void>()
{
@Override
public Void call()
{
triggerExternalAccess.countDown();
awaitLatch( triggerFinishFlip );
return null;
}
}, null );
return null;
}
};
}
private Callable<Void> noOp()
{
return new Callable<Void>()
{
@Override
public Void call() throws Exception
{
return null;
}
};
}
public static IndexProxyFactory singleProxy( final IndexProxy proxy )
{
return new IndexProxyFactory()
{
@Override
public IndexProxy create()
{
return proxy;
}
};
}
private FailedIndexProxyFactory singleFailedDelegate( final IndexProxy failed )
{
return new FailedIndexProxyFactory()
{
@Override
public IndexProxy create( Throwable failure )
{
return failed;
}
};
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_FlippableIndexProxyTest.java
|
4,928
|
private class LockingIndexUpdater extends DelegatingIndexUpdater
{
private LockingIndexUpdater( IndexUpdater delegate )
{
super( delegate );
lock.readLock().lock();
}
@Override
public void process( NodePropertyUpdate update ) throws IOException, IndexEntryConflictException
{
delegate.process( update );
}
@Override
public void close() throws IOException, IndexEntryConflictException
{
try
{
delegate.close();
}
finally
{
lock.readLock().unlock();
}
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_index_FlippableIndexProxy.java
|
4,929
|
public class FlippableIndexProxy implements IndexProxy
{
private boolean closed;
private final ReadWriteLock lock = new ReentrantReadWriteLock( true );
private IndexProxyFactory flipTarget;
private IndexProxy delegate;
public FlippableIndexProxy()
{
this( null );
}
public FlippableIndexProxy( IndexProxy originalDelegate )
{
this.delegate = originalDelegate;
}
@Override
public void start() throws IOException
{
lock.readLock().lock();
try
{
delegate.start();
}
finally
{
lock.readLock().unlock();
}
}
@Override
public IndexUpdater newUpdater( IndexUpdateMode mode )
{
// Making use of reentrant locks to ensure that the delegate's constructor is called under lock protection
// while still retaining the lock until a call to close on the returned IndexUpdater
lock.readLock().lock();
try
{
return new LockingIndexUpdater( delegate.newUpdater( mode ) );
}
finally
{
lock.readLock().unlock();
}
}
@Override
public Future<Void> drop() throws IOException
{
lock.readLock().lock();
try
{
closed = true;
return delegate.drop();
}
finally
{
lock.readLock().unlock();
}
}
@Override
public void force() throws IOException
{
lock.readLock().lock();
try
{
delegate.force();
}
finally
{
lock.readLock().unlock();
}
}
@Override
public IndexDescriptor getDescriptor()
{
lock.readLock().lock();
try
{
return delegate.getDescriptor();
}
finally
{
lock.readLock().unlock();
}
}
@Override
public SchemaIndexProvider.Descriptor getProviderDescriptor()
{
lock.readLock().lock();
try
{
return delegate.getProviderDescriptor();
}
finally
{
lock.readLock().unlock();
}
}
@Override
public InternalIndexState getState()
{
lock.readLock().lock();
try
{
return delegate.getState();
}
finally
{
lock.readLock().unlock();
}
}
@Override
public Future<Void> close() throws IOException
{
lock.readLock().lock();
try
{
closed = true;
return delegate.close();
}
finally
{
lock.readLock().unlock();
}
}
@Override
public IndexReader newReader() throws IndexNotFoundKernelException
{
lock.readLock().lock();
try
{
return delegate.newReader();
}
finally
{
lock.readLock().unlock();
}
}
@Override
public boolean awaitStoreScanCompleted() throws IndexPopulationFailedKernelException, InterruptedException
{
IndexProxy proxy;
do
{
lock.readLock().lock();
proxy = delegate;
lock.readLock().unlock();
} while ( proxy.awaitStoreScanCompleted() );
return true;
}
@Override
public void activate() throws IndexActivationFailedKernelException
{
// use write lock, since activate() might call flip*() which acquires a write lock itself.
lock.writeLock().lock();
try
{
delegate.activate();
}
finally
{
lock.writeLock().unlock();
}
}
@Override
public void validate() throws IndexPopulationFailedKernelException, ConstraintVerificationFailedKernelException
{
lock.readLock().lock();
try
{
delegate.validate();
}
finally
{
lock.readLock().unlock();
}
}
@Override
public ResourceIterator<File> snapshotFiles() throws IOException
{
lock.readLock().lock();
try
{
return delegate.snapshotFiles();
}
finally
{
lock.readLock().unlock();
}
}
@Override
public IndexPopulationFailure getPopulationFailure() throws IllegalStateException
{
lock.readLock().lock();
try
{
return delegate.getPopulationFailure();
}
finally
{
lock.readLock().unlock();
}
}
public void setFlipTarget( IndexProxyFactory flipTarget )
{
lock.writeLock().lock();
try
{
this.flipTarget = flipTarget;
}
finally
{
lock.writeLock().unlock();
}
}
public void flipTo( IndexProxy targetDelegate )
{
lock.writeLock().lock();
try
{
this.delegate = targetDelegate;
}
finally
{
lock.writeLock().unlock();
}
}
public void flip( Callable<Void> actionDuringFlip, FailedIndexProxyFactory failureDelegate )
throws FlipFailedKernelException
{
lock.writeLock().lock();
try
{
assertStillOpenForBusiness();
try
{
actionDuringFlip.call();
this.delegate = flipTarget.create();
}
catch ( Exception e )
{
this.delegate = failureDelegate.create( e );
throw new ExceptionDuringFlipKernelException( e );
}
}
finally
{
lock.writeLock().unlock();
}
}
@Override
public String toString()
{
return getClass().getSimpleName() + " -> " + delegate + "[target:" + flipTarget + "]";
}
private void assertStillOpenForBusiness() throws IndexProxyAlreadyClosedKernelException
{
if ( closed )
{
throw new IndexProxyAlreadyClosedKernelException( this.getClass() );
}
}
private class LockingIndexUpdater extends DelegatingIndexUpdater
{
private LockingIndexUpdater( IndexUpdater delegate )
{
super( delegate );
lock.readLock().lock();
}
@Override
public void process( NodePropertyUpdate update ) throws IOException, IndexEntryConflictException
{
delegate.process( update );
}
@Override
public void close() throws IOException, IndexEntryConflictException
{
try
{
delegate.close();
}
finally
{
lock.readLock().unlock();
}
}
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_index_FlippableIndexProxy.java
|
4,930
|
public class FailedPopulatingIndexProxyFactory implements FailedIndexProxyFactory
{
private final IndexDescriptor descriptor;
private final SchemaIndexProvider.Descriptor providerDescriptor;
private final IndexPopulator populator;
private final String indexUserDescription;
FailedPopulatingIndexProxyFactory( IndexDescriptor descriptor,
SchemaIndexProvider.Descriptor providerDescriptor,
IndexPopulator populator,
String indexUserDescription )
{
this.descriptor = descriptor;
this.providerDescriptor = providerDescriptor;
this.populator = populator;
this.indexUserDescription = indexUserDescription;
}
@Override
public IndexProxy create( Throwable failure )
{
return
new FailedIndexProxy(
descriptor, providerDescriptor,
indexUserDescription, populator, failure( failure ) );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_index_FailedPopulatingIndexProxyFactory.java
|
4,931
|
public class FailedIndexProxy extends AbstractSwallowingIndexProxy
{
protected final IndexPopulator populator;
private final String indexUserDescription;
public FailedIndexProxy(IndexDescriptor descriptor, SchemaIndexProvider.Descriptor providerDescriptor,
String indexUserDescription,
IndexPopulator populator, IndexPopulationFailure populationFailure)
{
super( descriptor, providerDescriptor, populationFailure );
this.populator = populator;
this.indexUserDescription = indexUserDescription;
}
@Override
public Future<Void> drop() throws IOException
{
populator.drop();
return VOID;
}
@Override
public InternalIndexState getState()
{
return InternalIndexState.FAILED;
}
@Override
public boolean awaitStoreScanCompleted() throws IndexPopulationFailedKernelException
{
throw getPopulationFailure().asIndexPopulationFailure( getDescriptor(), indexUserDescription );
}
@Override
public void activate()
{
throw new UnsupportedOperationException( "Cannot activate a failed index." );
}
@Override
public void validate() throws IndexPopulationFailedKernelException
{
throw getPopulationFailure().asIndexPopulationFailure( getDescriptor(), indexUserDescription );
}
@Override
public ResourceIterator<File> snapshotFiles()
{
return emptyIterator();
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_index_FailedIndexProxy.java
|
4,932
|
public abstract class DelegatingIndexUpdater implements IndexUpdater
{
protected final IndexUpdater delegate;
public DelegatingIndexUpdater( IndexUpdater delegate )
{
this.delegate = delegate;
}
@Override
public void remove( Iterable<Long> nodeIds ) throws IOException
{
delegate.remove( nodeIds );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_index_DelegatingIndexUpdater.java
|
4,933
|
public class DelegatingIndexProxy extends AbstractDelegatingIndexProxy
{
private final IndexProxy delegate;
public DelegatingIndexProxy( IndexProxy delegate )
{
this.delegate = delegate;
}
@Override
protected IndexProxy getDelegate()
{
return delegate;
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_index_DelegatingIndexProxy.java
|
4,934
|
{
@Override
public void create() throws IOException
{
populationCompletionLatch.startAndAwaitFinish();
super.create();
}
};
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_ControlledPopulationSchemaIndexProvider.java
|
4,935
|
public class ControlledPopulationSchemaIndexProvider extends SchemaIndexProvider
{
private IndexPopulator mockedPopulator = new IndexPopulator.Adapter();
private final IndexAccessor mockedWriter = mock( IndexAccessor.class );
private final CountDownLatch writerLatch = new CountDownLatch( 1 );
private InternalIndexState initialIndexState = POPULATING;
public final AtomicInteger populatorCallCount = new AtomicInteger();
public final AtomicInteger writerCallCount = new AtomicInteger();
private String failure;
public static final SchemaIndexProvider.Descriptor PROVIDER_DESCRIPTOR = new SchemaIndexProvider.Descriptor(
"controlled-population", "1.0" );
public ControlledPopulationSchemaIndexProvider()
{
super( PROVIDER_DESCRIPTOR, 10 );
setInitialIndexState( initialIndexState );
}
public DoubleLatch installPopulationJobCompletionLatch()
{
final DoubleLatch populationCompletionLatch = new DoubleLatch();
mockedPopulator = new IndexPopulator.Adapter()
{
@Override
public void create() throws IOException
{
populationCompletionLatch.startAndAwaitFinish();
super.create();
}
};
return populationCompletionLatch;
}
public void awaitFullyPopulated()
{
awaitLatch( writerLatch );
}
@Override
public IndexPopulator getPopulator( long indexId, IndexDescriptor descriptor, IndexConfiguration config )
{
populatorCallCount.incrementAndGet();
return mockedPopulator;
}
@Override
public IndexAccessor getOnlineAccessor( long indexId, IndexConfiguration config )
{
writerCallCount.incrementAndGet();
writerLatch.countDown();
return mockedWriter;
}
@Override
public InternalIndexState getInitialState( long indexId )
{
return initialIndexState;
}
public void setInitialIndexState( InternalIndexState initialIndexState )
{
this.initialIndexState = initialIndexState;
}
@Override
public String getPopulationFailure( long indexId ) throws IllegalStateException
{
if ( this.failure == null )
{
throw new IllegalStateException();
}
return this.failure;
}
@Override
public int compareTo( SchemaIndexProvider o )
{
return 1;
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_ControlledPopulationSchemaIndexProvider.java
|
4,936
|
{
@Override
public void run()
{
try
{
action.run();
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
}
} ).start();
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_ContractCheckingIndexProxyTest.java
|
4,937
|
protected static final class RelationshipRepresentation implements
Representation<Relationship>
{
private final Representation<? super Node> nodes;
private final Representation<? super Relationship> rel;
public RelationshipRepresentation( Representation<? super Node> nodes,
Representation<? super Relationship> rel )
{
this.nodes = nodes;
this.rel = rel;
}
public String represent( Relationship item )
{
return nodes.represent( item.getStartNode() ) + " "
+ rel.represent( item ) + " "
+ nodes.represent( item.getEndNode() );
}
}
| false
|
community_graph-algo_src_test_java_common_AbstractTestBase.java
|
4,938
|
{
@Override
public boolean accept( long nodeId )
{
try
{
return nodeGetProperty( state, nodeId, propertyKeyId ).valueEquals( value );
}
catch ( EntityNotFoundException e )
{
throw new ThisShouldNotHappenError( "Chris", "An index claims a node by id " + nodeId +
" has the value. However, it looks like that node does not exist.", e);
}
}
};
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_StateHandlingStatementOperations.java
|
4,939
|
public class SchemaStateConcern implements SchemaStateOperations
{
private final UpdateableSchemaState schemaState;
public SchemaStateConcern( UpdateableSchemaState schemaState )
{
this.schemaState = schemaState;
}
@Override
public <K, V> V schemaStateGetOrCreate( KernelStatement state, K key, Function<K, V> creator )
{
return schemaState.getOrCreate( key, creator );
}
@Override
public <K> boolean schemaStateContains( KernelStatement state, K key )
{
return schemaState.get( key ) != null;
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_SchemaStateConcern.java
|
4,940
|
public class SchemaLoggingIT
{
private final TestLogging logging = new TestLogging();
@Rule public ImpermanentDatabaseRule dbRule = new ImpermanentDatabaseRule(logging);
@Test
public void shouldLogUserReadableLabelAndPropertyNames() throws Exception
{
//noinspection deprecation
GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI();
String labelName = "User";
String property = "name";
// when
createIndex( db, labelName, property );
// then
logging.getMessagesLog( IndexPopulationJob.class ).assertExactly(
info( "Index population started: [:User(name) [provider: {key=in-memory, version=1.0}]]" ),
info( "Index population completed. Index is now online: [:User(name) [provider: {key=in-memory, version=1.0}]]" )
);
}
private void createIndex( @SuppressWarnings("deprecation") GraphDatabaseAPI db, String labelName, String property )
{
try ( Transaction tx = db.beginTx() )
{
db.schema().indexFor( label( labelName ) ).on( property ).create();
tx.success();
}
try ( Transaction tx = db.beginTx() )
{
db.schema().awaitIndexesOnline( 1, TimeUnit.MINUTES );
tx.success();
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_SchemaLoggingIT.java
|
4,941
|
public class PropertyTransactionStateTest
{
private GraphDatabaseService db;
@Before
public void setUp() throws Exception
{
db = new TestGraphDatabaseFactory().newImpermanentDatabase();
}
@Test
public void testUpdateDoubleArrayProperty() throws Exception
{
Node node;
try ( Transaction tx = db.beginTx() )
{
node = db.createNode();
node.setProperty( "foo", new double[] { 0, 0, 0, 0 } );
tx.success();
}
try ( Transaction tx = db.beginTx() )
{
for ( int i = 0; i < 100; i++ )
{
double[] data = (double[]) node.getProperty( "foo" );
data[2] = i;
data[3] = i;
node.setProperty( "foo", data );
assertArrayEquals( new double[] { 0, 0, i, i }, (double[]) node.getProperty( "foo" ), 0.1D );
}
}
}
@Test
public void testStringPropertyUpdate() throws Exception
{
String key = "foo";
Node node;
try ( Transaction tx = db.beginTx() )
{
node = db.createNode();
node.setProperty( key, "one" );
tx.success();
}
try ( Transaction tx = db.beginTx() )
{
node.setProperty( key, "one" );
node.setProperty( key, "two" );
assertEquals( "two", node.getProperty( key ) );
}
}
@Test
public void testSetDoubleArrayProperty() throws Exception
{
db.beginTx();
Node node = db.createNode();
for ( int i = 0; i < 100; i++ )
{
node.setProperty( "foo", new double[] { 0, 0, i, i } );
assertArrayEquals( new double[] { 0, 0, i, i }, (double[]) node.getProperty( "foo" ), 0.1D );
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_PropertyTransactionStateTest.java
|
4,942
|
public class KernelTest
{
@Test
public void shouldNotAllowCreationOfConstraintsWhenInHA() throws Exception
{
//noinspection deprecation
GraphDatabaseAPI db = new FakeHaDatabase();
ThreadToStatementContextBridge stmtBridge =
db.getDependencyResolver().resolveDependency( ThreadToStatementContextBridge.class );
try ( Transaction ignored = db.beginTx() )
{
Statement statement = stmtBridge.instance();
try
{
statement.schemaWriteOperations().uniquenessConstraintCreate( 1, 1 );
fail( "expected exception here" );
}
catch ( InvalidTransactionTypeKernelException e )
{
assertThat( e.getMessage(), containsString( "HA" ) );
}
}
db.shutdown();
}
@SuppressWarnings("deprecation")
class FakeHaDatabase extends ImpermanentGraphDatabase
{
@Override
public void assertSchemaWritesAllowed() throws InvalidTransactionTypeKernelException
{
throw new InvalidTransactionTypeKernelException(
"Creation or deletion of constraints is not possible while running in a HA cluster. " +
"In order to do that, please restart in non-HA mode and propagate the database copy to " +
"all slaves" );
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_KernelTest.java
|
4,943
|
public class KernelStatementTest
{
@Test
public void shouldCloseOpenedLabelScanReader() throws Exception
{
// given
LabelScanStore scanStore = mock( LabelScanStore.class );
LabelScanReader scanReader = mock( LabelScanReader.class );
when( scanStore.newReader() ).thenReturn( scanReader );
KernelStatement statement =
new KernelStatement(
mock( KernelTransactionImplementation.class ),
mock( IndexReaderFactory.class ), scanStore, null, null, null, null, null );
statement.acquire();
// when
LabelScanReader actualReader = statement.getLabelScanReader();
// then
assertEquals( scanReader, actualReader );
// when
statement.close();
// then
verify( scanStore ).newReader();
verifyNoMoreInteractions( scanStore );
verify( scanReader ).close();
verifyNoMoreInteractions( scanReader );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_KernelStatementTest.java
|
4,944
|
public class KernelStatement implements TxState.Holder, Statement
{
private final KernelTransactionImplementation transaction;
protected final LockHolder lockHolder;
protected final TxState.Holder txStateHolder;
protected final IndexReaderFactory indexReaderFactory;
protected final LabelScanStore labelScanStore;
protected NeoStoreTransaction neoStoreTransaction;
private LabelScanReader labelScanReader;
private int referenceCount;
private final OperationsFacade facade;
private boolean closed;
public KernelStatement( KernelTransactionImplementation transaction, IndexReaderFactory indexReaderFactory,
LabelScanStore labelScanStore,
TxState.Holder txStateHolder, LockHolder lockHolder, LegacyKernelOperations
legacyKernelOperations, StatementOperationParts operations,
NeoStoreTransaction neoStoreTransaction )
{
this.transaction = transaction;
this.lockHolder = lockHolder;
this.indexReaderFactory = indexReaderFactory;
this.txStateHolder = txStateHolder;
this.labelScanStore = labelScanStore;
this.neoStoreTransaction = neoStoreTransaction;
this.facade = new OperationsFacade( this, legacyKernelOperations, operations );
}
@Override
public ReadOperations readOperations()
{
return facade;
}
@Override
public TokenWriteOperations tokenWriteOperations() throws ReadOnlyDatabaseKernelException
{
transaction.assertTokenWriteAllowed();
return facade;
}
@Override
public DataWriteOperations dataWriteOperations()
throws InvalidTransactionTypeKernelException, ReadOnlyDatabaseKernelException
{
transaction.upgradeToDataTransaction();
return facade;
}
@Override
public SchemaWriteOperations schemaWriteOperations()
throws InvalidTransactionTypeKernelException, ReadOnlyDatabaseKernelException
{
transaction.upgradeToSchemaTransaction();
return facade;
}
@Override
public TxState txState()
{
return txStateHolder.txState();
}
@Override
public boolean hasTxState()
{
return txStateHolder.hasTxState();
}
@Override
public boolean hasTxStateWithChanges()
{
return txStateHolder.hasTxStateWithChanges();
}
@Override
public void close()
{
if ( !closed && release() )
{
closed = true;
indexReaderFactory.close();
if ( null != labelScanReader )
{
labelScanReader.close();
}
transaction.releaseStatement( this );
}
}
void assertOpen()
{
if ( closed )
{
throw new NotInTransactionException( "The statement has been closed." );
}
}
public LockHolder locks()
{
return lockHolder;
}
public IndexReader getIndexReader( long indexId ) throws IndexNotFoundKernelException
{
return indexReaderFactory.newReader( indexId );
}
public IndexReader getFreshIndexReader( long indexId ) throws IndexNotFoundKernelException
{
return indexReaderFactory.newUnCachedReader( indexId );
}
public LabelScanReader getLabelScanReader()
{
if ( labelScanReader == null )
{
labelScanReader = labelScanStore.newReader();
}
return labelScanReader;
}
final void acquire()
{
referenceCount++;
}
private boolean release()
{
return --referenceCount == 0;
}
final void forceClose()
{
referenceCount = 0;
close();
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_KernelStatement.java
|
4,945
|
public class KernelSchemaStateStoreTest
{
private KernelSchemaStateStore stateStore;
@Test
public void should_apply_updates_correctly()
{
// GIVEN
stateStore.apply( MapUtil.stringMap( "key", "created_value" ) );
// WHEN
String result = stateStore.get( "key" );
// THEN
assertEquals( "created_value", result );
}
@Test
public void should_flush()
{
// GIVEN
stateStore.apply( MapUtil.stringMap( "key", "created_value" ) );
// WHEN
stateStore.clear();
// THEN
String result = stateStore.get( "key" );
assertEquals( null, result );
}
@Before
public void before()
{
this.stateStore = new KernelSchemaStateStore();
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_KernelSchemaStateStoreTest.java
|
4,946
|
public class KernelSchemaStateStore implements UpdateableSchemaState
{
private Map<Object, Object> state;
private ReadWriteLock lock = new ReentrantReadWriteLock( true );
public KernelSchemaStateStore()
{
this(new HashMap<Object, Object>());
}
public KernelSchemaStateStore( Map<Object, Object> state )
{
this.state = state;
}
@SuppressWarnings("unchecked")
public <K, V> V get(K key)
{
lock.readLock().lock();
try {
return (V) state.get( key );
}
finally {
lock.readLock().unlock();
}
}
@SuppressWarnings("unchecked")
@Override
public <K, V> V getOrCreate(K key, Function<K, V> creator) {
V currentValue = get(key);
if (currentValue == null)
{
lock.writeLock().lock();
try {
V lockedValue = (V) state.get( key );
if (lockedValue == null)
{
V newValue = creator.apply( key );
state.put( key, newValue );
return newValue;
}
else
return lockedValue;
}
finally {
lock.writeLock().unlock();
}
}
else
return currentValue;
}
public void replace(Map<Object, Object> replacement)
{
lock.writeLock().lock();
try {
state = replacement;
}
finally {
lock.writeLock().unlock();
}
}
public <K, V> void apply(Map<K, V> updates)
{
lock.writeLock().lock();
try {
state.putAll( updates );
}
finally {
lock.writeLock().unlock();
}
}
public void clear()
{
lock.writeLock().lock();
try {
state.clear();
}
finally {
lock.writeLock().unlock();
}
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_KernelSchemaStateStore.java
|
4,947
|
{
@Override
public String apply( String from )
{
return value;
}
} );
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_KernelSchemaStateFlushingTest.java
|
4,948
|
public class KernelSchemaStateFlushingTest
{
public @Rule ImpermanentDatabaseRule dbRule = new ImpermanentDatabaseRule();
private GraphDatabaseAPI db;
private ThreadToStatementContextBridge ctxProvider;
private PersistenceManager persistenceManager;
@Test
public void shouldKeepSchemaStateIfSchemaIsNotModified()
{
// given
String before = commitToSchemaState( "test", "before" );
// then
assertEquals( "before", before );
// given
String after = commitToSchemaState( "test", "after" );
// then
assertEquals( "before", after );
}
@Test
public void shouldInvalidateSchemaStateOnCreateIndex() throws Exception
{
// given
commitToSchemaState( "test", "before" );
IndexDescriptor descriptor = createIndex();
awaitIndexOnline( descriptor );
// when
String after = commitToSchemaState( "test", "after" );
// then
assertEquals( "after", after );
}
@Test
public void shouldInvalidateSchemaStateOnDropIndex() throws Exception
{
IndexDescriptor descriptor = createIndex();
awaitIndexOnline( descriptor );
commitToSchemaState( "test", "before" );
dropIndex( descriptor );
// when
String after = commitToSchemaState( "test", "after" );
// then
assertEquals( "after", after );
}
@Test
public void shouldInvalidateSchemaStateOnCreateConstraint() throws Exception
{
// given
commitToSchemaState( "test", "before" );
createConstraint();
// when
String after = commitToSchemaState( "test", "after" );
// then
assertEquals( "after", after );
}
@Test
public void shouldInvalidateSchemaStateOnDropConstraint() throws Exception
{
// given
UniquenessConstraint descriptor = createConstraint();
commitToSchemaState( "test", "before" );
dropConstraint( descriptor );
// when
String after = commitToSchemaState( "test", "after" );
// then
assertEquals( "after", after );
}
private UniquenessConstraint createConstraint() throws KernelException
{
try ( Transaction tx = db.beginTx() )
{
UniquenessConstraint descriptor;
try ( Statement statement = ctxProvider.instance() )
{
descriptor = statement.schemaWriteOperations().uniquenessConstraintCreate( 1, 1 );
}
tx.success();
return descriptor;
}
}
private void dropConstraint( UniquenessConstraint descriptor ) throws KernelException
{
try ( Transaction tx = db.beginTx() )
{
try ( Statement statement = ctxProvider.instance() )
{
statement.schemaWriteOperations().constraintDrop( descriptor );
}
tx.success();
}
}
private IndexDescriptor createIndex() throws KernelException
{
try ( Transaction tx = db.beginTx() )
{
IndexDescriptor descriptor;
try ( Statement statement = ctxProvider.instance() )
{
descriptor = statement.schemaWriteOperations().indexCreate( 1, 1 );
}
tx.success();
return descriptor;
}
}
private void dropIndex( IndexDescriptor descriptor ) throws KernelException
{
try ( Transaction tx = db.beginTx() )
{
try ( Statement statement = ctxProvider.instance() )
{
statement.schemaWriteOperations().indexDrop( descriptor );
}
tx.success();
}
}
private void awaitIndexOnline( IndexDescriptor descriptor ) throws IndexNotFoundKernelException
{
try ( Transaction tx = db.beginTx() )
{
try ( Statement statement = ctxProvider.instance() )
{
SchemaIndexTestHelper.awaitIndexOnline( statement.readOperations(), descriptor );
}
tx.success();
}
}
private String commitToSchemaState( String key, String value )
{
try ( Transaction tx = db.beginTx() )
{
KernelTransaction txc = persistenceManager.currentKernelTransactionForWriting();
String result;
try
{
result = getOrCreateFromState( txc, key, value );
return result;
}
finally
{
tx.success();
}
}
}
private String getOrCreateFromState( KernelTransaction tx, String key, final String value )
{
try ( Statement statement = tx.acquireStatement() )
{
return statement.readOperations().schemaStateGetOrCreate( key, new Function<String, String>()
{
@Override
public String apply( String from )
{
return value;
}
} );
}
}
@Before
public void setup()
{
db = dbRule.getGraphDatabaseAPI();
persistenceManager = db.getDependencyResolver().resolveDependency( PersistenceManager.class );
ctxProvider = db.getDependencyResolver().resolveDependency( ThreadToStatementContextBridge.class );
}
@After
public void after()
{
db.shutdown();
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_KernelSchemaStateFlushingTest.java
|
4,949
|
public class Kernel extends LifecycleAdapter implements KernelAPI
{
private final AbstractTransactionManager transactionManager;
private final PropertyKeyTokenHolder propertyKeyTokenHolder;
private final LabelTokenHolder labelTokenHolder;
private final RelationshipTypeTokenHolder relationshipTypeTokenHolder;
private final PersistenceManager persistenceManager;
private final LockManager lockManager;
private final UpdateableSchemaState schemaState;
private final SchemaWriteGuard schemaWriteGuard;
private final IndexingService indexService;
private final NeoStore neoStore;
private final Provider<NeoStore> neoStoreProvider;
private final PersistenceCache persistenceCache;
private final SchemaCache schemaCache;
private final SchemaIndexProviderMap providerMap;
private final LabelScanStore labelScanStore;
private final NodeManager nodeManager;
private final LegacyKernelOperations legacyKernelOperations;
private final StatementOperationParts statementOperations;
private final boolean readOnly;
private final LegacyPropertyTrackers legacyPropertyTrackers;
private boolean isShutdown = false;
public Kernel( AbstractTransactionManager transactionManager, PropertyKeyTokenHolder propertyKeyTokenHolder,
LabelTokenHolder labelTokenHolder, RelationshipTypeTokenHolder relationshipTypeTokenHolder,
PersistenceManager persistenceManager, LockManager lockManager, UpdateableSchemaState schemaState,
SchemaWriteGuard schemaWriteGuard,
IndexingService indexService, NodeManager nodeManager, Provider<NeoStore> neoStore, PersistenceCache persistenceCache,
SchemaCache schemaCache, SchemaIndexProviderMap providerMap, LabelScanStore labelScanStore, boolean readOnly )
{
this.transactionManager = transactionManager;
this.propertyKeyTokenHolder = propertyKeyTokenHolder;
this.labelTokenHolder = labelTokenHolder;
this.relationshipTypeTokenHolder = relationshipTypeTokenHolder;
this.persistenceManager = persistenceManager;
this.lockManager = lockManager;
this.schemaState = schemaState;
this.providerMap = providerMap;
this.readOnly = readOnly;
this.schemaWriteGuard = schemaWriteGuard;
this.indexService = indexService;
this.neoStore = neoStore.instance();
this.neoStoreProvider = neoStore;
this.persistenceCache = persistenceCache;
this.schemaCache = schemaCache;
this.labelScanStore = labelScanStore;
this.nodeManager = nodeManager;
this.legacyPropertyTrackers = new LegacyPropertyTrackers( propertyKeyTokenHolder,
nodeManager.getNodePropertyTrackers(),
nodeManager.getRelationshipPropertyTrackers(),
nodeManager );
this.legacyKernelOperations = new DefaultLegacyKernelOperations( nodeManager );
this.statementOperations = buildStatementOperations();
}
@Override
public void start()
{
for ( SchemaRule schemaRule : loop( neoStore.getSchemaStore().loadAllSchemaRules() ) )
{
schemaCache.addSchemaRule( schemaRule );
}
}
@Override
public void stop()
{
isShutdown = true;
}
@Override
public KernelTransaction newTransaction()
{
checkIfShutdown();
return new KernelTransactionImplementation( statementOperations, legacyKernelOperations, readOnly,
schemaWriteGuard, labelScanStore, indexService, transactionManager, nodeManager,
schemaState, new LockHolderImpl( lockManager, getJTATransaction(), nodeManager ),
persistenceManager, providerMap, neoStore, getLegacyTxState() );
}
// We temporarily need this until all transaction state has moved into the kernel
private TransactionState getLegacyTxState()
{
try
{
TransactionState legacyState = transactionManager.getTransactionState();
return legacyState != null ? legacyState : TransactionState.NO_STATE;
}
catch ( RuntimeException e )
{
// If the transaction manager is in a bad state, we use an empty transaction state. It's not
// a great thing, but without this we can't create kernel transactions during recovery.
// Accepting that this is terrible for now, since the plan is to remove this dependency on the JTA
// transaction entirely.
// This should be safe to do, since we only use the JTA tx for locking, and we don't do any locking during
// recovery.
return TransactionState.NO_STATE;
}
}
// We temporarily depend on this to satisfy locking. This should go away once all locks are handled in the kernel.
private Transaction getJTATransaction()
{
try
{
return transactionManager.getTransaction();
}
catch ( SystemException e )
{
// If the transaction manager is in a bad state, we return a placebo transaction. It's not
// a great thing, but without this we can't create kernel transactions during recovery.
// Accepting that this is terrible for now, since the plan is to remove this dependency on the JTA
// transaction entirely.
// This should be safe to do, since we only use the JTA tx for locking, and we don't do any locking during
// recovery.
return new NoOpJTATransaction();
}
}
private void checkIfShutdown()
{
if ( isShutdown )
{
throw new DatabaseShutdownException();
}
}
private StatementOperationParts buildStatementOperations()
{
// Bottom layer: Read-access to committed data
StoreReadLayer storeLayer = new CacheLayer( new DiskLayer( propertyKeyTokenHolder, labelTokenHolder,
relationshipTypeTokenHolder, new SchemaStorage( neoStore.getSchemaStore() ), neoStoreProvider,
indexService ), persistenceCache, indexService, schemaCache );
// + Transaction state handling
StateHandlingStatementOperations stateHandlingContext = new StateHandlingStatementOperations(
storeLayer, legacyPropertyTrackers,
new ConstraintIndexCreator( new Transactor( transactionManager, persistenceManager ), indexService ) );
StatementOperationParts parts = new StatementOperationParts( stateHandlingContext, stateHandlingContext,
stateHandlingContext, stateHandlingContext, stateHandlingContext, stateHandlingContext,
new SchemaStateConcern( schemaState ) );
// + Constraints
ConstraintEnforcingEntityOperations constraintEnforcingEntityOperations =
new ConstraintEnforcingEntityOperations( parts.entityWriteOperations(), parts.entityReadOperations(),
parts.schemaReadOperations() );
// + Data integrity
DataIntegrityValidatingStatementOperations dataIntegrityContext = new
DataIntegrityValidatingStatementOperations(
parts.keyWriteOperations(),
parts.schemaReadOperations(),
parts.schemaWriteOperations() );
parts = parts.override( null, dataIntegrityContext, constraintEnforcingEntityOperations,
constraintEnforcingEntityOperations, null, dataIntegrityContext, null );
// + Locking
LockingStatementOperations lockingContext = new LockingStatementOperations(
parts.entityWriteOperations(),
parts.schemaReadOperations(),
parts.schemaWriteOperations(),
parts.schemaStateOperations() );
parts = parts.override( null, null, null, lockingContext, lockingContext, lockingContext, lockingContext );
return parts;
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_Kernel.java
|
4,950
|
class Caching implements IndexReaderFactory
{
private Map<Long,IndexReader> indexReaders = null;
private final IndexingService indexingService;
public Caching( IndexingService indexingService )
{
this.indexingService = indexingService;
}
@Override
public IndexReader newReader( long indexId ) throws IndexNotFoundKernelException
{
if( indexReaders == null )
{
indexReaders = new HashMap<>();
}
IndexReader reader = indexReaders.get( indexId );
if ( reader == null )
{
reader = newUnCachedReader( indexId );
indexReaders.put( indexId, reader );
}
return reader;
}
public IndexReader newUnCachedReader( long indexId ) throws IndexNotFoundKernelException
{
IndexProxy index = indexingService.getProxyForRule( indexId );
return index.newReader();
}
@Override
public void close()
{
if ( indexReaders != null )
{
for ( IndexReader indexReader : indexReaders.values() )
{
indexReader.close();
}
}
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_IndexReaderFactory.java
|
4,951
|
{
@Override
public boolean accept( Long item )
{
return item % 2 == 1l;
}
};
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_DiffSetsTest.java
|
4,952
|
public class DiffSetsTest
{
@Test
public void testAdd()
{
// GIVEN
DiffSets<Long> actual = new DiffSets<>();
// WHEN
actual.add( 1L );
actual.add( 2L );
// THEN
assertEquals( asSet( 1L, 2L ), actual.getAdded() );
assertTrue( actual.getRemoved().isEmpty() );
}
@Test
public void testRemove()
{
// GIVEN
DiffSets<Long> actual = new DiffSets<>();
// WHEN
actual.add( 1L );
actual.remove( 2L );
// THEN
assertEquals( asSet( 1L ), actual.getAdded() );
assertEquals( asSet( 2L ), actual.getRemoved() );
}
@Test
public void testAddRemove()
{
// GIVEN
DiffSets<Long> actual = new DiffSets<>();
// WHEN
actual.add( 1L );
actual.remove( 1L );
// THEN
assertTrue( actual.getAdded().isEmpty() );
assertTrue( actual.getRemoved().isEmpty() );
}
@Test
public void testRemoveAdd()
{
// GIVEN
DiffSets<Long> actual = new DiffSets<>();
// WHEN
actual.remove( 1L );
actual.add( 1L );
// THEN
assertEquals( asSet( 1L ), actual.getAdded() );
assertTrue( actual.getRemoved().isEmpty() );
}
@Test
public void testIsAddedOrRemoved()
{
// GIVEN
DiffSets<Long> actual = new DiffSets<>();
// WHEN
actual.add( 1L );
actual.remove( 10L );
// THEN
assertTrue( actual.isAdded( 1L ) );
assertTrue( !actual.isAdded( 2L ) );
assertTrue( actual.isRemoved( 10L ) );
assertTrue( !actual.isRemoved( 2L ) );
}
@Test
public void testAddRemoveAll()
{
// GIVEN
DiffSets<Long> actual = new DiffSets<>();
// WHEN
actual.addAll( iterator( 1L, 2L ) );
actual.removeAll( iterator( 2L, 3L ) );
// THEN
assertEquals( asSet( 1L ), actual.getAdded() );
assertEquals( asSet( 3L ), actual.getRemoved() );
}
@Test
public void testFilterAdded()
{
// GIVEN
DiffSets<Long> actual = new DiffSets<>();
actual.addAll( iterator( 1L, 2L ) );
actual.removeAll( iterator( 3L, 4L ) );
// WHEN
DiffSets<Long> filtered = actual.filterAdded( ODD_FILTER );
// THEN
assertEquals( asSet( 1L ), filtered.getAdded() );
assertEquals( asSet( 3L, 4L ), filtered.getRemoved() );
}
@Test
public void testReturnSourceFromApplyWithEmptyDiffSets() throws Exception
{
// GIVEN
DiffSets<Long> diffSets = DiffSets.emptyDiffSets();
// WHEN
Iterator<Long> result = diffSets.apply( asList( 18l ).iterator() );
// THEN
assertEquals( asList( 18l ), asCollection( result ) );
}
@Test
public void testAppendAddedToSourceInApply() throws Exception
{
// GIVEN
DiffSets<Long> diffSets = new DiffSets<>();
diffSets.add( 52l );
diffSets.remove( 43l );
// WHEN
Iterator<Long> result = diffSets.apply( asList( 18l ).iterator() );
// THEN
assertEquals( asList( 18l, 52l ), asCollection( result ) );
}
@Test
public void testFilterRemovedFromSourceInApply() throws Exception
{
// GIVEN
DiffSets<Long> diffSets = new DiffSets<>();
diffSets.remove( 43l );
// WHEN
Iterator<Long> result = diffSets.apply( asList( 42l, 43l, 44l ).iterator() );
// THEN
assertEquals( asList( 42l, 44l ), asCollection( result ) );
}
@Test
public void testFilterAddedFromSourceInApply() throws Exception
{
// GIVEN
DiffSets<Long> diffSets = new DiffSets<>();
diffSets.add( 42l );
diffSets.add( 44l );
// WHEN
Iterator<Long> result = diffSets.apply( asList( 42l, 43l ).iterator() );
// THEN
Collection<Long> collectedResult = asCollection( result );
assertEquals( 3, collectedResult.size() );
assertThat( collectedResult, hasItems( 43l, 42l, 44l ) );
}
@Test
public void replaceMultipleTimesWithAnInitialValue() throws Exception
{
// GIVEN
// an initial value, meaning an added value in "this transaction"
DiffSets<Integer> diff = new DiffSets<>();
diff.add( 0 );
// WHEN
// replacing that value two times
diff.replace( 0, 1 );
diff.replace( 1, 2 );
// THEN
// there should not be any removed value, only the last one added
assertEquals( asSet( 2 ), diff.getAdded() );
assertEquals( asSet(), diff.getRemoved() );
}
@Test
public void replaceMultipleTimesWithNoInitialValue() throws Exception
{
// GIVEN
// no initial value, meaning a value existing before "this transaction"
DiffSets<Integer> diff = new DiffSets<>();
// WHEN
// replacing that value two times
diff.replace( 0, 1 );
diff.replace( 1, 2 );
// THEN
// the initial value should show up as removed and the last one as added
assertEquals( asSet( 2 ), diff.getAdded() );
assertEquals( asSet( 0 ), diff.getRemoved() );
}
private static final Predicate<Long> ODD_FILTER = new Predicate<Long>()
{
@Override
public boolean accept( Long item )
{
return item % 2 == 1l;
}
};
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_DiffSetsTest.java
|
4,953
|
public class DefaultLegacyKernelOperations implements LegacyKernelOperations
{
private final NodeManager nodeManager;
public DefaultLegacyKernelOperations( NodeManager nodeManager )
{
this.nodeManager = nodeManager;
}
@Override
public long nodeCreate( Statement state )
{
return nodeManager.createNode().getId();
}
@Override
public long relationshipCreate( Statement state, long relationshipTypeId, long startNodeId, long endNodeId )
throws RelationshipTypeIdNotFoundKernelException, EntityNotFoundException
{
NodeImpl startNode;
try
{
startNode = nodeManager.getNodeForProxy( startNodeId, LockType.WRITE );
}
catch ( NotFoundException e )
{
throw new EntityNotFoundException( EntityType.NODE, startNodeId, e );
}
try
{
return nodeManager.createRelationship( nodeManager.newNodeProxyById( startNodeId ), startNode,
nodeManager.newNodeProxyById( endNodeId ), relationshipTypeId )
.getId();
}
catch ( NotFoundException e )
{
throw new EntityNotFoundException( EntityType.NODE, endNodeId, e );
}
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_DefaultLegacyKernelOperations.java
|
4,954
|
public class DataStatementArgumentVerificationTest
{
@Test
public void shouldReturnNoPropertyFromNodeGetPropertyWithoutDelegatingForNoSuchPropertyKeyIdConstant()
throws Exception
{
// given
DataWriteOperations statement = stubStatement();
// when
Property property = statement.nodeGetProperty( 17, StatementConstants.NO_SUCH_PROPERTY_KEY );
// then
assertFalse( "should return NoProperty", property.isDefined() );
}
@Test
public void shouldReturnNoPropertyFromRelationshipGetPropertyWithoutDelegatingForNoSuchPropertyKeyIdConstant()
throws Exception
{
// given
DataWriteOperations statement = stubStatement();
// when
Property property = statement.relationshipGetProperty( 17, StatementConstants.NO_SUCH_PROPERTY_KEY );
// then
assertFalse( "should return NoProperty", property.isDefined() );
}
@Test
public void shouldReturnNoPropertyFromGraphGetPropertyWithoutDelegatingForNoSuchPropertyKeyIdConstant()
throws Exception
{
// given
DataWriteOperations statement = stubStatement();
// when
Property property = statement.graphGetProperty( StatementConstants.NO_SUCH_PROPERTY_KEY );
// then
assertFalse( "should return NoProperty", property.isDefined() );
}
@Test
public void shouldReturnEmptyIdIteratorFromNodesGetForLabelForNoSuchLabelConstant() throws Exception
{
// given
DataWriteOperations statement = stubStatement();
// when
PrimitiveLongIterator nodes = statement.nodesGetForLabel( StatementConstants.NO_SUCH_LABEL );
// then
assertFalse( "should not contain any ids", nodes.hasNext() );
}
@Test
public void shouldAlwaysReturnFalseFromNodeHasLabelForNoSuchLabelConstant() throws Exception
{
// given
DataWriteOperations statement = stubStatement();
// when
boolean hasLabel = statement.nodeHasLabel( 17, StatementConstants.NO_SUCH_LABEL );
// then
assertFalse( "should not contain any ids", hasLabel );
}
private OperationsFacade stubStatement()
{
return new OperationsFacade( mock( KernelStatement.class ), null, null );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_DataStatementArgumentVerificationTest.java
|
4,955
|
{
@Override
public Iterator<T> answer( InvocationOnMock invocationOnMock ) throws Throwable
{
return iterator( content );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_DataIntegrityValidatingStatementOperationsTest.java
|
4,956
|
public class DataIntegrityValidatingStatementOperationsTest
{
@Test
public void shouldDisallowReAddingIndex() throws Exception
{
// GIVEN
int label = 0, propertyKey = 7;
IndexDescriptor rule = new IndexDescriptor( label, propertyKey );
SchemaReadOperations innerRead = mock( SchemaReadOperations.class );
SchemaWriteOperations innerWrite = mock( SchemaWriteOperations.class );
DataIntegrityValidatingStatementOperations ctx =
new DataIntegrityValidatingStatementOperations( null, innerRead, innerWrite );
when( innerRead.indexesGetForLabel( state, rule.getLabelId() ) ).thenAnswer( withIterator( rule ) );
// WHEN
try
{
ctx.indexCreate( state, label, propertyKey );
fail( "Should have thrown exception." );
}
catch ( AlreadyIndexedException e )
{
// ok
}
// THEN
verify( innerWrite, never() ).indexCreate( eq( state ), anyInt(), anyInt() );
}
@Test
public void shouldDisallowAddingIndexWhenConstraintIndexExists() throws Exception
{
// GIVEN
int label = 0, propertyKey = 7;
IndexDescriptor rule = new IndexDescriptor( label, propertyKey );
SchemaReadOperations innerRead = mock( SchemaReadOperations.class );
SchemaWriteOperations innerWrite = mock( SchemaWriteOperations.class );
DataIntegrityValidatingStatementOperations ctx =
new DataIntegrityValidatingStatementOperations( null, innerRead, innerWrite );
when( innerRead.indexesGetForLabel( state, rule.getLabelId() ) ).thenAnswer( withIterator( ) );
when( innerRead.uniqueIndexesGetForLabel( state, rule.getLabelId() ) ).thenAnswer( withIterator( rule ) );
// WHEN
try
{
ctx.indexCreate( state, label, propertyKey );
fail( "Should have thrown exception." );
}
catch ( AlreadyConstrainedException e )
{
// ok
}
// THEN
verify( innerWrite, never() ).indexCreate( eq( state ), anyInt(), anyInt() );
}
@Test
public void shouldDisallowDroppingIndexThatDoesNotExist() throws Exception
{
// GIVEN
int label = 0, propertyKey = 7;
IndexDescriptor indexDescriptor = new IndexDescriptor( label, propertyKey );
SchemaReadOperations innerRead = mock( SchemaReadOperations.class );
SchemaWriteOperations innerWrite = mock( SchemaWriteOperations.class );
DataIntegrityValidatingStatementOperations ctx =
new DataIntegrityValidatingStatementOperations( null, innerRead, innerWrite );
when( innerRead.uniqueIndexesGetForLabel( state, indexDescriptor.getLabelId() ) ).thenAnswer( withIterator( ) );
when( innerRead.indexesGetForLabel( state, indexDescriptor.getLabelId() ) ).thenAnswer( withIterator( ) );
// WHEN
try
{
ctx.indexDrop( state, indexDescriptor );
fail( "Should have thrown exception." );
}
catch ( DropIndexFailureException e )
{
assertThat(e.getCause(), instanceOf( NoSuchIndexException.class) );
}
// THEN
verify( innerWrite, never() ).indexCreate( eq( state ), anyInt(), anyInt() );
}
@Test
public void shouldDisallowDroppingIndexWhenConstraintIndexExists() throws Exception
{
// GIVEN
int label = 0, propertyKey = 7;
IndexDescriptor indexDescriptor = new IndexDescriptor( label, propertyKey );
SchemaReadOperations innerRead = mock( SchemaReadOperations.class );
SchemaWriteOperations innerWrite = mock( SchemaWriteOperations.class );
DataIntegrityValidatingStatementOperations ctx =
new DataIntegrityValidatingStatementOperations( null, innerRead, innerWrite );
when( innerRead.uniqueIndexesGetForLabel( state, indexDescriptor.getLabelId() ) ).thenAnswer(
withIterator( indexDescriptor ) );
when( innerRead.indexesGetForLabel( state, indexDescriptor.getLabelId() ) ).thenAnswer( withIterator() );
// WHEN
try
{
ctx.indexDrop( state, new IndexDescriptor( label, propertyKey ) );
fail( "Should have thrown exception." );
}
catch ( DropIndexFailureException e )
{
assertThat(e.getCause(), instanceOf( IndexBelongsToConstraintException.class) );
}
// THEN
verify( innerWrite, never() ).indexCreate( eq( state ), anyInt(), anyInt() );
}
@Test
public void shouldDisallowDroppingConstraintIndexThatDoesNotExists() throws Exception
{
// GIVEN
int label = 0, propertyKey = 7;
IndexDescriptor indexDescriptor = new IndexDescriptor( label, propertyKey );
SchemaReadOperations innerRead = mock( SchemaReadOperations.class );
SchemaWriteOperations innerWrite = mock( SchemaWriteOperations.class );
DataIntegrityValidatingStatementOperations ctx =
new DataIntegrityValidatingStatementOperations( null, innerRead, innerWrite );
when( innerRead.uniqueIndexesGetForLabel( state, indexDescriptor.getLabelId() ) ).thenAnswer(
withIterator( indexDescriptor ) );
when( innerRead.indexesGetForLabel( state, indexDescriptor.getLabelId() ) ).thenAnswer( withIterator() );
// WHEN
try
{
ctx.indexDrop( state, new IndexDescriptor( label, propertyKey ) );
fail( "Should have thrown exception." );
}
catch ( DropIndexFailureException e )
{
assertThat(e.getCause(), instanceOf( IndexBelongsToConstraintException.class) );
}
// THEN
verify( innerWrite, never() ).indexCreate( eq( state ), anyInt(), anyInt() );
}
@Test
public void shouldDisallowDroppingConstraintIndexThatIsReallyJustRegularIndex() throws Exception
{
// GIVEN
int label = 0, propertyKey = 7;
IndexDescriptor indexDescriptor = new IndexDescriptor( label, propertyKey );
SchemaReadOperations innerRead = mock( SchemaReadOperations.class );
SchemaWriteOperations innerWrite = mock( SchemaWriteOperations.class );
DataIntegrityValidatingStatementOperations ctx =
new DataIntegrityValidatingStatementOperations( null, innerRead, innerWrite );
when( innerRead.uniqueIndexesGetForLabel( state, indexDescriptor.getLabelId() ) ).thenAnswer(
withIterator( indexDescriptor ) );
when( innerRead.indexesGetForLabel( state, indexDescriptor.getLabelId() ) ).thenAnswer( withIterator() );
// WHEN
try
{
ctx.indexDrop( state, new IndexDescriptor( label, propertyKey ) );
fail( "Should have thrown exception." );
}
catch ( DropIndexFailureException e )
{
assertThat(e.getCause(), instanceOf( IndexBelongsToConstraintException.class) );
}
// THEN
verify( innerWrite, never() ).indexCreate( eq( state ), anyInt(), anyInt() );
}
@Test
public void shouldDisallowNullOrEmptyPropertyKey() throws Exception
{
KeyWriteOperations inner = mock( KeyWriteOperations.class );
DataIntegrityValidatingStatementOperations ctx =
new DataIntegrityValidatingStatementOperations( inner, null, null );
try
{
ctx.propertyKeyGetOrCreateForName( state, null );
fail( "Should not be able to create null property key" );
}
catch ( IllegalTokenNameException e )
{ // good
}
try
{
ctx.propertyKeyGetOrCreateForName( state, "" );
fail( "Should not be able to create empty property key" );
}
catch ( IllegalTokenNameException e )
{ // good
}
}
@Test
public void shouldDisallowNullOrEmptyLabelName() throws Exception
{
KeyWriteOperations inner = mock( KeyWriteOperations.class );
DataIntegrityValidatingStatementOperations ctx =
new DataIntegrityValidatingStatementOperations( inner, null, null );
try
{
ctx.labelGetOrCreateForName( state, null );
fail( "Should not be able to create null label" );
}
catch ( IllegalTokenNameException e )
{ // good
}
try
{
ctx.labelGetOrCreateForName( state, "" );
fail( "Should not be able to create empty label" );
}
catch ( IllegalTokenNameException e )
{ // good
}
}
@Test( expected = SchemaKernelException.class )
public void shouldFailInvalidLabelNames() throws Exception
{
// Given
DataIntegrityValidatingStatementOperations ctx =
new DataIntegrityValidatingStatementOperations( null, null, null );
// When
ctx.labelGetOrCreateForName( state, "" );
}
@Test( expected = SchemaKernelException.class )
public void shouldFailOnNullLabel() throws Exception
{
// Given
DataIntegrityValidatingStatementOperations ctx =
new DataIntegrityValidatingStatementOperations( null, null, null );
// When
ctx.labelGetOrCreateForName( state, null );
}
@SafeVarargs
private static <T> Answer<Iterator<T>> withIterator( final T... content )
{
return new Answer<Iterator<T>>()
{
@Override
public Iterator<T> answer( InvocationOnMock invocationOnMock ) throws Throwable
{
return iterator( content );
}
};
}
private final KernelStatement state = StatementOperationsTestHelper.mockedState();
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_DataIntegrityValidatingStatementOperationsTest.java
|
4,957
|
public class DataIntegrityValidatingStatementOperations implements
KeyWriteOperations,
SchemaWriteOperations
{
private final KeyWriteOperations keyWriteDelegate;
private final SchemaReadOperations schemaReadDelegate;
private final SchemaWriteOperations schemaWriteDelegate;
public DataIntegrityValidatingStatementOperations(
KeyWriteOperations keyWriteDelegate,
SchemaReadOperations schemaReadDelegate,
SchemaWriteOperations schemaWriteDelegate )
{
this.keyWriteDelegate = keyWriteDelegate;
this.schemaReadDelegate = schemaReadDelegate;
this.schemaWriteDelegate = schemaWriteDelegate;
}
@Override
public int propertyKeyGetOrCreateForName( Statement state, String propertyKey )
throws IllegalTokenNameException
{
// KISS - but refactor into a general purpose constraint checker later on
return keyWriteDelegate.propertyKeyGetOrCreateForName( state, checkValidTokenName( propertyKey ) );
}
@Override
public int relationshipTypeGetOrCreateForName( Statement state, String relationshipTypeName )
throws IllegalTokenNameException
{
return keyWriteDelegate.relationshipTypeGetOrCreateForName( state, checkValidTokenName( relationshipTypeName ) );
}
@Override
public int labelGetOrCreateForName( Statement state, String label )
throws IllegalTokenNameException, TooManyLabelsException
{
// KISS - but refactor into a general purpose constraint checker later on
return keyWriteDelegate.labelGetOrCreateForName( state, checkValidTokenName( label ) );
}
@Override
public IndexDescriptor indexCreate( KernelStatement state, int labelId, int propertyKey )
throws AddIndexFailureException, AlreadyIndexedException, AlreadyConstrainedException
{
checkIndexExistence( state, labelId, propertyKey );
return schemaWriteDelegate.indexCreate( state, labelId, propertyKey );
}
@Override
public void indexDrop( KernelStatement state, IndexDescriptor descriptor ) throws DropIndexFailureException
{
try
{
assertIsNotUniqueIndex( descriptor, schemaReadDelegate.uniqueIndexesGetForLabel(
state, descriptor.getLabelId() ) );
assertIndexExists( descriptor, schemaReadDelegate.indexesGetForLabel( state, descriptor.getLabelId() ) );
}
catch ( IndexBelongsToConstraintException | NoSuchIndexException e )
{
throw new DropIndexFailureException( descriptor, e );
}
schemaWriteDelegate.indexDrop( state, descriptor );
}
@Override
public void uniqueIndexDrop( KernelStatement state, IndexDescriptor descriptor ) throws DropIndexFailureException
{
schemaWriteDelegate.uniqueIndexDrop( state, descriptor );
}
@Override
public UniquenessConstraint uniquenessConstraintCreate( KernelStatement state, int labelId, int propertyKey )
throws AlreadyConstrainedException, CreateConstraintFailureException, AlreadyIndexedException
{
Iterator<UniquenessConstraint> constraints = schemaReadDelegate.constraintsGetForLabelAndPropertyKey(
state, labelId, propertyKey );
if ( constraints.hasNext() )
{
throw new AlreadyConstrainedException( constraints.next() );
}
// It is not allowed to create uniqueness constraints on indexed label/property pairs
checkIndexExistence( state, labelId, propertyKey );
return schemaWriteDelegate.uniquenessConstraintCreate( state, labelId, propertyKey );
}
@Override
public void constraintDrop( KernelStatement state, UniquenessConstraint constraint ) throws DropConstraintFailureException
{
try
{
assertConstraintExists( constraint, schemaReadDelegate.constraintsGetForLabelAndPropertyKey(
state, constraint.label(), constraint.propertyKeyId() ) );
}
catch ( NoSuchConstraintException e )
{
throw new DropConstraintFailureException( constraint, e );
}
schemaWriteDelegate.constraintDrop( state, constraint );
}
private void checkIndexExistence( KernelStatement state, int labelId, int propertyKey )
throws AlreadyIndexedException, AlreadyConstrainedException
{
for ( IndexDescriptor descriptor : loop( schemaReadDelegate.indexesGetForLabel( state, labelId ) ) )
{
if ( descriptor.getPropertyKeyId() == propertyKey )
{
throw new AlreadyIndexedException( descriptor );
}
}
for ( IndexDescriptor descriptor : loop( schemaReadDelegate.uniqueIndexesGetForLabel( state, labelId ) ) )
{
if ( descriptor.getPropertyKeyId() == propertyKey )
{
throw new AlreadyConstrainedException(
new UniquenessConstraint( descriptor.getLabelId(), descriptor.getPropertyKeyId() ) );
}
}
}
private String checkValidTokenName( String name ) throws IllegalTokenNameException
{
if ( name == null || name.isEmpty() )
{
throw new IllegalTokenNameException( name );
}
return name;
}
private void assertIsNotUniqueIndex( IndexDescriptor descriptor, Iterator<IndexDescriptor> uniqueIndexes )
throws IndexBelongsToConstraintException
{
while ( uniqueIndexes.hasNext() )
{
IndexDescriptor uniqueIndex = uniqueIndexes.next();
if ( uniqueIndex.getPropertyKeyId() == descriptor.getPropertyKeyId() )
{
throw new IndexBelongsToConstraintException( descriptor );
}
}
}
private void assertIndexExists( IndexDescriptor descriptor, Iterator<IndexDescriptor> indexes )
throws NoSuchIndexException
{
for ( IndexDescriptor existing : loop( indexes ) )
{
if ( existing.getPropertyKeyId() == descriptor.getPropertyKeyId() )
{
return;
}
}
throw new NoSuchIndexException( descriptor );
}
private void assertConstraintExists( UniquenessConstraint constraint, Iterator<UniquenessConstraint> constraints )
throws NoSuchConstraintException
{
for ( UniquenessConstraint existing : loop( constraints ) )
{
if ( existing.equals( constraint.label(), constraint.propertyKeyId() ) )
{
return;
}
}
throw new NoSuchConstraintException( constraint );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_DataIntegrityValidatingStatementOperations.java
|
4,958
|
private static abstract class FailureRewrite<T> implements Function<GraphDatabaseService, T>
{
private final String message;
FailureRewrite( String message )
{
this.message = message;
}
@Override
public T apply( GraphDatabaseService graphDb )
{
try
{
return perform( graphDb );
}
catch ( AssertionError e )
{
AssertionError error = new AssertionError( message + ": " + e.getMessage() );
error.setStackTrace( e.getStackTrace() );
throw error;
}
}
abstract T perform( GraphDatabaseService graphDb );
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_DataAndSchemaTransactionSeparationIT.java
|
4,959
|
{
@Override
public Relationship apply( GraphDatabaseService graphDb )
{
return nodes.first().createRelationshipTo( nodes.other(), withName( "RELATED" ) );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_DataAndSchemaTransactionSeparationIT.java
|
4,960
|
{
@Override
public Pair<Node, Node> apply( GraphDatabaseService graphDb )
{
return Pair.of( graphDb.createNode(), graphDb.createNode() );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_DataAndSchemaTransactionSeparationIT.java
|
4,961
|
@SuppressWarnings("deprecation")
class FakeHaDatabase extends ImpermanentGraphDatabase
{
@Override
public void assertSchemaWritesAllowed() throws InvalidTransactionTypeKernelException
{
throw new InvalidTransactionTypeKernelException(
"Creation or deletion of constraints is not possible while running in a HA cluster. " +
"In order to do that, please restart in non-HA mode and propagate the database copy to " +
"all slaves" );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_KernelTest.java
|
4,962
|
public class KernelTransactionImplementation implements KernelTransaction, TxState.Holder
{
private final SchemaWriteGuard schemaWriteGuard;
private final IndexingService indexService;
private final LockHolder lockHolder;
private final LabelScanStore labelScanStore;
private final SchemaStorage schemaStorage;
private final ConstraintIndexCreator constraintIndexCreator;
private final PersistenceManager persistenceManager;
private final SchemaIndexProviderMap providerMap;
private final UpdateableSchemaState schemaState;
private final OldTxStateBridge legacyStateBridge;
private final LegacyKernelOperations legacyKernelOperations;
private final StatementOperationParts operations;
private final boolean readOnly;
private TransactionType transactionType = TransactionType.ANY;
private boolean closing, closed;
private TxStateImpl txState;
public KernelTransactionImplementation( StatementOperationParts operations,
LegacyKernelOperations legacyKernelOperations, boolean readOnly,
SchemaWriteGuard schemaWriteGuard, LabelScanStore labelScanStore,
IndexingService indexService,
AbstractTransactionManager transactionManager, NodeManager nodeManager,
UpdateableSchemaState schemaState,
LockHolder lockHolder, PersistenceManager persistenceManager,
SchemaIndexProviderMap providerMap, NeoStore neoStore,
TransactionState legacyTxState )
{
this.operations = operations;
this.legacyKernelOperations = legacyKernelOperations;
this.readOnly = readOnly;
this.schemaWriteGuard = schemaWriteGuard;
this.labelScanStore = labelScanStore;
this.indexService = indexService;
this.providerMap = providerMap;
this.schemaState = schemaState;
this.persistenceManager = persistenceManager;
this.lockHolder = lockHolder;
constraintIndexCreator = new ConstraintIndexCreator( new Transactor( transactionManager, persistenceManager ),
this.indexService );
schemaStorage = new SchemaStorage( neoStore.getSchemaStore() );
legacyStateBridge = new OldTxStateBridgeImpl( nodeManager, legacyTxState );
}
public void prepare()
{
beginClose();
try
{
createTransactionCommands();
}
finally
{
closing = false;
}
}
public void commit() throws TransactionFailureException
{
try
{
release();
close();
}
catch ( ReleaseLocksFailedKernelException e )
{
throw new TransactionFailureException( new RuntimeException( e.getMessage(), e ) );
}
finally
{
closing = false;
}
}
public void rollback() throws TransactionFailureException
{
beginClose();
try
{
try
{
dropCreatedConstraintIndexes();
}
catch ( IllegalStateException | SecurityException e )
{
throw new TransactionFailureException( e );
}
finally
{
try
{
release();
}
catch ( ReleaseLocksFailedKernelException e )
{
throw new TransactionFailureException(
Exceptions.withCause( new RollbackException( e.getMessage() ), e ) );
}
}
close();
}
finally
{
closing = false;
}
}
public void release() throws ReleaseLocksFailedKernelException
{
lockHolder.releaseLocks();
}
private void ensureWriteTransaction()
{
persistenceManager.getResource().forWriting();
}
/** Implements reusing the same underlying {@link KernelStatement} for overlapping statements. */
private KernelStatement currentStatement;
@Override
public KernelStatement acquireStatement()
{
assertOpen();
if ( currentStatement == null )
{
currentStatement = new KernelStatement( this, new IndexReaderFactory.Caching( indexService ),
labelScanStore, this, lockHolder, legacyKernelOperations, operations,
// Just use forReading since read/write has been decided prior to this
persistenceManager.getResource().forReading() );
}
currentStatement.acquire();
return currentStatement;
}
public void releaseStatement( Statement statement )
{
assert currentStatement == statement;
currentStatement = null;
}
public void upgradeToDataTransaction() throws InvalidTransactionTypeKernelException, ReadOnlyDatabaseKernelException
{
assertDatabaseWritable();
ensureWriteTransaction();
transactionType = transactionType.upgradeToDataTransaction();
}
public void upgradeToSchemaTransaction() throws InvalidTransactionTypeKernelException, ReadOnlyDatabaseKernelException
{
doUpgradeToSchemaTransaction();
ensureWriteTransaction();
transactionType = transactionType.upgradeToSchemaTransaction();
}
public void doUpgradeToSchemaTransaction() throws InvalidTransactionTypeKernelException, ReadOnlyDatabaseKernelException
{
assertDatabaseWritable();
schemaWriteGuard.assertSchemaWritesAllowed();
}
private void assertDatabaseWritable() throws ReadOnlyDatabaseKernelException
{
if ( readOnly )
{
throw new ReadOnlyDatabaseKernelException();
}
}
public void assertTokenWriteAllowed() throws ReadOnlyDatabaseKernelException
{
assertDatabaseWritable();
}
private void dropCreatedConstraintIndexes() throws TransactionFailureException
{
if ( hasTxStateWithChanges() )
{
for ( IndexDescriptor createdConstraintIndex : txState().constraintIndexesCreatedInTx() )
{
try
{
// TODO logically, which statement should this operation be performed on?
constraintIndexCreator.dropUniquenessConstraintIndex( createdConstraintIndex );
}
catch ( DropIndexFailureException e )
{
throw new IllegalStateException( "Constraint index that was created in a transaction should be " +
"possible to drop during rollback of that transaction.", e );
}
catch ( TransactionFailureException e )
{
throw e;
}
catch ( TransactionalException e )
{
throw new IllegalStateException( "The transaction manager could not fulfill the transaction for " +
"dropping the constraint.", e );
}
}
}
}
@Override
public TxState txState()
{
if ( !hasTxState() )
{
txState = new TxStateImpl( legacyStateBridge, persistenceManager, null );
}
return txState;
}
@Override
public boolean hasTxState()
{
return null != txState;
}
@Override
public boolean hasTxStateWithChanges()
{
return legacyStateBridge.hasChanges() || (hasTxState() && txState.hasChanges());
}
private void close()
{
assertOpen();
closed = true;
if ( currentStatement != null )
{
currentStatement.forceClose();
currentStatement = null;
}
}
private void beginClose()
{
assertOpen();
if ( closing )
{
throw new IllegalStateException( "This transaction is already being closed." );
}
if ( currentStatement != null )
{
currentStatement.forceClose();
currentStatement = null;
}
closing = true;
}
private void createTransactionCommands()
{
if ( hasTxStateWithChanges() )
{
final AtomicBoolean clearState = new AtomicBoolean( false );
txState().accept( new TxState.Visitor()
{
@Override
public void visitNodeLabelChanges( long id, Set<Integer> added, Set<Integer> removed )
{
// TODO: move store level changes here.
}
@Override
public void visitAddedIndex( IndexDescriptor element, boolean isConstraintIndex )
{
SchemaIndexProvider.Descriptor providerDescriptor = providerMap.getDefaultProvider()
.getProviderDescriptor();
IndexRule rule;
if ( isConstraintIndex )
{
rule = IndexRule.constraintIndexRule( schemaStorage.newRuleId(), element.getLabelId(),
element.getPropertyKeyId(), providerDescriptor,
null );
}
else
{
rule = IndexRule.indexRule( schemaStorage.newRuleId(), element.getLabelId(),
element.getPropertyKeyId(), providerDescriptor );
}
persistenceManager.createSchemaRule( rule );
}
@Override
public void visitRemovedIndex( IndexDescriptor element, boolean isConstraintIndex )
{
try
{
SchemaStorage.IndexRuleKind kind = isConstraintIndex?
SchemaStorage.IndexRuleKind.CONSTRAINT : SchemaStorage.IndexRuleKind.INDEX;
IndexRule rule = schemaStorage.indexRule( element.getLabelId(), element.getPropertyKeyId(), kind );
persistenceManager.dropSchemaRule( rule );
}
catch ( SchemaRuleNotFoundException e )
{
throw new ThisShouldNotHappenError(
"Tobias Lindaaker",
"Index to be removed should exist, since its existence should have " +
"been validated earlier and the schema should have been locked.", e );
}
}
@Override
public void visitAddedConstraint( UniquenessConstraint element )
{
clearState.set( true );
long constraintId = schemaStorage.newRuleId();
IndexRule indexRule;
try
{
indexRule = schemaStorage.indexRule(
element.label(),
element.propertyKeyId(),
SchemaStorage.IndexRuleKind.CONSTRAINT );
}
catch ( SchemaRuleNotFoundException e )
{
throw new ThisShouldNotHappenError(
"Jacob Hansson",
"Index is always created for the constraint before this point.", e );
}
persistenceManager.createSchemaRule( UniquenessConstraintRule.uniquenessConstraintRule(
constraintId, element.label(), element.propertyKeyId(), indexRule.getId() ) );
persistenceManager.setConstraintIndexOwner( indexRule, constraintId );
}
@Override
public void visitRemovedConstraint( UniquenessConstraint element )
{
try
{
clearState.set( true );
UniquenessConstraintRule rule = schemaStorage
.uniquenessConstraint( element.label(), element.propertyKeyId() );
persistenceManager.dropSchemaRule( rule );
}
catch ( SchemaRuleNotFoundException e )
{
throw new ThisShouldNotHappenError(
"Tobias Lindaaker",
"Constraint to be removed should exist, since its existence should " +
"have been validated earlier and the schema should have been locked." );
}
// Remove the index for the constraint as well
visitRemovedIndex( new IndexDescriptor( element.label(), element.propertyKeyId() ), true );
}
} );
if ( clearState.get() )
{
schemaState.clear();
}
}
}
private void assertOpen()
{
if ( closed )
{
throw new IllegalStateException( "This transaction has already been completed." );
}
}
public boolean isReadOnly()
{
return !hasTxState() || !txState.hasChanges();
}
private enum TransactionType
{
ANY,
DATA
{
@Override
TransactionType upgradeToSchemaTransaction() throws InvalidTransactionTypeKernelException
{
throw new InvalidTransactionTypeKernelException(
"Cannot perform schema updates in a transaction that has performed data updates." );
}
},
SCHEMA
{
@Override
TransactionType upgradeToDataTransaction() throws InvalidTransactionTypeKernelException
{
throw new InvalidTransactionTypeKernelException(
"Cannot perform data updates in a transaction that has performed schema updates." );
}
};
TransactionType upgradeToDataTransaction() throws InvalidTransactionTypeKernelException
{
return DATA;
}
TransactionType upgradeToSchemaTransaction() throws InvalidTransactionTypeKernelException
{
return SCHEMA;
}
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_KernelTransactionImplementation.java
|
4,963
|
{
@Override
public void visitNodeLabelChanges( long id, Set<Integer> added, Set<Integer> removed )
{
// TODO: move store level changes here.
}
@Override
public void visitAddedIndex( IndexDescriptor element, boolean isConstraintIndex )
{
SchemaIndexProvider.Descriptor providerDescriptor = providerMap.getDefaultProvider()
.getProviderDescriptor();
IndexRule rule;
if ( isConstraintIndex )
{
rule = IndexRule.constraintIndexRule( schemaStorage.newRuleId(), element.getLabelId(),
element.getPropertyKeyId(), providerDescriptor,
null );
}
else
{
rule = IndexRule.indexRule( schemaStorage.newRuleId(), element.getLabelId(),
element.getPropertyKeyId(), providerDescriptor );
}
persistenceManager.createSchemaRule( rule );
}
@Override
public void visitRemovedIndex( IndexDescriptor element, boolean isConstraintIndex )
{
try
{
SchemaStorage.IndexRuleKind kind = isConstraintIndex?
SchemaStorage.IndexRuleKind.CONSTRAINT : SchemaStorage.IndexRuleKind.INDEX;
IndexRule rule = schemaStorage.indexRule( element.getLabelId(), element.getPropertyKeyId(), kind );
persistenceManager.dropSchemaRule( rule );
}
catch ( SchemaRuleNotFoundException e )
{
throw new ThisShouldNotHappenError(
"Tobias Lindaaker",
"Index to be removed should exist, since its existence should have " +
"been validated earlier and the schema should have been locked.", e );
}
}
@Override
public void visitAddedConstraint( UniquenessConstraint element )
{
clearState.set( true );
long constraintId = schemaStorage.newRuleId();
IndexRule indexRule;
try
{
indexRule = schemaStorage.indexRule(
element.label(),
element.propertyKeyId(),
SchemaStorage.IndexRuleKind.CONSTRAINT );
}
catch ( SchemaRuleNotFoundException e )
{
throw new ThisShouldNotHappenError(
"Jacob Hansson",
"Index is always created for the constraint before this point.", e );
}
persistenceManager.createSchemaRule( UniquenessConstraintRule.uniquenessConstraintRule(
constraintId, element.label(), element.propertyKeyId(), indexRule.getId() ) );
persistenceManager.setConstraintIndexOwner( indexRule, constraintId );
}
@Override
public void visitRemovedConstraint( UniquenessConstraint element )
{
try
{
clearState.set( true );
UniquenessConstraintRule rule = schemaStorage
.uniquenessConstraint( element.label(), element.propertyKeyId() );
persistenceManager.dropSchemaRule( rule );
}
catch ( SchemaRuleNotFoundException e )
{
throw new ThisShouldNotHappenError(
"Tobias Lindaaker",
"Constraint to be removed should exist, since its existence should " +
"have been validated earlier and the schema should have been locked." );
}
// Remove the index for the constraint as well
visitRemovedIndex( new IndexDescriptor( element.label(), element.propertyKeyId() ), true );
}
} );
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_KernelTransactionImplementation.java
|
4,964
|
private class RelationshipLock extends EntityLock implements Relationship
{
public RelationshipLock( long id )
{
super( id );
}
@Override
public Node getStartNode()
{
throw unsupportedOperation();
}
@Override
public Node getEndNode()
{
throw unsupportedOperation();
}
@Override
public Node getOtherNode( Node node )
{
throw unsupportedOperation();
}
@Override
public Node[] getNodes()
{
throw unsupportedOperation();
}
@Override
public RelationshipType getType()
{
throw unsupportedOperation();
}
@Override
public boolean isType( RelationshipType type )
{
throw unsupportedOperation();
}
@Override
public boolean equals( Object o )
{
return o instanceof Relationship && this.getId() == ((Relationship) o).getId();
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_LockHolderImpl.java
|
4,965
|
public class PrimitiveLongIteratorForArrayTest
{
@Test
public void shouldIterateEmptyArray() throws Exception
{
// given
PrimitiveLongIterator iterator = new PrimitiveLongIteratorForArray();
// when
assertFalse( "should not have next element", iterator.hasNext() );
try
{
iterator.next();
fail("Expected NoSuchElementException");
}
catch ( NoSuchElementException e )
{
assertNull( e.getMessage() );
}
}
@Test
public void shouldIterateNonEmptyArray() throws Exception
{
// given
PrimitiveLongIterator primitiveLongs = new PrimitiveLongIteratorForArray( 42l, 23l );
// when
assertThat( asList( 42l, 23l ).iterator(), hasSamePrimitiveItems( primitiveLongs) );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_PrimitiveLongIteratorForArrayTest.java
|
4,966
|
public class OperationsFacade implements ReadOperations, DataWriteOperations, SchemaWriteOperations
{
final KernelStatement statement;
private final LegacyKernelOperations legacyKernelOperations;
private final StatementOperationParts operations;
OperationsFacade( KernelStatement statement, LegacyKernelOperations legacyKernelOperations,
StatementOperationParts operations )
{
this.statement = statement;
this.legacyKernelOperations = legacyKernelOperations;
this.operations = operations;
}
// <DataRead>
final KeyReadOperations tokenRead()
{
return operations.keyReadOperations();
}
final KeyWriteOperations tokenWrite()
{
return operations.keyWriteOperations();
}
final EntityReadOperations dataRead()
{
return operations.entityReadOperations();
}
final EntityWriteOperations dataWrite()
{
return operations.entityWriteOperations();
}
final SchemaReadOperations schemaRead()
{
return operations.schemaReadOperations();
}
final org.neo4j.kernel.impl.api.operations.SchemaWriteOperations schemaWrite()
{
return operations.schemaWriteOperations();
}
final SchemaStateOperations schemaState()
{
return operations.schemaStateOperations();
}
final LegacyKernelOperations legacyOps()
{
return legacyKernelOperations;
}
// <DataRead>
@Override
public PrimitiveLongIterator nodesGetForLabel( int labelId )
{
statement.assertOpen();
if ( labelId == StatementConstants.NO_SUCH_LABEL )
{
return emptyPrimitiveLongIterator();
}
return dataRead().nodesGetForLabel( statement, labelId );
}
@Override
public PrimitiveLongIterator nodesGetFromIndexLookup( IndexDescriptor index, Object value )
throws IndexNotFoundKernelException
{
statement.assertOpen();
return dataRead().nodesGetFromIndexLookup( statement, index, value );
}
@Override
public long nodeGetUniqueFromIndexLookup( IndexDescriptor index, Object value )
throws IndexNotFoundKernelException, IndexBrokenKernelException
{
statement.assertOpen();
return dataRead().nodeGetUniqueFromIndexLookup( statement, index, value );
}
@Override
public boolean nodeHasLabel( long nodeId, int labelId ) throws EntityNotFoundException
{
statement.assertOpen();
return labelId != StatementConstants.NO_SUCH_LABEL && dataRead().nodeHasLabel( statement, nodeId, labelId );
}
@Override
public PrimitiveIntIterator nodeGetLabels( long nodeId ) throws EntityNotFoundException
{
statement.assertOpen();
return dataRead().nodeGetLabels( statement, nodeId );
}
@Override
public Property nodeGetProperty( long nodeId, int propertyKeyId ) throws EntityNotFoundException
{
statement.assertOpen();
if ( propertyKeyId == StatementConstants.NO_SUCH_PROPERTY_KEY )
{
return Property.noNodeProperty( nodeId, propertyKeyId );
}
return dataRead().nodeGetProperty( statement, nodeId, propertyKeyId );
}
@Override
public Property relationshipGetProperty( long relationshipId, int propertyKeyId ) throws EntityNotFoundException
{
statement.assertOpen();
if ( propertyKeyId == StatementConstants.NO_SUCH_PROPERTY_KEY )
{
return Property.noRelationshipProperty( relationshipId, propertyKeyId );
}
return dataRead().relationshipGetProperty( statement, relationshipId, propertyKeyId );
}
@Override
public Property graphGetProperty( int propertyKeyId )
{
statement.assertOpen();
if ( propertyKeyId == StatementConstants.NO_SUCH_PROPERTY_KEY )
{
return Property.noGraphProperty( propertyKeyId );
}
return dataRead().graphGetProperty( statement, propertyKeyId );
}
@Override
public Iterator<DefinedProperty> nodeGetAllProperties( long nodeId ) throws EntityNotFoundException
{
statement.assertOpen();
return dataRead().nodeGetAllProperties( statement, nodeId );
}
@Override
public Iterator<DefinedProperty> relationshipGetAllProperties( long relationshipId )
throws EntityNotFoundException
{
statement.assertOpen();
return dataRead().relationshipGetAllProperties( statement, relationshipId );
}
@Override
public Iterator<DefinedProperty> graphGetAllProperties()
{
statement.assertOpen();
return dataRead().graphGetAllProperties( statement );
}
// </DataRead>
// <SchemaRead>
@Override
public IndexDescriptor indexesGetForLabelAndPropertyKey( int labelId, int propertyKeyId )
throws SchemaRuleNotFoundException
{
statement.assertOpen();
return schemaRead().indexesGetForLabelAndPropertyKey( statement, labelId, propertyKeyId );
}
@Override
public Iterator<IndexDescriptor> indexesGetForLabel( int labelId )
{
statement.assertOpen();
return schemaRead().indexesGetForLabel( statement, labelId );
}
@Override
public Iterator<IndexDescriptor> indexesGetAll()
{
statement.assertOpen();
return schemaRead().indexesGetAll( statement );
}
@Override
public IndexDescriptor uniqueIndexGetForLabelAndPropertyKey( int labelId, int propertyKeyId )
throws SchemaRuleNotFoundException
{
IndexDescriptor result = null;
Iterator<IndexDescriptor> indexes = uniqueIndexesGetForLabel( labelId );
while ( indexes.hasNext() )
{
IndexDescriptor index = indexes.next();
if ( index.getPropertyKeyId() == propertyKeyId )
{
if ( null == result )
{
result = index;
}
else
{
throw new SchemaRuleNotFoundException( labelId, propertyKeyId, "duplicate uniqueness index" );
}
}
}
if ( null == result )
{
throw new SchemaRuleNotFoundException( labelId, propertyKeyId, "uniqueness index not found" );
}
return result;
}
@Override
public Iterator<IndexDescriptor> uniqueIndexesGetForLabel( int labelId )
{
statement.assertOpen();
return schemaRead().uniqueIndexesGetForLabel( statement, labelId );
}
@Override
public Long indexGetOwningUniquenessConstraintId( IndexDescriptor index ) throws SchemaRuleNotFoundException
{
statement.assertOpen();
return schemaRead().indexGetOwningUniquenessConstraintId( statement, index );
}
@Override
public Iterator<IndexDescriptor> uniqueIndexesGetAll()
{
statement.assertOpen();
return schemaRead().uniqueIndexesGetAll( statement );
}
@Override
public InternalIndexState indexGetState( IndexDescriptor descriptor ) throws IndexNotFoundKernelException
{
statement.assertOpen();
return schemaRead().indexGetState( statement, descriptor );
}
@Override
public String indexGetFailure( IndexDescriptor descriptor ) throws IndexNotFoundKernelException
{
statement.assertOpen();
return schemaRead().indexGetFailure( statement, descriptor );
}
@Override
public Iterator<UniquenessConstraint> constraintsGetForLabelAndPropertyKey( int labelId, int propertyKeyId )
{
statement.assertOpen();
return schemaRead().constraintsGetForLabelAndPropertyKey( statement, labelId, propertyKeyId );
}
@Override
public Iterator<UniquenessConstraint> constraintsGetForLabel( int labelId )
{
statement.assertOpen();
return schemaRead().constraintsGetForLabel( statement, labelId );
}
@Override
public Iterator<UniquenessConstraint> constraintsGetAll()
{
statement.assertOpen();
return schemaRead().constraintsGetAll( statement );
}
// </SchemaRead>
// <TokenRead>
@Override
public int labelGetForName( String labelName )
{
statement.assertOpen();
return tokenRead().labelGetForName( statement, labelName );
}
@Override
public String labelGetName( int labelId ) throws LabelNotFoundKernelException
{
statement.assertOpen();
return tokenRead().labelGetName( statement, labelId );
}
@Override
public int propertyKeyGetForName( String propertyKeyName )
{
statement.assertOpen();
return tokenRead().propertyKeyGetForName( statement, propertyKeyName );
}
@Override
public String propertyKeyGetName( int propertyKeyId ) throws PropertyKeyIdNotFoundKernelException
{
statement.assertOpen();
return tokenRead().propertyKeyGetName( statement, propertyKeyId );
}
@Override
public Iterator<Token> propertyKeyGetAllTokens()
{
statement.assertOpen();
return tokenRead().propertyKeyGetAllTokens( statement );
}
@Override
public Iterator<Token> labelsGetAllTokens()
{
statement.assertOpen();
return tokenRead().labelsGetAllTokens( statement );
}
@Override
public int relationshipTypeGetForName( String relationshipTypeName )
{
statement.assertOpen();
return tokenRead().relationshipTypeGetForName( statement, relationshipTypeName );
}
@Override
public String relationshipTypeGetName( int relationshipTypeId ) throws RelationshipTypeIdNotFoundKernelException
{
statement.assertOpen();
return tokenRead().relationshipTypeGetName( statement, relationshipTypeId );
}
// </TokenRead>
// <TokenWrite>
@Override
public int labelGetOrCreateForName( String labelName ) throws IllegalTokenNameException, TooManyLabelsException
{
statement.assertOpen();
return tokenWrite().labelGetOrCreateForName( statement, labelName );
}
@Override
public int propertyKeyGetOrCreateForName( String propertyKeyName ) throws IllegalTokenNameException
{
statement.assertOpen();
return tokenWrite().propertyKeyGetOrCreateForName( statement, propertyKeyName );
}
@Override
public int relationshipTypeGetOrCreateForName( String relationshipTypeName ) throws IllegalTokenNameException
{
statement.assertOpen();
return tokenWrite().relationshipTypeGetOrCreateForName( statement, relationshipTypeName );
}
// </TokenWrite>
// <SchemaState>
@Override
public <K, V> V schemaStateGetOrCreate( K key, Function<K, V> creator )
{
return schemaState().schemaStateGetOrCreate( statement, key, creator );
}
// </SchemaState>
// <DataWrite>
@Override
public long nodeCreate()
{
statement.assertOpen();
return legacyOps().nodeCreate( statement );
}
@Override
public void nodeDelete( long nodeId )
{
statement.assertOpen();
dataWrite().nodeDelete( statement, nodeId );
}
@Override
public long relationshipCreate( long relationshipTypeId, long startNodeId, long endNodeId )
throws RelationshipTypeIdNotFoundKernelException, EntityNotFoundException
{
statement.assertOpen();
return legacyOps().relationshipCreate( statement, relationshipTypeId, startNodeId, endNodeId );
}
@Override
public void relationshipDelete( long relationshipId )
{
statement.assertOpen();
dataWrite().relationshipDelete( statement, relationshipId );
}
@Override
public boolean nodeAddLabel( long nodeId, int labelId )
throws EntityNotFoundException, ConstraintValidationKernelException
{
statement.assertOpen();
return dataWrite().nodeAddLabel( statement, nodeId, labelId );
}
@Override
public boolean nodeRemoveLabel( long nodeId, int labelId ) throws EntityNotFoundException
{
statement.assertOpen();
return dataWrite().nodeRemoveLabel( statement, nodeId, labelId );
}
@Override
public Property nodeSetProperty( long nodeId, DefinedProperty property )
throws EntityNotFoundException, ConstraintValidationKernelException
{
statement.assertOpen();
return dataWrite().nodeSetProperty( statement, nodeId, property );
}
@Override
public Property relationshipSetProperty( long relationshipId, DefinedProperty property )
throws EntityNotFoundException
{
statement.assertOpen();
return dataWrite().relationshipSetProperty( statement, relationshipId, property );
}
@Override
public Property graphSetProperty( DefinedProperty property )
{
statement.assertOpen();
return dataWrite().graphSetProperty( statement, property );
}
@Override
public Property nodeRemoveProperty( long nodeId, int propertyKeyId ) throws EntityNotFoundException
{
statement.assertOpen();
return dataWrite().nodeRemoveProperty( statement, nodeId, propertyKeyId );
}
@Override
public Property relationshipRemoveProperty( long relationshipId, int propertyKeyId ) throws EntityNotFoundException
{
statement.assertOpen();
return dataWrite().relationshipRemoveProperty( statement, relationshipId, propertyKeyId );
}
@Override
public Property graphRemoveProperty( int propertyKeyId )
{
statement.assertOpen();
return dataWrite().graphRemoveProperty( statement, propertyKeyId );
}
// </DataWrite>
// <SchemaWrite>
@Override
public IndexDescriptor indexCreate( int labelId, int propertyKeyId )
throws AddIndexFailureException, AlreadyIndexedException, AlreadyConstrainedException
{
statement.assertOpen();
return schemaWrite().indexCreate( statement, labelId, propertyKeyId );
}
@Override
public void indexDrop( IndexDescriptor descriptor ) throws DropIndexFailureException
{
statement.assertOpen();
schemaWrite().indexDrop( statement, descriptor );
}
@Override
public UniquenessConstraint uniquenessConstraintCreate( int labelId, int propertyKeyId )
throws CreateConstraintFailureException, AlreadyConstrainedException, AlreadyIndexedException
{
statement.assertOpen();
return schemaWrite().uniquenessConstraintCreate( statement, labelId, propertyKeyId );
}
@Override
public void constraintDrop( UniquenessConstraint constraint ) throws DropConstraintFailureException
{
statement.assertOpen();
schemaWrite().constraintDrop( statement, constraint );
}
@Override
public void uniqueIndexDrop( IndexDescriptor descriptor ) throws DropIndexFailureException
{
schemaWrite().uniqueIndexDrop( statement, descriptor );
}
// </SchemaWrite>
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_OperationsFacade.java
|
4,967
|
public class NonTransactionalTokenNameLookup implements TokenNameLookup
{
private final LabelTokenHolder labelTokenHolder;
private final PropertyKeyTokenHolder propertyKeyTokenHolder;
public NonTransactionalTokenNameLookup( LabelTokenHolder labelTokenHolder, PropertyKeyTokenHolder
propertyKeyTokenHolder )
{
this.labelTokenHolder = labelTokenHolder;
this.propertyKeyTokenHolder = propertyKeyTokenHolder;
}
@Override
public String labelGetName( int labelId )
{
try
{
Token token = labelTokenHolder.getTokenByIdOrNull( labelId );
if(token != null)
{
return token.name();
}
}
catch(RuntimeException e)
{
// Ignore errors from reading key.
}
return format( "label[%d]", labelId );
}
@Override
public String propertyKeyGetName( int propertyKeyId )
{
try
{
Token token = propertyKeyTokenHolder.getTokenByIdOrNull( propertyKeyId );
if(token != null)
{
return token.name();
}
}
catch(RuntimeException e)
{
// Ignore errors from reading key
}
return format("property[%d]", propertyKeyId);
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_NonTransactionalTokenNameLookup.java
|
4,968
|
public class NoOpJTATransaction implements Transaction
{
@Override
public void commit() throws HeuristicMixedException, HeuristicRollbackException, RollbackException, SecurityException, SystemException
{
throw new UnsupportedOperationException( "Not allowed." );
}
@Override
public boolean delistResource( XAResource xaResource, int i ) throws IllegalStateException, SystemException
{
throw new UnsupportedOperationException( "Not allowed." );
}
@Override
public boolean enlistResource( XAResource xaResource ) throws IllegalStateException, RollbackException,
SystemException
{
throw new UnsupportedOperationException( "Not allowed." );
}
@Override
public int getStatus() throws SystemException
{
throw new UnsupportedOperationException( "Not allowed." );
}
@Override
public void registerSynchronization( Synchronization synchronization ) throws IllegalStateException, RollbackException, SystemException
{
throw new UnsupportedOperationException( "Not allowed." );
}
@Override
public void rollback() throws IllegalStateException, SystemException
{
throw new UnsupportedOperationException( "Not allowed." );
}
@Override
public void setRollbackOnly() throws IllegalStateException, SystemException
{
throw new UnsupportedOperationException( "Not allowed." );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_NoOpJTATransaction.java
|
4,969
|
public class LongDiffSetsTest
{
// TODO empty diffset EMPTY
// TODO null/isEmpty elements
// System.out.println( asCollection( iteratorResult ) );
// System.out.println( asCollection( toJavaIterator( primitiveResult ) ) );
@Test
public void shouldContainSourceForEmptyDiffSets() throws Exception
{
// given
DiffSets<Long> diffSets = new DiffSets<>( );
Iterator<Long> expected = diffSets.apply( iteratorSource( 1l, 2l ) );
// when
PrimitiveLongIterator actual = diffSets.applyPrimitiveLongIterator( primitiveSource( 1l, 2l ) );
// then
assertThat( expected, hasSamePrimitiveItems( actual ) );
}
@Test
public void shouldContainFilteredSourceForDiffSetsWithRemovedElements() throws Exception
{
// given
DiffSets<Long> diffSets = new DiffSets<>( );
diffSets.remove( 17l );
diffSets.remove( 18l );
Iterator<Long> expected = diffSets.apply( iteratorSource( 1L, 17l, 3l ) );
// when
PrimitiveLongIterator actual = diffSets.applyPrimitiveLongIterator( primitiveSource( 1l, 17l, 3l ) );
// then
assertThat( expected, hasSamePrimitiveItems( actual ) );
}
@Test
public void shouldContainFilteredSourceForDiffSetsWithAddedElements() throws Exception
{
// given
DiffSets<Long> diffSets = new DiffSets<>( );
diffSets.add( 17l );
diffSets.add( 18l );
Iterator<Long> expected = diffSets.apply( iteratorSource( 1L, 17l, 3l ) );
// when
PrimitiveLongIterator actual = diffSets.applyPrimitiveLongIterator( primitiveSource( 1l, 17l, 3l ) );
// then
assertThat( expected, hasSamePrimitiveItems( actual ) );
}
@Test
public void shouldContainAddedElementsForDiffSetsWithAddedElements() throws Exception
{
// given
DiffSets<Long> diffSets = new DiffSets<>( );
diffSets.add( 19l );
diffSets.add( 20l );
Iterator<Long> expected = diffSets.apply( iteratorSource( 19l ) );
// when
PrimitiveLongIterator actual = diffSets.applyPrimitiveLongIterator( primitiveSource( 19l ) );
// then
assertThat( expected, hasSamePrimitiveItems( actual ) );
}
private static PrimitiveLongIterator primitiveSource( long... values )
{
return new PrimitiveLongIteratorForArray( values );
}
private static Iterator<Long> iteratorSource( Long... values )
{
return asList( values ).iterator();
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_LongDiffSetsTest.java
|
4,970
|
public class LockingStatementOperationsTest
{
private final LockingStatementOperations lockingOps;
private final EntityWriteOperations entityWriteOps;
private final SchemaReadOperations schemaReadOps;
private final SchemaWriteOperations schemaWriteOps;
private final LockHolder locks = mock( LockHolder.class );
private final InOrder order;
private final KernelStatement state = new KernelStatement( null, null, null, null, locks, null, null, null );
public LockingStatementOperationsTest()
{
entityWriteOps = mock( EntityWriteOperations.class );
schemaReadOps = mock( SchemaReadOperations.class );
schemaWriteOps = mock( SchemaWriteOperations.class );
order = inOrder( locks, entityWriteOps, schemaReadOps, schemaWriteOps );
lockingOps = new LockingStatementOperations( entityWriteOps, schemaReadOps, schemaWriteOps, null );
}
@Test
public void shouldAcquireEntityWriteLockBeforeAddingLabelToNode() throws Exception
{
// when
lockingOps.nodeAddLabel( state, 123, 456 );
// then
order.verify( locks ).acquireNodeWriteLock( 123 );
order.verify( entityWriteOps ).nodeAddLabel( state, 123, 456 );
}
@Test
public void shouldAcquireSchemaReadLockBeforeAddingLabelToNode() throws Exception
{
// when
lockingOps.nodeAddLabel( state, 123, 456 );
// then
order.verify( locks ).acquireSchemaReadLock();
order.verify( entityWriteOps ).nodeAddLabel( state, 123, 456 );
}
@Test
public void shouldAcquireEntityWriteLockBeforeSettingPropertyOnNode() throws Exception
{
// given
DefinedProperty property = Property.property( 8, 9 );
// when
lockingOps.nodeSetProperty( state, 123, property );
// then
order.verify( locks ).acquireNodeWriteLock( 123 );
order.verify( entityWriteOps ).nodeSetProperty( state, 123, property );
}
@Test
public void shouldAcquireSchemaReadLockBeforeSettingPropertyOnNode() throws Exception
{
// given
DefinedProperty property = Property.property( 8, 9 );
// when
lockingOps.nodeSetProperty( state, 123, property );
// then
order.verify( locks ).acquireSchemaReadLock();
order.verify( entityWriteOps ).nodeSetProperty( state, 123, property );
}
@Test
public void shouldAcquireEntityWriteLockBeforeDeletingNode()
{
// WHEN
lockingOps.nodeDelete( state, 123 );
//THEN
order.verify( locks ).acquireNodeWriteLock( 123 );
order.verify( entityWriteOps ).nodeDelete( state, 123 );
}
@Test
public void shouldAcquireSchemaWriteLockBeforeAddingIndexRule() throws Exception
{
// given
IndexDescriptor rule = mock( IndexDescriptor.class );
when( schemaWriteOps.indexCreate( state, 123, 456 ) ).thenReturn( rule );
// when
IndexDescriptor result = lockingOps.indexCreate( state, 123, 456 );
// then
assertSame( rule, result );
order.verify( locks ).acquireSchemaWriteLock();
order.verify( schemaWriteOps ).indexCreate( state, 123, 456 );
}
@Test
public void shouldAcquireSchemaWriteLockBeforeRemovingIndexRule() throws Exception
{
// given
IndexDescriptor rule = new IndexDescriptor( 0, 0 );
// when
lockingOps.indexDrop( state, rule );
// then
order.verify( locks ).acquireSchemaWriteLock();
order.verify( schemaWriteOps ).indexDrop( state, rule );
}
@Test
public void shouldAcquireSchemaReadLockBeforeGettingIndexRules() throws Exception
{
// given
Iterator<IndexDescriptor> rules = Collections.emptyIterator();
when( schemaReadOps.indexesGetAll( state ) ).thenReturn( rules );
// when
Iterator<IndexDescriptor> result = lockingOps.indexesGetAll( state );
// then
assertSame( rules, result );
order.verify( locks ).acquireSchemaReadLock();
order.verify( schemaReadOps ).indexesGetAll( state );
}
@Test
public void shouldAcquireSchemaWriteLockBeforeCreatingUniquenessConstraint() throws Exception
{
// given
UniquenessConstraint constraint = new UniquenessConstraint( 0, 0 );
when( schemaWriteOps.uniquenessConstraintCreate( state, 123, 456 ) ).thenReturn( constraint );
// when
UniquenessConstraint result = lockingOps.uniquenessConstraintCreate( state, 123, 456 );
// then
assertSame( constraint, result );
order.verify( locks ).acquireSchemaWriteLock();
order.verify( schemaWriteOps ).uniquenessConstraintCreate( state, 123, 456 );
}
@Test
public void shouldAcquireSchemaWriteLockBeforeDroppingConstraint() throws Exception
{
// given
UniquenessConstraint constraint = new UniquenessConstraint( 1, 2 );
// when
lockingOps.constraintDrop( state, constraint );
// then
order.verify( locks ).acquireSchemaWriteLock();
order.verify( schemaWriteOps ).constraintDrop( state, constraint );
}
@Test
public void shouldAcquireSchemaReadLockBeforeGettingConstraintsByLabelAndProperty() throws Exception
{
// given
Iterator<UniquenessConstraint> constraints = Collections.emptyIterator();
when( schemaReadOps.constraintsGetForLabelAndPropertyKey( state, 123, 456 ) ).thenReturn( constraints );
// when
Iterator<UniquenessConstraint> result = lockingOps.constraintsGetForLabelAndPropertyKey( state, 123, 456 );
// then
assertSame( constraints, result );
order.verify( locks ).acquireSchemaReadLock();
order.verify( schemaReadOps ).constraintsGetForLabelAndPropertyKey( state, 123, 456 );
}
@Test
public void shouldAcquireSchemaReadLockBeforeGettingConstraintsByLabel() throws Exception
{
// given
Iterator<UniquenessConstraint> constraints = Collections.emptyIterator();
when( schemaReadOps.constraintsGetForLabel( state, 123 ) ).thenReturn( constraints );
// when
Iterator<UniquenessConstraint> result = lockingOps.constraintsGetForLabel( state, 123 );
// then
assertSame( constraints, result );
order.verify( locks ).acquireSchemaReadLock();
order.verify( schemaReadOps ).constraintsGetForLabel( state, 123 );
}
@Test
public void shouldAcquireSchemaReadLockBeforeGettingAllConstraints() throws Exception
{
// given
Iterator<UniquenessConstraint> constraints = Collections.emptyIterator();
when( schemaReadOps.constraintsGetAll( state ) ).thenReturn( constraints );
// when
Iterator<UniquenessConstraint> result = lockingOps.constraintsGetAll( state );
// then
assertSame( constraints, result );
order.verify( locks ).acquireSchemaReadLock();
order.verify( schemaReadOps ).constraintsGetAll( state );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_LockingStatementOperationsTest.java
|
4,971
|
public class LockingStatementOperations implements
EntityWriteOperations,
SchemaReadOperations,
SchemaWriteOperations,
SchemaStateOperations
{
private final EntityWriteOperations entityWriteDelegate;
private final SchemaReadOperations schemaReadDelegate;
private final SchemaWriteOperations schemaWriteDelegate;
private final SchemaStateOperations schemaStateDelegate;
public LockingStatementOperations(
EntityWriteOperations entityWriteDelegate,
SchemaReadOperations schemaReadDelegate,
SchemaWriteOperations schemaWriteDelegate,
SchemaStateOperations schemaStateDelegate )
{
this.entityWriteDelegate = entityWriteDelegate;
this.schemaReadDelegate = schemaReadDelegate;
this.schemaWriteDelegate = schemaWriteDelegate;
this.schemaStateDelegate = schemaStateDelegate;
}
@Override
public boolean nodeAddLabel( KernelStatement state, long nodeId, int labelId )
throws EntityNotFoundException, ConstraintValidationKernelException
{
// TODO (BBC, 22/11/13):
// In order to enforce constraints we need to check whether this change violates constraints; we therefore need
// the schema lock to ensure that our view of constraints is consistent.
//
// We would like this locking to be done naturally when ConstraintEnforcingEntityOperations calls
// SchemaReadOperations#constraintsGetForLabel, but the SchemaReadOperations object that
// ConstraintEnforcingEntityOperations has a reference to does not lock because of the way the cake is
// constructed.
//
// It would be cleaner if the schema and data cakes were separated so that the SchemaReadOperations object used
// by ConstraintEnforcingEntityOperations included the full cake, with locking included.
state.locks().acquireSchemaReadLock();
state.locks().acquireNodeWriteLock( nodeId );
return entityWriteDelegate.nodeAddLabel( state, nodeId, labelId );
}
@Override
public boolean nodeRemoveLabel( KernelStatement state, long nodeId, int labelId ) throws EntityNotFoundException
{
state.locks().acquireNodeWriteLock( nodeId );
return entityWriteDelegate.nodeRemoveLabel( state, nodeId, labelId );
}
@Override
public IndexDescriptor indexCreate( KernelStatement state, int labelId, int propertyKey )
throws AddIndexFailureException, AlreadyIndexedException, AlreadyConstrainedException
{
state.locks().acquireSchemaWriteLock();
return schemaWriteDelegate.indexCreate( state, labelId, propertyKey );
}
@Override
public void indexDrop( KernelStatement state, IndexDescriptor descriptor ) throws DropIndexFailureException
{
state.locks().acquireSchemaWriteLock();
schemaWriteDelegate.indexDrop( state, descriptor );
}
@Override
public void uniqueIndexDrop( KernelStatement state, IndexDescriptor descriptor ) throws DropIndexFailureException
{
state.locks().acquireSchemaWriteLock();
schemaWriteDelegate.uniqueIndexDrop( state, descriptor );
}
@Override
public <K, V> V schemaStateGetOrCreate( KernelStatement state, K key, Function<K, V> creator )
{
state.locks().acquireSchemaReadLock();
return schemaStateDelegate.schemaStateGetOrCreate( state, key, creator );
}
@Override
public <K> boolean schemaStateContains( KernelStatement state, K key )
{
state.locks().acquireSchemaReadLock();
return schemaStateDelegate.schemaStateContains( state, key );
}
@Override
public Iterator<IndexDescriptor> indexesGetForLabel( KernelStatement state, int labelId )
{
state.locks().acquireSchemaReadLock();
return schemaReadDelegate.indexesGetForLabel( state, labelId );
}
@Override
public IndexDescriptor indexesGetForLabelAndPropertyKey( KernelStatement state, int labelId, int propertyKey )
throws SchemaRuleNotFoundException
{
state.locks().acquireSchemaReadLock();
return schemaReadDelegate.indexesGetForLabelAndPropertyKey( state, labelId, propertyKey );
}
@Override
public Iterator<IndexDescriptor> indexesGetAll( KernelStatement state )
{
state.locks().acquireSchemaReadLock();
return schemaReadDelegate.indexesGetAll( state );
}
@Override
public InternalIndexState indexGetState( KernelStatement state, IndexDescriptor descriptor ) throws IndexNotFoundKernelException
{
state.locks().acquireSchemaReadLock();
return schemaReadDelegate.indexGetState( state, descriptor );
}
@Override
public Long indexGetOwningUniquenessConstraintId( KernelStatement state, IndexDescriptor index ) throws SchemaRuleNotFoundException
{
state.locks().acquireSchemaReadLock();
return schemaReadDelegate.indexGetOwningUniquenessConstraintId( state, index );
}
@Override
public long indexGetCommittedId( KernelStatement state, IndexDescriptor index, SchemaStorage.IndexRuleKind kind )
throws SchemaRuleNotFoundException
{
state.locks().acquireSchemaReadLock();
return schemaReadDelegate.indexGetCommittedId( state, index, kind );
}
@Override
public Iterator<IndexDescriptor> uniqueIndexesGetForLabel( KernelStatement state, int labelId )
{
state.locks().acquireSchemaReadLock();
return schemaReadDelegate.uniqueIndexesGetForLabel( state, labelId );
}
@Override
public Iterator<IndexDescriptor> uniqueIndexesGetAll( KernelStatement state )
{
state.locks().acquireSchemaReadLock();
return schemaReadDelegate.uniqueIndexesGetAll( state );
}
@Override
public void nodeDelete( KernelStatement state, long nodeId )
{
state.locks().acquireNodeWriteLock( nodeId );
entityWriteDelegate.nodeDelete( state, nodeId );
}
@Override
public void relationshipDelete( KernelStatement state, long relationshipId )
{
state.locks().acquireRelationshipWriteLock( relationshipId );
entityWriteDelegate.relationshipDelete( state, relationshipId );
}
@Override
public UniquenessConstraint uniquenessConstraintCreate( KernelStatement state, int labelId, int propertyKeyId )
throws CreateConstraintFailureException, AlreadyConstrainedException, AlreadyIndexedException
{
state.locks().acquireSchemaWriteLock();
return schemaWriteDelegate.uniquenessConstraintCreate( state, labelId, propertyKeyId );
}
@Override
public Iterator<UniquenessConstraint> constraintsGetForLabelAndPropertyKey( KernelStatement state, int labelId, int propertyKeyId )
{
state.locks().acquireSchemaReadLock();
return schemaReadDelegate.constraintsGetForLabelAndPropertyKey( state, labelId, propertyKeyId );
}
@Override
public Iterator<UniquenessConstraint> constraintsGetForLabel( KernelStatement state, int labelId )
{
state.locks().acquireSchemaReadLock();
return schemaReadDelegate.constraintsGetForLabel( state, labelId );
}
@Override
public Iterator<UniquenessConstraint> constraintsGetAll( KernelStatement state )
{
state.locks().acquireSchemaReadLock();
return schemaReadDelegate.constraintsGetAll( state );
}
@Override
public void constraintDrop( KernelStatement state, UniquenessConstraint constraint )
throws DropConstraintFailureException
{
state.locks().acquireSchemaWriteLock();
schemaWriteDelegate.constraintDrop( state, constraint );
}
@Override
public Property nodeSetProperty( KernelStatement state, long nodeId, DefinedProperty property )
throws EntityNotFoundException, ConstraintValidationKernelException
{
// TODO (BBC, 22/11/13):
// In order to enforce constraints we need to check whether this change violates constraints; we therefore need
// the schema lock to ensure that our view of constraints is consistent.
//
// We would like this locking to be done naturally when ConstraintEnforcingEntityOperations calls
// SchemaReadOperations#constraintsGetForLabel, but the SchemaReadOperations object that
// ConstraintEnforcingEntityOperations has a reference to does not lock because of the way the cake is
// constructed.
//
// It would be cleaner if the schema and data cakes were separated so that the SchemaReadOperations object used
// by ConstraintEnforcingEntityOperations included the full cake, with locking included.
state.locks().acquireSchemaReadLock();
state.locks().acquireNodeWriteLock( nodeId );
return entityWriteDelegate.nodeSetProperty( state, nodeId, property );
}
@Override
public Property nodeRemoveProperty( KernelStatement state, long nodeId, int propertyKeyId )
throws EntityNotFoundException
{
state.locks().acquireNodeWriteLock( nodeId );
return entityWriteDelegate.nodeRemoveProperty( state, nodeId, propertyKeyId );
}
@Override
public Property relationshipSetProperty( KernelStatement state, long relationshipId, DefinedProperty property )
throws EntityNotFoundException
{
state.locks().acquireRelationshipWriteLock( relationshipId );
return entityWriteDelegate.relationshipSetProperty( state, relationshipId, property );
}
@Override
public Property relationshipRemoveProperty( KernelStatement state, long relationshipId, int propertyKeyId )
throws EntityNotFoundException
{
state.locks().acquireRelationshipWriteLock( relationshipId );
return entityWriteDelegate.relationshipRemoveProperty( state, relationshipId, propertyKeyId );
}
@Override
public Property graphSetProperty( KernelStatement state, DefinedProperty property )
{
state.locks().acquireGraphWriteLock();
return entityWriteDelegate.graphSetProperty( state, property );
}
@Override
public Property graphRemoveProperty( KernelStatement state, int propertyKeyId )
{
state.locks().acquireGraphWriteLock();
return entityWriteDelegate.graphRemoveProperty( state, propertyKeyId );
}
// === TODO Below is unnecessary delegate methods
@Override
public String indexGetFailure( Statement state, IndexDescriptor descriptor )
throws IndexNotFoundKernelException
{
return schemaReadDelegate.indexGetFailure( state, descriptor );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_LockingStatementOperations.java
|
4,972
|
public class LockHolderTest
{
@Test
public void shouldAcquireSchemaReadLock()
{
// GIVEN
LockManager mgr = mock( LockManager.class );
Transaction tx = mock( Transaction.class );
NodeManager nm = mock( NodeManager.class );
LockHolder holder = new LockHolderImpl( mgr, tx, nm );
// WHEN
holder.acquireSchemaReadLock();
// THEN
Mockito.verify( mgr ).getReadLock( any( SchemaLock.class ), Matchers.eq( tx ) );
}
@Test
public void shouldAcquireSchemaWriteLock()
{
// GIVEN
LockManager mgr = mock( LockManager.class );
Transaction tx = mock( Transaction.class );
NodeManager nm = mock( NodeManager.class );
LockHolder holder = new LockHolderImpl( mgr, tx, nm );
// WHEN
holder.acquireSchemaWriteLock();
// THEN
Mockito.verify( mgr ).getWriteLock( any( SchemaLock.class ), Matchers.eq( tx ) );
}
@Test
public void shouldReleaseSchemaReadLockOnRelease() throws ReleaseLocksFailedKernelException
{
// GIVEN
LockManager mgr = mock( LockManager.class );
Transaction tx = mock( Transaction.class );
NodeManager nm = mock( NodeManager.class );
LockHolder holder = new LockHolderImpl( mgr, tx, nm );
// WHEN
holder.acquireSchemaReadLock();
holder.releaseLocks();
// THEN
Mockito.verify( mgr ).releaseReadLock( any( SchemaLock.class ), Matchers.eq( tx ) );
}
@Test
public void shouldReleaseSchemaWriteLockOnRelease() throws ReleaseLocksFailedKernelException
{
// GIVEN
LockManager mgr = mock( LockManager.class );
Transaction tx = mock( Transaction.class );
NodeManager nm = mock( NodeManager.class );
LockHolder holder = new LockHolderImpl( mgr, tx, nm );
// WHEN
holder.acquireSchemaWriteLock();
holder.releaseLocks();
// THEN
Mockito.verify( mgr ).releaseWriteLock( any( SchemaLock.class ), Matchers.eq( tx ) );
}
@Test
public void shouldThrowExceptionWhenAttemptingToReleaseUnknownLocks()
{
// For instance, this can happen if the locks were taken prior to a master-switch,
// and then attempted released after the master-switch.
// GIVEN
LockManager mgr = mock( LockManager.class );
Transaction tx = mock( Transaction.class );
NodeManager nm = mock( NodeManager.class );
LockHolder holder = new LockHolderImpl( mgr, tx, nm );
doThrow( new LockNotFoundException( "Sad face" ) )
.when( mgr )
.releaseWriteLock( anyObject(), any( Transaction.class ) );
doThrow( new LockNotFoundException( "Sad face" ) )
.when( mgr )
.releaseReadLock( anyObject(), any( Transaction.class ) );
// WHEN
holder.acquireSchemaReadLock();
holder.acquireSchemaReadLock();
holder.acquireNodeWriteLock( 1337 );
// THEN
try
{
holder.releaseLocks();
fail( "Expected releaseLocks to throw" );
}
catch ( ReleaseLocksFailedKernelException e )
{
assertThat( e.getMessage(), containsString( "[READ SchemaLocks: 2, WRITE NodeLocks: 1]" ) );
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_LockHolderTest.java
|
4,973
|
private class RegisteringReleasableLock implements ReleasableLock
{
private LockReleaseCallback callback;
private RegisteringReleasableLock( LockReleaseCallback callback )
{
this.callback = callback;
}
@Override
public void release()
{
if ( callback == null )
{
throw new IllegalStateException();
}
callback.release();
callback = null;
}
@Override
public void registerWithTransaction()
{
if ( callback == null )
{
throw new IllegalStateException();
}
locks.add( callback );
callback = null;
}
@Override
public void close()
{
if ( callback != null )
{
registerWithTransaction();
}
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_LockHolderImpl.java
|
4,974
|
DATA
{
@Override
TransactionType upgradeToSchemaTransaction() throws InvalidTransactionTypeKernelException
{
throw new InvalidTransactionTypeKernelException(
"Cannot perform schema updates in a transaction that has performed data updates." );
}
},
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_KernelTransactionImplementation.java
|
4,975
|
@SuppressWarnings("deprecation")
private class NodeLock extends EntityLock implements Node
{
public NodeLock( long id )
{
super( id );
}
@Override
public Iterable<Relationship> getRelationships()
{
throw unsupportedOperation();
}
@Override
public boolean hasRelationship()
{
throw unsupportedOperation();
}
@Override
public Iterable<Relationship> getRelationships( RelationshipType... types )
{
throw unsupportedOperation();
}
@Override
public Iterable<Relationship> getRelationships( Direction direction, RelationshipType... types )
{
throw unsupportedOperation();
}
@Override
public boolean hasRelationship( RelationshipType... types )
{
throw unsupportedOperation();
}
@Override
public boolean hasRelationship( Direction direction, RelationshipType... types )
{
throw unsupportedOperation();
}
@Override
public Iterable<Relationship> getRelationships( Direction dir )
{
throw unsupportedOperation();
}
@Override
public boolean hasRelationship( Direction dir )
{
throw unsupportedOperation();
}
@Override
public Iterable<Relationship> getRelationships( RelationshipType type, Direction dir )
{
throw unsupportedOperation();
}
@Override
public boolean hasRelationship( RelationshipType type, Direction dir )
{
throw unsupportedOperation();
}
@Override
public Relationship getSingleRelationship( RelationshipType type, Direction dir )
{
throw unsupportedOperation();
}
@Override
public Relationship createRelationshipTo( Node otherNode, RelationshipType type )
{
throw unsupportedOperation();
}
@Override
public Traverser traverse( Traverser.Order traversalOrder, StopEvaluator stopEvaluator, ReturnableEvaluator
returnableEvaluator, RelationshipType relationshipType, Direction direction )
{
throw unsupportedOperation();
}
@Override
public Traverser traverse( Traverser.Order traversalOrder, StopEvaluator stopEvaluator, ReturnableEvaluator
returnableEvaluator, RelationshipType firstRelationshipType, Direction firstDirection,
RelationshipType secondRelationshipType, Direction secondDirection )
{
throw unsupportedOperation();
}
@Override
public Traverser traverse( Traverser.Order traversalOrder, StopEvaluator stopEvaluator, ReturnableEvaluator
returnableEvaluator, Object... relationshipTypesAndDirections )
{
throw unsupportedOperation();
}
@Override
public void addLabel( Label label )
{
throw unsupportedOperation();
}
@Override
public void removeLabel( Label label )
{
throw unsupportedOperation();
}
@Override
public boolean hasLabel( Label label )
{
throw unsupportedOperation();
}
@Override
public ResourceIterable<Label> getLabels()
{
throw unsupportedOperation();
}
@Override
public boolean equals( Object o )
{
return o instanceof Node && this.getId() == ((Node) o).getId();
}
// NOTE hashCode is implemented in super
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_LockHolderImpl.java
|
4,976
|
private final class LockReleaseCallback
{
private final LockType lockType;
private final Object lock;
public LockReleaseCallback( LockType lockType, Object lock )
{
this.lockType = lockType;
this.lock = lock;
}
public void release()
{
lockType.release( lockManager, lock, tx );
}
@Override
public String toString()
{
return String.format( "%s_LOCK(%s)", lockType.name(), lock );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_LockHolderImpl.java
|
4,977
|
private class GraphLock extends EntityLock implements GraphProperties
{
public GraphLock()
{
super( -1 );
}
@Override
public NodeManager getNodeManager()
{
return nodeManager;
}
@Override
public boolean equals( Object o )
{
return o instanceof GraphProperties
&& this.getNodeManager().equals( ((GraphProperties) o).getNodeManager() );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_LockHolderImpl.java
|
4,978
|
private abstract class EntityLock implements PropertyContainer
{
private final long id;
public EntityLock( long id )
{
this.id = id;
}
@Override
public String toString()
{
return String.format( "%s[id=%d]", getClass().getSimpleName(), id );
}
public long getId()
{
return id;
}
public void delete()
{
throw unsupportedOperation();
}
@Override
public GraphDatabaseService getGraphDatabase()
{
throw unsupportedOperation();
}
@Override
public boolean hasProperty( String key )
{
throw unsupportedOperation();
}
@Override
public Object getProperty( String key )
{
throw unsupportedOperation();
}
@Override
public Object getProperty( String key, Object defaultValue )
{
throw unsupportedOperation();
}
@Override
public void setProperty( String key, Object value )
{
throw unsupportedOperation();
}
@Override
public Object removeProperty( String key )
{
throw unsupportedOperation();
}
@Override
public Iterable<String> getPropertyKeys()
{
throw unsupportedOperation();
}
@Override
public int hashCode()
{
return (int) ((id >>> 32) ^ id);
}
protected UnsupportedOperationException unsupportedOperation()
{
return new UnsupportedOperationException( getClass().getSimpleName() +
" does not support this operation." );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_LockHolderImpl.java
|
4,979
|
public class LockHolderImpl implements LockHolder
{
private final LockManager lockManager;
private final Transaction tx;
private final List<LockReleaseCallback> locks = new ArrayList<>();
private final NodeManager nodeManager;
public LockHolderImpl( LockManager lockManager, Transaction tx, NodeManager nodeManager )
{
this.lockManager = lockManager;
// Once we have moved all locking into the kernel, we should refactor the locking to not use the CoreAPI
// transaction to track who is locking stuff.
this.tx = tx;
// TODO Not happy about the NodeManager dependency. It's needed a.t.m. for making
// equality comparison between GraphProperties instances. It should change.
this.nodeManager = nodeManager;
}
@Override
public void acquireNodeReadLock( long nodeId )
{
NodeLock resource = new NodeLock( nodeId );
lockManager.getReadLock( resource, tx );
locks.add( new LockReleaseCallback( LockType.READ, resource ) );
}
@Override
public void acquireNodeWriteLock( long nodeId )
{
NodeLock resource = new NodeLock( nodeId );
lockManager.getWriteLock( resource, tx );
locks.add( new LockReleaseCallback( LockType.WRITE, resource ) );
}
@Override
public void acquireRelationshipReadLock( long relationshipId )
{
RelationshipLock resource = new RelationshipLock( relationshipId );
lockManager.getReadLock( resource, tx );
locks.add( new LockReleaseCallback( LockType.READ, resource ) );
}
@Override
public void acquireRelationshipWriteLock( long relationshipId )
{
RelationshipLock resource = new RelationshipLock( relationshipId );
lockManager.getWriteLock( resource, tx );
locks.add( new LockReleaseCallback( LockType.WRITE, resource ) );
}
@Override
public void acquireGraphWriteLock()
{
GraphLock resource = new GraphLock();
lockManager.getWriteLock( resource, tx );
locks.add( new LockReleaseCallback( LockType.WRITE, resource ) );
}
@Override
public void acquireSchemaReadLock()
{
SchemaLock resource = new SchemaLock();
lockManager.getReadLock( resource, tx );
locks.add( new LockReleaseCallback( LockType.READ, resource ) );
}
@Override
public void acquireSchemaWriteLock()
{
SchemaLock resource = new SchemaLock();
lockManager.getWriteLock( resource, tx );
locks.add( new LockReleaseCallback( LockType.WRITE, resource ) );
}
@Override
public void acquireIndexEntryWriteLock( int labelId, int propertyKeyId, String propertyValue )
{
IndexEntryLock resource = new IndexEntryLock( labelId, propertyKeyId, propertyValue );
lockManager.getWriteLock( resource, tx );
locks.add( new LockReleaseCallback( LockType.WRITE, resource ) );
}
@Override
public ReleasableLock getReleasableIndexEntryReadLock( int labelId, int propertyKeyId, String propertyValue )
{
IndexEntryLock resource = new IndexEntryLock( labelId, propertyKeyId, propertyValue );
lockManager.getReadLock( resource, tx );
return new RegisteringReleasableLock( new LockReleaseCallback( LockType.READ, resource ) );
}
@Override
public ReleasableLock getReleasableIndexEntryWriteLock( int labelId, int propertyKeyId, String propertyValue )
{
IndexEntryLock resource = new IndexEntryLock( labelId, propertyKeyId, propertyValue );
lockManager.getWriteLock( resource, tx );
return new RegisteringReleasableLock( new LockReleaseCallback( LockType.WRITE, resource ) );
}
private class RegisteringReleasableLock implements ReleasableLock
{
private LockReleaseCallback callback;
private RegisteringReleasableLock( LockReleaseCallback callback )
{
this.callback = callback;
}
@Override
public void release()
{
if ( callback == null )
{
throw new IllegalStateException();
}
callback.release();
callback = null;
}
@Override
public void registerWithTransaction()
{
if ( callback == null )
{
throw new IllegalStateException();
}
locks.add( callback );
callback = null;
}
@Override
public void close()
{
if ( callback != null )
{
registerWithTransaction();
}
}
}
@Override
public void releaseLocks() throws ReleaseLocksFailedKernelException
{
Collection<LockReleaseCallback> releaseFailures = null;
Exception releaseException = null;
for ( LockReleaseCallback lockElement : locks )
{
try
{
lockElement.release();
}
catch ( Exception e )
{
releaseException = e;
if ( releaseFailures == null )
{
releaseFailures = new ArrayList<>();
}
releaseFailures.add( lockElement );
}
}
if ( releaseException != null )
{
throw new ReleaseLocksFailedKernelException(
"Unable to release locks: " + describeLockGroups( releaseFailures ) + ". " +
"Perhaps we have had a master-switch since the transaction was started?",
releaseException );
}
locks.clear();
}
private static String describeLockGroups( Collection<LockReleaseCallback> locks )
{
Map<Class<?>, AtomicInteger> readLockCounterMap = new HashMap<>();
Map<Class<?>, AtomicInteger> writeLockCounterMap = new HashMap<>();
for ( LockReleaseCallback lock : locks )
{
Map<Class<?>, AtomicInteger> map =
lock.lockType == LockType.READ? readLockCounterMap : writeLockCounterMap;
AtomicInteger counter = map.get( lock.lock.getClass() );
if ( counter == null )
{
counter = new AtomicInteger();
map.put( lock.lock.getClass(), counter );
}
counter.incrementAndGet();
}
StringBuilder sb = new StringBuilder( "[" );
for ( Map.Entry<Class<?>, AtomicInteger> readEntry : readLockCounterMap.entrySet() )
{
sb.append( "READ " ).append( readEntry.getKey().getSimpleName() ).append( "s: " );
sb.append( readEntry.getValue().get() ).append( ", " );
}
for ( Map.Entry<Class<?>, AtomicInteger> writeEntry : writeLockCounterMap.entrySet() )
{
sb.append( "WRITE " ).append( writeEntry.getKey().getSimpleName() ).append( "s: " );
sb.append( writeEntry.getValue().get() ).append( ", " );
}
if ( sb.length() > 1 )
{
sb.setLength( sb.length() - 2 ); // Cut off the last ", "
}
return sb.append( ']' ).toString();
}
private final class LockReleaseCallback
{
private final LockType lockType;
private final Object lock;
public LockReleaseCallback( LockType lockType, Object lock )
{
this.lockType = lockType;
this.lock = lock;
}
public void release()
{
lockType.release( lockManager, lock, tx );
}
@Override
public String toString()
{
return String.format( "%s_LOCK(%s)", lockType.name(), lock );
}
}
private abstract class EntityLock implements PropertyContainer
{
private final long id;
public EntityLock( long id )
{
this.id = id;
}
@Override
public String toString()
{
return String.format( "%s[id=%d]", getClass().getSimpleName(), id );
}
public long getId()
{
return id;
}
public void delete()
{
throw unsupportedOperation();
}
@Override
public GraphDatabaseService getGraphDatabase()
{
throw unsupportedOperation();
}
@Override
public boolean hasProperty( String key )
{
throw unsupportedOperation();
}
@Override
public Object getProperty( String key )
{
throw unsupportedOperation();
}
@Override
public Object getProperty( String key, Object defaultValue )
{
throw unsupportedOperation();
}
@Override
public void setProperty( String key, Object value )
{
throw unsupportedOperation();
}
@Override
public Object removeProperty( String key )
{
throw unsupportedOperation();
}
@Override
public Iterable<String> getPropertyKeys()
{
throw unsupportedOperation();
}
@Override
public int hashCode()
{
return (int) ((id >>> 32) ^ id);
}
protected UnsupportedOperationException unsupportedOperation()
{
return new UnsupportedOperationException( getClass().getSimpleName() +
" does not support this operation." );
}
}
// Have them be releasable also since they are internal and will save the
// amount of garbage produced
@SuppressWarnings("deprecation")
private class NodeLock extends EntityLock implements Node
{
public NodeLock( long id )
{
super( id );
}
@Override
public Iterable<Relationship> getRelationships()
{
throw unsupportedOperation();
}
@Override
public boolean hasRelationship()
{
throw unsupportedOperation();
}
@Override
public Iterable<Relationship> getRelationships( RelationshipType... types )
{
throw unsupportedOperation();
}
@Override
public Iterable<Relationship> getRelationships( Direction direction, RelationshipType... types )
{
throw unsupportedOperation();
}
@Override
public boolean hasRelationship( RelationshipType... types )
{
throw unsupportedOperation();
}
@Override
public boolean hasRelationship( Direction direction, RelationshipType... types )
{
throw unsupportedOperation();
}
@Override
public Iterable<Relationship> getRelationships( Direction dir )
{
throw unsupportedOperation();
}
@Override
public boolean hasRelationship( Direction dir )
{
throw unsupportedOperation();
}
@Override
public Iterable<Relationship> getRelationships( RelationshipType type, Direction dir )
{
throw unsupportedOperation();
}
@Override
public boolean hasRelationship( RelationshipType type, Direction dir )
{
throw unsupportedOperation();
}
@Override
public Relationship getSingleRelationship( RelationshipType type, Direction dir )
{
throw unsupportedOperation();
}
@Override
public Relationship createRelationshipTo( Node otherNode, RelationshipType type )
{
throw unsupportedOperation();
}
@Override
public Traverser traverse( Traverser.Order traversalOrder, StopEvaluator stopEvaluator, ReturnableEvaluator
returnableEvaluator, RelationshipType relationshipType, Direction direction )
{
throw unsupportedOperation();
}
@Override
public Traverser traverse( Traverser.Order traversalOrder, StopEvaluator stopEvaluator, ReturnableEvaluator
returnableEvaluator, RelationshipType firstRelationshipType, Direction firstDirection,
RelationshipType secondRelationshipType, Direction secondDirection )
{
throw unsupportedOperation();
}
@Override
public Traverser traverse( Traverser.Order traversalOrder, StopEvaluator stopEvaluator, ReturnableEvaluator
returnableEvaluator, Object... relationshipTypesAndDirections )
{
throw unsupportedOperation();
}
@Override
public void addLabel( Label label )
{
throw unsupportedOperation();
}
@Override
public void removeLabel( Label label )
{
throw unsupportedOperation();
}
@Override
public boolean hasLabel( Label label )
{
throw unsupportedOperation();
}
@Override
public ResourceIterable<Label> getLabels()
{
throw unsupportedOperation();
}
@Override
public boolean equals( Object o )
{
return o instanceof Node && this.getId() == ((Node) o).getId();
}
// NOTE hashCode is implemented in super
}
private class RelationshipLock extends EntityLock implements Relationship
{
public RelationshipLock( long id )
{
super( id );
}
@Override
public Node getStartNode()
{
throw unsupportedOperation();
}
@Override
public Node getEndNode()
{
throw unsupportedOperation();
}
@Override
public Node getOtherNode( Node node )
{
throw unsupportedOperation();
}
@Override
public Node[] getNodes()
{
throw unsupportedOperation();
}
@Override
public RelationshipType getType()
{
throw unsupportedOperation();
}
@Override
public boolean isType( RelationshipType type )
{
throw unsupportedOperation();
}
@Override
public boolean equals( Object o )
{
return o instanceof Relationship && this.getId() == ((Relationship) o).getId();
}
}
private class GraphLock extends EntityLock implements GraphProperties
{
public GraphLock()
{
super( -1 );
}
@Override
public NodeManager getNodeManager()
{
return nodeManager;
}
@Override
public boolean equals( Object o )
{
return o instanceof GraphProperties
&& this.getNodeManager().equals( ((GraphProperties) o).getNodeManager() );
}
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_LockHolderImpl.java
|
4,980
|
public class LegacyPropertyTrackers
{
private final List<PropertyTracker<Node>> nodeTrackers;
private final List<PropertyTracker<Relationship>> relationshipTrackers;
private final PropertyKeyTokenHolder propertyKeyTokenHolder;
private final EntityFactory entityFactory;
public LegacyPropertyTrackers( PropertyKeyTokenHolder propertyKeyTokenHolder,
List<PropertyTracker<Node>> nodeTrackers,
List<PropertyTracker<Relationship>> relationshipTrackers,
EntityFactory entityFactory )
{
this.propertyKeyTokenHolder = propertyKeyTokenHolder;
this.nodeTrackers = nodeTrackers;
this.relationshipTrackers = relationshipTrackers;
this.entityFactory = entityFactory;
}
public void nodeAddStoreProperty( long nodeId, DefinedProperty property )
{
if ( !nodeTrackers.isEmpty() )
{
Node node = entityFactory.newNodeProxyById( nodeId );
for ( PropertyTracker<Node> tracker : nodeTrackers )
{
tracker.propertyAdded( node, propertyKeyName( property ), property.value() );
}
}
}
public void nodeChangeStoreProperty( long nodeId, DefinedProperty previousProperty, DefinedProperty property )
{
if ( !nodeTrackers.isEmpty() )
{
Node node = entityFactory.newNodeProxyById( nodeId );
for ( PropertyTracker<Node> tracker : nodeTrackers )
{
tracker.propertyChanged( node, propertyKeyName( property ), previousProperty.value( null ),
property.value( null ) );
}
}
}
public void relationshipAddStoreProperty( long relationshipId, DefinedProperty property )
{
if ( !relationshipTrackers.isEmpty() )
{
Relationship relationship = entityFactory.newRelationshipProxyById( relationshipId );
for ( PropertyTracker<Relationship> tracker : relationshipTrackers )
{
tracker.propertyAdded( relationship, propertyKeyName( property ), property.value() );
}
}
}
public void relationshipChangeStoreProperty( long relationshipId, DefinedProperty previousProperty, DefinedProperty property )
{
if ( !relationshipTrackers.isEmpty() )
{
Relationship relationship = entityFactory.newRelationshipProxyById( relationshipId );
for ( PropertyTracker<Relationship> tracker : relationshipTrackers )
{
tracker.propertyChanged( relationship, propertyKeyName( property ),
previousProperty.value( null ), property.value( null ) );
}
}
}
public void nodeRemoveStoreProperty( long nodeId, DefinedProperty property )
{
if ( !nodeTrackers.isEmpty() )
{
Node node = entityFactory.newNodeProxyById( nodeId );
for ( PropertyTracker<Node> tracker : nodeTrackers )
{
tracker.propertyRemoved( node, propertyKeyName( property ), property.value() );
}
}
}
public void relationshipRemoveStoreProperty( long relationshipId, DefinedProperty property )
{
if ( !relationshipTrackers.isEmpty() )
{
Relationship relationship = entityFactory.newRelationshipProxyById( relationshipId );
for ( PropertyTracker<Relationship> tracker : relationshipTrackers )
{
tracker.propertyRemoved( relationship, propertyKeyName( property ), property.value() );
}
}
}
private String propertyKeyName( Property property )
{
try
{
return propertyKeyTokenHolder.getTokenById( (int) property.propertyKeyId() ).name();
}
catch ( TokenNotFoundException e )
{
throw new IllegalStateException( "Property key " + property.propertyKeyId() + " should exist" );
}
}
public void nodeDelete( long nodeId )
{
if ( !nodeTrackers.isEmpty() )
{
Node node = entityFactory.newNodeProxyById( nodeId );
Iterable<String> propertyKeys = node.getPropertyKeys();
for ( String key : propertyKeys )
{
Object value = node.getProperty( key );
for ( PropertyTracker<Node> tracker : nodeTrackers )
{
tracker.propertyRemoved( node, key, value );
}
}
}
}
public void relationshipDelete( long relationshipId )
{
if ( !relationshipTrackers.isEmpty() )
{
Relationship relationship = entityFactory.newRelationshipProxyById( relationshipId );
Iterable<String> propertyKeys = relationship.getPropertyKeys();
for ( String key : propertyKeys )
{
Object value = relationship.getProperty( key );
for ( PropertyTracker<Relationship> tracker : relationshipTrackers )
{
tracker.propertyRemoved( relationship, key, value );
}
}
}
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_LegacyPropertyTrackers.java
|
4,981
|
public class LabelRecoveryTest
{
/**
* Reading a node command might leave a node record which referred to
* labels in one or more dynamic records as marked as heavy even if that
* node already had references to dynamic records, changed in a transaction,
* but had no labels on that node changed within that same transaction.
* Now defensively only marks as heavy if there were one or more dynamic
* records provided when providing the record object with the label field
* value. This would give the opportuniy to load the dynamic records the
* next time that record would be ensured heavy.
*/
@Test
public void shouldRecoverNodeWithDynamicLabelRecords() throws Exception
{
// GIVEN
database = new TestGraphDatabaseFactory().setFileSystem( fs ).newImpermanentDatabase();
Node node;
Label[] labels = new Label[] { label( "a" ),
label( "b" ),
label( "c" ),
label( "d" ),
label( "e" ),
label( "f" ),
label( "g" ),
label( "h" ),
label( "i" ),
label( "j" ),
label( "k" ) };
try ( Transaction tx = database.beginTx() )
{
node = database.createNode( labels );
tx.success();
}
// WHEN
try ( Transaction tx = database.beginTx() )
{
node.setProperty( "prop", "value" );
tx.success();
}
EphemeralFileSystemAbstraction snapshot = fs.snapshot();
database.shutdown();
database = new TestGraphDatabaseFactory().setFileSystem( snapshot ).newImpermanentDatabase();
// THEN
try ( Transaction tx = database.beginTx() )
{
node = database.getNodeById( node.getId() );
for ( Label label : labels )
{
assertTrue( node.hasLabel( label ) );
}
}
}
@After
public void tearDown()
{
if ( database != null )
{
database.shutdown();
}
fs.shutdown();
}
public final EphemeralFileSystemAbstraction fs = new EphemeralFileSystemAbstraction();
private GraphDatabaseService database;
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_api_LabelRecoveryTest.java
|
4,982
|
SCHEMA
{
@Override
TransactionType upgradeToDataTransaction() throws InvalidTransactionTypeKernelException
{
throw new InvalidTransactionTypeKernelException(
"Cannot perform data updates in a transaction that has performed schema updates." );
}
};
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_api_KernelTransactionImplementation.java
|
4,983
|
{
@Override
public Iterable<Slave> prioritize( Iterable<Slave> slaves )
{
return slaves;
}
};
| false
|
enterprise_ha_src_main_java_org_neo4j_kernel_ha_com_master_SlavePriorities.java
|
4,984
|
{
@Override
public Response<Void> call( Slave master, RequestContext context, ChannelBuffer input,
ChannelBuffer target )
{
return master.pullUpdates( readString( input ), input.readLong() );
}
}, VOID_SERIALIZER );
| false
|
enterprise_ha_src_main_java_org_neo4j_kernel_ha_com_master_SlaveClient.java
|
4,985
|
ACQUIRE_RELATIONSHIP_WRITE_LOCK( new AquireLockCall()
{
@Override
public Response<LockResult> lock( Master master, RequestContext context, long... ids )
{
return master.acquireRelationshipWriteLock( context, ids );
}
}, LOCK_SERIALIZER )
{
@Override
public boolean isLock()
{
return true;
}
},
| false
|
enterprise_ha_src_main_java_org_neo4j_kernel_ha_HaRequestType201.java
|
4,986
|
private static class FakeDataSource extends XaDataSource
{
private static final byte[] BRANCH = new byte[]{0, 1, 2};
private static final String NAME = "fake";
private final File dir;
FakeDataSource()
{
super( BRANCH, NAME );
this.dir = TargetDirectory.forTest( getClass() ).makeGraphDbDir();
}
@Override
public XaConnection getXaConnection()
{
throw new UnsupportedOperationException();
}
@Override
public LogExtractor getLogExtractor( long startTxId, long endTxIdHint ) throws IOException
{
return LogExtractor.from( FS, dir, new Monitors().newMonitor( ByteCounterMonitor.class ), startTxId );
}
@Override
public void init() throws Throwable
{
}
@Override
public void start() throws Throwable
{
}
@Override
public void stop() throws Throwable
{
}
@Override
public void shutdown() throws Throwable
{
}
}
| false
|
enterprise_ha_src_test_java_org_neo4j_kernel_ha_TestMasterCommittingAtSlave.java
|
4,987
|
public class TestMasterCommittingAtSlave
{
private Iterable<Slave> slaves;
private XaDataSource dataSource;
private FakeStringLogger log;
@Test
public void commitSuccessfullyToTheFirstOne() throws Exception
{
MasterTxIdGenerator generator = newGenerator( 3, 1, givenOrder() );
generator.committed( dataSource, 0, 2, null );
assertCalls( (FakeSlave) slaves.iterator().next(), 2l );
assertNoFailureLogs();
}
@Test
public void commitACoupleOfTransactionsSuccessfully() throws Exception
{
MasterTxIdGenerator generator = newGenerator( 3, 1, givenOrder() );
generator.committed( dataSource, 0, 2, null );
generator.committed( dataSource, 0, 3, null );
generator.committed( dataSource, 0, 4, null );
assertCalls( (FakeSlave) slaves.iterator().next(), 2, 3, 4 );
assertNoFailureLogs();
}
@Test
public void commitFailureAtFirstOneShouldMoveOnToNext() throws Exception
{
MasterTxIdGenerator generator = newGenerator( 3, 1, givenOrder(), true );
generator.committed( dataSource, 0, 2, null );
Iterator<Slave> slaveIt = slaves.iterator();
assertCalls( (FakeSlave) slaveIt.next() );
assertCalls( (FakeSlave) slaveIt.next(), 2 );
assertNoFailureLogs();
}
@Test
public void commitSuccessfullyAtThreeSlaves() throws Exception
{
MasterTxIdGenerator generator = newGenerator( 5, 3, givenOrder() );
generator.committed( dataSource, 0, 2, null );
generator.committed( dataSource, 0, 3, 1 );
generator.committed( dataSource, 0, 4, 3 );
Iterator<Slave> slaveIt = slaves.iterator();
assertCalls( (FakeSlave) slaveIt.next(), 2, 3, 4 );
assertCalls( (FakeSlave) slaveIt.next(), 2, 4 );
assertCalls( (FakeSlave) slaveIt.next(), 2, 3 );
assertCalls( (FakeSlave) slaveIt.next() );
assertCalls( (FakeSlave) slaveIt.next() );
assertNoFailureLogs();
}
@Test
public void commitSuccessfullyOnSomeOfThreeSlaves() throws Exception
{
MasterTxIdGenerator generator = newGenerator( 5, 3, givenOrder(), false, true, true );
generator.committed( dataSource, 0, 2, null );
Iterator<Slave> slaveIt = slaves.iterator();
assertCalls( (FakeSlave) slaveIt.next(), 2 );
slaveIt.next();
slaveIt.next();
assertCalls( (FakeSlave) slaveIt.next(), 2 );
assertCalls( (FakeSlave) slaveIt.next(), 2 );
assertNoFailureLogs();
}
@Test
public void roundRobinSingleSlave() throws Exception
{
MasterTxIdGenerator generator = newGenerator( 3, 1, roundRobin() );
for ( long tx = 2; tx <= 6; tx++ )
{
generator.committed( dataSource, 0, tx, null );
}
Iterator<Slave> slaveIt = slaves.iterator();
assertCalls( (FakeSlave) slaveIt.next(), 2, 5 );
assertCalls( (FakeSlave) slaveIt.next(), 3, 6 );
assertCalls( (FakeSlave) slaveIt.next(), 4 );
assertNoFailureLogs();
}
@Test
public void roundRobinSomeFailing() throws Exception
{
MasterTxIdGenerator generator = newGenerator( 4, 2, roundRobin(), false, true );
for ( long tx = 2; tx <= 6; tx++ )
{
generator.committed( dataSource, 0, tx, null );
}
/* SLAVE | TX
* 0 | 2 5 6
* F 1 |
* 2 | 2 3 4 6
* 3 | 3 4 5
*/
Iterator<Slave> slaveIt = slaves.iterator();
assertCalls( (FakeSlave) slaveIt.next(), 2, 5, 6 );
slaveIt.next();
assertCalls( (FakeSlave) slaveIt.next(), 2, 3, 4, 6 );
assertCalls( (FakeSlave) slaveIt.next(), 3, 4, 5 );
assertNoFailureLogs();
}
@Test
public void notEnoughSlavesSuccessful() throws Exception
{
MasterTxIdGenerator generator = newGenerator( 3, 2, givenOrder(), true, true );
generator.committed( dataSource, 0, 2, null );
Iterator<Slave> slaveIt = slaves.iterator();
slaveIt.next();
slaveIt.next();
assertCalls( (FakeSlave) slaveIt.next(), 2 );
assertFailureLogs();
}
@Test
public void testFixedPriorityStrategy()
{
int[] serverIds = new int[]{55, 101, 66};
SlavePriority fixed = SlavePriorities.fixed();
ArrayList<Slave> slaves = new ArrayList<Slave>( 3 );
slaves.add( new FakeSlave( false, serverIds[0] ) );
slaves.add( new FakeSlave( false, serverIds[1] ) );
slaves.add( new FakeSlave( false, serverIds[2] ) );
Iterator<Slave> sortedSlaves = fixed.prioritize( slaves ).iterator();
assertEquals( serverIds[1], sortedSlaves.next().getServerId() );
assertEquals( serverIds[2], sortedSlaves.next().getServerId() );
assertEquals( serverIds[0], sortedSlaves.next().getServerId() );
assertTrue( !sortedSlaves.hasNext() );
}
private void assertNoFailureLogs()
{
assertFalse( "Errors:" + log.errors.toString(), log.unexpectedExceptionLogged );
}
private void assertFailureLogs()
{
assertTrue( log.unexpectedExceptionLogged );
}
private void assertCalls( FakeSlave slave, long... txs )
{
for ( long tx : txs )
{
Long slaveTx = slave.popCalledTx();
assertNotNull( slaveTx );
assertEquals( (Long) tx, slaveTx );
}
assertFalse( slave.moreTxs() );
}
private MasterTxIdGenerator newGenerator( int slaveCount, int replication, SlavePriority slavePriority,
boolean... failingSlaves ) throws Exception
{
slaves = instantiateSlaves( slaveCount, failingSlaves );
dataSource = new FakeDataSource();
log = new FakeStringLogger();
Config config = new Config( MapUtil.stringMap(
HaSettings.tx_push_factor.name(), "" + replication ) );
Neo4jJobScheduler scheduler = new Neo4jJobScheduler( new TestLogger() );
MasterTxIdGenerator result = new MasterTxIdGenerator( MasterTxIdGenerator.from( config, slavePriority ),
log, new Slaves()
{
@Override
public Iterable<Slave> getSlaves()
{
return slaves;
}
}, new CommitPusher( scheduler ) );
// Life
try
{
scheduler.init();
scheduler.start();
result.init();
result.start();
}
catch ( Throwable e )
{
throw Exceptions.launderedException( e );
}
return result;
}
private Iterable<Slave> instantiateSlaves( int count, boolean[] failingSlaves )
{
List<Slave> slaves = new ArrayList<Slave>();
for ( int i = 0; i < count; i++ )
{
slaves.add( new FakeSlave( i < failingSlaves.length && failingSlaves[i], i ) );
}
return slaves;
}
private static final FileSystemAbstraction FS = new DefaultFileSystemAbstraction();
private static class FakeDataSource extends XaDataSource
{
private static final byte[] BRANCH = new byte[]{0, 1, 2};
private static final String NAME = "fake";
private final File dir;
FakeDataSource()
{
super( BRANCH, NAME );
this.dir = TargetDirectory.forTest( getClass() ).makeGraphDbDir();
}
@Override
public XaConnection getXaConnection()
{
throw new UnsupportedOperationException();
}
@Override
public LogExtractor getLogExtractor( long startTxId, long endTxIdHint ) throws IOException
{
return LogExtractor.from( FS, dir, new Monitors().newMonitor( ByteCounterMonitor.class ), startTxId );
}
@Override
public void init() throws Throwable
{
}
@Override
public void start() throws Throwable
{
}
@Override
public void stop() throws Throwable
{
}
@Override
public void shutdown() throws Throwable
{
}
}
private static class FakeSlave implements Slave
{
private volatile Queue<Long> calledWithTxId = new LinkedList<Long>();
private final boolean failing;
private final int serverId;
FakeSlave( boolean failing, int serverId )
{
this.failing = failing;
this.serverId = serverId;
}
@Override
public Response<Void> pullUpdates( String resource, long txId )
{
if ( failing )
{
throw new ComException( "Told to fail" );
}
calledWithTxId.add( txId );
return new Response<Void>( null, new StoreId(), TransactionStream.EMPTY, ResourceReleaser.NO_OP );
}
Long popCalledTx()
{
return calledWithTxId.poll();
}
boolean moreTxs()
{
return !calledWithTxId.isEmpty();
}
@Override
public int getServerId()
{
return serverId;
}
@Override
public String toString()
{
return "FakeSlave[" + serverId + "]";
}
}
private static class FakeStringLogger extends StringLogger
{
private volatile boolean unexpectedExceptionLogged;
private final StringBuilder errors = new StringBuilder();
@Override
public void logLongMessage( String msg, Visitor<LineLogger, RuntimeException> source, boolean flush )
{
addError( msg );
}
private void addError( String msg )
{
if ( !msg.contains( "communication" ) )
{
unexpectedExceptionLogged = true;
}
errors.append( errors.length() > 0 ? "," : "" ).append( msg );
}
@Override
public void logMessage( String msg, boolean flush )
{
addError( msg );
}
@Override
public void logMessage( String msg, LogMarker marker )
{
addError( msg );
}
@Override
public void logMessage( String msg, Throwable cause, boolean flush )
{
addError( msg );
}
@Override
public void addRotationListener( Runnable listener )
{
}
@Override
public void flush()
{
}
@Override
public void close()
{
}
@Override
protected void logLine( String line )
{
addError( line );
}
}
}
| false
|
enterprise_ha_src_test_java_org_neo4j_kernel_ha_TestMasterCommittingAtSlave.java
|
4,988
|
public class TestBasicHaOperations
{
@Rule
public LoggerRule logger = new LoggerRule();
public TargetDirectory dir = TargetDirectory.forTest( getClass() );
private ClusterManager clusterManager;
@After
public void after() throws Throwable
{
if ( clusterManager != null )
{
clusterManager.stop();
clusterManager = null;
}
}
@Test
public void testBasicFailover() throws Throwable
{
// given
clusterManager = new ClusterManager( clusterOfSize( 3 ), dir.cleanDirectory( "failover" ), stringMap() );
clusterManager.start();
ClusterManager.ManagedCluster cluster = clusterManager.getDefaultCluster();
cluster.await( ClusterManager.allSeesAllAsAvailable() );
HighlyAvailableGraphDatabase master = cluster.getMaster();
HighlyAvailableGraphDatabase slave1 = cluster.getAnySlave();
HighlyAvailableGraphDatabase slave2 = cluster.getAnySlave( slave1 );
// When
long start = System.nanoTime();
cluster.shutdown( master );
logger.getLogger().warn( "Shut down master" );
cluster.await( ClusterManager.masterAvailable() );
long end = System.nanoTime();
logger.getLogger().warn( "Failover took:" + (end - start) / 1000000 + "ms" );
// Then
boolean slave1Master = slave1.isMaster();
boolean slave2Master = slave2.isMaster();
if ( slave1Master )
{
assertFalse( slave2Master );
}
else
{
assertTrue( slave2Master );
}
}
@Test
public void testBasicPropagationFromSlaveToMaster() throws Throwable
{
// given
clusterManager = new ClusterManager( clusterOfSize( 3 ), dir.cleanDirectory( "propagation" ),
stringMap( tx_push_factor.name(), "2" ) );
clusterManager.start();
ClusterManager.ManagedCluster cluster = clusterManager.getDefaultCluster();
cluster.await( ClusterManager.allSeesAllAsAvailable() );
long nodeId = 0;
HighlyAvailableGraphDatabase slave = cluster.getAnySlave();
try ( Transaction tx = slave.beginTx() )
{
Node node = slave.createNode();
node.setProperty( "Hello", "World" );
nodeId = node.getId();
tx.success();
}
HighlyAvailableGraphDatabase master = cluster.getMaster();
try ( Transaction tx = master.beginTx() )
{
String value = master.getNodeById( nodeId ).getProperty( "Hello" ).toString();
logger.getLogger().info( "Hello=" + value );
assertEquals( "World", value );
tx.success();
}
}
@Test
public void testBasicPropagationFromMasterToSlave() throws Throwable
{
// given
clusterManager = new ClusterManager( clusterOfSize( 3 ), dir.cleanDirectory( "propagation" ),
stringMap( tx_push_factor.name(), "2" ) );
clusterManager.start();
ClusterManager.ManagedCluster cluster = clusterManager.getDefaultCluster();
cluster.await( ClusterManager.allSeesAllAsAvailable() );
long nodeId = 0;
HighlyAvailableGraphDatabase master = cluster.getMaster();
try ( Transaction tx = master.beginTx() )
{
Node node = master.createNode();
node.setProperty( "Hello", "World" );
nodeId = node.getId();
tx.success();
}
// No need to wait, the push factor is 2
HighlyAvailableGraphDatabase slave1 = cluster.getAnySlave();
String value;
try ( Transaction tx = slave1.beginTx() )
{
value = slave1.getNodeById( nodeId ).getProperty( "Hello" ).toString();
logger.getLogger().info( "Hello=" + value );
assertEquals( "World", value );
tx.success();
}
HighlyAvailableGraphDatabase slave2 = cluster.getAnySlave(slave1);
try ( Transaction tx = slave2.beginTx() )
{
value = slave2.getNodeById( nodeId ).getProperty( "Hello" ).toString();
logger.getLogger().info( "Hello=" + value );
assertEquals( "World", value );
tx.success();
}
}
}
| false
|
enterprise_ha_src_test_java_org_neo4j_kernel_ha_TestBasicHaOperations.java
|
4,989
|
public class StoreUnableToParticipateInClusterException extends IllegalStateException
{
public StoreUnableToParticipateInClusterException()
{
super();
}
public StoreUnableToParticipateInClusterException( String message, Throwable cause )
{
super( message, cause );
}
public StoreUnableToParticipateInClusterException( String message )
{
super( message );
}
public StoreUnableToParticipateInClusterException( Throwable cause )
{
super( cause );
}
}
| false
|
enterprise_ha_src_main_java_org_neo4j_kernel_ha_StoreUnableToParticipateInClusterException.java
|
4,990
|
public class StoreOutOfDateException extends StoreUnableToParticipateInClusterException
{
public StoreOutOfDateException()
{
super();
}
public StoreOutOfDateException( String message, Throwable cause )
{
super( message, cause );
}
public StoreOutOfDateException( String message )
{
super( message );
}
public StoreOutOfDateException( Throwable cause )
{
super( cause );
}
}
| false
|
enterprise_ha_src_main_java_org_neo4j_kernel_ha_StoreOutOfDateException.java
|
4,991
|
public class SlaveRelationshipTypeCreator implements TokenCreator
{
private final Master master;
private final RequestContextFactory requestContextFactory;
private final HaXaDataSourceManager xaDsm;
public SlaveRelationshipTypeCreator( Master master, RequestContextFactory requestContextFactory,
HaXaDataSourceManager xaDsm )
{
this.master = master;
this.requestContextFactory = requestContextFactory;
this.xaDsm = xaDsm;
}
@Override
public int getOrCreate( AbstractTransactionManager txManager, EntityIdGenerator idGenerator,
PersistenceManager persistence, String name )
{
Response<Integer> response = master.createRelationshipType( requestContextFactory.newRequestContext(), name );
xaDsm.applyTransactions( response );
return response.response().intValue();
}
}
| false
|
enterprise_ha_src_main_java_org_neo4j_kernel_ha_SlaveRelationshipTypeCreator.java
|
4,992
|
public class SlavePropertyTokenCreator implements TokenCreator
{
private final Master master;
private final RequestContextFactory requestContextFactory;
private final HaXaDataSourceManager xaDsm;
public SlavePropertyTokenCreator( Master master, RequestContextFactory requestContextFactory,
HaXaDataSourceManager xaDsm )
{
this.master = master;
this.requestContextFactory = requestContextFactory;
this.xaDsm = xaDsm;
}
@Override
public int getOrCreate( AbstractTransactionManager txManager, EntityIdGenerator idGenerator,
PersistenceManager persistence, String name )
{
Response<Integer> response = master.createPropertyKey( requestContextFactory.newRequestContext(), name );
xaDsm.applyTransactions( response );
return response.response().intValue();
}
}
| false
|
enterprise_ha_src_main_java_org_neo4j_kernel_ha_SlavePropertyTokenCreator.java
|
4,993
|
public class SlaveLabelTokenCreator implements TokenCreator
{
private final Master master;
private final RequestContextFactory requestContextFactory;
private final HaXaDataSourceManager xaDsm;
public SlaveLabelTokenCreator( Master master, RequestContextFactory requestContextFactory,
HaXaDataSourceManager xaDsm )
{
this.master = master;
this.requestContextFactory = requestContextFactory;
this.xaDsm = xaDsm;
}
@Override
public int getOrCreate( AbstractTransactionManager txManager, EntityIdGenerator idGenerator,
PersistenceManager persistence, String name )
{
Response<Integer> response = master.createLabel( requestContextFactory.newRequestContext(), name );
xaDsm.applyTransactions( response );
return response.response().intValue();
}
}
| false
|
enterprise_ha_src_main_java_org_neo4j_kernel_ha_SlaveLabelTokenCreator.java
|
4,994
|
public class RelationshipTypeCreatorModeSwitcher extends AbstractModeSwitcher<TokenCreator>
{
private final HaXaDataSourceManager xaDsm;
private final DelegateInvocationHandler<Master> master;
private final RequestContextFactory requestContextFactory;
private final Logging logging;
public RelationshipTypeCreatorModeSwitcher( HighAvailabilityMemberStateMachine stateMachine,
DelegateInvocationHandler<TokenCreator> delegate,
HaXaDataSourceManager xaDsm,
DelegateInvocationHandler<Master> master,
RequestContextFactory requestContextFactory, Logging logging
)
{
super( stateMachine, delegate );
this.xaDsm = xaDsm;
this.master = master;
this.requestContextFactory = requestContextFactory;
this.logging = logging;
}
@Override
protected TokenCreator getMasterImpl()
{
return new DefaultRelationshipTypeCreator( logging );
}
@Override
protected TokenCreator getSlaveImpl( URI serverHaUri )
{
return new SlaveRelationshipTypeCreator( master.cement(), requestContextFactory, xaDsm );
}
}
| false
|
enterprise_ha_src_main_java_org_neo4j_kernel_ha_RelationshipTypeCreatorModeSwitcher.java
|
4,995
|
public class PropertyKeyCreatorModeSwitcher extends AbstractModeSwitcher<TokenCreator>
{
private final HaXaDataSourceManager xaDsm;
private final DelegateInvocationHandler<Master> master;
private final RequestContextFactory requestContextFactory;
private final Logging logging;
public PropertyKeyCreatorModeSwitcher( HighAvailabilityMemberStateMachine stateMachine,
DelegateInvocationHandler<TokenCreator> delegate,
HaXaDataSourceManager xaDsm,
DelegateInvocationHandler<Master> master,
RequestContextFactory requestContextFactory, Logging logging
)
{
super( stateMachine, delegate );
this.xaDsm = xaDsm;
this.master = master;
this.requestContextFactory = requestContextFactory;
this.logging = logging;
}
@Override
protected TokenCreator getMasterImpl()
{
return new DefaultPropertyTokenCreator( logging );
}
@Override
protected TokenCreator getSlaveImpl( URI serverHaUri )
{
return new SlavePropertyTokenCreator( master.cement(), requestContextFactory, xaDsm );
}
}
| false
|
enterprise_ha_src_main_java_org_neo4j_kernel_ha_PropertyKeyCreatorModeSwitcher.java
|
4,996
|
public class OnDiskLastTxIdGetterTest
{
@Test
public void testGetLastTxIdNoFilePresent() throws Exception
{
OnDiskLastTxIdGetter getter = new OnDiskLastTxIdGetter(
TargetDirectory.forTest( getClass() ).cleanDirectory( "no-store" ) );
assertEquals( -1, getter.getLastTxId() );
}
}
| false
|
enterprise_ha_src_test_java_org_neo4j_kernel_ha_OnDiskLastTxIdGetterTest.java
|
4,997
|
public class NeoStoreUtil
{
private final long creationTime;
private final long randomId;
private final long txId;
private final long logVersion;
private final long storeVersion;
private final long firstGraphProp;
private File file;
public static void main( String[] args )
{
if ( args.length < 1 )
{
System.err.println( "Supply one argument which is the store directory of a neo4j graph database" );
System.exit( 1 );
}
System.out.println( new NeoStoreUtil( new File( args[0] ) ) );
}
public NeoStoreUtil( File storeDir )
{
this( storeDir, new DefaultFileSystemAbstraction() );
}
public NeoStoreUtil( File storeDir, FileSystemAbstraction fs )
{
StoreChannel channel = null;
try
{
channel = fs.open( neoStoreFile( storeDir ), "r" );
int recordsToRead = 6;
ByteBuffer buf = ByteBuffer.allocate( recordsToRead*NeoStore.RECORD_SIZE );
if ( channel.read( buf ) != recordsToRead*NeoStore.RECORD_SIZE )
{
throw new RuntimeException( "Unable to read neo store header information" );
}
buf.flip();
creationTime = nextRecord( buf );
randomId = nextRecord( buf );
logVersion = nextRecord( buf );
txId = nextRecord( buf );
storeVersion = nextRecord( buf );
firstGraphProp = nextRecord( buf );
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
finally
{
if ( channel != null )
{
try
{
channel.close();
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
}
}
}
private long nextRecord( ByteBuffer buf )
{
buf.get(); // in use byte
return buf.getLong();
}
public long getCreationTime()
{
return creationTime;
}
public long getStoreId()
{
return randomId;
}
public long getLastCommittedTx()
{
return txId;
}
public long getLogVersion()
{
return logVersion;
}
public long getStoreVersion()
{
return storeVersion;
}
public StoreId asStoreId()
{
return new StoreId( creationTime, randomId, storeVersion );
}
@Override
public String toString()
{
return format( "Neostore contents of " + this.file + ":%n" +
"0: creation time: %s%n" +
"1: random id: %s%n" +
"2: log version: %s%n" +
"3: tx id: %s%n" +
"4: store version: %s%n" +
"5: first graph prop: %s%n" +
" => store id: %s",
creationTime,
randomId,
logVersion,
txId,
storeVersion,
firstGraphProp,
new StoreId( creationTime, randomId, storeVersion ) );
}
public static boolean storeExists( File storeDir )
{
return storeExists( storeDir, new DefaultFileSystemAbstraction() );
}
public static boolean storeExists( File storeDir, FileSystemAbstraction fs )
{
return fs.fileExists( neoStoreFile( storeDir ) );
}
private static File neoStoreFile( File storeDir )
{
return new File( storeDir, NeoStore.DEFAULT_NAME );
}
}
| false
|
enterprise_ha_src_main_java_org_neo4j_kernel_ha_NeoStoreUtil.java
|
4,998
|
public class MasterEpochTest
{
@Test
public void shouldFailSubsequentRequestsAfterAllocateIdsAfterMasterSwitch() throws Throwable
{
// GIVEN
SPI spi = mock( SPI.class );
IdAllocation servedIdAllocation = idAllocation( 0, 999 );
when( spi.allocateIds( any( IdType.class ) ) ).thenReturn( servedIdAllocation );
when( spi.getMasterIdForCommittedTx( anyLong() ) ).thenReturn( Pair.of( 1, 10L ) );
StoreId storeId = new StoreId();
MasterImpl master = new MasterImpl( spi,
mock( MasterImpl.Monitor.class ), new TestLogging(),
new Config( stringMap( ClusterSettings.server_id.name(), "1" ) ) );
HandshakeResult handshake = master.handshake( 1, storeId ).response();
master.start();
// WHEN/THEN
IdAllocation idAllocation = master.allocateIds( context( handshake.epoch() ), IdType.NODE ).response();
assertEquals( servedIdAllocation.getHighestIdInUse(), idAllocation.getHighestIdInUse() );
try
{
master.allocateIds( context( handshake.epoch()+1 ), IdType.NODE );
fail( "Should fail with invalid epoch" );
}
catch ( InvalidEpochException e )
{ // Good
}
}
private IdAllocation idAllocation( long from, int length )
{
return new IdAllocation( new IdRange( new long[0], from, length ), from+length, 0 );
}
private RequestContext context( long epoch )
{
return new RequestContext( epoch, 0, 0, new Tx[0], 0, 0 );
}
}
| false
|
enterprise_ha_src_test_java_org_neo4j_kernel_ha_MasterEpochTest.java
|
4,999
|
public class MasterElectionInput
{
private final long lastCommittedTx;
private final int masterForTx;
public MasterElectionInput( long lastCommittedTx, int masterForTx )
{
this.lastCommittedTx = lastCommittedTx;
this.masterForTx = masterForTx;
}
public long getLastCommittedTx()
{
return lastCommittedTx;
}
public int getMasterForTx()
{
return masterForTx;
}
}
| false
|
enterprise_ha_src_main_java_org_neo4j_kernel_ha_MasterElectionInput.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.