Unnamed: 0
int64 0
6.7k
| func
stringlengths 12
89.6k
| target
bool 2
classes | project
stringlengths 45
151
|
|---|---|---|---|
4,600
|
{
@Override
public Response<LockResult> call( Master master, RequestContext context, ChannelBuffer input,
ChannelBuffer target )
{
return master.acquireIndexWriteLock( context, readString( input ), readString( input ) );
}
}, LOCK_SERIALIZER )
| false
|
enterprise_ha_src_main_java_org_neo4j_kernel_ha_HaRequestType20.java
|
4,601
|
ACQUIRE_INDEX_READ_LOCK( new TargetCaller<Master, LockResult>()
{
@Override
public Response<LockResult> call( Master master, RequestContext context, ChannelBuffer input,
ChannelBuffer target )
{
return master.acquireIndexReadLock( context, readString( input ), readString( input ) );
}
}, LOCK_SERIALIZER )
{
@Override
public boolean isLock()
{
return true;
}
},
| false
|
enterprise_ha_src_main_java_org_neo4j_kernel_ha_HaRequestType20.java
|
4,602
|
{
@Override
public Response<LockResult> call( Master master, RequestContext context, ChannelBuffer input,
ChannelBuffer target )
{
return master.acquireIndexReadLock( context, readString( input ), readString( input ) );
}
}, LOCK_SERIALIZER )
| false
|
enterprise_ha_src_main_java_org_neo4j_kernel_ha_HaRequestType20.java
|
4,603
|
ACQUIRE_GRAPH_READ_LOCK( new TargetCaller<Master, LockResult>()
{
@Override
public Response<LockResult> call( Master master, RequestContext context, ChannelBuffer input,
ChannelBuffer target )
{
return master.acquireGraphReadLock( context );
}
}, LOCK_SERIALIZER )
{
@Override
public boolean isLock()
{
return true;
}
},
| false
|
enterprise_ha_src_main_java_org_neo4j_kernel_ha_HaRequestType20.java
|
4,604
|
{
@Override
public Response<LockResult> call( Master master, RequestContext context, ChannelBuffer input,
ChannelBuffer target )
{
return master.acquireGraphReadLock( context );
}
}, LOCK_SERIALIZER )
| false
|
enterprise_ha_src_main_java_org_neo4j_kernel_ha_HaRequestType20.java
|
4,605
|
ACQUIRE_GRAPH_WRITE_LOCK( new TargetCaller<Master, LockResult>()
{
@Override
public Response<LockResult> call( Master master, RequestContext context, ChannelBuffer input,
ChannelBuffer target )
{
return master.acquireGraphWriteLock( context );
}
}, LOCK_SERIALIZER )
{
@Override
public boolean isLock()
{
return true;
}
},
| false
|
enterprise_ha_src_main_java_org_neo4j_kernel_ha_HaRequestType20.java
|
4,606
|
{
@Override
public Response<LockResult> call( Master master, RequestContext context, ChannelBuffer input,
ChannelBuffer target )
{
return master.acquireGraphWriteLock( context );
}
}, LOCK_SERIALIZER )
| false
|
enterprise_ha_src_main_java_org_neo4j_kernel_ha_HaRequestType20.java
|
4,607
|
{
@Override
public Response<Void> call( Master master, RequestContext context, ChannelBuffer input,
ChannelBuffer target )
{
return master.initializeTx( context );
}
}, VOID_SERIALIZER ),
| false
|
enterprise_ha_src_main_java_org_neo4j_kernel_ha_HaRequestType20.java
|
4,608
|
{
@Override
public Response<LockResult> lock( Master master, RequestContext context, long... ids )
{
return master.acquireRelationshipReadLock( context, ids );
}
}, LOCK_SERIALIZER )
| false
|
enterprise_ha_src_main_java_org_neo4j_kernel_ha_HaRequestType20.java
|
4,609
|
{
@Override
public Response<Void> call( Master master, RequestContext context, ChannelBuffer input,
final ChannelBuffer target )
{
return master.copyTransactions( context, readString( input ), input.readLong(), input.readLong() );
}
}, VOID_SERIALIZER ),
| false
|
enterprise_ha_src_main_java_org_neo4j_kernel_ha_HaRequestType20.java
|
4,610
|
{
@Override
public Response<Void> call( Master master, RequestContext context, ChannelBuffer input,
final ChannelBuffer target )
{
return master.copyStore( context, new ToNetworkStoreWriter( target, new Monitors() ) );
}
}, VOID_SERIALIZER ),
| false
|
enterprise_ha_src_main_java_org_neo4j_kernel_ha_HaRequestType20.java
|
4,611
|
{
@Override
public void write( HandshakeResult responseObject, ChannelBuffer result ) throws IOException
{
result.writeInt( responseObject.txAuthor() );
result.writeLong( responseObject.txChecksum() );
}
} ),
| false
|
enterprise_ha_src_main_java_org_neo4j_kernel_ha_HaRequestType20.java
|
4,612
|
{
@Override
public Response<HandshakeResult> call( Master master, RequestContext context, ChannelBuffer input,
ChannelBuffer target )
{
return master.handshake( input.readLong(), null );
}
}, new ObjectSerializer<HandshakeResult>()
| false
|
enterprise_ha_src_main_java_org_neo4j_kernel_ha_HaRequestType20.java
|
4,613
|
{
@Override
public Response<Void> call( Master master, RequestContext context, ChannelBuffer input,
ChannelBuffer target )
{
return master.finishTransaction( context, readBoolean( input ) );
}
}, VOID_SERIALIZER ),
| false
|
enterprise_ha_src_main_java_org_neo4j_kernel_ha_HaRequestType20.java
|
4,614
|
{
@Override
public Response<Void> call( Master master, RequestContext context, ChannelBuffer input,
ChannelBuffer target )
{
return master.pullUpdates( context );
}
}, VOID_SERIALIZER ),
| false
|
enterprise_ha_src_main_java_org_neo4j_kernel_ha_HaRequestType20.java
|
4,615
|
{
@Override
public Response<Long> call( Master master, RequestContext context, ChannelBuffer input,
ChannelBuffer target )
{
String resource = readString( input );
final ReadableByteChannel reader = new BlockLogReader( input );
return master.commitSingleResourceTransaction( context, resource, TxExtractor.create( reader ) );
}
}, LONG_SERIALIZER ),
| false
|
enterprise_ha_src_main_java_org_neo4j_kernel_ha_HaRequestType20.java
|
4,616
|
ACQUIRE_RELATIONSHIP_READ_LOCK( new AquireLockCall()
{
@Override
public Response<LockResult> lock( Master master, RequestContext context, long... ids )
{
return master.acquireRelationshipReadLock( context, ids );
}
}, LOCK_SERIALIZER )
{
@Override
public boolean isLock()
{
return true;
}
},
| false
|
enterprise_ha_src_main_java_org_neo4j_kernel_ha_HaRequestType20.java
|
4,617
|
class ByteArrayProperty extends DefinedProperty
{
private final byte[] value;
ByteArrayProperty( int propertyKeyId, byte[] value )
{
super( propertyKeyId );
assert value != null;
this.value = value;
}
@Override
public byte[] value()
{
return value.clone();
}
@Override
public boolean valueEquals( Object value )
{
if ( value instanceof byte[] )
{
return Arrays.equals( this.value, (byte[]) value );
}
return valueCompare( this.value, value );
}
@Override
int valueHash()
{
return Arrays.hashCode( value );
}
@Override
boolean hasEqualValue( DefinedProperty that )
{
return Arrays.equals( this.value, ((ByteArrayProperty)that).value );
}
@Override
public int sizeOfObjectInBytesIncludingOverhead()
{
return withObjectOverhead( withReference( sizeOfArray( value ) ) );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_api_properties_ByteArrayProperty.java
|
4,618
|
class BooleanArrayProperty extends DefinedProperty
{
private final boolean[] value;
BooleanArrayProperty( int propertyKeyId, boolean[] value )
{
super( propertyKeyId );
assert value != null;
this.value = value;
}
@Override
public boolean[] value()
{
return value.clone();
}
@Override
public boolean valueEquals( Object value )
{
if ( value instanceof boolean[] )
{
return Arrays.equals( this.value, (boolean[]) value );
}
return valueCompare( this.value, value );
}
@Override
int valueHash()
{
return Arrays.hashCode( value );
}
@Override
boolean hasEqualValue( DefinedProperty that )
{
return Arrays.equals( this.value, ((BooleanArrayProperty)that).value );
}
@Override
public int sizeOfObjectInBytesIncludingOverhead()
{
return withObjectOverhead( withReference( sizeOfArray( value ) ) );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_api_properties_BooleanArrayProperty.java
|
4,619
|
ACQUIRE_NODE_READ_LOCK( new AquireLockCall()
{
@Override
public Response<LockResult> lock( Master master, RequestContext context, long... ids )
{
return master.acquireNodeReadLock( context, ids );
}
}, LOCK_SERIALIZER )
{
@Override
public boolean isLock()
{
return true;
}
},
| false
|
enterprise_ha_src_main_java_org_neo4j_kernel_ha_HaRequestType201.java
|
4,620
|
public class LuceneIndexIndexProviderApprovalTest extends SchemaIndexProviderApprovalTest
{
public LuceneIndexIndexProviderApprovalTest( TestValue value )
{
super( value );
}
}
| false
|
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_LuceneIndexIndexProviderApprovalTest.java
|
4,621
|
public class LuceneIndexConstraintProviderApprovalTest extends SchemaConstraintProviderApprovalTest
{
public LuceneIndexConstraintProviderApprovalTest( TestValue value )
{
super( value );
}
}
| false
|
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_LuceneIndexConstraintProviderApprovalTest.java
|
4,622
|
public class LuceneIndexAccessorTest
{
@Test
public void indexReaderShouldHonorRepeatableReads() throws Exception
{
// GIVEN
updateAndCommit( asList( add( nodeId, value ) ) );
IndexReader reader = accessor.newReader();
// WHEN
updateAndCommit( asList( remove( nodeId, value ) ) );
// THEN
assertEquals( asSet( nodeId ), asUniqueSet( reader.lookup( value ) ) );
reader.close();
}
@Test
public void multipleIndexReadersFromDifferentPointsInTimeCanSeeDifferentResults() throws Exception
{
// WHEN
updateAndCommit( asList( add( nodeId, value ) ) );
IndexReader firstReader = accessor.newReader();
updateAndCommit( asList( add( nodeId2, value ) ) );
IndexReader secondReader = accessor.newReader();
// THEN
assertEquals( asSet( nodeId ), asUniqueSet( firstReader.lookup( value ) ) );
assertEquals( asSet( nodeId, nodeId2 ), asUniqueSet( secondReader.lookup( value ) ) );
firstReader.close();
secondReader.close();
}
@Test
public void canAddNewData() throws Exception
{
// WHEN
updateAndCommit( asList(
add( nodeId, value ),
add( nodeId2, value2 ) ) );
IndexReader reader = accessor.newReader();
// THEN
assertEquals( asSet( nodeId ), asUniqueSet( reader.lookup( value ) ) );
reader.close();
}
@Test
public void canChangeExistingData() throws Exception
{
// GIVEN
updateAndCommit( asList( add( nodeId, value ) ) );
// WHEN
updateAndCommit( asList( change( nodeId, value, value2 ) ) );
IndexReader reader = accessor.newReader();
// THEN
assertEquals( asSet( nodeId ), asUniqueSet( reader.lookup( value2 ) ) );
assertEquals( emptySetOf( Long.class ), asUniqueSet( reader.lookup( value ) ) );
reader.close();
}
@Test
public void canRemoveExistingData() throws Exception
{
// GIVEN
updateAndCommit( asList(
add( nodeId, value ),
add( nodeId2, value ) ) );
// WHEN
updateAndCommit( asList( remove( nodeId, value ) ) );
IndexReader reader = accessor.newReader();
// THEN
assertEquals( asSet( nodeId2 ), asUniqueSet( reader.lookup( value ) ) );
reader.close();
}
private final long nodeId = 1, nodeId2 = 2;
private final Object value = "value", value2 = 40;
private final LuceneDocumentStructure documentLogic = new LuceneDocumentStructure();
private final IndexWriterStatus writerLogic = new IndexWriterStatus();
private final File dir = new File( "dir" );
private LuceneIndexAccessor accessor;
private DirectoryFactory.InMemoryDirectoryFactory dirFactory;
@Before
public void before() throws Exception
{
dirFactory = new DirectoryFactory.InMemoryDirectoryFactory();
accessor = new NonUniqueLuceneIndexAccessor( documentLogic, standard(), writerLogic, dirFactory, dir );
}
@After
public void after()
{
dirFactory.close();
}
private NodePropertyUpdate add( long nodeId, Object value )
{
return NodePropertyUpdate.add( nodeId, 0, value, new long[0] );
}
private NodePropertyUpdate remove( long nodeId, Object value )
{
return NodePropertyUpdate.remove( nodeId, 0, value, new long[0] );
}
private NodePropertyUpdate change( long nodeId, Object valueBefore, Object valueAfter )
{
return NodePropertyUpdate.change( nodeId, 0, valueBefore, new long[0], valueAfter, new long[0] );
}
private void updateAndCommit( List<NodePropertyUpdate> nodePropertyUpdates )
throws IOException, IndexEntryConflictException
{
try ( IndexUpdater updater = accessor.newUpdater( IndexUpdateMode.ONLINE ) )
{
for ( NodePropertyUpdate update : nodePropertyUpdates )
{
updater.process( update );
}
}
}
}
| false
|
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_LuceneIndexAccessorTest.java
|
4,623
|
class LuceneIndexAccessorReader implements IndexReader
{
private final IndexSearcher searcher;
private final LuceneDocumentStructure documentLogic;
private final SearcherManager searcherManager;
LuceneIndexAccessorReader( SearcherManager searcherManager, LuceneDocumentStructure documentLogic )
{
this.searcherManager = searcherManager;
this.searcher = searcherManager.acquire();
this.documentLogic = documentLogic;
}
@Override
public PrimitiveLongIterator lookup( final Object value )
{
try
{
Hits hits = new Hits( searcher, documentLogic.newQuery( value ), null );
return new HitsPrimitiveLongIterator( hits, documentLogic );
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
}
@Override
public void close()
{
try
{
searcherManager.release( searcher );
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
}
}
| false
|
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_LuceneIndexAccessorReader.java
|
4,624
|
private class LuceneIndexUpdater implements IndexUpdater
{
private final boolean inRecovery;
private LuceneIndexUpdater( boolean inRecovery )
{
this.inRecovery = inRecovery;
}
@Override
public void process( NodePropertyUpdate update ) throws IOException
{
switch ( update.getUpdateMode() )
{
case ADDED:
if ( inRecovery )
{
addRecovered( update.getNodeId(), update.getValueAfter() );
}
else
{
add( update.getNodeId(), update.getValueAfter() );
}
break;
case CHANGED:
change( update.getNodeId(), update.getValueAfter() );
break;
case REMOVED:
LuceneIndexAccessor.this.remove( update.getNodeId() );
break;
default:
throw new UnsupportedOperationException();
}
}
@Override
public void close() throws IOException, IndexEntryConflictException
{
searcherManager.maybeRefresh();
}
@Override
public void remove( Iterable<Long> nodeIds ) throws IOException
{
for ( long nodeId : nodeIds )
{
LuceneIndexAccessor.this.remove( nodeId );
}
}
}
| false
|
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_LuceneIndexAccessor.java
|
4,625
|
abstract class LuceneIndexAccessor implements IndexAccessor
{
protected final LuceneDocumentStructure documentStructure;
protected final SearcherManager searcherManager;
protected final IndexWriter writer;
private final IndexWriterStatus writerStatus;
private final Directory dir;
private final File dirFile;
LuceneIndexAccessor( LuceneDocumentStructure documentStructure, LuceneIndexWriterFactory indexWriterFactory,
IndexWriterStatus writerStatus, DirectoryFactory dirFactory, File dirFile )
throws IOException
{
this.documentStructure = documentStructure;
this.dirFile = dirFile;
this.dir = dirFactory.open( dirFile );
this.writer = indexWriterFactory.create( dir );
this.writerStatus = writerStatus;
this.searcherManager = new SearcherManager( writer, true, new SearcherFactory() );
}
@Override
public IndexUpdater newUpdater( IndexUpdateMode mode )
{
switch ( mode )
{
case ONLINE:
return new LuceneIndexUpdater( false );
case RECOVERY:
return new LuceneIndexUpdater( true );
default:
throw new ThisShouldNotHappenError( "Stefan", "Unsupported update mode" );
}
}
@Override
public void drop() throws IOException
{
closeIndexResources();
deleteDirectoryContents( dir );
}
@Override
public void force() throws IOException
{
writerStatus.commitAsOnline( writer );
}
@Override
public void close() throws IOException
{
closeIndexResources();
dir.close();
}
private void closeIndexResources() throws IOException
{
writerStatus.close( writer );
searcherManager.close();
}
@Override
public IndexReader newReader()
{
return new LuceneIndexAccessorReader( searcherManager, documentStructure );
}
@Override
public BoundedIterable<Long> newAllEntriesReader()
{
return new LuceneAllEntriesIndexAccessorReader( new LuceneAllDocumentsReader( searcherManager ), documentStructure );
}
@Override
public ResourceIterator<File> snapshotFiles() throws IOException
{
return new LuceneSnapshotter().snapshot( this.dirFile, writer );
}
private void addRecovered( long nodeId, Object value ) throws IOException
{
IndexSearcher searcher = searcherManager.acquire();
try
{
TopDocs hits = searcher.search( new TermQuery( documentStructure.newQueryForChangeOrRemove( nodeId ) ), 1 );
if ( hits.totalHits > 0 )
{
writer.updateDocument( documentStructure.newQueryForChangeOrRemove( nodeId ),
documentStructure.newDocumentRepresentingProperty( nodeId, value ) );
}
else
{
add( nodeId, value );
}
}
finally
{
searcherManager.release( searcher );
}
}
protected void add( long nodeId, Object value ) throws IOException
{
writer.addDocument( documentStructure.newDocumentRepresentingProperty( nodeId, value ) );
}
protected void change( long nodeId, Object valueAfter ) throws IOException
{
writer.updateDocument( documentStructure.newQueryForChangeOrRemove( nodeId ),
documentStructure.newDocumentRepresentingProperty( nodeId, valueAfter ) );
}
protected void remove( long nodeId ) throws IOException
{
writer.deleteDocuments( documentStructure.newQueryForChangeOrRemove( nodeId ) );
}
private class LuceneIndexUpdater implements IndexUpdater
{
private final boolean inRecovery;
private LuceneIndexUpdater( boolean inRecovery )
{
this.inRecovery = inRecovery;
}
@Override
public void process( NodePropertyUpdate update ) throws IOException
{
switch ( update.getUpdateMode() )
{
case ADDED:
if ( inRecovery )
{
addRecovered( update.getNodeId(), update.getValueAfter() );
}
else
{
add( update.getNodeId(), update.getValueAfter() );
}
break;
case CHANGED:
change( update.getNodeId(), update.getValueAfter() );
break;
case REMOVED:
LuceneIndexAccessor.this.remove( update.getNodeId() );
break;
default:
throw new UnsupportedOperationException();
}
}
@Override
public void close() throws IOException, IndexEntryConflictException
{
searcherManager.maybeRefresh();
}
@Override
public void remove( Iterable<Long> nodeIds ) throws IOException
{
for ( long nodeId : nodeIds )
{
LuceneIndexAccessor.this.remove( nodeId );
}
}
}
}
| false
|
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_LuceneIndexAccessor.java
|
4,626
|
public class LuceneDocumentStructureTest
{
@Test
public void shouldBuildDocumentRepresentingStringProperty() throws Exception
{
// given
Document document = new LuceneDocumentStructure().newDocumentRepresentingProperty( 123, "hello" );
// then
assertEquals("123", document.get( NODE_ID_KEY ));
assertEquals("hello", document.get( String.key() ));
}
@Test
public void shouldBuildDocumentRepresentingBoolProperty() throws Exception
{
// given
Document document = new LuceneDocumentStructure().newDocumentRepresentingProperty( 123, true );
// then
assertEquals("123", document.get( NODE_ID_KEY ));
assertEquals("true", document.get( Bool.key() ));
}
@Test
public void shouldBuildDocumentRepresentingNumberProperty() throws Exception
{
// given
Document document = new LuceneDocumentStructure().newDocumentRepresentingProperty( 123, 12 );
// then
assertEquals("123", document.get( NODE_ID_KEY ));
assertEquals( NumericUtils.doubleToPrefixCoded( 12.0 ), document.get( Number.key() ) );
}
@Test
public void shouldBuildDocumentRepresentingArrayProperty() throws Exception
{
// given
Document document = new LuceneDocumentStructure().newDocumentRepresentingProperty( 123, new Integer[] { 1,2,3 } );
// then
assertEquals("123", document.get( NODE_ID_KEY ));
assertEquals("D1.0|2.0|3.0|", document.get( Array.key() ));
}
@Test
public void shouldBuildQueryRepresentingBoolProperty() throws Exception
{
// given
TermQuery query = (TermQuery) new LuceneDocumentStructure().newQuery( true );
// then
assertEquals( "true", query.getTerm().text() );
}
@Test
public void shouldBuildQueryRepresentingStringProperty() throws Exception
{
// given
TermQuery query = (TermQuery) new LuceneDocumentStructure().newQuery( "Characters" );
// then
assertEquals( "Characters", query.getTerm().text() );
}
@SuppressWarnings("unchecked")
@Test
public void shouldBuildQueryRepresentingNumberProperty() throws Exception
{
// given
TermQuery query = (TermQuery) new LuceneDocumentStructure().newQuery( 12 );
// then
assertEquals( NumericUtils.doubleToPrefixCoded( 12.0 ), query.getTerm().text() );
}
@Test
public void shouldBuildQueryRepresentingArrayProperty() throws Exception
{
// given
TermQuery query = (TermQuery) new LuceneDocumentStructure().newQuery( new Integer[] { 1,2,3 } );
// then
assertEquals( "D1.0|2.0|3.0|", query.getTerm().text() );
}
}
| false
|
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_LuceneDocumentStructureTest.java
|
4,627
|
String
{
@Override
String key()
{
return "string";
}
@Override
boolean canEncode( Object value )
{
// Any other type can be safely serialised as a string
return true;
}
@Override
Fieldable encodeField( Object value )
{
return field( key(), value.toString() );
}
@Override
Query encodeQuery( Object value )
{
return new TermQuery( new Term( key(), value.toString() ) );
}
};
| false
|
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_LuceneDocumentStructure.java
|
4,628
|
Bool
{
@Override
String key()
{
return "bool";
}
@Override
boolean canEncode( Object value )
{
return value instanceof Boolean;
}
@Override
Fieldable encodeField( Object value )
{
return field( key(), value.toString() );
}
@Override
Query encodeQuery( Object value )
{
return new TermQuery( new Term( key(), value.toString() ) );
}
},
| false
|
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_LuceneDocumentStructure.java
|
4,629
|
Array
{
@Override
String key()
{
return "array";
}
@Override
boolean canEncode( Object value )
{
return value.getClass().isArray();
}
@Override
Fieldable encodeField( Object value )
{
return field( key(), ArrayEncoder.encode( value ) );
}
@Override
Query encodeQuery( Object value )
{
return new TermQuery( new Term( key(), ArrayEncoder.encode( value ) ) );
}
},
| false
|
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_LuceneDocumentStructure.java
|
4,630
|
Number
{
@Override
String key()
{
return "number";
}
@Override
boolean canEncode( Object value )
{
return value instanceof Number;
}
@Override
Fieldable encodeField( Object value )
{
String encodedString = NumericUtils.doubleToPrefixCoded( ((Number)value).doubleValue() );
return field( key(), encodedString );
}
@Override
Query encodeQuery( Object value )
{
String encodedString = NumericUtils.doubleToPrefixCoded( ((Number)value).doubleValue() );
return new TermQuery( new Term( key(), encodedString ) );
}
},
| false
|
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_LuceneDocumentStructure.java
|
4,631
|
public class LuceneDocumentStructure
{
static final String NODE_ID_KEY = "id";
Document newDocument( long nodeId )
{
Document document = new Document();
document.add( field( NODE_ID_KEY, "" + nodeId, YES ) );
return document;
}
enum ValueEncoding
{
Number
{
@Override
String key()
{
return "number";
}
@Override
boolean canEncode( Object value )
{
return value instanceof Number;
}
@Override
Fieldable encodeField( Object value )
{
String encodedString = NumericUtils.doubleToPrefixCoded( ((Number)value).doubleValue() );
return field( key(), encodedString );
}
@Override
Query encodeQuery( Object value )
{
String encodedString = NumericUtils.doubleToPrefixCoded( ((Number)value).doubleValue() );
return new TermQuery( new Term( key(), encodedString ) );
}
},
Array
{
@Override
String key()
{
return "array";
}
@Override
boolean canEncode( Object value )
{
return value.getClass().isArray();
}
@Override
Fieldable encodeField( Object value )
{
return field( key(), ArrayEncoder.encode( value ) );
}
@Override
Query encodeQuery( Object value )
{
return new TermQuery( new Term( key(), ArrayEncoder.encode( value ) ) );
}
},
Bool
{
@Override
String key()
{
return "bool";
}
@Override
boolean canEncode( Object value )
{
return value instanceof Boolean;
}
@Override
Fieldable encodeField( Object value )
{
return field( key(), value.toString() );
}
@Override
Query encodeQuery( Object value )
{
return new TermQuery( new Term( key(), value.toString() ) );
}
},
String
{
@Override
String key()
{
return "string";
}
@Override
boolean canEncode( Object value )
{
// Any other type can be safely serialised as a string
return true;
}
@Override
Fieldable encodeField( Object value )
{
return field( key(), value.toString() );
}
@Override
Query encodeQuery( Object value )
{
return new TermQuery( new Term( key(), value.toString() ) );
}
};
abstract String key();
abstract boolean canEncode( Object value );
abstract Fieldable encodeField( Object value );
abstract Query encodeQuery( Object value );
}
public Document newDocumentRepresentingProperty( long nodeId, Object value )
{
Document document = newDocument( nodeId );
for ( ValueEncoding encoding : ValueEncoding.values() )
{
if ( encoding.canEncode( value ) )
{
document.add( encoding.encodeField( value ) );
break;
}
}
return document;
}
private static Field field( String fieldIdentifier, String value )
{
return field( fieldIdentifier, value, NO );
}
private static Field field( String fieldIdentifier, String value, Field.Store store )
{
Field result = new Field( fieldIdentifier, value, store, NOT_ANALYZED );
result.setOmitNorms( true );
result.setIndexOptions( IndexOptions.DOCS_ONLY );
return result;
}
public Query newQuery( Object value )
{
for ( ValueEncoding encoding : ValueEncoding.values() )
{
if ( encoding.canEncode( value ) )
{
return encoding.encodeQuery( value );
}
}
throw new IllegalArgumentException( format( "Unable to create newQuery for %s", value ) );
}
public Term newQueryForChangeOrRemove( long nodeId )
{
return new Term( NODE_ID_KEY, "" + nodeId );
}
public long getNodeId( Document from )
{
return Long.parseLong( from.get( NODE_ID_KEY ) );
}
}
| false
|
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_LuceneDocumentStructure.java
|
4,632
|
{
private int id = 0;
public boolean hasNext()
{
return iterator.hasNext();
}
public LuceneNodeLabelRange next()
{
return parse( id++, iterator.next() );
}
public void remove()
{
iterator.remove();
}
};
| false
|
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_LuceneAllEntriesLabelScanReader.java
|
4,633
|
public class LuceneAllEntriesLabelScanReader implements AllEntriesLabelScanReader
{
private final BitmapDocumentFormat format;
private final BoundedIterable<Document> documents;
public LuceneAllEntriesLabelScanReader( BoundedIterable<Document> documents, BitmapDocumentFormat format )
{
this.documents = documents;
this.format = format;
}
@Override
public Iterator<NodeLabelRange> iterator()
{
final Iterator<Document> iterator = documents.iterator();
return new Iterator<NodeLabelRange>()
{
private int id = 0;
public boolean hasNext()
{
return iterator.hasNext();
}
public LuceneNodeLabelRange next()
{
return parse( id++, iterator.next() );
}
public void remove()
{
iterator.remove();
}
};
}
@Override
public void close() throws IOException
{
documents.close();
}
@Override
public long maxCount()
{
return documents.maxCount();
}
private LuceneNodeLabelRange parse( int id, Document document )
{
List<Fieldable> fields = document.getFields();
long[] labelIds = new long[fields.size() - 1];
Bitmap[] bitmaps = new Bitmap[fields.size() - 1];
int i = 0;
long rangeId = -1;
for ( Fieldable field : fields )
{
if ( format.isRangeField( field ) )
{
rangeId = format.rangeOf( field );
}
else
{
labelIds[i] = format.labelId( field );
bitmaps[i] = format.readBitmap( field );
i++;
}
}
assert (rangeId >= 0);
return LuceneNodeLabelRange.fromBitmapStructure( id, labelIds, getLongs( bitmaps, rangeId ) );
}
private long[][] getLongs( Bitmap[] bitmaps, long rangeId )
{
long[][] nodeIds = new long[bitmaps.length][];
for ( int k = 0; k < nodeIds.length; k++ )
{
nodeIds[k] = format.bitmapFormat().convertRangeAndBitmapToArray( rangeId, bitmaps[k].bitmap() );
}
return nodeIds;
}
}
| false
|
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_LuceneAllEntriesLabelScanReader.java
|
4,634
|
{
public boolean hasNext()
{
return iterator.hasNext();
}
public Long next()
{
return parse( iterator.next() );
}
public void remove()
{
iterator.remove();
}
};
| false
|
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_LuceneAllEntriesIndexAccessorReader.java
|
4,635
|
public class LuceneAllEntriesIndexAccessorReader implements BoundedIterable<Long>
{
private final BoundedIterable<Document> documents;
private final LuceneDocumentStructure documentLogic;
public LuceneAllEntriesIndexAccessorReader( BoundedIterable<Document> documents, LuceneDocumentStructure documentLogic )
{
this.documents = documents;
this.documentLogic = documentLogic;
}
@Override
public long maxCount()
{
return documents.maxCount();
}
@Override
public Iterator<Long> iterator()
{
final Iterator<Document> iterator = documents.iterator();
return new Iterator<Long>()
{
public boolean hasNext()
{
return iterator.hasNext();
}
public Long next()
{
return parse( iterator.next() );
}
public void remove()
{
iterator.remove();
}
};
}
@Override
public void close() throws IOException
{
documents.close();
}
private Long parse( Document document )
{
return documentLogic.getNodeId( document );
}
}
| false
|
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_LuceneAllEntriesIndexAccessorReader.java
|
4,636
|
private static class SearcherStub extends IndexSearcher
{
private final String[] elements;
public SearcherStub( IndexReader r, String[] elements )
{
super( r );
this.elements = elements;
}
@Override
public Document doc( int docID ) throws IOException
{
Document document = new Document();
document.add( new Field( "element", elements[docID], Field.Store.YES, Field.Index.NO ) );
return document;
}
@Override
public int maxDoc()
{
return elements.length;
}
}
| false
|
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_LuceneAllDocumentsReaderTest.java
|
4,637
|
private static class SearcherManagerStub extends ReferenceManager<IndexSearcher>
{
SearcherManagerStub( IndexSearcher searcher )
{
this.current = searcher;
}
@Override
protected void decRef( IndexSearcher reference ) throws IOException
{
}
@Override
protected IndexSearcher refreshIfNeeded( IndexSearcher referenceToRefresh ) throws IOException
{
return null;
}
@Override
protected boolean tryIncRef( IndexSearcher reference )
{
return true;
}
}
| false
|
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_LuceneAllDocumentsReaderTest.java
|
4,638
|
{
@Override
public Boolean answer( InvocationOnMock invocation ) throws Throwable
{
if ( (int) invocation.getArguments()[0] >= elements.length )
{
throw new IllegalArgumentException( "Doc id out of range" );
}
return true;
}
} );
| false
|
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_LuceneAllDocumentsReaderTest.java
|
4,639
|
public class LuceneAllDocumentsReaderTest
{
@Test
public void shouldIterateOverAllLuceneDocumentsWhereNoDocumentsHaveBeenDeleted() throws Exception
{
// given
String[] elements = {"A", "B", "C"};
IndexReader indexReader = mock( IndexReader.class );
when( indexReader.isDeleted( anyInt() ) ).thenReturn( false );
LuceneAllDocumentsReader reader =
new LuceneAllDocumentsReader(
new SearcherManagerStub( new SearcherStub( indexReader, elements ) ) );
// when
Iterator<Document> iterator = reader.iterator();
List<Document> actualDocuments = new ArrayList<>( IteratorUtil.asCollection( iterator ) );
// then
for ( int i = 0; i < elements.length; i++ )
{
assertEquals( elements[i], actualDocuments.get( i ).get( "element" ) );
}
}
@Test
public void shouldFindNoDocumentsIfTheyHaveAllBeenDeleted() throws Exception
{
// given
final String[] elements = {"A", "B", "C"};
final IndexReader indexReader = mock( IndexReader.class );
when( indexReader.isDeleted( anyInt() ) ).thenAnswer( new Answer<Boolean>()
{
@Override
public Boolean answer( InvocationOnMock invocation ) throws Throwable
{
if ( (int) invocation.getArguments()[0] >= elements.length )
{
throw new IllegalArgumentException( "Doc id out of range" );
}
return true;
}
} );
LuceneAllDocumentsReader reader =
new LuceneAllDocumentsReader(
new SearcherManagerStub( new SearcherStub( indexReader, elements ) ) );
// when
Iterator<Document> iterator = reader.iterator();
// then
assertFalse( iterator.hasNext() );
}
private static class SearcherStub extends IndexSearcher
{
private final String[] elements;
public SearcherStub( IndexReader r, String[] elements )
{
super( r );
this.elements = elements;
}
@Override
public Document doc( int docID ) throws IOException
{
Document document = new Document();
document.add( new Field( "element", elements[docID], Field.Store.YES, Field.Index.NO ) );
return document;
}
@Override
public int maxDoc()
{
return elements.length;
}
}
private static class SearcherManagerStub extends ReferenceManager<IndexSearcher>
{
SearcherManagerStub( IndexSearcher searcher )
{
this.current = searcher;
}
@Override
protected void decRef( IndexSearcher reference ) throws IOException
{
}
@Override
protected IndexSearcher refreshIfNeeded( IndexSearcher referenceToRefresh ) throws IOException
{
return null;
}
@Override
protected boolean tryIncRef( IndexSearcher reference )
{
return true;
}
}
}
| false
|
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_LuceneAllDocumentsReaderTest.java
|
4,640
|
public class LuceneIndexIT
{
@Test
public void shouldProvideStoreSnapshot() throws Exception
{
// Given
updateAndCommit( asList(
add( nodeId, value ),
add( nodeId2, value ) ) );
accessor.force();
// When & Then
try(ResourceIterator<File> snapshot = accessor.snapshotFiles())
{
assertThat( asUniqueSetOfNames( snapshot ), equalTo( asSet(
"_0.nrm",
"_0.tis",
"_0.fnm",
"_0.tii",
"segments_1",
"_0.frq",
"_0.fdx",
"_0.fdt" ) ) );
}
}
@Test
public void shouldProvideStoreSnapshotWhenThereAreNoCommits() throws Exception
{
// Given
// A completely un-used index
// When & Then
try(ResourceIterator<File> snapshot = accessor.snapshotFiles())
{
assertThat( asUniqueSetOfNames( snapshot ), equalTo( emptySetOf( String.class ) ) );
}
}
private Set<String> asUniqueSetOfNames( ResourceIterator<File> files )
{
ArrayList<String> out = new ArrayList<>();
while(files.hasNext())
out.add( files.next().getName() );
return asUniqueSet( out );
}
private final long nodeId = 1, nodeId2 = 2;
private final Object value = "value";
private final LuceneDocumentStructure documentLogic = new LuceneDocumentStructure();
private final IndexWriterStatus writerLogic = new IndexWriterStatus();
private LuceneIndexAccessor accessor;
private DirectoryFactory dirFactory;
@Rule
public TargetDirectory.TestDirectory testDir = TargetDirectory.testDirForTest( getClass() );
@Before
public void before() throws Exception
{
dirFactory = DirectoryFactory.PERSISTENT;
accessor = new NonUniqueLuceneIndexAccessor( documentLogic, standard(), writerLogic, dirFactory, testDir.directory() );
}
@After
public void after() throws IOException
{
accessor.close();
dirFactory.close();
}
private NodePropertyUpdate add( long nodeId, Object value )
{
return NodePropertyUpdate.add( nodeId, 0, value, new long[0] );
}
private void updateAndCommit( List<NodePropertyUpdate> nodePropertyUpdates )
throws IOException, IndexEntryConflictException
{
try ( IndexUpdater updater = accessor.newUpdater( IndexUpdateMode.ONLINE ) )
{
for ( NodePropertyUpdate update : nodePropertyUpdates )
{
updater.process( update );
}
}
}
}
| false
|
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_LuceneIndexIT.java
|
4,641
|
public abstract class LuceneIndexPopulator implements IndexPopulator
{
protected final LuceneDocumentStructure documentStructure;
private final LuceneIndexWriterFactory indexWriterFactory;
private final IndexWriterStatus writerStatus;
private final DirectoryFactory dirFactory;
private final File dirFile;
private final FailureStorage failureStorage;
private final long indexId;
protected IndexWriter writer;
private Directory directory;
LuceneIndexPopulator(
LuceneDocumentStructure documentStructure, LuceneIndexWriterFactory indexWriterFactory,
IndexWriterStatus writerStatus, DirectoryFactory dirFactory, File dirFile,
FailureStorage failureStorage, long indexId )
{
this.documentStructure = documentStructure;
this.indexWriterFactory = indexWriterFactory;
this.writerStatus = writerStatus;
this.dirFactory = dirFactory;
this.dirFile = dirFile;
this.failureStorage = failureStorage;
this.indexId = indexId;
}
@Override
public void create() throws IOException
{
this.directory = dirFactory.open( dirFile );
DirectorySupport.deleteDirectoryContents( directory );
failureStorage.reserveForIndex( indexId );
writer = indexWriterFactory.create( directory );
}
@Override
public void drop() throws IOException
{
if ( writer != null )
{
writerStatus.close( writer );
}
try
{
DirectorySupport.deleteDirectoryContents( directory = directory == null ? dirFactory.open( dirFile ) : directory );
}
catch ( AlreadyClosedException e )
{ // It was closed, open again just to be able to delete the files
DirectorySupport.deleteDirectoryContents( directory = dirFactory.open( dirFile ) );
}
finally
{
if ( directory != null )
{
directory.close();
}
}
failureStorage.clearForIndex( indexId );
}
@Override
public void close( boolean populationCompletedSuccessfully ) throws IOException
{
try
{
if ( populationCompletedSuccessfully )
{
flush();
writerStatus.commitAsOnline( writer );
}
}
finally
{
if ( writer != null )
{
writerStatus.close( writer );
}
if ( directory != null )
{
directory.close();
}
}
}
@Override
public void markAsFailed( String failure ) throws IOException
{
failureStorage.storeIndexFailure( indexId, failure );
}
protected abstract void flush() throws IOException;
}
| false
|
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_LuceneIndexPopulator.java
|
4,642
|
public class LuceneAllDocumentsReader implements BoundedIterable<Document>
{
private final IndexSearcher searcher;
private final ReferenceManager<IndexSearcher> searcherManager;
public LuceneAllDocumentsReader(
ReferenceManager<IndexSearcher> searcherManager )
{
this.searcherManager = searcherManager;
this.searcher = searcherManager.acquire();
}
@Override
public long maxCount()
{
return maxDocIdBoundary();
}
@Override
public Iterator<Document> iterator()
{
return new PrefetchingIterator<Document>()
{
private int docId;
@Override
protected Document fetchNextOrNull()
{
Document document = null;
while ( document == null && isPossibleDocId( docId ) )
{
if ( ! deleted( docId ) )
{
document = getDocument( docId );
}
docId++;
}
return document;
}
};
}
@Override
public void close()
{
try
{
searcherManager.release( searcher );
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
}
private Document getDocument( int docId )
{
try
{
return searcher.doc( docId );
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
}
private boolean deleted( int docId )
{
return searcher.getIndexReader().isDeleted( docId );
}
private boolean isPossibleDocId( int docId )
{
return docId < maxDocIdBoundary();
}
private int maxDocIdBoundary()
{
return searcher.maxDoc();
}
}
| false
|
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_LuceneAllDocumentsReader.java
|
4,643
|
public class LuceneIndexRecoveryIT
{
@Test
public void addShouldBeIdempotentWhenDoingRecovery() throws Exception
{
// Given
startDb(createLuceneIndexFactory());
Label myLabel = label( "MyLabel" );
createIndex( myLabel );
createNode( myLabel, 12 );
assertEquals( 1, doIndexLookup( myLabel, 12 ).size() );
// And Given
killDb();
// When
startDb( createLuceneIndexFactory() );
// Then
assertEquals( 1, doIndexLookup( myLabel, 12 ).size() );
}
@Test
public void changeShouldBeIdempotentWhenDoingRecovery() throws Exception
{
// Given
startDb(createLuceneIndexFactory());
Label myLabel = label( "MyLabel" );
createIndex( myLabel );
long node = createNode( myLabel, 12 );
rotateLogs();
updateNode( node, 13 );
// And Given
killDb();
// When
startDb( createLuceneIndexFactory() );
// Then
assertEquals( 0, doIndexLookup( myLabel, 12 ).size() );
assertEquals( 1, doIndexLookup( myLabel, 13 ).size() );
}
@Test
public void removeShouldBeIdempotentWhenDoingRecovery() throws Exception
{
// Given
startDb(createLuceneIndexFactory());
Label myLabel = label( "MyLabel" );
createIndex( myLabel );
long node = createNode( myLabel, 12 );
rotateLogs();
deleteNode( node );
// And Given
killDb();
// When
startDb( createLuceneIndexFactory() );
// Then
assertEquals( 0, doIndexLookup( myLabel, 12 ).size() );
}
private void deleteNode( long node )
{
Transaction tx = db.beginTx();
try
{
db.getNodeById( node ).delete();
tx.success();
}
finally
{
tx.finish();
}
}
@Test
public void shouldNotAddTwiceDuringRecoveryIfCrashedDuringPopulation() throws Exception
{
// Given
startDb( createAlwaysInitiallyPopulatingLuceneIndexFactory() );
Label myLabel = label( "MyLabel" );
createIndex( myLabel );
long nodeId = createNode( myLabel, 12 );
assertEquals( 1, doIndexLookup( myLabel, 12 ).size() );
// And Given
killDb();
// When
startDb( createAlwaysInitiallyPopulatingLuceneIndexFactory() );
Transaction transaction = db.beginTx();
try
{
IndexDefinition indexDefinition = db.schema().getIndexes().iterator().next();
db.schema().awaitIndexOnline( indexDefinition, 10l, TimeUnit.SECONDS );
// Then
assertEquals( 12, db.getNodeById( nodeId ).getProperty( NUM_BANANAS_KEY ) );
assertEquals( 1, doIndexLookup( myLabel, 12 ).size() );
}
finally
{
transaction.finish();
}
}
@Test
public void shouldNotUpdateTwiceDuringRecovery() throws Exception
{
// Given
startDb(createLuceneIndexFactory());
Label myLabel = label( "MyLabel" );
createIndex( myLabel );
long nodeId = createNode( myLabel, 12 );
updateNode(nodeId, 14);
// And Given
killDb();
// When
startDb( createLuceneIndexFactory() );
// Then
assertEquals( 0, doIndexLookup( myLabel, 12 ).size() );
assertEquals( 1, doIndexLookup( myLabel, 14 ).size() );
}
private GraphDatabaseAPI db;
private DirectoryFactory directoryFactory;
private final DirectoryFactory ignoreCloseDirectoryFactory = new DirectoryFactory()
{
@Override
public Directory open( File dir ) throws IOException
{
return directoryFactory.open( dir );
}
@Override
public void close()
{
}
@Override
public void dumpToZip( ZipOutputStream zip, byte[] scratchPad ) throws IOException
{
directoryFactory.dumpToZip( zip, scratchPad );
}
};
@Rule
public EphemeralFileSystemRule fs = new EphemeralFileSystemRule();
private final String NUM_BANANAS_KEY = "number_of_bananas_owned";
private void startDb( KernelExtensionFactory<?> indexProviderFactory )
{
if ( db != null )
{
db.shutdown();
}
TestGraphDatabaseFactory factory = new TestGraphDatabaseFactory();
factory.setFileSystem( fs.get() );
factory.addKernelExtensions( Arrays.<KernelExtensionFactory<?>>asList( indexProviderFactory ) );
db = (GraphDatabaseAPI) factory.newImpermanentDatabase();
}
private void killDb()
{
if ( db != null )
{
fs.snapshot( new Runnable()
{
@Override
public void run()
{
db.shutdown();
db = null;
}
} );
}
}
@Before
public void before()
{
directoryFactory = new DirectoryFactory.InMemoryDirectoryFactory();
}
@After
public void after()
{
if ( db != null )
{
db.shutdown();
}
directoryFactory.close();
}
private void rotateLogs()
{
db.getDependencyResolver().resolveDependency( XaDataSourceManager.class ).rotateLogicalLogs();
}
private void createIndex( Label label )
{
Transaction tx = db.beginTx();
IndexDefinition definition = db.schema().indexFor( label ).on( NUM_BANANAS_KEY ).create();
tx.success();
tx.finish();
tx = db.beginTx();
db.schema().awaitIndexOnline( definition, 10, TimeUnit.SECONDS );
tx.finish();
}
private Set<Node> doIndexLookup( Label myLabel, Object value )
{
Transaction tx = db.beginTx();
Iterable<Node> iter = db.findNodesByLabelAndProperty( myLabel, NUM_BANANAS_KEY, value );
Set<Node> nodes = asUniqueSet( iter );
tx.success();
tx.finish();
return nodes;
}
private long createNode( Label label, int number )
throws PropertyKeyNotFoundException, LabelNotFoundKernelException
{
Transaction tx = db.beginTx();
try
{
Node node = db.createNode( label );
node.setProperty( NUM_BANANAS_KEY, number );
tx.success();
return node.getId();
}
finally
{
tx.finish();
}
}
private void updateNode( long nodeId, int value )
{
Transaction tx = db.beginTx();
try
{
Node node = db.getNodeById( nodeId );
node.setProperty( NUM_BANANAS_KEY, value );
tx.success();
}
finally
{
tx.finish();
}
}
// Creates a lucene index factory with the shared in-memory directory
private KernelExtensionFactory<?> createAlwaysInitiallyPopulatingLuceneIndexFactory()
{
return new KernelExtensionFactory<LuceneSchemaIndexProviderFactory.Dependencies>(
LuceneSchemaIndexProviderFactory.PROVIDER_DESCRIPTOR.getKey() )
{
@Override
public Lifecycle newKernelExtension( LuceneSchemaIndexProviderFactory.Dependencies dependencies )
throws Throwable
{
return new LuceneSchemaIndexProvider( ignoreCloseDirectoryFactory, dependencies.getConfig() )
{
@Override
public InternalIndexState getInitialState( long indexId )
{
return InternalIndexState.POPULATING;
}
};
}
};
}
// Creates a lucene index factory with the shared in-memory directory
private KernelExtensionFactory<?> createLuceneIndexFactory()
{
return new KernelExtensionFactory<LuceneSchemaIndexProviderFactory.Dependencies>(
LuceneSchemaIndexProviderFactory.PROVIDER_DESCRIPTOR.getKey() )
{
@Override
public Lifecycle newKernelExtension( LuceneSchemaIndexProviderFactory.Dependencies dependencies )
throws Throwable
{
return new LuceneSchemaIndexProvider( ignoreCloseDirectoryFactory, dependencies.getConfig() )
{
@Override
public int compareTo( SchemaIndexProvider o )
{
return 1;
}
};
}
};
}
}
| false
|
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_LuceneIndexRecoveryIT.java
|
4,644
|
{
private Map<Integer, Document> docIds = new HashMap<>();
@Override
public TopDocs search( Query query, int n )
{
Document document = storage.get( ((TermQuery) query).getTerm() );
if ( document == null )
{
return new TopDocs( 0, new ScoreDoc[0], 0 );
}
int docId = new Random().nextInt();
docIds.put( docId, document );
int score = 10;
return new TopDocs( 1, new ScoreDoc[]{new ScoreDoc( docId, score )}, score );
}
@Override
public Document doc( int docID )
{
return docIds.get( docID );
}
};
| false
|
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_LuceneLabelScanStoreWriterTest.java
|
4,645
|
private class StubStorageService implements LabelScanStorageStrategy.StorageService
{
private Map<Term, Document> storage = new HashMap<>();
@Override
public void updateDocument( Term term, Document document ) throws IOException
{
storage.put( term, document );
}
@Override
public void deleteDocuments( Term term ) throws IOException
{
storage.remove( term );
}
@Override
public IndexSearcher acquireSearcher()
{
return new IndexSearcher( mock( IndexReader.class ) )
{
private Map<Integer, Document> docIds = new HashMap<>();
@Override
public TopDocs search( Query query, int n )
{
Document document = storage.get( ((TermQuery) query).getTerm() );
if ( document == null )
{
return new TopDocs( 0, new ScoreDoc[0], 0 );
}
int docId = new Random().nextInt();
docIds.put( docId, document );
int score = 10;
return new TopDocs( 1, new ScoreDoc[]{new ScoreDoc( docId, score )}, score );
}
@Override
public Document doc( int docID )
{
return docIds.get( docID );
}
};
}
@Override
public void releaseSearcher( IndexSearcher searcher ) throws IOException
{
}
@Override
public void refreshSearcher() throws IOException
{
}
public Document getDocument( Term term )
{
return storage.get( term );
}
}
| false
|
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_LuceneLabelScanStoreWriterTest.java
|
4,646
|
public class LuceneLabelScanStoreWriterTest
{
public static final BitmapDocumentFormat FORMAT = BitmapDocumentFormat._32;
@Test
public void shouldComplainIfNodesSuppliedOutOfRangeOrder() throws Exception
{
// given
int nodeId1 = 1;
int nodeId2 = 33;
long node1Range = FORMAT.bitmapFormat().rangeOf( nodeId1 );
long node2Range = FORMAT.bitmapFormat().rangeOf( nodeId2 );
assertNotEquals( node1Range, node2Range );
// when
LuceneLabelScanWriter writer = new LuceneLabelScanWriter( new StubStorageService(), FORMAT );
writer.write( NodeLabelUpdate.labelChanges( nodeId2, new long[]{}, new long[]{} ) );
try
{
writer.write( NodeLabelUpdate.labelChanges( nodeId1, new long[]{}, new long[]{} ) );
fail( "Should have thrown exception" );
}
catch ( IllegalArgumentException e )
{
// expected
}
}
@Test
public void shouldStoreDocumentWithNodeIdsAndLabelsInIt() throws Exception
{
// given
int nodeId = 1;
int label1 = 201;
int label2 = 202;
StubStorageService storage = new StubStorageService();
// when
LuceneLabelScanWriter writer = new LuceneLabelScanWriter( storage, FORMAT );
writer.write( NodeLabelUpdate.labelChanges( nodeId, new long[]{}, new long[]{label1, label2} ) );
writer.close();
// then
long range = FORMAT.bitmapFormat().rangeOf( nodeId );
Document document = storage.getDocument( new Term( RANGE, valueOf( range ) ) );
assertTrue( FORMAT.bitmapFormat().hasLabel( parseLong( document.get( valueOf( label1 ) ) ),
nodeId ) );
assertTrue( FORMAT.bitmapFormat().hasLabel( parseLong( document.get( valueOf( label2 ) ) ), nodeId ) );
}
@Test
public void shouldStoreDocumentWithNodeIdsInTheSameRange() throws Exception
{
// given
int nodeId1 = 1;
int nodeId2 = 3;
int label1 = 201;
int label2 = 202;
StubStorageService storage = new StubStorageService();
BitmapDocumentFormat format = BitmapDocumentFormat._32;
long range = format.bitmapFormat().rangeOf( nodeId1 );
assertEquals( range, format.bitmapFormat().rangeOf( nodeId2 ) );
// when
LuceneLabelScanWriter writer = new LuceneLabelScanWriter( storage, format );
writer.write( NodeLabelUpdate.labelChanges( nodeId1, new long[]{}, new long[]{label1} ) );
writer.write( NodeLabelUpdate.labelChanges( nodeId2, new long[]{}, new long[]{label2} ) );
writer.close();
// then
Document document = storage.getDocument( new Term( RANGE, valueOf( range ) ) );
assertTrue( format.bitmapFormat().hasLabel( parseLong( document.get( valueOf( label1 ) ) ), nodeId1 ) );
assertTrue( format.bitmapFormat().hasLabel( parseLong( document.get( valueOf( label2 ) ) ), nodeId2 ) );
}
@Test
public void shouldStoreDocumentWithNodeIdsInADifferentRange() throws Exception
{
// given
int nodeId1 = 1;
int nodeId2 = 33;
int label1 = 201;
int label2 = 202;
StubStorageService storage = new StubStorageService();
BitmapDocumentFormat format = BitmapDocumentFormat._32;
long node1Range = format.bitmapFormat().rangeOf( nodeId1 );
long node2Range = format.bitmapFormat().rangeOf( nodeId2 );
assertNotEquals( node1Range, node2Range );
// when
LuceneLabelScanWriter writer = new LuceneLabelScanWriter( storage, format );
writer.write( NodeLabelUpdate.labelChanges( nodeId1, new long[]{}, new long[]{label1} ) );
writer.write( NodeLabelUpdate.labelChanges( nodeId2, new long[]{}, new long[]{label2} ) );
writer.close();
// then
Document document1 = storage.getDocument( new Term( RANGE, valueOf( node1Range ) ) );
assertTrue( format.bitmapFormat().hasLabel( parseLong( document1.get( valueOf( label1 ) ) ), nodeId1 ) );
Document document2 = storage.getDocument( new Term( RANGE, valueOf( node2Range ) ) );
assertTrue( format.bitmapFormat().hasLabel( parseLong( document2.get( valueOf( label2 ) ) ), nodeId2 ) );
}
@Test
public void shouldUpdateExistingDocumentWithNodesInTheSameRange() throws Exception
{
// given
int nodeId1 = 1;
int nodeId2 = 3;
int label1 = 201;
int label2 = 202;
StubStorageService storage = new StubStorageService();
BitmapDocumentFormat format = BitmapDocumentFormat._32;
long range = format.bitmapFormat().rangeOf( nodeId1 );
assertEquals( range, format.bitmapFormat().rangeOf( nodeId2 ) );
// node already indexed
LuceneLabelScanWriter writer = new LuceneLabelScanWriter( storage, format );
writer.write( NodeLabelUpdate.labelChanges( nodeId1, new long[]{}, new long[]{label1} ) );
writer.close();
// when
writer = new LuceneLabelScanWriter( storage, format );
writer.write( NodeLabelUpdate.labelChanges( nodeId2, new long[]{}, new long[]{label2} ) );
writer.close();
// then
Document document = storage.getDocument( new Term( RANGE, valueOf( range ) ) );
assertTrue( format.bitmapFormat().hasLabel( parseLong( document.get( valueOf( label1 ) ) ), nodeId1 ) );
assertTrue( format.bitmapFormat().hasLabel( parseLong( document.get( valueOf( label2 ) ) ), nodeId2 ) );
}
private class StubStorageService implements LabelScanStorageStrategy.StorageService
{
private Map<Term, Document> storage = new HashMap<>();
@Override
public void updateDocument( Term term, Document document ) throws IOException
{
storage.put( term, document );
}
@Override
public void deleteDocuments( Term term ) throws IOException
{
storage.remove( term );
}
@Override
public IndexSearcher acquireSearcher()
{
return new IndexSearcher( mock( IndexReader.class ) )
{
private Map<Integer, Document> docIds = new HashMap<>();
@Override
public TopDocs search( Query query, int n )
{
Document document = storage.get( ((TermQuery) query).getTerm() );
if ( document == null )
{
return new TopDocs( 0, new ScoreDoc[0], 0 );
}
int docId = new Random().nextInt();
docIds.put( docId, document );
int score = 10;
return new TopDocs( 1, new ScoreDoc[]{new ScoreDoc( docId, score )}, score );
}
@Override
public Document doc( int docID )
{
return docIds.get( docID );
}
};
}
@Override
public void releaseSearcher( IndexSearcher searcher ) throws IOException
{
}
@Override
public void refreshSearcher() throws IOException
{
}
public Document getDocument( Term term )
{
return storage.get( term );
}
}
}
| false
|
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_LuceneLabelScanStoreWriterTest.java
|
4,647
|
private static class TrackingMonitor implements LuceneLabelScanStore.Monitor
{
boolean initCalled, rebuildingCalled, rebuiltCalled, noIndexCalled;
@Override
public void noIndex()
{
noIndexCalled = true;
}
@Override
public void lockedIndex( LockObtainFailedException e )
{
}
@Override
public void corruptIndex( IOException corruptionException )
{
}
@Override
public void rebuilding()
{
rebuildingCalled = true;
}
@Override
public void rebuilt( long roughNodeCount )
{
rebuiltCalled = true;
}
@Override
public void init()
{
initCalled = true;
}
}
| false
|
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_LuceneLabelScanStoreTest.java
|
4,648
|
{
@Override
public Iterator<NodeLabelUpdate> iterator()
{
return existingData.iterator();
}
@Override
public long highestNodeId()
{
return existingData.size(); // Well... not really
}
@Override
public PrimitiveLongIterator labelIds()
{
return emptyPrimitiveLongIterator();
}
};
| false
|
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_LuceneLabelScanStoreTest.java
|
4,649
|
{
private int i = -1;
@Override
protected NodeLabelUpdate fetchNextOrNull()
{
return ++i < nodeCount ? labelChanges( i, NO_LABELS, new long[]{labelId} ) : null;
}
} );
| false
|
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_LuceneLabelScanStoreTest.java
|
4,650
|
@RunWith(Parameterized.class)
public class LuceneLabelScanStoreTest
{
private static final long[] NO_LABELS = new long[0];
@Test
public void shouldUpdateIndexOnLabelChange() throws Exception
{
// GIVEN
int labelId = 1;
long nodeId = 10;
start();
// WHEN
write( iterator( labelChanges( nodeId, NO_LABELS, new long[]{labelId} ) ) );
// THEN
assertNodesForLabel( labelId, nodeId );
}
@Test
public void shouldUpdateIndexOnAddedLabels() throws Exception
{
// GIVEN
int labelId1 = 1, labelId2 = 2;
long nodeId = 10;
start();
write( iterator( labelChanges( nodeId, NO_LABELS, new long[]{labelId1} ) ) );
assertNodesForLabel( labelId2 );
// WHEN
write( iterator( labelChanges( nodeId, NO_LABELS, new long[]{labelId1, labelId2} ) ) );
// THEN
assertNodesForLabel( labelId1, nodeId );
assertNodesForLabel( labelId2, nodeId );
}
@Test
public void shouldUpdateIndexOnRemovedLabels() throws Exception
{
// GIVEN
int labelId1 = 1, labelId2 = 2;
long nodeId = 10;
start();
write( iterator( labelChanges( nodeId, NO_LABELS, new long[]{labelId1, labelId2} ) ) );
assertNodesForLabel( labelId1, nodeId );
assertNodesForLabel( labelId2, nodeId );
// WHEN
write( iterator( labelChanges( nodeId, new long[]{labelId1, labelId2}, new long[]{labelId2} ) ) );
// THEN
assertNodesForLabel( labelId1 );
assertNodesForLabel( labelId2, nodeId );
}
@Test
public void shouldDeleteFromIndexWhenDeletedNode() throws Exception
{
// GIVEN
int labelId = 1;
long nodeId = 10;
start();
write( iterator( labelChanges( nodeId, NO_LABELS, new long[]{labelId} ) ) );
// WHEN
write( iterator( labelChanges( nodeId, new long[]{labelId}, NO_LABELS ) ) );
// THEN
assertNodesForLabel( labelId );
}
@Test
public void shouldScanSingleRange() throws Exception
{
// GIVEN
int labelId1 = 1, labelId2 = 2;
long nodeId1 = 10, nodeId2 = 11;
start( asList(
labelChanges( nodeId1, NO_LABELS, new long[] { labelId1 } ),
labelChanges( nodeId2, NO_LABELS, new long[] { labelId1, labelId2 } )
) );
// WHEN
AllEntriesLabelScanReader reader = store.newAllEntriesReader();
NodeLabelRange range = single( reader.iterator() );
// THEN
assertArrayEquals( new long[]{nodeId1, nodeId2}, sorted( range.nodes() ) );
assertArrayEquals( new long[]{labelId1}, sorted( range.labels( nodeId1 ) ) );
assertArrayEquals( new long[]{labelId1, labelId2}, sorted( range.labels( nodeId2 ) ) );
}
@Test
public void shouldScanMultipleRanges() throws Exception
{
// GIVEN
int labelId1 = 1, labelId2 = 2;
long nodeId1 = 10, nodeId2 = 1280;
start( asList(
labelChanges( nodeId1, NO_LABELS, new long[] { labelId1 } ),
labelChanges( nodeId2, NO_LABELS, new long[] { labelId1, labelId2 } )
) );
// WHEN
AllEntriesLabelScanReader reader = store.newAllEntriesReader();
Iterator<NodeLabelRange> iterator = reader.iterator();
NodeLabelRange range1 = iterator.next();
NodeLabelRange range2 = iterator.next();
assertFalse( iterator.hasNext() );
// THEN
assertArrayEquals( new long[] { nodeId1 }, sorted( range1.nodes() ) );
assertArrayEquals( new long[] { nodeId2 }, sorted( range2.nodes() ) );
assertArrayEquals( new long[] { labelId1 }, sorted( range1.labels( nodeId1 ) ) );
assertArrayEquals( new long[] { labelId1, labelId2 }, sorted( range2.labels( nodeId2 ) ) );
}
@Test
public void shouldWorkWithAFullRange() throws Exception
{
// given
long labelId = 0;
List<NodeLabelUpdate> updates = new ArrayList<>( );
for ( int i = 0; i < 34; i++)
{
updates.add( NodeLabelUpdate.labelChanges(i, new long[] {}, new long[]{labelId}));
}
start(updates);
// when
LabelScanReader reader = store.newReader();
Set<Long> nodesWithLabel = asSet( reader.nodesWithLabel( (int) labelId ) );
// then
for ( long i = 0; i < 34; i++ )
{
assertThat( nodesWithLabel, hasItem( i ) );
Set<Long> labels = asSet( reader.labelsForNode( i ) );
assertThat( labels, hasItem( labelId ) );
}
}
@Test
public void shouldUpdateAFullRange() throws Exception
{
// given
long label0Id = 0;
List<NodeLabelUpdate> label0Updates = new ArrayList<>( );
for ( int i = 0; i < 34; i++)
{
label0Updates.add( NodeLabelUpdate.labelChanges( i, new long[]{}, new long[]{label0Id} ) );
}
start(label0Updates);
// when
write( Collections.<NodeLabelUpdate>emptyIterator() );
// then
LabelScanReader reader = store.newReader();
Set<Long> nodesWithLabel0 = asSet( reader.nodesWithLabel( (int) label0Id ) );
for ( long i = 0; i < 34; i++ )
{
assertThat( nodesWithLabel0, hasItem( i ) );
Set<Long> labels = asSet( reader.labelsForNode( i ) );
assertThat( labels, hasItem( label0Id ) );
}
}
private void write( Iterator<NodeLabelUpdate> iterator ) throws IOException
{
try ( LabelScanWriter writer = store.newWriter() )
{
while ( iterator.hasNext() )
{
writer.write( iterator.next() );
}
}
}
private long[] sorted( long[] input )
{
Arrays.sort( input );
return input;
}
@Test
public void shouldRebuildFromScratchIfIndexMissing() throws Exception
{
// GIVEN a start of the store with existing data in it
start( asList(
labelChanges( 1, NO_LABELS, new long[] {1} ),
labelChanges( 2, NO_LABELS, new long[] {1, 2} )
) );
// THEN
assertTrue( "Didn't rebuild the store on startup",
monitor.noIndexCalled&monitor.rebuildingCalled&monitor.rebuiltCalled );
assertNodesForLabel( 1,
1, 2 );
assertNodesForLabel( 2,
2 );
}
@Test
public void shouldRefuseStartIfIndexCorrupted() throws Exception
{
// GIVEN a start of the store with existing data in it
usePersistentDirectory();
List<NodeLabelUpdate> data = asList(
labelChanges( 1, NO_LABELS, new long[] {1} ),
labelChanges( 2, NO_LABELS, new long[] {1, 2} ) );
start( data );
// WHEN the index is corrupted and then started again
try
{
scrambleIndexFilesAndRestart( data );
fail("Should not have been able to start.");
}
catch( LifecycleException e )
{
assertThat(e.getCause(), instanceOf( IOException.class ));
assertThat(e.getCause().getMessage(), equalTo(
"Label scan store is corrupted, and needs to be rebuilt. To trigger a rebuild, ensure the " +
"database is stopped, delete the files in '"+dir.getAbsolutePath()+"', and then start the " +
"database again." ));
}
}
@Test
public void shouldFindDecentAmountOfNodesForALabel() throws Exception
{
// GIVEN
// 16 is the magic number of the page iterator
// 32 is the number of nodes in each lucene document
final int labelId = 1, nodeCount = 32*16 + 10;
start();
write( new PrefetchingIterator<NodeLabelUpdate>()
{
private int i = -1;
@Override
protected NodeLabelUpdate fetchNextOrNull()
{
return ++i < nodeCount ? labelChanges( i, NO_LABELS, new long[]{labelId} ) : null;
}
} );
// WHEN
Set<Long> nodeSet = new TreeSet<>();
LabelScanReader reader = store.newReader();
PrimitiveLongIterator nodes = reader.nodesWithLabel( labelId );
while ( nodes.hasNext() )
{
nodeSet.add( nodes.next() );
}
reader.close();
// THEN
assertEquals( "Found gaps in node id range: " + gaps( nodeSet, nodeCount ), nodeCount, nodeSet.size() );
}
@Test
public void shouldFindAllLabelsForGivenNode() throws Exception
{
// GIVEN
// 16 is the magic number of the page iterator
// 32 is the number of nodes in each lucene document
final long labelId1 = 1, labelId2 = 2, labelId3 = 87;
start();
int nodeId = 42;
write( IteratorUtil.iterator( labelChanges( nodeId, NO_LABELS, new long[]{labelId1, labelId2} ) ) );
write( IteratorUtil.iterator( labelChanges( 41, NO_LABELS, new long[]{labelId3, labelId2} ) ) );
// WHEN
LabelScanReader reader = store.newReader();
// THEN
assertThat( asSet( reader.labelsForNode( nodeId ) ), hasItems(labelId1, labelId2) );
reader.close();
}
private Set<Long> gaps( Set<Long> ids, int expectedCount )
{
Set<Long> gaps = new HashSet<>();
for ( long i = 0; i < expectedCount; i++ )
{
if ( !ids.contains( i ) )
{
gaps.add( i );
}
}
return gaps;
}
private final LabelScanStorageStrategy strategy;
public LuceneLabelScanStoreTest( LabelScanStorageStrategy strategy )
{
this.strategy = strategy;
}
@Parameterized.Parameters(name = "{0}")
public static List<Object[]> parameterizedWithStrategies()
{
return asList(
new Object[]{
new NodeRangeDocumentLabelScanStorageStrategy(
BitmapDocumentFormat._32 )},
new Object[]{
new NodeRangeDocumentLabelScanStorageStrategy(
BitmapDocumentFormat._64 )}
);
}
private void assertNodesForLabel( int labelId, long... expectedNodeIds )
{
Set<Long> nodeSet = new HashSet<>();
PrimitiveLongIterator nodes = store.newReader().nodesWithLabel( labelId );
while ( nodes.hasNext() )
{
nodeSet.add( nodes.next() );
}
for ( long expectedNodeId : expectedNodeIds )
{
assertTrue( "Expected node " + expectedNodeId + " not found in scan store",
nodeSet.remove( expectedNodeId ) );
}
assertTrue( "Unexpected nodes in scan store " + nodeSet, nodeSet.isEmpty() );
}
private final File dir = TargetDirectory.forTest( getClass() ).cleanDirectory( "lucene" );
private final Random random = new Random();
private DirectoryFactory directoryFactory = new DirectoryFactory.InMemoryDirectoryFactory();
private LifeSupport life;
private TrackingMonitor monitor;
private LuceneLabelScanStore store;
private List<NodeLabelUpdate> noData()
{
return emptyList();
}
private void usePersistentDirectory()
{
directoryFactory = DirectoryFactory.PERSISTENT;
}
private void start()
{
start( noData() );
}
private void start( List<NodeLabelUpdate> existingData )
{
life = new LifeSupport();
monitor = new TrackingMonitor();
store = life.add( new LuceneLabelScanStore(
strategy,
directoryFactory, dir, new DefaultFileSystemAbstraction(), standard(), asStream( existingData ),
monitor ) );
life.start();
assertTrue( monitor.initCalled );
}
private FullStoreChangeStream asStream( final List<NodeLabelUpdate> existingData )
{
return new FullStoreChangeStream()
{
@Override
public Iterator<NodeLabelUpdate> iterator()
{
return existingData.iterator();
}
@Override
public long highestNodeId()
{
return existingData.size(); // Well... not really
}
@Override
public PrimitiveLongIterator labelIds()
{
return emptyPrimitiveLongIterator();
}
};
}
private void scrambleIndexFilesAndRestart( List<NodeLabelUpdate> data ) throws IOException
{
shutdown();
File[] files = dir.listFiles();
if ( files != null )
{
for ( File indexFile : files )
{
scrambleFile( indexFile );
}
}
start( data );
}
private void scrambleFile( File file ) throws IOException
{
try ( RandomAccessFile fileAccess = new RandomAccessFile( file, "rw" );
FileChannel channel = fileAccess.getChannel() )
{
// The files will be small, so OK to allocate a buffer for the full size
byte[] bytes = new byte[(int) channel.size()];
putRandomBytes( bytes );
ByteBuffer buffer = ByteBuffer.wrap( bytes );
channel.position( 0 );
channel.write( buffer );
}
}
private void putRandomBytes( byte[] bytes )
{
for ( int i = 0; i < bytes.length; i++ )
{
bytes[i] = (byte) random.nextInt();
}
}
@Before
public void clearDir() throws IOException
{
if(dir.exists())
{
deleteRecursively( dir );
}
}
@After
public void shutdown() throws IOException
{
life.shutdown();
}
private static class TrackingMonitor implements LuceneLabelScanStore.Monitor
{
boolean initCalled, rebuildingCalled, rebuiltCalled, noIndexCalled;
@Override
public void noIndex()
{
noIndexCalled = true;
}
@Override
public void lockedIndex( LockObtainFailedException e )
{
}
@Override
public void corruptIndex( IOException corruptionException )
{
}
@Override
public void rebuilding()
{
rebuildingCalled = true;
}
@Override
public void rebuilt( long roughNodeCount )
{
rebuiltCalled = true;
}
@Override
public void init()
{
initCalled = true;
}
}
}
| false
|
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_LuceneLabelScanStoreTest.java
|
4,651
|
@Service.Implementation(KernelExtensionFactory.class)
public class LuceneLabelScanStoreExtension extends KernelExtensionFactory<LuceneLabelScanStoreExtension.Dependencies>
{
private final int priority;
private final Monitor monitor;
public interface Dependencies
{
Config getConfig();
FileSystemAbstraction getFileSystem();
NeoStoreProvider getNeoStoreProvider();
Logging getLogging();
}
public LuceneLabelScanStoreExtension()
{
this( 10, null );
}
LuceneLabelScanStoreExtension( int priority, Monitor monitor )
{
super( "lucene");
this.priority = priority;
this.monitor = monitor;
}
@Override
public LabelScanStoreProvider newKernelExtension( Dependencies dependencies ) throws Throwable
{
DirectoryFactory directoryFactory = directoryFactory( dependencies.getConfig(), dependencies.getFileSystem() );
File storeDir = dependencies.getConfig().get( GraphDatabaseSettings.store_dir );
LuceneLabelScanStore scanStore = new LuceneLabelScanStore(
new NodeRangeDocumentLabelScanStorageStrategy(),
// <db>/schema/label/lucene
directoryFactory, new File( new File( new File( storeDir, "schema" ), "label" ), "lucene" ),
dependencies.getFileSystem(), standard(),
fullStoreLabelUpdateStream( dependencies.getNeoStoreProvider() ),
monitor != null ? monitor : loggerMonitor( dependencies.getLogging() ) );
return new LabelScanStoreProvider( scanStore, priority );
}
}
| false
|
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_LuceneLabelScanStoreExtension.java
|
4,652
|
{
@Override
public PrimitiveLongIterator nodesWithLabel( int labelId )
{
return strategy.nodesWithLabel( searcher, labelId );
}
@Override
public void close()
{
try
{
releaseSearcher( searcher );
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
}
@Override
public Iterator<Long> labelsForNode( long nodeId )
{
return strategy.labelsForNode(searcher, nodeId);
}
};
| false
|
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_LuceneLabelScanStore.java
|
4,653
|
{
@Override
public void init()
{ // Don't log anything here
}
@Override
public void noIndex()
{
logger.info( "No lucene scan store index found, this might just be first use. " +
"Preparing to rebuild." );
}
@Override
public void lockedIndex( LockObtainFailedException e )
{
logger.warn( "Index is locked by another process or database", e );
}
@Override
public void corruptIndex( IOException corruptionException )
{
logger.warn( "Corrupt lucene scan store index found. Preparing to rebuild.",
corruptionException );
}
@Override
public void rebuilding()
{
logger.info( "Rebuilding lucene scan store, this may take a while" );
}
@Override
public void rebuilt( long highNodeId )
{
logger.info( "Lucene scan store rebuilt (roughly " + highNodeId + " nodes)" );
}
};
| false
|
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_LuceneLabelScanStore.java
|
4,654
|
public class LuceneLabelScanStore
implements LabelScanStore, LabelScanStorageStrategy.StorageService
{
private final LabelScanStorageStrategy strategy;
private final DirectoryFactory directoryFactory;
private final LuceneIndexWriterFactory writerFactory;
// We get in a full store stream here in case we need to fully rebuild the store if it's missing or corrupted.
private final FullStoreChangeStream fullStoreStream;
private final Monitor monitor;
private Directory directory;
private SearcherManager searcherManager;
private IndexWriter writer;
private boolean needsRebuild;
private final File directoryLocation;
private final FileSystemAbstraction fs;
public interface Monitor
{
void init();
void noIndex();
void lockedIndex( LockObtainFailedException e );
void corruptIndex( IOException e );
void rebuilding();
void rebuilt( long roughNodeCount );
}
public static Monitor loggerMonitor( Logging logging )
{
final StringLogger logger = logging.getMessagesLog( LuceneLabelScanStore.class );
return new Monitor()
{
@Override
public void init()
{ // Don't log anything here
}
@Override
public void noIndex()
{
logger.info( "No lucene scan store index found, this might just be first use. " +
"Preparing to rebuild." );
}
@Override
public void lockedIndex( LockObtainFailedException e )
{
logger.warn( "Index is locked by another process or database", e );
}
@Override
public void corruptIndex( IOException corruptionException )
{
logger.warn( "Corrupt lucene scan store index found. Preparing to rebuild.",
corruptionException );
}
@Override
public void rebuilding()
{
logger.info( "Rebuilding lucene scan store, this may take a while" );
}
@Override
public void rebuilt( long highNodeId )
{
logger.info( "Lucene scan store rebuilt (roughly " + highNodeId + " nodes)" );
}
};
}
public LuceneLabelScanStore( LabelScanStorageStrategy strategy, DirectoryFactory directoryFactory,
File directoryLocation, FileSystemAbstraction fs, LuceneIndexWriterFactory writerFactory,
FullStoreChangeStream fullStoreStream, Monitor monitor )
{
this.strategy = strategy;
this.directoryFactory = directoryFactory;
this.directoryLocation = directoryLocation;
this.fs = fs;
this.writerFactory = writerFactory;
this.fullStoreStream = fullStoreStream;
this.monitor = monitor;
}
@Override
public void deleteDocuments( Term documentTerm ) throws IOException
{
writer.deleteDocuments( documentTerm );
}
@Override
public void updateDocument( Term documentTerm, Document document ) throws IOException
{
writer.updateDocument( documentTerm, document );
}
@Override
public IndexSearcher acquireSearcher()
{
return searcherManager.acquire();
}
@Override
public void refreshSearcher() throws IOException
{
searcherManager.maybeRefresh();
}
@Override
public void releaseSearcher( IndexSearcher searcher ) throws IOException
{
searcherManager.release( searcher );
}
@Override
public AllEntriesLabelScanReader newAllEntriesReader()
{
return strategy.newNodeLabelReader( searcherManager );
}
@Override
public void recover( Iterator<NodeLabelUpdate> updates ) throws IOException
{
// The way we update and commit fits for recovery as well since we use writer.updateDocument(...)
// which deletes any existing documents and just adds the new and up-to-date version.
write( updates );
}
@Override
public void force()
{
try
{
writer.commit();
}
catch ( IOException e )
{
throw new UnderlyingStorageException( e );
}
}
@Override
public LabelScanReader newReader()
{
final IndexSearcher searcher = acquireSearcher();
return new LabelScanReader()
{
@Override
public PrimitiveLongIterator nodesWithLabel( int labelId )
{
return strategy.nodesWithLabel( searcher, labelId );
}
@Override
public void close()
{
try
{
releaseSearcher( searcher );
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
}
@Override
public Iterator<Long> labelsForNode( long nodeId )
{
return strategy.labelsForNode(searcher, nodeId);
}
};
}
@Override
public ResourceIterator<File> snapshotStoreFiles() throws IOException
{
return new LuceneSnapshotter().snapshot( directoryLocation, writer );
}
@Override
public void init() throws IOException
{
monitor.init();
directory = directoryFactory.open( directoryLocation );
if ( !indexExists() )
{ // This is the first time we start up this scan store, prepare to rebuild from scratch later.
monitor.noIndex();
prepareRebuildOfIndex();
}
try
{
// Try to open it, this will throw exception if index is corrupt.
// Opening it directly using the writer may hide corruption problems.
IndexReader.open( directory ).close();
writer = writerFactory.create( directory );
}
catch ( IndexNotFoundException e )
{
// No index present, create one
monitor.noIndex();
prepareRebuildOfIndex();
writer = writerFactory.create( directory );
}
catch ( LockObtainFailedException e )
{
monitor.lockedIndex( e );
throw e;
}
catch( IOException e )
{
// The index was somehow corrupted, fail
monitor.corruptIndex( e );
throw new IOException( "Label scan store is corrupted, and needs to be rebuilt. " +
"To trigger a rebuild, ensure the database is stopped, delete the files in '" +
directoryLocation.getAbsolutePath() + "', and then start the database again." );
}
searcherManager = new SearcherManager( writer, true, new SearcherFactory() );
}
@Override
public void start() throws IOException
{
if ( needsRebuild )
{ // we saw in init() that we need to rebuild the index, so do it here after the
// neostore has been properly started.
monitor.rebuilding();
write( fullStoreStream.iterator() );
monitor.rebuilt( fullStoreStream.highestNodeId() );
needsRebuild = false;
}
}
private void write( Iterator<NodeLabelUpdate> updates ) throws IOException
{
try ( LabelScanWriter writer = newWriter() )
{
while ( updates.hasNext() )
{
writer.write( updates.next() );
}
}
}
@Override
public void stop()
{ // Not needed
}
@Override
public void shutdown() throws IOException
{
searcherManager.close();
writer.close( true );
directory.close();
directory = null;
}
@Override
public LabelScanWriter newWriter()
{
return strategy.acquireWriter( this );
}
private boolean indexExists()
{
if ( !fs.fileExists( directoryLocation ) )
{
return false;
}
File[] files = fs.listFiles( directoryLocation );
return files != null && files.length > 0;
}
private void prepareRebuildOfIndex() throws IOException
{
directory.close();
fs.deleteRecursively( directoryLocation );
fs.mkdirs( directoryLocation );
needsRebuild = true;
directory = directoryFactory.open( directoryLocation );
}
}
| false
|
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_LuceneLabelScanStore.java
|
4,655
|
{
@Override
public DirectoryFactory apply( Class<DirectoryFactory> directoryFactoryClass )
{
return new DirectoryFactory.InMemoryDirectoryFactory();
}
};
| false
|
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_LuceneKernelExtensions.java
|
4,656
|
public class LuceneKernelExtensions
{
public static DirectoryFactory directoryFactory( Config config, FileSystemAbstraction fileSystem )
{
if ( config.get( InternalAbstractGraphDatabase.Configuration.ephemeral ) )
{
return fileSystem.getOrCreateThirdPartyFileSystem( DirectoryFactory.class, IN_MEMORY_FACTORY );
}
return fileSystem.getOrCreateThirdPartyFileSystem( DirectoryFactory.class,
Functions.<Class<DirectoryFactory>, DirectoryFactory>constant( DirectoryFactory.PERSISTENT ) );
}
public static final Function<Class<DirectoryFactory>, DirectoryFactory> IN_MEMORY_FACTORY =
new Function<Class<DirectoryFactory>, DirectoryFactory>()
{
@Override
public DirectoryFactory apply( Class<DirectoryFactory> directoryFactoryClass )
{
return new DirectoryFactory.InMemoryDirectoryFactory();
}
};
}
| false
|
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_LuceneKernelExtensions.java
|
4,657
|
{
@Override
public int compareTo( SchemaIndexProvider o )
{
return 1;
}
};
| false
|
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_LuceneIndexRecoveryIT.java
|
4,658
|
{
@Override
public Lifecycle newKernelExtension( LuceneSchemaIndexProviderFactory.Dependencies dependencies )
throws Throwable
{
return new LuceneSchemaIndexProvider( ignoreCloseDirectoryFactory, dependencies.getConfig() )
{
@Override
public int compareTo( SchemaIndexProvider o )
{
return 1;
}
};
}
};
| false
|
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_LuceneIndexRecoveryIT.java
|
4,659
|
{
@Override
public InternalIndexState getInitialState( long indexId )
{
return InternalIndexState.POPULATING;
}
};
| false
|
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_LuceneIndexRecoveryIT.java
|
4,660
|
{
@Override
public Lifecycle newKernelExtension( LuceneSchemaIndexProviderFactory.Dependencies dependencies )
throws Throwable
{
return new LuceneSchemaIndexProvider( ignoreCloseDirectoryFactory, dependencies.getConfig() )
{
@Override
public InternalIndexState getInitialState( long indexId )
{
return InternalIndexState.POPULATING;
}
};
}
};
| false
|
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_LuceneIndexRecoveryIT.java
|
4,661
|
{
@Override
public void run()
{
db.shutdown();
db = null;
}
} );
| false
|
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_LuceneIndexRecoveryIT.java
|
4,662
|
{
@Override
public Directory open( File dir ) throws IOException
{
return directoryFactory.open( dir );
}
@Override
public void close()
{
}
@Override
public void dumpToZip( ZipOutputStream zip, byte[] scratchPad ) throws IOException
{
directoryFactory.dumpToZip( zip, scratchPad );
}
};
| false
|
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_LuceneIndexRecoveryIT.java
|
4,663
|
{
private int docId;
@Override
protected Document fetchNextOrNull()
{
Document document = null;
while ( document == null && isPossibleDocId( docId ) )
{
if ( ! deleted( docId ) )
{
document = getDocument( docId );
}
docId++;
}
return document;
}
};
| false
|
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_LuceneAllDocumentsReader.java
|
4,664
|
private static class TestMonitor implements LuceneLabelScanStore.Monitor
{
private volatile int callsTo_init;
private volatile int timesRebuiltWithData;
@Override
public void init()
{
callsTo_init++;
}
@Override
public void noIndex()
{
}
@Override
public void lockedIndex( LockObtainFailedException e )
{
}
@Override
public void corruptIndex( IOException e )
{
}
@Override
public void rebuilding()
{
}
@Override
public void rebuilt( long roughNodeCount )
{
// In HA each slave database will startup with an empty database before realizing that
// it needs to copy a store from its master, let alone find its master.
// So we're expecting one call to this method from each slave with node count == 0. Ignore those.
// We're tracking number of times we're rebuilding the index where there's data to rebuild,
// i.e. after the db has been copied from the master.
if ( roughNodeCount > 0 )
{
timesRebuiltWithData++;
}
}
}
| false
|
enterprise_ha_src_test_java_org_neo4j_kernel_api_impl_index_LabelScanStoreHaIT.java
|
4,665
|
public class NodeLabelUpdateNodeIdComparatorTest
{
@Test
public void shouldCompareNodeLabelUpdatesByNodeId() throws Exception
{
assertEquals( comparator().compare( updateWithId( 1 ), updateWithId( 1 ) ), 0);
assertEquals( comparator().compare( updateWithId( 2 ), updateWithId( 1 ) ), 1);
assertEquals( comparator().compare( updateWithId( 0 ), updateWithId( 1 ) ), -1);
}
private NodeLabelUpdateNodeIdComparator comparator()
{
return new NodeLabelUpdateNodeIdComparator();
}
private NodeLabelUpdate updateWithId( int nodeId )
{
return NodeLabelUpdate.labelChanges( nodeId, new long[]{}, new long[]{} );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_api_labelscan_NodeLabelUpdateNodeIdComparatorTest.java
|
4,666
|
public class UniqueConstraintViolationKernelException extends ConstraintViolationKernelException
{
private final int labelId;
private final int propertyKeyId;
private final Object value;
private final long existingNodeId;
public UniqueConstraintViolationKernelException( int labelId, int propertyKeyId, Object value, long existingNodeId )
{
super( "Node %d already exists with label %d and property %d=%s", existingNodeId, labelId, propertyKeyId, value );
this.labelId = labelId;
this.propertyKeyId = propertyKeyId;
this.value = value;
this.existingNodeId = existingNodeId;
}
@Override
public String getUserMessage( TokenNameLookup tokenNameLookup )
{
return format( "Node %d already exists with label %s and property \"%s\"=[%s]", existingNodeId,
tokenNameLookup.labelGetName( labelId ),
tokenNameLookup.propertyKeyGetName( propertyKeyId ),
value );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_api_exceptions_schema_UniqueConstraintViolationKernelException.java
|
4,667
|
public class TooManyLabelsException extends SchemaKernelException
{
public TooManyLabelsException( Throwable cause )
{
super( Status.Schema.LabelLimitReached, "The maximum number of labels available has been reached. Cannot create more labels.", cause );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_api_exceptions_schema_TooManyLabelsException.java
|
4,668
|
public class SchemaRuleNotFoundException extends SchemaKernelException
{
public SchemaRuleNotFoundException( String message )
{
super( Status.Schema.NoSuchSchemaRule, message );
}
public SchemaRuleNotFoundException( String message, Throwable cause )
{
super( Status.Schema.NoSuchSchemaRule, message, cause );
}
public SchemaRuleNotFoundException( long labelId, long propertyKeyId, String message )
{
this( message( labelId, propertyKeyId, message ) );
}
private static String message( long labelId, long propertyKeyId, String message )
{
return format( "Index rule(s) for label: %s and property: %s: %s", labelId, propertyKeyId, message );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_api_exceptions_schema_SchemaRuleNotFoundException.java
|
4,669
|
public abstract class SchemaKernelException extends KernelException
{
protected SchemaKernelException( Status statusCode, Throwable cause, String message, Object... parameters )
{
super( statusCode, cause, message, parameters );
}
public SchemaKernelException( Status statusCode, String message, Throwable cause )
{
super( statusCode, cause, message );
}
public SchemaKernelException( Status statusCode, String message )
{
super( statusCode, message );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_api_exceptions_schema_SchemaKernelException.java
|
4,670
|
public class NoSuchIndexException extends SchemaKernelException
{
private final IndexDescriptor descriptor;
private final static String message = "No such INDEX ON %s.";
public NoSuchIndexException( IndexDescriptor descriptor )
{
super( Status.Schema.NoSuchIndex, format( message, descriptor ) );
this.descriptor = descriptor;
}
@Override
public String getUserMessage( TokenNameLookup tokenNameLookup )
{
return format( message, descriptor.userDescription( tokenNameLookup ) );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_api_exceptions_schema_NoSuchIndexException.java
|
4,671
|
public class NoSuchConstraintException extends SchemaKernelException
{
private final UniquenessConstraint constraint;
private final static String message = "No such constraint %s.";
public NoSuchConstraintException( UniquenessConstraint constraint )
{
super( Status.Schema.NoSuchConstraint, format( message, constraint ) );
this.constraint = constraint;
}
@Override
public String getUserMessage( TokenNameLookup tokenNameLookup )
{
return format( message, constraint.userDescription( tokenNameLookup ) );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_api_exceptions_schema_NoSuchConstraintException.java
|
4,672
|
public class MalformedSchemaRuleException extends SchemaKernelException
{
public MalformedSchemaRuleException( Throwable cause, String message, Object... parameters )
{
super( Status.General.CorruptSchemaRule, cause, message, parameters );
}
public MalformedSchemaRuleException( String message, Throwable cause )
{
super( Status.General.CorruptSchemaRule, message, cause );
}
public MalformedSchemaRuleException( String message )
{
super( Status.General.CorruptSchemaRule, message );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_api_exceptions_schema_MalformedSchemaRuleException.java
|
4,673
|
public class IndexBrokenKernelException extends KernelException
{
public IndexBrokenKernelException( String indexFailureCause )
{
super( Status.General.FailedIndex, "The index is in a failed state: '%s'.", indexFailureCause );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_api_exceptions_schema_IndexBrokenKernelException.java
|
4,674
|
public class IndexBelongsToConstraintException extends SchemaKernelException
{
private final IndexDescriptor index;
private final static String message = "Index belongs to constraint: %s";
public IndexBelongsToConstraintException( IndexDescriptor index )
{
super( Status.Schema.IndexBelongsToConstraint, format( "Index belongs to constraint: %s", index ) );
this.index = index;
}
@Override
public String getUserMessage( TokenNameLookup tokenNameLookup )
{
return format( message, index.userDescription( tokenNameLookup ) );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_api_exceptions_schema_IndexBelongsToConstraintException.java
|
4,675
|
public class IllegalTokenNameException extends SchemaKernelException
{
public IllegalTokenNameException( String tokenName )
{
super( Status.Schema.IllegalTokenName,
String.format( "%s is not a valid token name. Only non-null, non-empty strings are allowed.",
tokenName != null ? "'" + tokenName + "'" : "Null" ) );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_api_exceptions_schema_IllegalTokenNameException.java
|
4,676
|
public class DropIndexFailureException extends SchemaKernelException
{
private final IndexDescriptor indexDescriptor;
private final static String message = "Unable to drop index on %s: %s";
public DropIndexFailureException( IndexDescriptor indexDescriptor, SchemaKernelException cause )
{
super( Status.Schema.IndexDropFailure, format( message, indexDescriptor, cause.getMessage() ), cause );
this.indexDescriptor = indexDescriptor;
}
@Override
public String getUserMessage( TokenNameLookup tokenNameLookup )
{
return format( message, indexDescriptor.userDescription( tokenNameLookup ),
((KernelException) getCause()).getUserMessage( tokenNameLookup ) );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_api_exceptions_schema_DropIndexFailureException.java
|
4,677
|
public class DropConstraintFailureException extends SchemaKernelException
{
private final UniquenessConstraint constraint;
public DropConstraintFailureException( UniquenessConstraint constraint, Throwable cause )
{
super( Status.Schema.ConstraintDropFailure, cause, "Unable to drop constraint %s: %s", constraint, cause.getMessage() );
this.constraint = constraint;
}
public UniquenessConstraint constraint()
{
return constraint;
}
@Override
public String getUserMessage( TokenNameLookup tokenNameLookup )
{
String message = "Unable to drop " + constraint.userDescription( tokenNameLookup );
if ( getCause() instanceof KernelException )
{
KernelException cause = (KernelException) getCause();
return String.format( "%s:%n%s", message, cause.getUserMessage( tokenNameLookup ) );
}
return message;
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_api_exceptions_schema_DropConstraintFailureException.java
|
4,678
|
public class CreateConstraintFailureException extends SchemaKernelException
{
private final UniquenessConstraint constraint;
public CreateConstraintFailureException( UniquenessConstraint constraint, Throwable cause )
{
super( Status.Schema.ConstraintCreationFailure, cause, "Unable to create constraint %s: %s", constraint,
cause.getMessage() );
this.constraint = constraint;
}
public UniquenessConstraint constraint()
{
return constraint;
}
@Override
public String getUserMessage( TokenNameLookup tokenNameLookup )
{
String message = "Unable to create " + constraint.userDescription( tokenNameLookup );
if ( getCause() instanceof KernelException )
{
KernelException cause = (KernelException) getCause();
return String.format( "%s:%n%s", message, cause.getUserMessage( tokenNameLookup ) );
}
return message;
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_api_exceptions_schema_CreateConstraintFailureException.java
|
4,679
|
public abstract class ConstraintViolationKernelException extends ConstraintValidationKernelException
{
protected ConstraintViolationKernelException( String message, Object... parameters )
{
super( message, parameters );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_api_exceptions_schema_ConstraintViolationKernelException.java
|
4,680
|
public static final class Evidence
{
private final IndexEntryConflictException conflict;
public Evidence( IndexEntryConflictException conflict )
{
this.conflict = conflict;
}
@Override
public boolean equals( Object o )
{
return this == o || !(o == null || getClass() != o.getClass()) &&
conflict.equals( ((Evidence) o).conflict );
}
@Override
public int hashCode()
{
return conflict.hashCode();
}
@Override
public String toString()
{
return "Evidence{" +
"conflict=" + conflict +
'}';
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_api_exceptions_schema_ConstraintVerificationFailedKernelException.java
|
4,681
|
public class ConstraintVerificationFailedKernelException extends KernelException
{
private final UniquenessConstraint constraint;
public static final class Evidence
{
private final IndexEntryConflictException conflict;
public Evidence( IndexEntryConflictException conflict )
{
this.conflict = conflict;
}
@Override
public boolean equals( Object o )
{
return this == o || !(o == null || getClass() != o.getClass()) &&
conflict.equals( ((Evidence) o).conflict );
}
@Override
public int hashCode()
{
return conflict.hashCode();
}
@Override
public String toString()
{
return "Evidence{" +
"conflict=" + conflict +
'}';
}
}
private final Set<Evidence> evidence;
public ConstraintVerificationFailedKernelException( UniquenessConstraint constraint, Set<Evidence> evidence )
{
super( Status.Schema.ConstraintVerificationFailure, "Existing data does not satisfy %s.", constraint );
this.constraint = constraint;
this.evidence = evidence;
}
public ConstraintVerificationFailedKernelException( UniquenessConstraint constraint, Throwable failure )
{
super( Status.Schema.ConstraintVerificationFailure, failure, "Failed to verify constraint %s: %s", constraint,
failure.getMessage() );
this.constraint = constraint;
this.evidence = null;
}
public Set<Evidence> evidence()
{
return evidence == null ? Collections.<Evidence>emptySet() : Collections.unmodifiableSet( evidence );
}
@Override
public String getUserMessage( TokenNameLookup tokenNameLookup )
{
StringBuilder message = new StringBuilder();
for ( Evidence evidenceItem : evidence() )
{
IndexEntryConflictException conflict = evidenceItem.conflict;
message.append( conflict.evidenceMessage(
tokenNameLookup.labelGetName( constraint.label() ),
tokenNameLookup.propertyKeyGetName( constraint.propertyKeyId() ) ) );
}
return message.toString();
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_api_exceptions_schema_ConstraintVerificationFailedKernelException.java
|
4,682
|
public abstract class ConstraintValidationKernelException extends KernelException
{
protected ConstraintValidationKernelException( String message, Object... parameters )
{
super( Status.Schema.ConstraintViolation, message, parameters );
}
protected ConstraintValidationKernelException( Throwable cause, String message, Object... parameters )
{
super( Status.Schema.ConstraintViolation, cause, message, parameters );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_api_exceptions_schema_ConstraintValidationKernelException.java
|
4,683
|
public class AlreadyIndexedException extends SchemaKernelException
{
private static final String MESSAGE = "Already indexed %s.";
private final IndexDescriptor descriptor;
public AlreadyIndexedException( IndexDescriptor descriptor )
{
super( Status.Schema.IndexAlreadyExists, String.format( MESSAGE, descriptor ) );
this.descriptor = descriptor;
}
@Override
public String getUserMessage( TokenNameLookup tokenNameLookup )
{
return String.format( String.format( MESSAGE, descriptor.userDescription( tokenNameLookup ) ) );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_api_exceptions_schema_AlreadyIndexedException.java
|
4,684
|
public class AlreadyConstrainedException extends SchemaKernelException
{
private final UniquenessConstraint constraint;
private final static String message = "Already constrained %s.";
public AlreadyConstrainedException( UniquenessConstraint constraint )
{
super( Status.Schema.ConstraintAlreadyExists, format( message, constraint ) );
this.constraint = constraint;
}
@Override
public String getUserMessage( TokenNameLookup tokenNameLookup )
{
return format( message, constraint.userDescription( tokenNameLookup ) );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_api_exceptions_schema_AlreadyConstrainedException.java
|
4,685
|
public class AddIndexFailureException extends SchemaKernelException
{
private final static String MESSAGE = "Unable to add index %s : %s";
private final int labelId;
private final int propertyKey;
public AddIndexFailureException( int labelId, int propertyKey, KernelException cause )
{
super( Status.Schema.IndexCreationFailure, format( MESSAGE, new IndexDescriptor( labelId, propertyKey ), cause.getMessage() ), cause );
this.labelId = labelId;
this.propertyKey = propertyKey;
}
@Override
public String getUserMessage( TokenNameLookup tokenNameLookup )
{
return String.format( format( MESSAGE,
new IndexDescriptor( labelId, propertyKey ).userDescription( tokenNameLookup ),
((KernelException) getCause()).getUserMessage( tokenNameLookup ) ) );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_api_exceptions_schema_AddIndexFailureException.java
|
4,686
|
public class UnableToValidateConstraintKernelException extends ConstraintValidationKernelException
{
public UnableToValidateConstraintKernelException( Throwable cause )
{
super( cause, "Unable to validate constraint." );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_api_exceptions_schema_UnableToValidateConstraintKernelException.java
|
4,687
|
class AllNodesCollector extends Collector
{
static List<Long> getAllNodes( DirectoryFactory directoryFactory, File indexDir, Object propertyValue ) throws IOException
{
Directory directory = directoryFactory.open( indexDir );
SearcherManager manager = new SearcherManager( directory, new SearcherFactory() );
IndexSearcher searcher = manager.acquire();
try
{
List<Long> nodes = new ArrayList<Long>();
LuceneDocumentStructure documentStructure = new LuceneDocumentStructure();
searcher.search( documentStructure.newQuery( propertyValue ), new AllNodesCollector( documentStructure, nodes ) );
return nodes;
}
finally
{
manager.release( searcher );
manager.close();
directory.close();
}
}
private final List<Long> nodeIds;
private final LuceneDocumentStructure documentLogic;
private IndexReader reader;
AllNodesCollector( LuceneDocumentStructure documentLogic, List<Long> nodeIds )
{
this.documentLogic = documentLogic;
this.nodeIds = nodeIds;
}
@Override
public void setScorer( Scorer scorer ) throws IOException
{
}
@Override
public void collect( int doc ) throws IOException
{
nodeIds.add( documentLogic.getNodeId( reader.document( doc ) ) );
}
@Override
public void setNextReader( IndexReader reader, int docBase ) throws IOException
{
this.reader = reader;
}
@Override
public boolean acceptsDocsOutOfOrder()
{
return true;
}
}
| false
|
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_AllNodesCollector.java
|
4,688
|
{
@Override
public void initializeStoreDir( int serverId, File storeDir ) throws IOException
{
if ( serverId == 1 )
{
GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase(
storeDir.getAbsolutePath() );
try
{
createSomeLabeledNodes( db,
new Label[] {Labels.First},
new Label[] {Labels.First, Labels.Second},
new Label[] {Labels.Second} );
}
finally
{
db.shutdown();
}
}
}
} ).build();
| false
|
enterprise_ha_src_test_java_org_neo4j_kernel_api_impl_index_LabelScanStoreHaIT.java
|
4,689
|
_32( BitmapFormat._32 )
{
@Override
protected NumericField setFieldValue( NumericField field, long bitmap )
{
assert (bitmap & 0xFFFFFFFF00000000L) == 0 :
"Tried to store a bitmap as int, but which had values outside int limits";
return field.setIntValue( (int) bitmap );
}
},
| false
|
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_BitmapDocumentFormat.java
|
4,690
|
public class LabelScanStoreHaIT
{
@Test
public void shouldCopyLabelScanStoreToNewSlaves() throws Exception
{
// This check is here o check so that the extension provided by this test is selected.
// It can be higher than 3 (number of cluster members) since some members may restart
// some services to switch role.
assertTrue( monitor.callsTo_init >= 3 );
// GIVEN
// An HA cluster where the master started with initial data consisting
// of a couple of nodes, each having one or more properties.
// The cluster starting up should have the slaves copy their stores from the master
// and get the label scan store with it.
// THEN
assertEquals( "Expected noone to build their label scan store index.",
0, monitor.timesRebuiltWithData );
for ( GraphDatabaseService db : cluster.getAllMembers() )
{
assertEquals( 2, numberOfNodesHavingLabel( db, Labels.First ) );
assertEquals( 2, numberOfNodesHavingLabel( db, Labels.First ) );
}
}
private int numberOfNodesHavingLabel( GraphDatabaseService db, Label label )
{
try ( Transaction tx = db.beginTx() )
{
int count = count( GlobalGraphOperations.at( db ).getAllNodesWithLabel( label ) );
tx.success();
return count;
}
}
private void createSomeLabeledNodes( GraphDatabaseService db, Label[]... labelArrays )
{
try ( Transaction tx = db.beginTx() )
{
for ( Label[] labels : labelArrays )
{
db.createNode( labels );
}
tx.success();
}
}
private static enum Labels implements Label
{
First,
Second;
}
private final File rootDirectory = TargetDirectory.forTest( getClass() ).cleanDirectory( "root" );
private ClusterManager clusterManager;
private final LifeSupport life = new LifeSupport();
private ManagedCluster cluster;
private final TestMonitor monitor = new TestMonitor();
@Before
public void setup()
{
KernelExtensionFactory<?> testExtension = new LuceneLabelScanStoreExtension( 100, monitor );
HighlyAvailableGraphDatabaseFactory factory = new HighlyAvailableGraphDatabaseFactory();
factory.addKernelExtensions( Arrays.<KernelExtensionFactory<?>>asList( testExtension ) );
clusterManager = new ClusterManager.Builder( rootDirectory )
.withDbFactory( factory )
.withStoreDirInitializer( new ClusterManager.StoreDirInitializer()
{
@Override
public void initializeStoreDir( int serverId, File storeDir ) throws IOException
{
if ( serverId == 1 )
{
GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase(
storeDir.getAbsolutePath() );
try
{
createSomeLabeledNodes( db,
new Label[] {Labels.First},
new Label[] {Labels.First, Labels.Second},
new Label[] {Labels.Second} );
}
finally
{
db.shutdown();
}
}
}
} ).build();
life.add( clusterManager );
life.start();
cluster = clusterManager.getDefaultCluster();
cluster.await( allSeesAllAsAvailable() );
cluster.await( allAvailabilityGuardsReleased() );
}
@After
public void teardown()
{
life.shutdown();
}
private static class TestMonitor implements LuceneLabelScanStore.Monitor
{
private volatile int callsTo_init;
private volatile int timesRebuiltWithData;
@Override
public void init()
{
callsTo_init++;
}
@Override
public void noIndex()
{
}
@Override
public void lockedIndex( LockObtainFailedException e )
{
}
@Override
public void corruptIndex( IOException e )
{
}
@Override
public void rebuilding()
{
}
@Override
public void rebuilt( long roughNodeCount )
{
// In HA each slave database will startup with an empty database before realizing that
// it needs to copy a store from its master, let alone find its master.
// So we're expecting one call to this method from each slave with node count == 0. Ignore those.
// We're tracking number of times we're rebuilding the index where there's data to rebuild,
// i.e. after the db has been copied from the master.
if ( roughNodeCount > 0 )
{
timesRebuiltWithData++;
}
}
}
}
| false
|
enterprise_ha_src_test_java_org_neo4j_kernel_api_impl_index_LabelScanStoreHaIT.java
|
4,691
|
class IndexWriterStatus
{
private static final String KEY_STATUS = "status";
private static final String ONLINE = "online";
public void commitAsOnline( IndexWriter writer ) throws IOException
{
writer.commit( stringMap( KEY_STATUS, ONLINE ) );
}
public boolean isOnline( Directory directory ) throws IOException
{
if ( !IndexReader.indexExists( directory ) )
return false;
IndexReader reader = null;
try
{
reader = IndexReader.open( directory );
Map<String, String> userData = reader.getIndexCommit().getUserData();
return ONLINE.equals( userData.get( KEY_STATUS ) );
}
finally
{
if ( reader != null )
{
reader.close();
}
}
}
public void close( IndexWriter writer ) throws IOException
{
writer.close( true );
}
}
| false
|
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_IndexWriterStatus.java
|
4,692
|
{
@Override
public IndexWriter create( Directory directory ) throws IOException
{
IndexWriterConfig writerConfig = new IndexWriterConfig( Version.LUCENE_36, LuceneDataSource.KEYWORD_ANALYZER );
writerConfig.setMaxBufferedDocs( 100000 ); // TODO figure out depending on environment?
writerConfig.setIndexDeletionPolicy( new MultipleBackupDeletionPolicy() );
writerConfig.setTermIndexInterval( 14 );
return new IndexWriter( directory, writerConfig );
}
};
| false
|
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_IndexWriterFactories.java
|
4,693
|
public class IndexWriterFactories
{
public static LuceneIndexWriterFactory standard()
{
return new LuceneIndexWriterFactory()
{
@Override
public IndexWriter create( Directory directory ) throws IOException
{
IndexWriterConfig writerConfig = new IndexWriterConfig( Version.LUCENE_36, LuceneDataSource.KEYWORD_ANALYZER );
writerConfig.setMaxBufferedDocs( 100000 ); // TODO figure out depending on environment?
writerConfig.setIndexDeletionPolicy( new MultipleBackupDeletionPolicy() );
writerConfig.setTermIndexInterval( 14 );
return new IndexWriter( directory, writerConfig );
}
};
}
}
| false
|
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_IndexWriterFactories.java
|
4,694
|
public class HitsPrimitiveLongIterator extends AbstractPrimitiveLongIterator
{
private final Hits hits;
private final int size;
private int index;
private final LuceneDocumentStructure documentStructure;
public HitsPrimitiveLongIterator( Hits hits, LuceneDocumentStructure documentStructure )
{
this.hits = hits;
this.documentStructure = documentStructure;
size = hits.length();
computeNext();
}
@Override
protected void computeNext()
{
if ( index < size )
{
try
{
next( documentStructure.getNodeId( hits.doc( index++ ) ) );
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
}
else
{
endReached();
}
}
}
| false
|
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_HitsPrimitiveLongIterator.java
|
4,695
|
public class DirectorySupport
{
public static void deleteDirectoryContents(Directory directory) throws IOException
{
for (String fileName : directory.listAll())
directory.deleteFile( fileName );
}
}
| false
|
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_DirectorySupport.java
|
4,696
|
final class UncloseableDirectory extends Directory
{
private final Directory delegate;
public UncloseableDirectory(Directory delegate)
{
this.delegate = delegate;
}
@Override
public void close() throws IOException
{
// No-op
}
@Override
public String[] listAll() throws IOException
{
return delegate.listAll();
}
@Override
public boolean fileExists( String s ) throws IOException
{
return delegate.fileExists( s );
}
@Deprecated
@Override
public long fileModified( String s ) throws IOException
{
return delegate.fileModified( s );
}
@Override
@Deprecated
public void touchFile( String s ) throws IOException
{
delegate.touchFile( s );
}
@Override
public void deleteFile( String s ) throws IOException
{
delegate.deleteFile( s );
}
@Override
public long fileLength( String s ) throws IOException
{
return delegate.fileLength( s );
}
@Override
public IndexOutput createOutput( String s ) throws IOException
{
return delegate.createOutput( s );
}
@Override
@Deprecated
public void sync( String name ) throws IOException
{
delegate.sync( name );
}
@Override
public void sync( Collection<String> names ) throws IOException
{
delegate.sync( names );
}
@Override
public IndexInput openInput( String s ) throws IOException
{
return delegate.openInput( s );
}
@Override
public IndexInput openInput( String name, int bufferSize ) throws IOException
{
return delegate.openInput( name, bufferSize );
}
@Override
public Lock makeLock( final String name )
{
return delegate.makeLock( name );
}
@Override
public void clearLock( String name ) throws IOException
{
delegate.clearLock( name );
}
@Override
public void setLockFactory( LockFactory lockFactory ) throws IOException
{
delegate.setLockFactory( lockFactory );
}
@Override
public LockFactory getLockFactory()
{
return delegate.getLockFactory();
}
@Override
public String getLockID()
{
return delegate.getLockID();
}
@Override
public String toString()
{
return delegate.toString();
}
@Override
public void copy( Directory to, String src, String dest ) throws IOException
{
delegate.copy( to, src, dest );
}
@Deprecated
public static void copy( Directory src, Directory dest, boolean closeDirSrc ) throws IOException
{
Directory.copy( src, dest, closeDirSrc );
}
}
| false
|
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_DirectoryFactory.java
|
4,697
|
final class Single implements DirectoryFactory
{
private final Directory directory;
public Single( Directory directory )
{
this.directory = directory;
}
@Override
public Directory open( File dir ) throws IOException
{
return directory;
}
@Override
public void close()
{
}
@Override
public void dumpToZip( ZipOutputStream zip, byte[] scratchPad )
{
throw new UnsupportedOperationException();
}
}
| false
|
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_DirectoryFactory.java
|
4,698
|
final class InMemoryDirectoryFactory implements DirectoryFactory
{
private final Map<File, RAMDirectory> directories = new HashMap<File, RAMDirectory>( );
@Override
public synchronized Directory open( File dir ) throws IOException
{
if(!directories.containsKey( dir ))
{
directories.put( dir, new RAMDirectory() );
}
return new UncloseableDirectory(directories.get(dir));
}
@Override
public synchronized void close()
{
for ( RAMDirectory ramDirectory : directories.values() )
{
ramDirectory.close();
}
directories.clear();
}
@Override
public void dumpToZip( ZipOutputStream zip, byte[] scratchPad ) throws IOException
{
for ( Map.Entry<File, RAMDirectory> entry : directories.entrySet() )
{
RAMDirectory ramDir = entry.getValue();
for ( String fileName : ramDir.listAll() )
{
zip.putNextEntry( new ZipEntry( new File( entry.getKey(), fileName ).getAbsolutePath() ) );
copy( ramDir.openInput( fileName ), zip, scratchPad );
zip.closeEntry();
}
}
}
private static void copy( IndexInput source, OutputStream target, byte[] buffer ) throws IOException
{
for ( long remaining = source.length(),read; remaining > 0;remaining -= read)
{
read = min( remaining, buffer.length );
source.readBytes( buffer, 0, (int) read );
target.write( buffer, 0, (int) read );
}
}
}
| false
|
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_DirectoryFactory.java
|
4,699
|
{
@SuppressWarnings("ResultOfMethodCallIgnored")
@Override
public Directory open( File dir ) throws IOException
{
dir.mkdirs();
return FSDirectory.open( dir );
}
@Override
public void close()
{
// No resources to release. This method only exists as a hook for test implementations.
}
@Override
public void dumpToZip( ZipOutputStream zip, byte[] scratchPad )
{
// do nothing
}
};
| false
|
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_DirectoryFactory.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.