Unnamed: 0
int64
0
6.7k
func
stringlengths
12
89.6k
target
bool
2 classes
project
stringlengths
45
151
4,700
{ @Override public Void doWork( Void state ) throws Exception { try ( IndexUpdater secondUpdater = populator.newPopulatingUpdater( propertyAccessor ) ) { // Just open it and let it be closed } return null; } }, 5, SECONDS );
false
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_DeferredConstraintVerificationUniqueLuceneIndexPopulatorTest.java
4,701
{ @Override public Void doWork( Void state ) throws Exception { populator.verifyDeferredConstraints( propertyAccessor ); return null; } } );
false
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_DeferredConstraintVerificationUniqueLuceneIndexPopulatorTest.java
4,702
{ @Override public Void doWork( Void state ) throws Exception { try ( IndexUpdater updater = populator.newPopulatingUpdater( propertyAccessor ) ) { // Just open it and let it be closed } return null; } } );
false
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_DeferredConstraintVerificationUniqueLuceneIndexPopulatorTest.java
4,703
public class DeferredConstraintVerificationUniqueLuceneIndexPopulatorTest { @Test public void shouldVerifyThatThereAreNoDuplicates() throws Exception { populator.add( 1, "value1" ); populator.add( 2, "value2" ); populator.add( 3, "value3" ); // when populator.verifyDeferredConstraints( propertyAccessor ); populator.close( true ); // then assertEquals( asList( 1l ), getAllNodes( directoryFactory, indexDirectory, "value1" ) ); assertEquals( asList( 2l ), getAllNodes( directoryFactory, indexDirectory, "value2" ) ); assertEquals( asList( 3l ), getAllNodes( directoryFactory, indexDirectory, "value3" ) ); } @Test public void shouldUpdateEntryForNodeThatHasAlreadyBeenIndexed() throws Exception { populator.add( 1, "value1" ); // when IndexUpdater updater = populator.newPopulatingUpdater( propertyAccessor ); updater.process( NodePropertyUpdate.change( 1, PROPERTY_KEY_ID, "value1", new long[]{}, "value2", new long[]{} ) ); populator.close( true ); // then assertEquals( Collections.EMPTY_LIST, getAllNodes( directoryFactory, indexDirectory, "value1" ) ); assertEquals( asList( 1l ), getAllNodes( directoryFactory, indexDirectory, "value2" ) ); } @Test public void shouldUpdateEntryForNodeThatHasPropertyRemovedAndThenAddedAgain() throws Exception { populator.add( 1, "value1" ); // when IndexUpdater updater = populator.newPopulatingUpdater( propertyAccessor ); updater.process( NodePropertyUpdate.remove( 1, PROPERTY_KEY_ID, "value1", new long[]{} ) ); updater.process( NodePropertyUpdate.add( 1, PROPERTY_KEY_ID, "value1", new long[]{} ) ); populator.close( true ); // then assertEquals( asList(1l), getAllNodes( directoryFactory, indexDirectory, "value1" ) ); } @Test public void shouldRemoveEntryForNodeThatHasAlreadyBeenIndexed() throws Exception { populator.add( 1, "value1" ); // when IndexUpdater updater = populator.newPopulatingUpdater( propertyAccessor ); updater.process( NodePropertyUpdate.remove( 1, PROPERTY_KEY_ID, "value1", new long[]{} ) ); populator.close( true ); // then assertEquals( Collections.EMPTY_LIST, getAllNodes( directoryFactory, indexDirectory, "value1" ) ); } @Test public void shouldBeAbleToHandleSwappingOfIndexValues() throws Exception { populator.add( 1, "value1" ); populator.add( 2, "value2" ); // when IndexUpdater updater = populator.newPopulatingUpdater( propertyAccessor ); updater.process( NodePropertyUpdate.change( 1, PROPERTY_KEY_ID, "value1", new long[]{}, "value2", new long[]{} ) ); updater.process( NodePropertyUpdate.change( 2, PROPERTY_KEY_ID, "value2", new long[]{}, "value1", new long[]{} ) ); populator.close( true ); // then assertEquals( asList( 2l ), getAllNodes( directoryFactory, indexDirectory, "value1" ) ); assertEquals( asList( 1l ), getAllNodes( directoryFactory, indexDirectory, "value2" ) ); } @Test public void shouldFailAtVerificationStageWithAlreadyIndexedStringValue() throws Exception { String value = "value1"; populator.add( 1, value ); populator.add( 2, "value2" ); populator.add( 3, value ); when( propertyAccessor.getProperty( 1, PROPERTY_KEY_ID ) ).thenReturn( stringProperty( PROPERTY_KEY_ID, value ) ); when( propertyAccessor.getProperty( 3, PROPERTY_KEY_ID ) ).thenReturn( stringProperty( PROPERTY_KEY_ID, value ) ); // when try { populator.verifyDeferredConstraints( propertyAccessor ); fail( "should have thrown exception" ); } // then catch ( PreexistingIndexEntryConflictException conflict ) { assertEquals( 1, conflict.getExistingNodeId() ); assertEquals( value, conflict.getPropertyValue() ); assertEquals( 3, conflict.getAddedNodeId() ); } } @Test public void shouldFailAtVerificationStageWithAlreadyIndexedNumberValue() throws Exception { populator.add( 1, 1 ); populator.add( 2, 2 ); populator.add( 3, 1 ); when( propertyAccessor.getProperty( 1, PROPERTY_KEY_ID ) ).thenReturn( intProperty( PROPERTY_KEY_ID, 1 ) ); when( propertyAccessor.getProperty( 3, PROPERTY_KEY_ID ) ).thenReturn( intProperty( PROPERTY_KEY_ID, 1 ) ); // when try { populator.verifyDeferredConstraints( propertyAccessor ); fail( "should have thrown exception" ); } // then catch ( PreexistingIndexEntryConflictException conflict ) { assertEquals( 1, conflict.getExistingNodeId() ); assertEquals( 1, conflict.getPropertyValue() ); assertEquals( 3, conflict.getAddedNodeId() ); } } @Test public void shouldRejectDuplicateEntryWhenUsingPopulatingUpdater() throws Exception { populator.add( 1, "value1" ); populator.add( 2, "value2" ); when( propertyAccessor.getProperty( 1, PROPERTY_KEY_ID ) ).thenReturn( stringProperty( PROPERTY_KEY_ID, "value1" ) ); when( propertyAccessor.getProperty( 3, PROPERTY_KEY_ID ) ).thenReturn( stringProperty( PROPERTY_KEY_ID, "value1" ) ); // when try { IndexUpdater updater = populator.newPopulatingUpdater( propertyAccessor ); updater.process( NodePropertyUpdate.add( 3, PROPERTY_KEY_ID, "value1", new long[]{} ) ); updater.close(); fail( "should have thrown exception" ); } // then catch ( PreexistingIndexEntryConflictException conflict ) { assertEquals( 1, conflict.getExistingNodeId() ); assertEquals( "value1", conflict.getPropertyValue() ); assertEquals( 3, conflict.getAddedNodeId() ); } } @Test public void shouldRejectDuplicateEntryAfterUsingPopulatingUpdater() throws Exception { String value = "value1"; IndexUpdater updater = populator.newPopulatingUpdater( propertyAccessor ); updater.process( NodePropertyUpdate.add( 1, PROPERTY_KEY_ID, value, new long[]{} ) ); populator.add( 2, value ); when( propertyAccessor.getProperty( 1, PROPERTY_KEY_ID ) ).thenReturn( stringProperty( PROPERTY_KEY_ID, value ) ); when( propertyAccessor.getProperty( 2, PROPERTY_KEY_ID ) ).thenReturn( stringProperty( PROPERTY_KEY_ID, value ) ); // when try { populator.verifyDeferredConstraints( propertyAccessor ); fail( "should have thrown exception" ); } // then catch ( PreexistingIndexEntryConflictException conflict ) { assertEquals( 1, conflict.getExistingNodeId() ); assertEquals( value, conflict.getPropertyValue() ); assertEquals( 2, conflict.getAddedNodeId() ); } } @Test public void shouldNotRejectDuplicateEntryOnSameNodeIdAfterUsingPopulatingUpdater() throws Exception { when( propertyAccessor.getProperty( 1, PROPERTY_KEY_ID ) ).thenReturn( stringProperty( PROPERTY_KEY_ID, "value1" ) ); IndexUpdater updater = populator.newPopulatingUpdater( propertyAccessor ); updater.process( NodePropertyUpdate.add( 1, PROPERTY_KEY_ID, "value1", new long[]{} ) ); updater.process( NodePropertyUpdate.change( 1, PROPERTY_KEY_ID, "value1", new long[]{}, "value1", new long[]{} ) ); updater.close(); populator.add( 2, "value2" ); populator.add( 3, "value3" ); // when populator.verifyDeferredConstraints( propertyAccessor ); populator.close( true ); // then assertEquals( asList( 1l ), getAllNodes( directoryFactory, indexDirectory, "value1" ) ); assertEquals( asList( 2l ), getAllNodes( directoryFactory, indexDirectory, "value2" ) ); assertEquals( asList( 3l ), getAllNodes( directoryFactory, indexDirectory, "value3" ) ); } @Test public void shouldNotRejectIndexCollisionsCausedByPrecisionLossAsDuplicates() throws Exception { // Given we have a collision in our index... populator.add( 1, 1000000000000000001L ); populator.add( 2, 2 ); populator.add( 3, 1000000000000000001L ); // ... but the actual data in the store does not collide when( propertyAccessor.getProperty( 1, PROPERTY_KEY_ID ) ).thenReturn( longProperty( PROPERTY_KEY_ID, 1000000000000000001L ) ); when( propertyAccessor.getProperty( 3, PROPERTY_KEY_ID ) ).thenReturn( longProperty( PROPERTY_KEY_ID, 1000000000000000002L ) ); // Then our verification should NOT fail: populator.verifyDeferredConstraints( propertyAccessor ); } @Test public void shouldCheckAllCollisionsFromPopulatorAdd() throws Exception { int iterations = 228; // This value has to be high enough to stress the EntrySet implementation long[] labels = new long[0]; IndexUpdater updater = populator.newPopulatingUpdater( propertyAccessor ); for ( int nodeId = 0; nodeId < iterations; nodeId++ ) { updater.process( NodePropertyUpdate.add( nodeId, PROPERTY_KEY_ID, 1, labels ) ); when( propertyAccessor.getProperty( nodeId, PROPERTY_KEY_ID ) ).thenReturn( intProperty( PROPERTY_KEY_ID, nodeId ) ); } // ... and the actual conflicting property: updater.process( NodePropertyUpdate.add( iterations, PROPERTY_KEY_ID, 1, labels ) ); when( propertyAccessor.getProperty( iterations, PROPERTY_KEY_ID ) ).thenReturn( intProperty( PROPERTY_KEY_ID, 1 ) ); // This collision is real!!! // when try { updater.close(); fail( "should have thrown exception" ); } // then catch ( PreexistingIndexEntryConflictException conflict ) { assertEquals( 1, conflict.getExistingNodeId() ); assertEquals( 1, conflict.getPropertyValue() ); assertEquals( iterations, conflict.getAddedNodeId() ); } } @Test public void shouldCheckAllCollisionsFromUpdaterClose() throws Exception { int iterations = 228; // This value has to be high enough to stress the EntrySet implementation for ( int nodeId = 0; nodeId < iterations; nodeId++ ) { populator.add( nodeId, 1 ); when( propertyAccessor.getProperty( nodeId, PROPERTY_KEY_ID ) ).thenReturn( intProperty( PROPERTY_KEY_ID, nodeId ) ); } // ... and the actual conflicting property: populator.add( iterations, 1 ); when( propertyAccessor.getProperty( iterations, PROPERTY_KEY_ID ) ).thenReturn( intProperty( PROPERTY_KEY_ID, 1 ) ); // This collision is real!!! // when try { populator.verifyDeferredConstraints( propertyAccessor ); fail( "should have thrown exception" ); } // then catch ( PreexistingIndexEntryConflictException conflict ) { assertEquals( 1, conflict.getExistingNodeId() ); assertEquals( 1, conflict.getPropertyValue() ); assertEquals( iterations, conflict.getAddedNodeId() ); } } @Test public void shouldReleaseSearcherProperlyAfterVerifyingDeferredConstraints() throws Exception { /* * This test was created due to a problem in closing an index updater after deferred constraints * had been verified, where it got stuck in a busy loop in ReferenceManager#acquire. */ // GIVEN an index updater that we close OtherThreadExecutor<Void> executor = cleanup.add( new OtherThreadExecutor<Void>( "Deferred", null ) ); executor.execute( new WorkerCommand<Void, Void>() { @Override public Void doWork( Void state ) throws Exception { try ( IndexUpdater updater = populator.newPopulatingUpdater( propertyAccessor ) ) { // Just open it and let it be closed } return null; } } ); // ... and where we verify deferred constraints after executor.execute( new WorkerCommand<Void, Void>() { @Override public Void doWork( Void state ) throws Exception { populator.verifyDeferredConstraints( propertyAccessor ); return null; } } ); // WHEN doing more index updating after that // THEN it should be able to complete within a very reasonable time executor.execute( new WorkerCommand<Void, Void>() { @Override public Void doWork( Void state ) throws Exception { try ( IndexUpdater secondUpdater = populator.newPopulatingUpdater( propertyAccessor ) ) { // Just open it and let it be closed } return null; } }, 5, SECONDS ); } private static final int LABEL_ID = 1; private static final int PROPERTY_KEY_ID = 2; private final FailureStorage failureStorage = mock( FailureStorage.class ); private final long indexId = 1; private final DirectoryFactory.InMemoryDirectoryFactory directoryFactory = new DirectoryFactory.InMemoryDirectoryFactory(); private final IndexDescriptor descriptor = new IndexDescriptor( LABEL_ID, PROPERTY_KEY_ID ); private File indexDirectory; private LuceneDocumentStructure documentLogic; private PropertyAccessor propertyAccessor; private DeferredConstraintVerificationUniqueLuceneIndexPopulator populator; public final @Rule CleanupRule cleanup = new CleanupRule(); @Before public void setUp() throws Exception { indexDirectory = new File( "target/whatever" ); documentLogic = new LuceneDocumentStructure(); propertyAccessor = mock( PropertyAccessor.class ); populator = new DeferredConstraintVerificationUniqueLuceneIndexPopulator( documentLogic, standard(), new IndexWriterStatus(), directoryFactory, indexDirectory, failureStorage, indexId, descriptor ); populator.create(); } }
false
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_DeferredConstraintVerificationUniqueLuceneIndexPopulatorTest.java
4,704
private static class EntrySet { static final int INCREMENT = 100; Object[] value = new Object[INCREMENT]; long[] nodeId = new long[INCREMENT]; EntrySet next; public void reset() { EntrySet current = this; do { for (int i = 0; i < INCREMENT; i++) { current.value[i] = null; current.nodeId[i] = StatementConstants.NO_SUCH_NODE; } current = next; } while ( current != null ); } }
false
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_DeferredConstraintVerificationUniqueLuceneIndexPopulator.java
4,705
private static class DuplicateCheckingCollector extends Collector { private final PropertyAccessor accessor; private final LuceneDocumentStructure documentStructure; private final int propertyKeyId; private final EntrySet actualValues; private IndexReader reader; private int docBase; public DuplicateCheckingCollector( PropertyAccessor accessor, LuceneDocumentStructure documentStructure, int propertyKeyId ) { this.accessor = accessor; this.documentStructure = documentStructure; this.propertyKeyId = propertyKeyId; actualValues = new EntrySet(); } @Override public void setScorer( Scorer scorer ) throws IOException { } @Override public void collect( int doc ) throws IOException { try { doCollect( doc ); } catch ( KernelException e ) { throw new ThisShouldNotHappenError( "Chris", "Indexed node should exist and have the indexed property.", e ); } catch ( PreexistingIndexEntryConflictException e ) { throw new IOException( e ); } } private void doCollect( int doc ) throws IOException, KernelException, PreexistingIndexEntryConflictException { Document document = reader.document( doc ); long nodeId = documentStructure.getNodeId( document ); Property property = accessor.getProperty( nodeId, propertyKeyId ); // We either have to find the first conflicting entry set element, // or append one for the property we just fetched: EntrySet current = actualValues; scan:do { for ( int i = 0; i < EntrySet.INCREMENT; i++ ) { Object value = current.value[i]; if ( current.nodeId[i] == StatementConstants.NO_SUCH_NODE ) { current.value[i] = property.value(); current.nodeId[i] = nodeId; if ( i == EntrySet.INCREMENT - 1 ) { current.next = new EntrySet(); } break scan; } else if ( property.valueEquals( value ) ) { throw new PreexistingIndexEntryConflictException( value, current.nodeId[i], nodeId ); } } current = current.next; } while ( current != null ); } @Override public void setNextReader( IndexReader reader, int docBase ) throws IOException { this.reader = reader; this.docBase = docBase; } @Override public boolean acceptsDocsOutOfOrder() { return true; } public void reset() { actualValues.reset(); // TODO benchmark this vs. not clearing and instead creating a new object, perhaps } }
false
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_DeferredConstraintVerificationUniqueLuceneIndexPopulator.java
4,706
{ List<Object> updatedPropertyValues = new ArrayList<>(); @Override public void process( NodePropertyUpdate update ) throws IOException, IndexEntryConflictException { long nodeId = update.getNodeId(); switch ( update.getUpdateMode() ) { case ADDED: case CHANGED: // We don't look at the "before" value, so adding and changing idempotently is done the same way. writer.updateDocument( documentStructure.newQueryForChangeOrRemove( nodeId ), documentStructure.newDocumentRepresentingProperty( nodeId, update.getValueAfter() ) ); updatedPropertyValues.add( update.getValueAfter() ); break; case REMOVED: writer.deleteDocuments( documentStructure.newQueryForChangeOrRemove( nodeId ) ); break; default: throw new IllegalStateException( "Unknown update mode " + update.getUpdateMode() ); } } @Override public void close() throws IOException, IndexEntryConflictException { searcherManager.maybeRefresh(); IndexSearcher searcher = searcherManager.acquire(); try { DuplicateCheckingCollector collector = duplicateCheckingCollector( accessor ); for ( Object propertyValue : updatedPropertyValues ) { collector.reset(); Query query = documentStructure.newQuery( propertyValue ); searcher.search( query, collector ); } } catch ( IOException e ) { Throwable cause = e.getCause(); if ( cause instanceof IndexEntryConflictException ) { throw (IndexEntryConflictException) cause; } throw e; } finally { searcherManager.release( searcher ); } } @Override public void remove( Iterable<Long> nodeIds ) { throw new UnsupportedOperationException( "should not remove() from populating index" ); } };
false
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_DeferredConstraintVerificationUniqueLuceneIndexPopulator.java
4,707
class DeferredConstraintVerificationUniqueLuceneIndexPopulator extends LuceneIndexPopulator { private final IndexDescriptor descriptor; private SearcherManager searcherManager; DeferredConstraintVerificationUniqueLuceneIndexPopulator( LuceneDocumentStructure documentStructure, LuceneIndexWriterFactory indexWriterFactory, IndexWriterStatus writerStatus, DirectoryFactory dirFactory, File dirFile, FailureStorage failureStorage, long indexId, IndexDescriptor descriptor ) { super( documentStructure, indexWriterFactory, writerStatus, dirFactory, dirFile, failureStorage, indexId ); this.descriptor = descriptor; } @Override public void create() throws IOException { super.create(); searcherManager = new SearcherManager( writer, true, new SearcherFactory() ); } @Override public void drop() { } @Override protected void flush() throws IOException { // no need to do anything yet. } @Override public void add( long nodeId, Object propertyValue ) throws IndexEntryConflictException, IOException { writer.addDocument( documentStructure.newDocumentRepresentingProperty( nodeId, propertyValue ) ); } @Override public void verifyDeferredConstraints( PropertyAccessor accessor ) throws IndexEntryConflictException, IOException { searcherManager.maybeRefresh(); IndexSearcher searcher = searcherManager.acquire(); try { DuplicateCheckingCollector collector = duplicateCheckingCollector( accessor ); TermEnum terms = searcher.getIndexReader().terms(); while ( terms.next() ) { Term term = terms.term(); if ( !NODE_ID_KEY.equals( term.field() ) && terms.docFreq() > 1 ) { collector.reset(); searcher.search( new TermQuery( term ), collector ); } } } catch ( IOException e ) { Throwable cause = e.getCause(); if ( cause instanceof IndexEntryConflictException ) { throw (IndexEntryConflictException) cause; } throw e; } finally { searcherManager.release( searcher ); } } private DuplicateCheckingCollector duplicateCheckingCollector( PropertyAccessor accessor ) { return new DuplicateCheckingCollector( accessor, documentStructure, descriptor.getPropertyKeyId() ); } @Override public IndexUpdater newPopulatingUpdater( final PropertyAccessor accessor ) throws IOException { return new IndexUpdater() { List<Object> updatedPropertyValues = new ArrayList<>(); @Override public void process( NodePropertyUpdate update ) throws IOException, IndexEntryConflictException { long nodeId = update.getNodeId(); switch ( update.getUpdateMode() ) { case ADDED: case CHANGED: // We don't look at the "before" value, so adding and changing idempotently is done the same way. writer.updateDocument( documentStructure.newQueryForChangeOrRemove( nodeId ), documentStructure.newDocumentRepresentingProperty( nodeId, update.getValueAfter() ) ); updatedPropertyValues.add( update.getValueAfter() ); break; case REMOVED: writer.deleteDocuments( documentStructure.newQueryForChangeOrRemove( nodeId ) ); break; default: throw new IllegalStateException( "Unknown update mode " + update.getUpdateMode() ); } } @Override public void close() throws IOException, IndexEntryConflictException { searcherManager.maybeRefresh(); IndexSearcher searcher = searcherManager.acquire(); try { DuplicateCheckingCollector collector = duplicateCheckingCollector( accessor ); for ( Object propertyValue : updatedPropertyValues ) { collector.reset(); Query query = documentStructure.newQuery( propertyValue ); searcher.search( query, collector ); } } catch ( IOException e ) { Throwable cause = e.getCause(); if ( cause instanceof IndexEntryConflictException ) { throw (IndexEntryConflictException) cause; } throw e; } finally { searcherManager.release( searcher ); } } @Override public void remove( Iterable<Long> nodeIds ) { throw new UnsupportedOperationException( "should not remove() from populating index" ); } }; } private static class DuplicateCheckingCollector extends Collector { private final PropertyAccessor accessor; private final LuceneDocumentStructure documentStructure; private final int propertyKeyId; private final EntrySet actualValues; private IndexReader reader; private int docBase; public DuplicateCheckingCollector( PropertyAccessor accessor, LuceneDocumentStructure documentStructure, int propertyKeyId ) { this.accessor = accessor; this.documentStructure = documentStructure; this.propertyKeyId = propertyKeyId; actualValues = new EntrySet(); } @Override public void setScorer( Scorer scorer ) throws IOException { } @Override public void collect( int doc ) throws IOException { try { doCollect( doc ); } catch ( KernelException e ) { throw new ThisShouldNotHappenError( "Chris", "Indexed node should exist and have the indexed property.", e ); } catch ( PreexistingIndexEntryConflictException e ) { throw new IOException( e ); } } private void doCollect( int doc ) throws IOException, KernelException, PreexistingIndexEntryConflictException { Document document = reader.document( doc ); long nodeId = documentStructure.getNodeId( document ); Property property = accessor.getProperty( nodeId, propertyKeyId ); // We either have to find the first conflicting entry set element, // or append one for the property we just fetched: EntrySet current = actualValues; scan:do { for ( int i = 0; i < EntrySet.INCREMENT; i++ ) { Object value = current.value[i]; if ( current.nodeId[i] == StatementConstants.NO_SUCH_NODE ) { current.value[i] = property.value(); current.nodeId[i] = nodeId; if ( i == EntrySet.INCREMENT - 1 ) { current.next = new EntrySet(); } break scan; } else if ( property.valueEquals( value ) ) { throw new PreexistingIndexEntryConflictException( value, current.nodeId[i], nodeId ); } } current = current.next; } while ( current != null ); } @Override public void setNextReader( IndexReader reader, int docBase ) throws IOException { this.reader = reader; this.docBase = docBase; } @Override public boolean acceptsDocsOutOfOrder() { return true; } public void reset() { actualValues.reset(); // TODO benchmark this vs. not clearing and instead creating a new object, perhaps } } /** * A small struct of arrays of nodeId + property value pairs, with a next pointer. * Should exhibit fairly fast linear iteration, small memory overhead and dynamic growth. * * NOTE: Must always call reset() before use! */ private static class EntrySet { static final int INCREMENT = 100; Object[] value = new Object[INCREMENT]; long[] nodeId = new long[INCREMENT]; EntrySet next; public void reset() { EntrySet current = this; do { for (int i = 0; i < INCREMENT; i++) { current.value[i] = null; current.nodeId[i] = StatementConstants.NO_SUCH_NODE; } current = next; } while ( current != null ); } } }
false
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_DeferredConstraintVerificationUniqueLuceneIndexPopulator.java
4,708
_64( BitmapFormat._64 ) { @Override protected NumericField setFieldValue( NumericField field, long bitmap ) { return field.setLongValue( bitmap ); } };
false
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_BitmapDocumentFormat.java
4,709
public class LuceneLabelScanWriter implements LabelScanWriter { private final LabelScanStorageStrategy.StorageService storage; private final BitmapDocumentFormat format; private final IndexSearcher searcher; private List<NodeLabelUpdate> updates; private long currentRange; public LuceneLabelScanWriter( LabelScanStorageStrategy.StorageService storage, BitmapDocumentFormat format ) { this.storage = storage; this.format = format; currentRange = -1; updates = new ArrayList<>( format.bitmapFormat().rangeSize() ); searcher = storage.acquireSearcher(); } @Override public void write( NodeLabelUpdate update ) throws IOException { long range = format.bitmapFormat().rangeOf( update.getNodeId() ); if ( range != currentRange ) { if ( range < currentRange ) { throw new IllegalArgumentException( "NodeLabelUpdates must be supplied in order of ascending node id" ); } flush(); currentRange = range; } updates.add( update ); } @Override public void close() throws IOException { flush(); storage.releaseSearcher( searcher ); storage.refreshSearcher(); } private Map<Long/*range*/, Bitmap> readLabelBitMapsInRange( IndexSearcher searcher, long range ) throws IOException { Map<Long/*label*/, Bitmap> fields = new HashMap<>(); Term documentTerm = format.rangeTerm( range ); TopDocs docs = searcher.search( new TermQuery( documentTerm ), 1 ); if ( docs != null && docs.totalHits != 0 ) { Document document = searcher.doc( docs.scoreDocs[0].doc ); for ( Fieldable field : document.getFields() ) { if ( !format.isRangeField( field ) ) { Long label = Long.valueOf( field.name() ); fields.put( label, format.readBitmap( field ) ); } } } return fields; } private void flush() throws IOException { if ( currentRange < 0 ) { return; } Map<Long/*label*/, Bitmap> fields = readLabelBitMapsInRange( searcher, currentRange ); updateFields( updates, fields ); Document document = new Document(); document.add( format.rangeField( currentRange ) ); for ( Map.Entry<Long/*label*/, Bitmap> field : fields.entrySet() ) { // one field per label Bitmap value = field.getValue(); if ( value.hasContent() ) { format.addLabelField( document, field.getKey(), value ); } } if ( isEmpty( document ) ) { storage.deleteDocuments( format.rangeTerm( document ) ); } else { storage.updateDocument( format.rangeTerm( document ), document ); } updates.clear(); } private boolean isEmpty( Document document ) { for ( Fieldable fieldable : document.getFields() ) { if ( !format.isRangeField( fieldable ) ) { return false; } } return true; } private void updateFields( Iterable<NodeLabelUpdate> updates, Map<Long/*label*/, Bitmap> fields ) { for ( NodeLabelUpdate update : updates ) { clearLabels( fields, update ); setLabels( fields, update ); } } private void clearLabels( Map<Long, Bitmap> fields, NodeLabelUpdate update ) { for ( Bitmap bitmap : fields.values() ) { format.bitmapFormat().set( bitmap, update.getNodeId(), false ); } } private void setLabels( Map<Long, Bitmap> fields, NodeLabelUpdate update ) { for ( long label : update.getLabelsAfter() ) { Bitmap bitmap = fields.get( label ); if ( bitmap == null ) { fields.put( label, bitmap = new Bitmap() ); } format.bitmapFormat().set( bitmap, update.getNodeId(), true ); } } }
false
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_LuceneLabelScanWriter.java
4,710
public class LuceneNodeLabelRange implements NodeLabelRange { private final int id; private final long[] nodeIds; private final long[][] labelIds; public LuceneNodeLabelRange( int id, long[] nodeIds, long[][] labelIds ) { this.id = id; this.labelIds = labelIds; this.nodeIds = nodeIds; } @Override public String toString() { StringBuilder result = new StringBuilder( "NodeLabelRange[docId=" ).append( id ); result.append( "; {" ); for ( int i = 0; i < nodeIds.length; i++ ) { if ( i != 0 ) { result.append( ", " ); } result.append( "Node[" ).append( nodeIds[i] ).append( "]: Labels[" ); String sep = ""; for ( long labelId : labelIds[i] ) { result.append( sep ).append( labelId ); sep = ", "; } result.append( "]" ); } return result.append( "}]" ).toString(); } @Override public int id() { return id; } @Override public long[] nodes() { return nodeIds; } @Override public long[] labels( long nodeId ) { for ( int i = 0; i < nodeIds.length; i++ ) { if ( nodeId == nodeIds[i] ) { return labelIds[i]; } } throw new IllegalArgumentException( "Unknown nodeId: " + nodeId ); } public static LuceneNodeLabelRange fromBitmapStructure( int id, long[] labelIds, long[][] nodeIdsByLabelIndex ) { Map<Long, List<Long>> labelsForEachNode = new HashMap<>( ); for ( int i = 0; i < labelIds.length; i++ ) { long labelId = labelIds[i]; for ( int j = 0; j < nodeIdsByLabelIndex[i].length; j++ ) { long nodeId = nodeIdsByLabelIndex[i][j]; List<Long> labelIdList = labelsForEachNode.get( nodeId ); if ( labelIdList == null ) { labelsForEachNode.put( nodeId, labelIdList = new ArrayList<>() ); } labelIdList.add( labelId ); } } Set<Long> nodeIdSet = labelsForEachNode.keySet(); long[] nodeIds = new long[ nodeIdSet.size() ]; long[][] labelIdsByNodeIndex = new long[ nodeIdSet.size() ][]; int nodeIndex = 0; for ( long nodeId : nodeIdSet ) { nodeIds[ nodeIndex ] = nodeId; List<Long> labelIdList = labelsForEachNode.get( nodeId ); long[] nodeLabelIds = new long[ labelIdList.size() ]; int labelIndex = 0; for ( long labelId : labelIdList ) { nodeLabelIds[ labelIndex ] = labelId; labelIndex++; } labelIdsByNodeIndex[ nodeIndex ] = nodeLabelIds; nodeIndex++; } return new LuceneNodeLabelRange( id, nodeIds, labelIdsByNodeIndex ); } }
false
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_LuceneNodeLabelRange.java
4,711
public class LuceneNodeLabelRangeTest { @Test public void shouldTransposeNodeIdsAndLabelIds() throws Exception { // given long[] labelIds = new long[]{1, 3, 5}; long[][] nodeIdsByLabelIndex = new long[][]{{0}, {2, 4}, {0, 2, 4}}; // when LuceneNodeLabelRange range = LuceneNodeLabelRange.fromBitmapStructure( 0, labelIds, nodeIdsByLabelIndex ); // then assertThat( asIterable( range.nodes() ), hasItems(0L, 2L, 4L)); assertThat( asIterable( range.labels( 0 ) ), hasItems( 1L, 5L ) ); assertThat( asIterable( range.labels( 2 ) ), hasItems( 3L, 5L ) ); assertThat( asIterable( range.labels( 4 ) ), hasItems( 3L, 5L ) ); } }
false
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_LuceneNodeLabelRangeTest.java
4,712
{ @Override public Object[] apply( TestValue testValue ) { return new Object[]{testValue}; } }, testValues ) );
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_SchemaIndexProviderApprovalTest.java
4,713
public static class Descriptor { private final String key; private final String version; public Descriptor( String key, String version ) { if (key == null) { throw new IllegalArgumentException( "null provider key prohibited" ); } if (key.length() == 0) { throw new IllegalArgumentException( "empty provider key prohibited" ); } if (version == null) { throw new IllegalArgumentException( "null provider version prohibited" ); } this.key = key; this.version = version; } public String getKey() { return key; } public String getVersion() { return version; } @Override public int hashCode() { return ( 23 + key.hashCode() ) ^ version.hashCode(); } @Override public boolean equals( Object obj ) { if ( obj != null && obj instanceof Descriptor ) { Descriptor otherDescriptor = (Descriptor) obj; return key.equals( otherDescriptor.getKey() ) && version.equals( otherDescriptor.getVersion() ); } return false; } @Override public String toString() { return "{key=" + key + ", version=" + version + "}"; } }
false
community_kernel_src_main_java_org_neo4j_kernel_api_index_SchemaIndexProvider.java
4,714
{ @Override @SuppressWarnings("unchecked") public <T> T select( Class<T> type, Iterable<T> candidates ) throws IllegalArgumentException { List<Comparable> all = (List<Comparable>) addToCollection( candidates, new ArrayList<T>() ); if ( all.isEmpty() ) { throw new IllegalArgumentException( "No schema index provider " + SchemaIndexProvider.class.getName() + " found. " + servicesClassPathEntryInformation() ); } Collections.sort( all ); return (T) all.get( all.size()-1 ); } };
false
community_kernel_src_main_java_org_neo4j_kernel_api_index_SchemaIndexProvider.java
4,715
{ private final IndexAccessor singleWriter = new IndexAccessor.Adapter(); private final IndexPopulator singlePopulator = new IndexPopulator.Adapter(); @Override public IndexAccessor getOnlineAccessor( long indexId, IndexConfiguration config ) { return singleWriter; } @Override public IndexPopulator getPopulator( long indexId, IndexDescriptor descriptor, IndexConfiguration config ) { return singlePopulator; } @Override public InternalIndexState getInitialState( long indexId ) { return InternalIndexState.POPULATING; } @Override public String getPopulationFailure( long indexId ) throws IllegalStateException { throw new IllegalStateException(); } };
false
community_kernel_src_main_java_org_neo4j_kernel_api_index_SchemaIndexProvider.java
4,716
public abstract class SchemaIndexProvider extends LifecycleAdapter implements Comparable<SchemaIndexProvider> { public static final SchemaIndexProvider NO_INDEX_PROVIDER = new SchemaIndexProvider( new Descriptor("no-index-provider", "1.0"), -1 ) { private final IndexAccessor singleWriter = new IndexAccessor.Adapter(); private final IndexPopulator singlePopulator = new IndexPopulator.Adapter(); @Override public IndexAccessor getOnlineAccessor( long indexId, IndexConfiguration config ) { return singleWriter; } @Override public IndexPopulator getPopulator( long indexId, IndexDescriptor descriptor, IndexConfiguration config ) { return singlePopulator; } @Override public InternalIndexState getInitialState( long indexId ) { return InternalIndexState.POPULATING; } @Override public String getPopulationFailure( long indexId ) throws IllegalStateException { throw new IllegalStateException(); } }; public static final SelectionStrategy HIGHEST_PRIORITIZED_OR_NONE = new SelectionStrategy() { @Override @SuppressWarnings("unchecked") public <T> T select( Class<T> type, Iterable<T> candidates ) throws IllegalArgumentException { List<Comparable> all = (List<Comparable>) addToCollection( candidates, new ArrayList<T>() ); if ( all.isEmpty() ) { throw new IllegalArgumentException( "No schema index provider " + SchemaIndexProvider.class.getName() + " found. " + servicesClassPathEntryInformation() ); } Collections.sort( all ); return (T) all.get( all.size()-1 ); } }; protected final int priority; private final Descriptor providerDescriptor; protected SchemaIndexProvider( Descriptor descriptor, int priority ) { assert descriptor != null; this.priority = priority; this.providerDescriptor = descriptor; } /** * Used for initially populating a created index, using batch insertion. */ public abstract IndexPopulator getPopulator( long indexId, IndexDescriptor descriptor, IndexConfiguration config ); /** * Used for updating an index once initial population has completed. */ public abstract IndexAccessor getOnlineAccessor( long indexId, IndexConfiguration config ) throws IOException; /** * Returns a failure previously gotten from {@link IndexPopulator#markAsFailed(String)} * * Implementations are expected to persist this failure and may elect to make use of * {@link org.neo4j.kernel.api.index.util.FailureStorage} for this purpose */ public abstract String getPopulationFailure( long indexId ) throws IllegalStateException; /** * Called during startup to find out which state an index is in. If {@link InternalIndexState#FAILED} * is returned then a further call to {@link #getPopulationFailure(long)} is expected and should return * the failure accepted by any call to {@link IndexPopulator#markAsFailed(String)} call at the time * of failure. */ public abstract InternalIndexState getInitialState( long indexId ); /** * @return a description of this index provider */ public Descriptor getProviderDescriptor() { return providerDescriptor; } @Override public int compareTo( SchemaIndexProvider o ) { return this.priority - o.priority; } @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } SchemaIndexProvider other = (SchemaIndexProvider) o; return priority == other.priority && providerDescriptor.equals( other.providerDescriptor ); } @Override public int hashCode() { int result = priority; result = 31 * result + (providerDescriptor != null ? providerDescriptor.hashCode() : 0); return result; } protected File getRootDirectory( Config config, String key ) { return new File( new File( new File( config.get( store_dir ), "schema" ), "index" ), key ); } public static class Descriptor { private final String key; private final String version; public Descriptor( String key, String version ) { if (key == null) { throw new IllegalArgumentException( "null provider key prohibited" ); } if (key.length() == 0) { throw new IllegalArgumentException( "empty provider key prohibited" ); } if (version == null) { throw new IllegalArgumentException( "null provider version prohibited" ); } this.key = key; this.version = version; } public String getKey() { return key; } public String getVersion() { return version; } @Override public int hashCode() { return ( 23 + key.hashCode() ) ^ version.hashCode(); } @Override public boolean equals( Object obj ) { if ( obj != null && obj instanceof Descriptor ) { Descriptor otherDescriptor = (Descriptor) obj; return key.equals( otherDescriptor.getKey() ) && version.equals( otherDescriptor.getVersion() ); } return false; } @Override public String toString() { return "{key=" + key + ", version=" + version + "}"; } } }
false
community_kernel_src_main_java_org_neo4j_kernel_api_index_SchemaIndexProvider.java
4,717
private static class ArrayEqualityObject { private final Object array; ArrayEqualityObject( Object array ) { this.array = array; } @Override public int hashCode() { return ArrayUtil.hashCode( array ); } @Override public boolean equals( Object obj ) { return obj instanceof ArrayEqualityObject && ArrayUtil.equals( array, ((ArrayEqualityObject) obj).array ); } @Override public String toString() { return ArrayUtil.toString( array ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_SchemaConstraintProviderApprovalTest.java
4,718
{ @Override public Object apply( Node node ) { Object value = node.getProperty( PROPERTY_KEY ); if ( value.getClass().isArray() ) { return new ArrayEqualityObject( value ); } return value; } };
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_SchemaConstraintProviderApprovalTest.java
4,719
{ @Override public Object[] apply( TestValue testValue ) { return new Object[]{testValue}; } }, testValues ) );
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_SchemaConstraintProviderApprovalTest.java
4,720
@RunWith(value = Parameterized.class) public abstract class SchemaConstraintProviderApprovalTest { /* These are the values that will be checked. Searching */ public enum TestValue { BOOLEAN_TRUE( true ), BOOLEAN_FALSE( false ), STRING_TRUE( "true" ), STRING_FALSE( "false" ), STRING_UPPER_A( "A" ), STRING_LOWER_A( "a" ), CHAR_UPPER_A( 'B' ), CHAR_LOWER_A( 'b' ), INT_42( 42 ), LONG_42( (long) 43 ), LARGE_LONG_1( 4611686018427387905l ), LARGE_LONG_2( 4611686018427387907l ), BYTE_42( (byte) 44 ), DOUBLE_42( (double) 41 ), DOUBLE_42andAHalf( 42.5d ), SHORT_42( (short) 45 ), FLOAT_42( (float) 46 ), FLOAT_42andAHalf( 41.5f ), ARRAY_OF_INTS( new int[]{1, 2, 3} ), ARRAY_OF_LONGS( new long[]{4, 5, 6} ), ARRAY_OF_LARGE_LONGS_1( new long[] { 4611686018427387905l } ), ARRAY_OF_LARGE_LONGS_2( new long[] { 4611686018427387906l } ), ARRAY_OF_LARGE_LONGS_3( new Long[] { 4611686018425387907l } ), ARRAY_OF_LARGE_LONGS_4( new Long[] { 4611686018425387908l } ), ARRAY_OF_BOOL_LIKE_STRING( new String[]{"true", "false", "true"} ), ARRAY_OF_BOOLS( new boolean[]{true, false, true} ), ARRAY_OF_DOUBLES( new double[]{7, 8, 9} ), ARRAY_OF_STRING( new String[]{"a", "b", "c"} ), EMPTY_ARRAY_OF_STRING( new String[0] ), ONE( new String[]{"", "||"} ), OTHER( new String[]{"||", ""} ), ANOTHER_ARRAY_OF_STRING( new String[]{"1|2|3"} ), ARRAY_OF_CHAR( new char[]{'d', 'e', 'f'} ); private final Object value; private TestValue( Object value ) { this.value = value; } } private static Map<TestValue, Set<Object>> noIndexRun; private static Map<TestValue, Set<Object>> constraintRun; private final TestValue currentValue; public SchemaConstraintProviderApprovalTest( TestValue value ) { currentValue = value; } @Parameters(name = "{0}") public static Collection<Object[]> data() { Iterable<TestValue> testValues = asIterable( TestValue.values() ); return asCollection( map( new Function<TestValue, Object[]>() { @Override public Object[] apply( TestValue testValue ) { return new Object[]{testValue}; } }, testValues ) ); } @BeforeClass public static void init() { GraphDatabaseService db = new TestGraphDatabaseFactory().newImpermanentDatabase(); for ( TestValue value : TestValue.values() ) { createNode( db, PROPERTY_KEY, value.value ); } noIndexRun = runFindByLabelAndProperty( db ); createConstraint( db, label( LABEL ), PROPERTY_KEY ); constraintRun = runFindByLabelAndProperty( db ); db.shutdown(); } public static final String LABEL = "Person"; public static final String PROPERTY_KEY = "name"; public static final Function<Node, Object> PROPERTY_EXTRACTOR = new Function<Node, Object>() { @Override public Object apply( Node node ) { Object value = node.getProperty( PROPERTY_KEY ); if ( value.getClass().isArray() ) { return new ArrayEqualityObject( value ); } return value; } }; @Test public void test() { Set<Object> noIndexResult = asSet( noIndexRun.get( currentValue ) ); Set<Object> constraintResult = asSet( constraintRun.get( currentValue ) ); String errorMessage = currentValue.toString(); assertEquals( errorMessage, noIndexResult, constraintResult ); } private static Map<TestValue, Set<Object>> runFindByLabelAndProperty( GraphDatabaseService db ) { HashMap<TestValue, Set<Object>> results = new HashMap<>(); try ( Transaction tx = db.beginTx() ) { for ( TestValue value : TestValue.values() ) { addToResults( db, results, value ); } tx.success(); } return results; } private static Node createNode( GraphDatabaseService db, String propertyKey, Object value ) { try ( Transaction tx = db.beginTx() ) { Node node = db.createNode( label( LABEL ) ); node.setProperty( propertyKey, value ); tx.success(); return node; } } private static void addToResults( GraphDatabaseService db, HashMap<TestValue, Set<Object>> results, TestValue value ) { ResourceIterable<Node> foundNodes = db.findNodesByLabelAndProperty( label( LABEL ), PROPERTY_KEY, value.value ); Set<Object> propertyValues = asSet( map( PROPERTY_EXTRACTOR, foundNodes ) ); results.put( value, propertyValues ); } private static class ArrayEqualityObject { private final Object array; ArrayEqualityObject( Object array ) { this.array = array; } @Override public int hashCode() { return ArrayUtil.hashCode( array ); } @Override public boolean equals( Object obj ) { return obj instanceof ArrayEqualityObject && ArrayUtil.equals( array, ((ArrayEqualityObject) obj).array ); } @Override public String toString() { return ArrayUtil.toString( array ); } } }
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_SchemaConstraintProviderApprovalTest.java
4,721
public class PreexistingIndexEntryConflictExceptionTest { @Test public void messageShouldIncludePropertyValueAndNodeIds() throws Exception { // given PreexistingIndexEntryConflictException e = new PreexistingIndexEntryConflictException( "value1", 11, 22 ); // then assertEquals( format( "Multiple nodes have property value 'value1':%n" + " node(11)%n" + " node(22)" ), e.getMessage() ); } @Test public void evidenceMessageShouldIncludeLabelAndPropertyKey() throws Exception { // given PreexistingIndexEntryConflictException e = new PreexistingIndexEntryConflictException( "value1", 11, 22 ); // then assertEquals( format( "Multiple nodes with label `Label1` have property `propertyKey1` = 'value1':%n" + " node(11)%n" + " node(22)" ), e.evidenceMessage("Label1", "propertyKey1") ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_PreexistingIndexEntryConflictExceptionTest.java
4,722
public class PreexistingIndexEntryConflictException extends IndexEntryConflictException { private final Object propertyValue; private final long addedNodeId; private final long existingNodeId; public PreexistingIndexEntryConflictException( Object propertyValue, long existingNodeId, long addedNodeId ) { super( format( "Multiple nodes have property value %s:%n" + " node(%d)%n" + " node(%d)", quote( propertyValue ), existingNodeId, addedNodeId ) ); this.addedNodeId = addedNodeId; this.propertyValue = propertyValue; this.existingNodeId = existingNodeId; } @Override public Object getPropertyValue() { return propertyValue; } @Override public String evidenceMessage( String labelName, String propertyKey ) { return format( "Multiple nodes with label `%s` have property `%s` = %s:%n" + " node(%d)%n" + " node(%d)", labelName, propertyKey, quote( propertyValue ), existingNodeId, addedNodeId ); } public long getAddedNodeId() { return addedNodeId; } public long getExistingNodeId() { return existingNodeId; } @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } PreexistingIndexEntryConflictException that = (PreexistingIndexEntryConflictException) o; return addedNodeId == that.addedNodeId && existingNodeId == that.existingNodeId && !(propertyValue != null ? !propertyValue.equals( that.propertyValue ) : that.propertyValue != null); } @Override public int hashCode() { int result = propertyValue != null ? propertyValue.hashCode() : 0; result = 31 * result + (int) (addedNodeId ^ (addedNodeId >>> 32)); result = 31 * result + (int) (existingNodeId ^ (existingNodeId >>> 32)); return result; } @Override public String toString() { return "PreexistingIndexEntryConflictException{" + "propertyValue=" + propertyValue + ", addedNodeId=" + addedNodeId + ", existingNodeId=" + existingNodeId + '}'; } }
false
community_kernel_src_main_java_org_neo4j_kernel_api_index_PreexistingIndexEntryConflictException.java
4,723
private static class Parameterization extends BlockJUnit4ClassRunner { private final ParameterBuilder builder; private final Constructor<?> constructor; Parameterization( ParameterBuilder builder, Constructor<?> constructor ) throws InitializationError { super( constructor.getDeclaringClass() ); this.builder = builder; this.constructor = constructor; } @Override protected void validateConstructor( List<Throwable> errors ) { // constructor is already verified } @Override protected Object createTest() throws Exception { return constructor.newInstance( builder.newSuiteInstance() ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_ParameterizedSuiteRunner.java
4,724
private static class ParameterBuilder extends RunnerBuilder { private final Map<Class<?>, Parameterization> parameterizations = new HashMap<Class<?>, Parameterization>(); private final Class<?> suiteClass; ParameterBuilder( Class<?> suiteClass ) throws InitializationError { this.suiteClass = suiteClass; boolean ok = false; for ( Constructor<?> suiteConstructor : suiteClass.getConstructors() ) { if ( suiteConstructor.getParameterTypes().length == 0 ) { if ( Modifier.isPublic( suiteConstructor.getModifiers() ) ) { ok = true; } break; } } List<Throwable> errors = new ArrayList<Throwable>(); if ( !ok ) { errors.add( new IllegalArgumentException( "Suite class (" + suiteClass.getName() + ") does not have a public zero-arg constructor." ) ); } if ( Modifier.isAbstract( suiteClass.getModifiers() ) ) { errors.add( new IllegalArgumentException( "Suite class (" + suiteClass.getName() + ") is abstract." ) ); } buildParameterizations( parameterizations, suiteClass, errors ); if ( !errors.isEmpty() ) { throw new InitializationError( errors ); } } @Override public Runner runnerForClass( Class<?> testClass ) throws Throwable { if ( testClass == this.suiteClass ) { return new BlockJUnit4ClassRunner( testClass ); } return parameterizations.get( testClass ); } Class<?>[] suiteClasses() { ArrayList<Class<?>> classes = new ArrayList<Class<?>>( parameterizations.keySet() ); for ( Method method : suiteClass.getMethods() ) { if ( method.getAnnotation( Test.class ) != null ) { classes.add( suiteClass ); } } return classes.toArray( new Class[classes.size()] ); } private void buildParameterizations( Map<Class<?>, Parameterization> result, Class<?> type, List<Throwable> errors ) { if ( type == Object.class ) { return; } buildParameterizations( result, type.getSuperclass(), errors ); SuiteClasses annotation = type.getAnnotation( SuiteClasses.class ); if ( annotation != null ) { for ( Class<?> test : annotation.value() ) { if ( !result.containsKey( test ) ) { try { result.put( test, new Parameterization( this, test.getConstructor( type ) ) ); } catch ( InitializationError failure ) { errors.addAll( failure.getCauses() ); } catch ( NoSuchMethodException e ) { errors.add( e ); } } } } } Object newSuiteInstance() throws Exception { return suiteClass.newInstance(); } }
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_ParameterizedSuiteRunner.java
4,725
public class ParameterizedSuiteRunner extends Suite { @SuppressWarnings("unused"/*used by jUnit through reflection*/) public ParameterizedSuiteRunner( Class<?> testClass ) throws InitializationError { this( testClass, new ParameterBuilder( testClass ) ); } ParameterizedSuiteRunner( Class<?> testClass, ParameterBuilder builder ) throws InitializationError { super( builder, testClass, builder.suiteClasses() ); } private static class ParameterBuilder extends RunnerBuilder { private final Map<Class<?>, Parameterization> parameterizations = new HashMap<Class<?>, Parameterization>(); private final Class<?> suiteClass; ParameterBuilder( Class<?> suiteClass ) throws InitializationError { this.suiteClass = suiteClass; boolean ok = false; for ( Constructor<?> suiteConstructor : suiteClass.getConstructors() ) { if ( suiteConstructor.getParameterTypes().length == 0 ) { if ( Modifier.isPublic( suiteConstructor.getModifiers() ) ) { ok = true; } break; } } List<Throwable> errors = new ArrayList<Throwable>(); if ( !ok ) { errors.add( new IllegalArgumentException( "Suite class (" + suiteClass.getName() + ") does not have a public zero-arg constructor." ) ); } if ( Modifier.isAbstract( suiteClass.getModifiers() ) ) { errors.add( new IllegalArgumentException( "Suite class (" + suiteClass.getName() + ") is abstract." ) ); } buildParameterizations( parameterizations, suiteClass, errors ); if ( !errors.isEmpty() ) { throw new InitializationError( errors ); } } @Override public Runner runnerForClass( Class<?> testClass ) throws Throwable { if ( testClass == this.suiteClass ) { return new BlockJUnit4ClassRunner( testClass ); } return parameterizations.get( testClass ); } Class<?>[] suiteClasses() { ArrayList<Class<?>> classes = new ArrayList<Class<?>>( parameterizations.keySet() ); for ( Method method : suiteClass.getMethods() ) { if ( method.getAnnotation( Test.class ) != null ) { classes.add( suiteClass ); } } return classes.toArray( new Class[classes.size()] ); } private void buildParameterizations( Map<Class<?>, Parameterization> result, Class<?> type, List<Throwable> errors ) { if ( type == Object.class ) { return; } buildParameterizations( result, type.getSuperclass(), errors ); SuiteClasses annotation = type.getAnnotation( SuiteClasses.class ); if ( annotation != null ) { for ( Class<?> test : annotation.value() ) { if ( !result.containsKey( test ) ) { try { result.put( test, new Parameterization( this, test.getConstructor( type ) ) ); } catch ( InitializationError failure ) { errors.addAll( failure.getCauses() ); } catch ( NoSuchMethodException e ) { errors.add( e ); } } } } } Object newSuiteInstance() throws Exception { return suiteClass.newInstance(); } } private static class Parameterization extends BlockJUnit4ClassRunner { private final ParameterBuilder builder; private final Constructor<?> constructor; Parameterization( ParameterBuilder builder, Constructor<?> constructor ) throws InitializationError { super( constructor.getDeclaringClass() ); this.builder = builder; this.constructor = constructor; } @Override protected void validateConstructor( List<Throwable> errors ) { // constructor is already verified } @Override protected Object createTest() throws Exception { return constructor.newInstance( builder.newSuiteInstance() ); } } }
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_ParameterizedSuiteRunner.java
4,726
{ @Override public Property getProperty( long nodeId, int propertyKeyId ) throws EntityNotFoundException, PropertyNotFoundException { return Property.stringProperty( propertyKeyId, propertyValue ); } };
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_NonUniqueIndexPopulatorCompatibility.java
4,727
@Ignore( "Not a test. This is a compatibility suite that provides test cases for verifying" + " SchemaIndexProvider implementations. Each index provider that is to be tested by this suite" + " must create their own test class extending IndexProviderCompatibilityTestSuite." + " The @Ignore annotation doesn't prevent these tests to run, it rather removes some annoying" + " errors or warnings in some IDEs about test classes needing a public zero-arg constructor." ) public class NonUniqueIndexPopulatorCompatibility extends IndexProviderCompatibilityTestSuite.Compatibility { public NonUniqueIndexPopulatorCompatibility( IndexProviderCompatibilityTestSuite testSuite ) { super( testSuite ); } @Test public void shouldProvidePopulatorThatAcceptsDuplicateEntries() throws Exception { // when IndexPopulator populator = indexProvider.getPopulator( 17, descriptor, new IndexConfiguration( false ) ); populator.create(); populator.add( 1, "value1" ); populator.add( 2, "value1" ); populator.close( true ); // then IndexAccessor accessor = indexProvider.getOnlineAccessor( 17, new IndexConfiguration( false ) ); try ( IndexReader reader = accessor.newReader() ) { PrimitiveLongIterator nodes = reader.lookup( "value1" ); assertEquals( asSet( 1l, 2l ), asSet( nodes ) ); } accessor.close(); } @Test public void shouldStorePopulationFailedForRetrievalFromProviderLater() throws Exception { // GIVEN IndexPopulator populator = indexProvider.getPopulator( 17, descriptor, new IndexConfiguration( false ) ); String failure = "The contrived failure"; // WHEN populator.markAsFailed( failure ); // THEN assertEquals( failure, indexProvider.getPopulationFailure( 17 ) ); } @Test public void shouldReportInitialStateAsFailedIfPopulationFailed() throws Exception { // GIVEN IndexPopulator populator = indexProvider.getPopulator( 17, descriptor, new IndexConfiguration( false ) ); String failure = "The contrived failure"; // WHEN populator.markAsFailed( failure ); // THEN assertEquals( FAILED, indexProvider.getInitialState( 17 ) ); } @Test public void shouldBeAbleToDropAClosedIndexPopulator() throws Exception { // GIVEN IndexPopulator populator = indexProvider.getPopulator( 17, descriptor, new IndexConfiguration( false ) ); populator.close( false ); // WHEN populator.drop(); // THEN - no exception should be thrown (it's been known to!) } @Test public void shouldApplyUpdatesIdempotently() throws Exception { // GIVEN IndexPopulator populator = indexProvider.getPopulator( 13, descriptor, new IndexConfiguration( false ) ); populator.create(); long nodeId = 1; int propertyKeyId = 10, labelId = 11; // Can we just use arbitrary ids here? final String propertyValue = "value1"; PropertyAccessor propertyAccessor = new PropertyAccessor() { @Override public Property getProperty( long nodeId, int propertyKeyId ) throws EntityNotFoundException, PropertyNotFoundException { return Property.stringProperty( propertyKeyId, propertyValue ); } }; // this update (using add())... populator.add( nodeId, propertyValue ); // ...is the same as this update (using update()) try ( IndexUpdater updater = populator.newPopulatingUpdater( propertyAccessor ) ) { updater.process( add( nodeId, propertyKeyId, propertyValue, new long[]{labelId} ) ); } populator.close( true ); // then IndexAccessor accessor = indexProvider.getOnlineAccessor( 13, new IndexConfiguration( false ) ); try ( IndexReader reader = accessor.newReader() ) { PrimitiveLongIterator nodes = reader.lookup( propertyValue ); assertEquals( asSet( 1l ), asSet( nodes ) ); } accessor.close(); } }
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_NonUniqueIndexPopulatorCompatibility.java
4,728
public class NodePropertyUpdate { private final long nodeId; private final int propertyKeyId; private final Object valueBefore; private final Object valueAfter; private final UpdateMode updateMode; private final long[] labelsBefore; private final long[] labelsAfter; private NodePropertyUpdate( long nodeId, int propertyKeyId, Object valueBefore, long[] labelsBefore, Object valueAfter, long[] labelsAfter, UpdateMode updateMode ) { this.nodeId = nodeId; this.propertyKeyId = propertyKeyId; this.valueBefore = valueBefore; this.labelsBefore = labelsBefore; this.valueAfter = valueAfter; this.labelsAfter = labelsAfter; this.updateMode = updateMode; } public long getNodeId() { return nodeId; } public int getPropertyKeyId() { return propertyKeyId; } public Object getValueBefore() { return valueBefore; } public Object getValueAfter() { return valueAfter; } public int getNumberOfLabelsBefore() { return labelsBefore.length; } public int getLabelBefore( int i ) { return (int) labelsBefore[i]; } public int getNumberOfLabelsAfter() { return labelsAfter.length; } public int getLabelAfter( int i ) { return (int) labelsAfter[i]; } public UpdateMode getUpdateMode() { return updateMode; } /** * Whether or not this property update is for the given {@code labelId}. * * If this property update comes from setting/changing/removing a property it will * affect all labels on that {@link Node}. * * If this property update comes from adding or removing labels to/from a {@link Node} * it will affect only those labels. * * @param labelId the label id the check. */ public boolean forLabel( long labelId ) { return updateMode.forLabel( labelsBefore, labelsAfter, labelId ); } @Override public String toString() { StringBuilder result = new StringBuilder( getClass().getSimpleName() ) .append( "[" ).append( nodeId ).append( ", prop:" ).append( propertyKeyId ).append( " " ); switch ( updateMode ) { case ADDED: result.append( "add:" ).append( valueAfter ); break; case CHANGED: result.append( "change:" ).append( valueBefore ).append( " => " ).append( valueAfter ); break; case REMOVED: result.append( "remove:" ).append( valueBefore ); break; default: throw new IllegalArgumentException( updateMode.toString() ); } result.append( ", labelsBefore:" ).append( Arrays.toString( labelsBefore ) ); result.append( ", labelsAfter:" ).append( Arrays.toString( labelsAfter ) ); return result.append( "]" ).toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode( labelsBefore ); result = prime * result + Arrays.hashCode( labelsAfter ); result = prime * result + (int) (nodeId ^ (nodeId >>> 32)); result = prime * result + propertyKeyId; result = prime * result + updateMode.hashCode(); return result; } @Override public boolean equals( Object obj ) { if ( this == obj ) { return true; } if ( obj == null ) { return false; } if ( getClass() != obj.getClass() ) { return false; } NodePropertyUpdate other = (NodePropertyUpdate) obj; return Arrays.equals( labelsBefore, other.labelsBefore ) && Arrays.equals( labelsAfter, other.labelsAfter ) && nodeId == other.nodeId && propertyKeyId == other.propertyKeyId && updateMode == other.updateMode && propertyValuesEqual( valueBefore, other.valueBefore ) && propertyValuesEqual( valueAfter, other.valueAfter ); } public static boolean propertyValuesEqual( Object a, Object b ) { if ( a == null ) { return b == null; } if ( b == null ) { return false; } if (a instanceof boolean[] && b instanceof boolean[]) { return Arrays.equals( (boolean[]) a, (boolean[]) b ); } if (a instanceof byte[] && b instanceof byte[]) { return Arrays.equals( (byte[]) a, (byte[]) b ); } if (a instanceof short[] && b instanceof short[]) { return Arrays.equals( (short[]) a, (short[]) b ); } if (a instanceof int[] && b instanceof int[]) { return Arrays.equals( (int[]) a, (int[]) b ); } if (a instanceof long[] && b instanceof long[]) { return Arrays.equals( (long[]) a, (long[]) b ); } if (a instanceof char[] && b instanceof char[]) { return Arrays.equals( (char[]) a, (char[]) b ); } if (a instanceof float[] && b instanceof float[]) { return Arrays.equals( (float[]) a, (float[]) b ); } if (a instanceof double[] && b instanceof double[]) { return Arrays.equals( (double[]) a, (double[]) b ); } if (a instanceof Object[] && b instanceof Object[]) { return Arrays.equals( (Object[]) a, (Object[]) b ); } return a.equals( b ); } public static final long[] EMPTY_LONG_ARRAY = new long[0]; public static NodePropertyUpdate add( long nodeId, int propertyKeyId, Object value, long[] labels ) { return new NodePropertyUpdate( nodeId, propertyKeyId, null, EMPTY_LONG_ARRAY, value, labels, ADDED ); } public static NodePropertyUpdate change( long nodeId, int propertyKeyId, Object valueBefore, long[] labelsBefore, Object valueAfter, long[] labelsAfter ) { return new NodePropertyUpdate( nodeId, propertyKeyId, valueBefore, labelsBefore, valueAfter, labelsAfter, CHANGED ); } public static NodePropertyUpdate remove( long nodeId, int propertyKeyId, Object value, long[] labels ) { return new NodePropertyUpdate( nodeId, propertyKeyId, value, labels, null, EMPTY_LONG_ARRAY, REMOVED ); } }
false
community_kernel_src_main_java_org_neo4j_kernel_api_index_NodePropertyUpdate.java
4,729
{ @Override public PrimitiveLongIterator lookup( Object value ) { return emptyPrimitiveLongIterator(); } @Override public void close() { } };
false
community_kernel_src_main_java_org_neo4j_kernel_api_index_IndexReader.java
4,730
public static abstract class Compatibility { protected final SchemaIndexProvider indexProvider; protected IndexDescriptor descriptor = new IndexDescriptor( 1, 2 ); public Compatibility( IndexProviderCompatibilityTestSuite testSuite ) { this.indexProvider = testSuite.createIndexProvider(); } }
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_IndexProviderCompatibilityTestSuite.java
4,731
@RunWith(ParameterizedSuiteRunner.class) @Suite.SuiteClasses({ NonUniqueIndexPopulatorCompatibility.class, UniqueIndexPopulatorCompatibility.class, UniqueIndexAccessorCompatibility.class, UniqueConstraintCompatibility.class }) public abstract class IndexProviderCompatibilityTestSuite { protected abstract SchemaIndexProvider createIndexProvider(); public static abstract class Compatibility { protected final SchemaIndexProvider indexProvider; protected IndexDescriptor descriptor = new IndexDescriptor( 1, 2 ); public Compatibility( IndexProviderCompatibilityTestSuite testSuite ) { this.indexProvider = testSuite.createIndexProvider(); } } }
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_IndexProviderCompatibilityTestSuite.java
4,732
@RunWith(value = Parameterized.class) public abstract class SchemaIndexProviderApprovalTest { /* These are the values that will be checked. Searching */ public enum TestValue { BOOLEAN_TRUE( true ), BOOLEAN_FALSE( false ), STRING_TRUE( "true" ), STRING_FALSE( "false" ), STRING_UPPER_A( "A" ), STRING_LOWER_A( "a" ), CHAR_UPPER_A( 'A' ), CHAR_LOWER_A( 'a' ), INT_42( 42 ), LONG_42( (long) 42 ), LARGE_LONG_1( 4611686018427387905l ), LARGE_LONG_2( 4611686018427387907l ), BYTE_42( (byte) 42 ), DOUBLE_42( (double) 42 ), DOUBLE_42andAHalf( 42.5d ), SHORT_42( (short) 42 ), FLOAT_42( (float) 42 ), FLOAT_42andAHalf( 42.5f ), ARRAY_OF_INTS( new int[]{1, 2, 3} ), ARRAY_OF_LONGS( new long[]{1, 2, 3} ), ARRAY_OF_LARGE_LONGS_1( new long[] { 4611686018427387905l } ), ARRAY_OF_LARGE_LONGS_2( new long[] { 4611686018427387906l } ), ARRAY_OF_LARGE_LONGS_3( new Long[] { 4611686018425387907l } ), ARRAY_OF_LARGE_LONGS_4( new Long[] { 4611686018425387908l } ), ARRAY_OF_BOOL_LIKE_STRING( new String[]{"true", "false", "true"} ), ARRAY_OF_BOOLS( new boolean[]{true, false, true} ), ARRAY_OF_DOUBLES( new double[]{1, 2, 3} ), ARRAY_OF_STRING( new String[]{"1", "2", "3"} ), EMPTY_ARRAY_OF_INTS( new int[0] ), EMPTY_ARRAY_OF_LONGS( new long[0] ), EMPTY_ARRAY_OF_BOOLS( new boolean[0] ), EMPTY_ARRAY_OF_DOUBLES( new double[0] ), EMPTY_ARRAY_OF_STRING( new String[0] ), ONE( new String[]{"", "||"} ), OTHER( new String[]{"||", ""} ), ANOTHER_ARRAY_OF_STRING( new String[]{"1|2|3"} ), ARRAY_OF_CHAR( new char[]{'1', '2', '3'} ); private final Object value; private TestValue( Object value ) { this.value = value; } } private static Map<TestValue, Set<Object>> noIndexRun; private static Map<TestValue, Set<Object>> indexRun; private final TestValue currentValue; public SchemaIndexProviderApprovalTest( TestValue value ) { currentValue = value; } @Parameters(name = "{0}") public static Collection<Object[]> data() { Iterable<TestValue> testValues = asIterable( TestValue.values() ); return asCollection( map( new Function<TestValue, Object[]>() { @Override public Object[] apply( TestValue testValue ) { return new Object[]{testValue}; } }, testValues ) ); } @BeforeClass public static void init() { GraphDatabaseService db = new TestGraphDatabaseFactory().newImpermanentDatabase(); for ( TestValue value : TestValue.values() ) { createNode( db, PROPERTY_KEY, value.value ); } noIndexRun = runFindByLabelAndProperty( db ); createIndex( db, label( LABEL ), PROPERTY_KEY ); indexRun = runFindByLabelAndProperty( db ); db.shutdown(); } public static final String LABEL = "Person"; public static final String PROPERTY_KEY = "name"; public static final Function<Node, Object> PROPERTY_EXTRACTOR = new Function<Node, Object>() { @Override public Object apply( Node node ) { Object value = node.getProperty( PROPERTY_KEY ); if ( value.getClass().isArray() ) { return new ArrayEqualityObject( value ); } return value; } }; @Test public void test() { Set<Object> noIndexResult = asSet( noIndexRun.get( currentValue ) ); Set<Object> indexResult = asSet( indexRun.get( currentValue ) ); String errorMessage = currentValue.toString(); assertEquals( errorMessage, noIndexResult, indexResult ); } private static Map<TestValue, Set<Object>> runFindByLabelAndProperty( GraphDatabaseService db ) { HashMap<TestValue, Set<Object>> results = new HashMap<>(); try ( Transaction tx = db.beginTx() ) { for ( TestValue value : TestValue.values() ) { addToResults( db, results, value ); } tx.success(); } return results; } private static Node createNode( GraphDatabaseService db, String propertyKey, Object value ) { try ( Transaction tx = db.beginTx() ) { Node node = db.createNode( label( LABEL ) ); node.setProperty( propertyKey, value ); tx.success(); return node; } } private static void addToResults( GraphDatabaseService db, HashMap<TestValue, Set<Object>> results, TestValue value ) { ResourceIterable<Node> foundNodes = db.findNodesByLabelAndProperty( label( LABEL ), PROPERTY_KEY, value.value ); Set<Object> propertyValues = asSet( map( PROPERTY_EXTRACTOR, foundNodes ) ); results.put( value, propertyValues ); } private static class ArrayEqualityObject { private final Object array; ArrayEqualityObject( Object array ) { this.array = array; } @Override public int hashCode() { return ArrayUtil.hashCode( array ); } @Override public boolean equals( Object obj ) { return obj instanceof ArrayEqualityObject && ArrayUtil.equals( array, ((ArrayEqualityObject) obj).array ); } @Override public String toString() { return ArrayUtil.toString( array ); } } }
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_SchemaIndexProviderApprovalTest.java
4,733
{ @Override public Object apply( Node node ) { Object value = node.getProperty( PROPERTY_KEY ); if ( value.getClass().isArray() ) { return new ArrayEqualityObject( value ); } return value; } };
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_SchemaIndexProviderApprovalTest.java
4,734
public class LuceneSchemaIndexCorruptionTest { @Test public void shouldMarkIndexAsFailedIfIndexIsCorrupt() throws Exception { // Given DirectoryFactory dirFactory = mock(DirectoryFactory.class); // This isn't quite correct, but it will trigger the correct code paths in our code when(dirFactory.open( any(File.class) )).thenThrow(new CorruptIndexException( "It's borken." )); LuceneSchemaIndexProvider p = new LuceneSchemaIndexProvider( dirFactory, new Config( stringMap( "store_dir", forTest( getClass() ).makeGraphDbDir().getAbsolutePath() ) ) ); // When InternalIndexState initialState = p.getInitialState( 1l ); // Then assertThat( initialState, equalTo(InternalIndexState.FAILED) ); } @Test public void shouldMarkAsFailedAndReturnCorrectFailureMessageWhenFailingWithFileNotFoundException() throws Exception { // Given DirectoryFactory dirFactory = mock(DirectoryFactory.class); // This isn't quite correct, but it will trigger the correct code paths in our code FileNotFoundException toThrow = new FileNotFoundException( "/some/path/somewhere" ); when(dirFactory.open( any(File.class) )).thenThrow( toThrow ); LuceneSchemaIndexProvider p = new LuceneSchemaIndexProvider( dirFactory, new Config( stringMap( "store_dir", forTest( getClass() ).makeGraphDbDir().getAbsolutePath() ) ) ); // When InternalIndexState initialState = p.getInitialState( 1l ); // Then assertThat( initialState, equalTo(InternalIndexState.FAILED) ); assertThat( p.getPopulationFailure( 1l ), equalTo( "File not found: " + toThrow.getMessage() ) ); } @Test public void shouldMarkAsFailedAndReturnCorrectFailureMessageWhenFailingWithEOFException() throws Exception { // Given DirectoryFactory dirFactory = mock(DirectoryFactory.class); // This isn't quite correct, but it will trigger the correct code paths in our code EOFException toThrow = new EOFException( "/some/path/somewhere" ); when(dirFactory.open( any(File.class) )).thenThrow( toThrow ); LuceneSchemaIndexProvider p = new LuceneSchemaIndexProvider( dirFactory, new Config( stringMap( "store_dir", forTest( getClass() ).makeGraphDbDir().getAbsolutePath() ) ) ); // When InternalIndexState initialState = p.getInitialState( 1l ); // Then assertThat( initialState, equalTo(InternalIndexState.FAILED) ); assertThat( p.getPopulationFailure( 1l ), equalTo( "EOF encountered: " + toThrow.getMessage() ) ); } @Test public void shouldDenyFailureForNonFailedIndex() throws Exception { // Given DirectoryFactory dirFactory = mock(DirectoryFactory.class); // This isn't quite correct, but it will trigger the correct code paths in our code EOFException toThrow = new EOFException( "/some/path/somewhere" ); when(dirFactory.open( any(File.class) )).thenThrow( toThrow ); LuceneSchemaIndexProvider p = new LuceneSchemaIndexProvider( dirFactory, new Config( stringMap( "store_dir", forTest( getClass() ).makeGraphDbDir().getAbsolutePath() ) ) ); // When InternalIndexState initialState = p.getInitialState( 1l ); // Then assertThat( initialState, equalTo( InternalIndexState.FAILED ) ); boolean exceptionOnOtherIndexThrown = false; try { p.getPopulationFailure( 2l ); } catch( IllegalStateException e ) { exceptionOnOtherIndexThrown = true; } assertTrue( exceptionOnOtherIndexThrown ); } }
false
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_LuceneSchemaIndexCorruptionTest.java
4,735
private static class ArrayEqualityObject { private final Object array; ArrayEqualityObject( Object array ) { this.array = array; } @Override public int hashCode() { return ArrayUtil.hashCode( array ); } @Override public boolean equals( Object obj ) { return obj instanceof ArrayEqualityObject && ArrayUtil.equals( array, ((ArrayEqualityObject) obj).array ); } @Override public String toString() { return ArrayUtil.toString( array ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_SchemaIndexProviderApprovalTest.java
4,736
public class NodeLabelUpdateNodeIdComparator implements Comparator<NodeLabelUpdate> { @Override public int compare( NodeLabelUpdate o1, NodeLabelUpdate o2 ) { long nodeId1 = o1.getNodeId(); long nodeId2 = o2.getNodeId(); if ( nodeId1 > nodeId2 ) { return 1; } else if ( nodeId1 == nodeId2 ) { return 0; } else { return -1; } } }
false
community_kernel_src_main_java_org_neo4j_kernel_api_labelscan_NodeLabelUpdateNodeIdComparator.java
4,737
public class NodeLabelUpdate { private final long nodeId; private final long[] labelsBefore; private final long[] labelsAfter; private NodeLabelUpdate( long nodeId, long[] labelsBefore, long[] labelsAfter ) { this.nodeId = nodeId; this.labelsBefore = labelsBefore; this.labelsAfter = labelsAfter; } public long getNodeId() { return nodeId; } public long[] getLabelsBefore() { return labelsBefore; } public long[] getLabelsAfter() { return labelsAfter; } @Override public String toString() { return getClass().getSimpleName() + "[node:" + nodeId + ", labelsBefore:" + Arrays.toString( labelsBefore ) + ", labelsAfter:" + Arrays.toString( labelsAfter ) + "]"; } public static NodeLabelUpdate labelChanges( long nodeId, long[] labelsBeforeChange, long[] labelsAfterChange ) { return new NodeLabelUpdate( nodeId, labelsBeforeChange, labelsAfterChange ); } }
false
community_kernel_src_main_java_org_neo4j_kernel_api_labelscan_NodeLabelUpdate.java
4,738
{ @Override public PrimitiveLongIterator nodesWithLabel( int labelId ) { return emptyPrimitiveLongIterator(); } @Override public Iterator<Long> labelsForNode( long nodeId ) { return emptyIterator(); } @Override public void close() { // Nothing to close } };
false
community_kernel_src_main_java_org_neo4j_kernel_api_labelscan_LabelScanReader.java
4,739
public class FolderLayout { private final File rootDirectory; public FolderLayout( File rootDirectory ) { this.rootDirectory = rootDirectory; } public File getFolder( long indexId ) { return new File( rootDirectory, "" + indexId ); } }
false
community_kernel_src_main_java_org_neo4j_kernel_api_index_util_FolderLayout.java
4,740
public class FailureStorage { public static final int MAX_FAILURE_SIZE = 16384; public static final String DEFAULT_FAILURE_FILE_NAME = "failure-message"; private final FolderLayout folderLayout; private final String failureFileName; /** * @param failureFileName name of failure files to be created * @param folderLayout describing where failure files should be stored */ public FailureStorage( FolderLayout folderLayout, String failureFileName ) { this.folderLayout = folderLayout; this.failureFileName = failureFileName; } public FailureStorage( FolderLayout folderLayout ) { this( folderLayout, DEFAULT_FAILURE_FILE_NAME ); } /** * Create/reserve an empty failure file for the given indexId. * * This will overwrite any pre-existing failure file. * * @param indexId id of the index * @throws IOException if the failure file could not be created */ public synchronized void reserveForIndex( long indexId ) throws IOException { File failureFile = failureFile( indexId ); try ( RandomAccessFile rwFile = new RandomAccessFile( failureFile, "rw" ) ) { FileChannel channel = rwFile.getChannel(); channel.write( ByteBuffer.wrap( new byte[MAX_FAILURE_SIZE] ) ); channel.force( true ); channel.close(); } } /** * Delete failure file for the given index id * * @param indexId of the index that failed */ public synchronized void clearForIndex( long indexId ) { failureFile( indexId ).delete(); } /** * @return the failure, if any. Otherwise {@code null} marking no failure. */ public synchronized String loadIndexFailure( long indexId ) { File failureFile = failureFile( indexId ); try { if ( !failureFile.exists() || !isFailed( failureFile ) ) { return null; } return readFailure( failureFile ); } catch ( IOException e ) { throw new RuntimeException( e ); } } /** * Store failure in failure file for index with the given id * * @param indexId of the index that failed * @param failure message describing the failure that needs to be stored * @throws IOException if the failure could not be stored */ public synchronized void storeIndexFailure( long indexId, String failure ) throws IOException { File failureFile = failureFile( indexId ); try ( RandomAccessFile rwFile = new RandomAccessFile( failureFile, "rw" ) ) { FileChannel channel = rwFile.getChannel(); byte[] data = failure.getBytes( "utf-8" ); channel.write( ByteBuffer.wrap( data, 0, Math.min( data.length, MAX_FAILURE_SIZE ) ) ); channel.force( true ); channel.close(); } } private File failureFile( long indexId ) { File folder = folderLayout.getFolder( indexId ); folder.mkdirs(); return new File( folder, failureFileName ); } private String readFailure( File failureFile ) throws IOException { try ( RandomAccessFile rwFile = new RandomAccessFile( failureFile, "r" ) ) { FileChannel channel = rwFile.getChannel(); byte[] data = new byte[(int) channel.size()]; int readData = channel.read( ByteBuffer.wrap( data ) ); channel.close(); return readData <= 0 ? "" : new String( withoutZeros( data ), "utf-8" ); } } private byte[] withoutZeros( byte[] data ) { byte[] result = new byte[ lengthOf(data) ]; System.arraycopy( data, 0, result, 0, result.length ); return result; } private int lengthOf( byte[] data ) { for (int i = 0; i < data.length; i++ ) { if ( 0 == data[i] ) { return i; } } return data.length; } private boolean isFailed( File failureFile ) throws IOException { try ( RandomAccessFile rFile = new RandomAccessFile( failureFile, "r" ) ) { FileChannel channel = rFile.getChannel(); byte[] data = new byte[(int) channel.size()]; channel.read( ByteBuffer.wrap( data ) ); channel.close(); return !allZero( data ); } } private boolean allZero( byte[] data ) { for ( byte b : data ) { if ( b != 0 ) { return false; } } return true; } }
false
community_kernel_src_main_java_org_neo4j_kernel_api_index_util_FailureStorage.java
4,741
@Ignore( "Not a test. This is a compatibility suite that provides test cases for verifying" + " SchemaIndexProvider implementations. Each index provider that is to be tested by this suite" + " must create their own test class extending IndexProviderCompatibilityTestSuite." + " The @Ignore annotation doesn't prevent these tests to run, it rather removes some annoying" + " errors or warnings in some IDEs about test classes needing a public zero-arg constructor." ) public class UniqueIndexPopulatorCompatibility extends IndexProviderCompatibilityTestSuite.Compatibility { public UniqueIndexPopulatorCompatibility( IndexProviderCompatibilityTestSuite testSuite ) { super( testSuite ); } /** * This is also checked by the UniqueConstraintCompatibility test, only not on this abstraction level. */ @Test public void shouldProvidePopulatorThatEnforcesUniqueConstraints() throws Exception { // when String value = "value1"; int nodeId1 = 1; int nodeId2 = 2; IndexPopulator populator = indexProvider.getPopulator( 17, descriptor, new IndexConfiguration( true ) ); populator.create(); populator.add( nodeId1, value ); populator.add( nodeId2, value ); try { PropertyAccessor propertyAccessor = mock( PropertyAccessor.class ); int propertyKeyId = descriptor.getPropertyKeyId(); when( propertyAccessor.getProperty( nodeId1, propertyKeyId )).thenReturn( stringProperty( propertyKeyId, value ) ); when( propertyAccessor.getProperty( nodeId2, propertyKeyId )).thenReturn( stringProperty( propertyKeyId, value ) ); populator.verifyDeferredConstraints( propertyAccessor ); fail( "expected exception" ); } // then catch ( PreexistingIndexEntryConflictException conflict ) { assertEquals( nodeId1, conflict.getExistingNodeId() ); assertEquals( value, conflict.getPropertyValue() ); assertEquals( nodeId2, conflict.getAddedNodeId() ); } } }
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_UniqueIndexPopulatorCompatibility.java
4,742
@Ignore( "Not a test. This is a compatibility suite that provides test cases for verifying" + " SchemaIndexProvider implementations. Each index provider that is to be tested by this suite" + " must create their own test class extending IndexProviderCompatibilityTestSuite." + " The @Ignore annotation doesn't prevent these tests to run, it rather removes some annoying" + " errors or warnings in some IDEs about test classes needing a public zero-arg constructor." ) public class UniqueIndexAccessorCompatibility extends IndexProviderCompatibilityTestSuite.Compatibility { private static final int PROPERTY_KEY_ID = 100; private IndexAccessor accessor; public UniqueIndexAccessorCompatibility( IndexProviderCompatibilityTestSuite testSuite ) { super( testSuite ); } @Test public void closingAnOnlineIndexUpdaterMustNotThrowEvenIfItHasBeenFedConflictingData() throws Exception { // The reason is that we use and close IndexUpdaters in commit - not in prepare - and therefor // we cannot have them go around and throw exceptions, because that could potentially break // recovery. // Conflicting data can happen because of faulty data coercion. These faults are resolved by // the exact-match filtering we do on index lookups in StateHandlingStatementOperations. updateAndCommit( asList( NodePropertyUpdate.add( 1L, PROPERTY_KEY_ID, "a", new long[]{1000} ), NodePropertyUpdate.add( 2L, PROPERTY_KEY_ID, "a", new long[]{1000} ) ) ); assertThat( getAllNodes( "a" ), equalTo( asList( 1L, 2L ) ) ); } @Before public void before() throws IOException { IndexConfiguration config = new IndexConfiguration( true ); IndexPopulator populator = indexProvider.getPopulator( 17, descriptor, config ); populator.create(); populator.close( true ); accessor = indexProvider.getOnlineAccessor( 17, config ); } @After public void after() throws IOException { accessor.drop(); accessor.close(); } private List<Long> getAllNodes( String propertyValue ) throws IOException { try ( IndexReader reader = accessor.newReader() ) { List<Long> list = new LinkedList<>(); for ( PrimitiveLongIterator iterator = reader.lookup( propertyValue ); iterator.hasNext(); ) { list.add( iterator.next() ); } Collections.sort( list ); return list; } } private void updateAndCommit( List<NodePropertyUpdate> updates ) throws IOException, IndexEntryConflictException { try ( IndexUpdater updater = accessor.newUpdater( IndexUpdateMode.ONLINE ) ) { for ( NodePropertyUpdate update : updates ) { updater.process( update ); } } } }
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_UniqueIndexAccessorCompatibility.java
4,743
private static class PredefinedSchemaIndexProviderFactory extends KernelExtensionFactory<PredefinedSchemaIndexProviderFactory.NoDeps> { private final SchemaIndexProvider indexProvider; @Override public Lifecycle newKernelExtension( NoDeps noDeps ) throws Throwable { return indexProvider; } public static interface NoDeps { } public PredefinedSchemaIndexProviderFactory( SchemaIndexProvider indexProvider ) { super( indexProvider.getClass().getSimpleName() ); this.indexProvider = indexProvider; } }
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_UniqueConstraintCompatibility.java
4,744
private abstract class Action implements Function<Transaction,Void> { private final String name; protected Action( String name ) { this.name = name; } @Override public String toString() { return name; } }
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_UniqueConstraintCompatibility.java
4,745
{ @Override public Void apply( Transaction transaction ) { assertThat( lookUpNode( propertyValue ), matcher ); return null; } };
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_UniqueConstraintCompatibility.java
4,746
{ @Override public Void apply( Transaction transaction ) { Assert.fail( message ); return null; } };
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_UniqueConstraintCompatibility.java
4,747
{ @Override public Void apply( Transaction transaction ) { node.addLabel( label ); return null; } };
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_UniqueConstraintCompatibility.java
4,748
{ @Override public Void apply( Transaction transaction ) { node.removeProperty( property ); return null; } };
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_UniqueConstraintCompatibility.java
4,749
{ @Override public Void apply( Transaction transaction ) { node.setProperty( property, value ); return null; } };
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_UniqueConstraintCompatibility.java
4,750
{ @Override public Void apply( Transaction transaction ) { Node node = db.createNode( label ); node.setProperty( property, propertyValue ); return null; } };
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_UniqueConstraintCompatibility.java
4,751
{ @Override public Void apply( Transaction transaction ) { transaction.success(); // We also call close() here, because some validations and checks don't run until commit transaction.close(); return null; } };
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_UniqueConstraintCompatibility.java
4,752
{ @Override public void run() { createUniqueConstraint( createConstraintTransactionStarted ); } } );
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_UniqueConstraintCompatibility.java
4,753
{ @Override public void run() { try ( Transaction tx = db.beginTx() ) { for ( Action action : actions ) { action.apply( tx ); } tx.success(); createNodeReadyLatch.countDown(); awaitUninterruptibly( createNodeCommitLatch ); } } } );
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_UniqueConstraintCompatibility.java
4,754
@Ignore( "Not a test. This is a compatibility suite that provides test cases for verifying" + " SchemaIndexProvider implementations. Each index provider that is to be tested by this suite" + " must create their own test class extending IndexProviderCompatibilityTestSuite." + " The @Ignore annotation doesn't prevent these tests to run, it rather removes some annoying" + " errors or warnings in some IDEs about test classes needing a public zero-arg constructor." ) public class UniqueConstraintCompatibility extends IndexProviderCompatibilityTestSuite.Compatibility { public UniqueConstraintCompatibility( IndexProviderCompatibilityTestSuite testSuite ) { super( testSuite ); } /* * There are a quite a number of permutations to consider, when it comes to unique * constraints. * * We have two supported providers: * - InMemoryIndexProvider * - LuceneSchemaIndexProvider * * An index can be in a number of states, two of which are interesting: * - ONLINE: the index is in active duty * - POPULATING: the index is in the process of being created and filled with data * * Further more, indexes that are POPULATING have two ways of ingesting data: * - Through add()'ing existing data * - Through NodePropertyUpdates sent to a "populating udpater" * * Then, when we add data to an index, two outcomes are possible, depending on the * data: * - The index does not contain an equivalent value, and the entity id is added to * the index. * - The index already contains an equivalent value, and the addition is rejected. * * And when it comes to observing these outcomes, there are a whole bunch of * interesting transaction states that are worth exploring: * - Adding a label to a node * - Removing a label from a node * - Combinations of adding and removing a label, ultimately adding it * - Combinations of adding and removing a label, ultimately removing it * - Adding a property * - Removing a property * - Changing an existing property * - Combinations of adding and removing a property, ultimately adding it * - Combinations of adding and removing a property, ultimately removing it * - Likewise combinations of adding, removing and changing a property * * To make matters worse, we index a number of different types, some of which may or * may not collide in the index because of coercion. We need to make sure that the * indexes deal with these values correctly. And we also have the ways in which these * operations can be performed in any number of transactions, for instance, if all * the conflicting nodes were added in the same transaction or not. * * All in all, we have many cases to test for! * * Still, it is possible to boild things down a little bit, because there are fewer * outcomes than there are scenarios that lead to those outcomes. With a bit of * luck, we can abstract over the scenarios that lead to those outcomes, and then * only write a test per outcome. These are the outcomes I see: * - Populating an index succeeds * - Populating an index fails because of the existing data * - Populating an index fails because of updates to data * - Adding to an online index succeeds * - Adding to an online index fails because of existing data * - Adding to an online index fails because of data in the same transaction * * There's a lot of work to be done here. */ // -- Tests: @Test public void onlineConstraintShouldAcceptDistinctValuesInDifferentTransactions() { // Given givenOnlineConstraint(); // When Node n; try ( Transaction tx = db.beginTx() ) { n = db.createNode( label ); n.setProperty( property, "n" ); tx.success(); } // Then transaction( assertLookupNode( "a", is( a ) ), assertLookupNode( "n" , is( n ) ) ); } @Test public void onlineConstraintShouldAcceptDistinctValuesInSameTransaction() { // Given givenOnlineConstraint(); // When Node n, m; try ( Transaction tx = db.beginTx() ) { n = db.createNode( label ); n.setProperty( property, "n" ); m = db.createNode( label ); m.setProperty( property, "m" ); tx.success(); } // Then transaction( assertLookupNode( "n", is( n ) ), assertLookupNode( "m", is( m ) ) ); } @Test public void onlineConstrainthouldNotFalselyCollideOnFindNodesByLabelAndProperty() throws Exception { // Given givenOnlineConstraint(); Node n, m; try ( Transaction tx = db.beginTx() ) { n = db.createNode( label ); n.setProperty( property, COLLISION_X ); tx.success(); } // When try ( Transaction tx = db.beginTx() ) { m = db.createNode( label ); m.setProperty( property, COLLISION_Y ); tx.success(); } // Then transaction( assertLookupNode( COLLISION_X, is( n ) ), assertLookupNode( COLLISION_Y, is( m ) ) ); } // Replaces UniqueIAC: shouldConsiderWholeTransactionForValidatingUniqueness @Test public void onlineConstraintShouldNotConflictOnIntermediateStatesInSameTransaction() { // Given givenOnlineConstraint(); // When transaction( setProperty( a, "b" ), setProperty( b, "a" ), success ); // Then transaction( assertLookupNode( "a", is( b ) ), assertLookupNode( "b", is( a ) ) ); } // Replaces UniqueIAC: shouldRejectChangingEntryToAlreadyIndexedValue @Test( expected = ConstraintViolationException.class ) public void onlineConstraintShouldRejectChangingEntryToAlreadyIndexedValue() { // Given givenOnlineConstraint(); transaction( setProperty( b, "b" ), success ); // When transaction( setProperty( b, "a" ), success, fail( "Changing a property to an already indexed value should have thrown" ) ); } // Replaces UniqueIPC: should*EnforceUnqieConstraintsAgainstDataAddedInSameTx @Test( expected = ConstraintViolationException.class) public void onlineConstraintShouldRejectConflictsInTheSameTransaction() throws Exception { // Given givenOnlineConstraint(); // Then transaction( setProperty( a, "x" ), setProperty( b, "x" ), success, fail( "Should have rejected changes of two node/properties to the same index value" ) ); } @Test public void onlineConstraintShouldRejectChangingEntryToAlreadyIndexedValueThatOtherTransactionsAreRemoving() throws Exception { // Given givenOnlineConstraint(); transaction( setProperty( b, "b" ), success ); Transaction otherTx = db.beginTx(); a.removeLabel( label ); suspend( otherTx ); // When try { transaction( setProperty( b, "a" ), success, fail( "Changing a property to an already indexed value should have thrown" ) ); } catch ( ConstraintViolationException ignore ) { // we're happy } finally { resume( otherTx ); otherTx.failure(); otherTx.close(); } } // Replaces UniqueIAC: shouldRemoveAndAddEntries @Test public void onlineConstraintShouldAddAndRemoveFromIndexAsPropertiesAndLabelsChange() { // Given givenOnlineConstraint(); // When transaction( setProperty( b, "b" ), success ); transaction( setProperty( c, "c" ), addLabel( c, label ), success ); transaction( setProperty( d, "d" ), addLabel( d, label ), success ); transaction( removeProperty( a ), success ); transaction( removeProperty( b ), success ); transaction( removeProperty( c ), success ); transaction( setProperty( a, "a" ), success ); transaction( setProperty( c, "c2" ), success ); // Then transaction( assertLookupNode( "a", is( a ) ), assertLookupNode( "b", is( nullValue( Node.class ) ) ), assertLookupNode( "c", is( nullValue( Node.class ) ) ), assertLookupNode( "d", is( d ) ), assertLookupNode( "c2", is( c ) ) ); } // Replaces UniqueIAC: shouldRejectEntryWithAlreadyIndexedValue @Test( expected = ConstraintViolationException.class ) public void onlineConstraintShouldRejectConflictingPropertyChange() { // Given givenOnlineConstraint(); // Then transaction( setProperty( b, "a" ), success, fail( "Setting b.name = \"a\" should have caused a conflict" ) ); } @Test( expected = ConstraintViolationException.class ) public void onlineConstraintShouldRejectConflictingLabelChange() { // Given givenOnlineConstraint(); // Then transaction( addLabel( c, label ), success, fail( "Setting c:Cybermen should have caused a conflict" ) ); } // Replaces UniqueIAC: shouldRejectAddingEntryToValueAlreadyIndexedByPriorChange @Test( expected = ConstraintViolationException.class ) public void onlineConstraintShouldRejectAddingEntryForValueAlreadyIndexedByPriorChange() { // Given givenOnlineConstraint(); // When transaction( setProperty( a, "a1" ), success ); // This is a CHANGE update // Then transaction( setProperty( b, "a1" ), success, fail( "Setting b.name = \"a1\" should have caused a conflict" ) ); } // Replaces UniqueIAC: shouldAddUniqueEntries // Replaces UniqueIPC: should*EnforceUniqueConstraintsAgainstDataAddedOnline @Test public void onlineConstraintShouldAcceptUniqueEntries() { // Given givenOnlineConstraint(); // When transaction( setProperty( b, "b" ), addLabel( d, label ), success ); transaction( setProperty( c, "c" ), addLabel( c, label ), success ); // Then transaction( assertLookupNode( "a", is( a ) ), assertLookupNode( "b", is( b ) ), assertLookupNode( "c", is( c ) ), assertLookupNode( "d", is( d ) ) ); } // Replaces UniqueIAC: shouldUpdateUniqueEntries @Test public void onlineConstraintShouldAcceptUniqueEntryChanges() { // Given givenOnlineConstraint(); // When transaction( setProperty( a, "a1" ), success ); // This is a CHANGE update // Then transaction( assertLookupNode( "a1", is( a ) ) ); } // Replaces UniqueIAC: shoouldRejectEntriesInSameTransactionWithDuplicateIndexedValue\ @Test( expected = ConstraintViolationException.class ) public void onlineConstraintShouldRejectDuplicateEntriesAddedInSameTransaction() { // Given givenOnlineConstraint(); // Then transaction( setProperty( b, "d" ), addLabel( d, label ), success, fail( "Setting b.name = \"d\" and d:Cybermen should have caused a conflict" )); } // Replaces UniqueIPC: should*EnforceUniqueConstraints // Replaces UniqueIPC: should*EnforceUniqueConstraintsAgainstDataAddedThroughPopulator @Test public void populatingConstraintMustAcceptDatasetOfUniqueEntries() { // Given givenUniqueDataset(); // Then this does not throw: createUniqueConstraint(); } @Test( expected = ConstraintViolationException.class ) public void populatingConstraintMustRejectDatasetWithDuplicateEntries() { // Given givenUniqueDataset(); transaction( setProperty( c, "b" ), // same property value as 'b' has success ); // Then this must throw: createUniqueConstraint(); } @Test public void populatingConstraintMustAcceptDatasetWithDalseIndexCollisions() { // Given givenUniqueDataset(); transaction( setProperty( b, COLLISION_X ), setProperty( c, COLLISION_Y ), success ); // Then this does not throw: createUniqueConstraint(); } @Test public void populatingConstraintMustAcceptDatasetThatGetsUpdatedWithUniqueEntries() throws Exception { // Given givenUniqueDataset(); // When Future<?> createConstraintTransaction = applyChangesToPopulatingUpdater( d.getId(), a.getId(), setProperty( d, "d1" ) ); // Then observe that our constraint was created successfully: createConstraintTransaction.get(); // Future.get() will throw an ExecutionException, if the Runnable threw an exception. } // Replaces UniqueLucIAT: shouldRejectEntryWithAlreadyIndexedValue @Test public void populatingConstraintMustRejectDatasetThatGetsUpdatedWithDuplicateAddition() throws Exception { // Given givenUniqueDataset(); // When Future<?> createConstraintTransaction = applyChangesToPopulatingUpdater( d.getId(), a.getId(), createNode( "b" ) ); // Then observe that our constraint creation failed: try { createConstraintTransaction.get(); Assert.fail( "expected to throw when PopulatingUpdater got duplicates" ); } catch ( ExecutionException ee ) { Throwable cause = ee.getCause(); assertThat( cause, instanceOf( ConstraintViolationException.class ) ); } } // Replaces UniqueLucIAT: shouldRejectChangingEntryToAlreadyIndexedValue @Test public void populatingConstraintMustRejectDatasetThatGetsUpdatedWithDuplicates() throws Exception { // Given givenUniqueDataset(); // When Future<?> createConstraintTransaction = applyChangesToPopulatingUpdater( d.getId(), a.getId(), setProperty( d, "b" ) ); // Then observe that our constraint creation failed: try { createConstraintTransaction.get(); Assert.fail( "expected to throw when PopulatingUpdater got duplicates" ); } catch ( ExecutionException ee ) { Throwable cause = ee.getCause(); assertThat( cause, instanceOf( ConstraintViolationException.class ) ); } } @Test public void populatingConstraintMustAcceptDatasetThatGestUpdatedWithFalseIndexCollisions() throws Exception { // Given givenUniqueDataset(); transaction( setProperty( a, COLLISION_X ), success ); // When Future<?> createConstraintTransaction = applyChangesToPopulatingUpdater( d.getId(), a.getId(), setProperty( d, COLLISION_Y ) ); // Then observe that our constraint was created successfully: createConstraintTransaction.get(); // Future.get() will throw an ExecutionException, if the Runnable threw an exception. } // Replaces UniqueLucIAT: shouldRejectEntriesInSameTransactionWithDuplicatedIndexedValues @Test public void populatingConstraintMustRejectDatasetThatGetsUpdatedWithDuplicatesInSameTransaction() throws Exception { // Given givenUniqueDataset(); // When Future<?> createConstraintTransaction = applyChangesToPopulatingUpdater( d.getId(), a.getId(), setProperty( d, "x" ), setProperty( c, "x" ) ); // Then observe that our constraint creation failed: try { createConstraintTransaction.get(); Assert.fail( "expected to throw when PopulatingUpdater got duplicates" ); } catch ( ExecutionException ee ) { Throwable cause = ee.getCause(); assertThat( cause, instanceOf( ConstraintViolationException.class ) ); } } @Test public void populatingConstraintMustAcceptDatasetThatGetsUpdatedWithDuplicatesThatAreLaterResolved() throws Exception { // Given givenUniqueDataset(); // When Future<?> createConstraintTransaction = applyChangesToPopulatingUpdater( d.getId(), a.getId(), setProperty( d, "b" ), // Cannot touch node 'a' because that one is locked setProperty( b, "c" ), setProperty( c, "d" ) ); // Then observe that our constraint was created successfully: createConstraintTransaction.get(); // Future.get() will throw an ExecutionException, if the Runnable threw an exception. } // Replaces UniqueLucIAT: shouldRejectAddingEntryToValueAlreadyIndexedByPriorChange @Test public void populatingUpdaterMustRejectDatasetWhereAdditionsConflictsWithPriorChanges() throws Exception { // Given givenUniqueDataset(); // When Future<?> createConstraintTransaction = applyChangesToPopulatingUpdater( d.getId(), a.getId(), setProperty( d, "x" ), createNode( "x" ) ); // Then observe that our constraint creation failed: try { createConstraintTransaction.get(); Assert.fail( "expected to throw when PopulatingUpdater got duplicates" ); } catch ( ExecutionException ee ) { Throwable cause = ee.getCause(); assertThat( cause, instanceOf( ConstraintViolationException.class ) ); } } /** * NOTE the tests using this will currently succeed for the wrong reasons, * because the data-changing transaction does not actually release the * schema read lock early enough for the PopulatingUpdater to come into * play. */ private Future<?> applyChangesToPopulatingUpdater( long blockDataChangeTransactionOnLockOnId, long blockPopulatorOnLockOnId, final Action... actions ) throws InterruptedException, ExecutionException { // We want to issue an update to an index populator for a constraint. // However, creating a constraint takes a schema write lock, while // creating nodes and setting their properties takes a schema read // lock. We need to sneak past these locks. final CountDownLatch createNodeReadyLatch = new CountDownLatch( 1 ); final CountDownLatch createNodeCommitLatch = new CountDownLatch( 1 ); Future<?> updatingTransaction = executor.submit( new Runnable() { @Override public void run() { try ( Transaction tx = db.beginTx() ) { for ( Action action : actions ) { action.apply( tx ); } tx.success(); createNodeReadyLatch.countDown(); awaitUninterruptibly( createNodeCommitLatch ); } } } ); createNodeReadyLatch.await(); // The above transaction now contain the changes we want to expose to // the IndexUpdater as updates. This will happen when we commit the // transaction. The transaction now also holds the schema read lock, // so we can't begin creating our constraint just yet. // We first have to unlock the schema, and then block just before we // send off our updates. We can do that by making another thread take a // read lock on the node we just created, and then initiate our commit. Lock lockBlockingDataChangeTransaction = getLockService().acquireNodeLock( blockDataChangeTransactionOnLockOnId, LockType.WRITE_LOCK ); // Before we begin creating the constraint, we take a write lock on an // "earlier" node, to hold up the populator for the constraint index. Lock lockBlockingIndexPopulator = getLockService().acquireNodeLock( blockPopulatorOnLockOnId, LockType.WRITE_LOCK ); // This thread tries to create a constraint. It should block, waiting for it's // population job to finish, and it's population job should in turn be blocked // on the lockBlockingIndexPopulator above: final CountDownLatch createConstraintTransactionStarted = new CountDownLatch( 1 ); Future<?> createConstraintTransaction = executor.submit( new Runnable() { @Override public void run() { createUniqueConstraint( createConstraintTransactionStarted ); } } ); createConstraintTransactionStarted.await(); // Now we can initiate the data-changing commit. It should then // release the schema read lock, and block on the // lockBlockingDataChangeTransaction. createNodeCommitLatch.countDown(); // Now we can issue updates to the populator in the still ongoing population job. // We do that by releasing the lock that is currently preventing our // data-changing transaction from committing. lockBlockingDataChangeTransaction.release(); // And we observe that our updating transaction has completed as well: updatingTransaction.get(); // Now we can release the lock blocking the populator, allowing it to finish: lockBlockingIndexPopulator.release(); // And return the future for examination: return createConstraintTransaction; } // -- Set Up: Data parts // These two values coalesce to the same double value, and therefor collides in our current index implementation: private static final long COLLISION_X = 4611686018427387905L; private static final long COLLISION_Y = 4611686018427387907L; private static final ExecutorService executor = Executors.newCachedThreadPool(); private Label label = DynamicLabel.label( "Cybermen" ); private String property = "name"; private Node a; private Node b; private Node c; private Node d; private GraphDatabaseService db; /** * Effectively: * * <pre><code> * CREATE CONSTRAINT ON (n:Cybermen) assert n.name is unique * ; * * CREATE (a:Cybermen {name: "a"}), * (b:Cybermen), * (c: {name: "a"}), * (d: {name: "d"}) * ; * </code></pre> */ private void givenOnlineConstraint() { createUniqueConstraint(); try ( Transaction tx = db.beginTx() ) { a = db.createNode( label ); a.setProperty( property, "a" ); b = db.createNode( label ); c = db.createNode(); c.setProperty( property, "a" ); d = db.createNode(); d.setProperty( property, "d" ); tx.success(); } } /** * Effectively: * * <pre><code> * CREATE (a:Cybermen {name: "a"}), * (b:Cybermen {name: "b"}), * (c:Cybermen {name: "c"}), * (d:Cybermen {name: "d"}) * ; * </code></pre> */ private void givenUniqueDataset() { try ( Transaction tx = db.beginTx() ) { a = db.createNode( label ); a.setProperty( property, "a" ); b = db.createNode( label ); b.setProperty( property, "b" ); c = db.createNode( label ); c.setProperty( property, "c" ); d = db.createNode( label ); d.setProperty( property, "d" ); tx.success(); } } /** * Effectively: * * <pre><code> * CREATE CONSTRAINT ON (n:Cybermen) assert n.name is unique * ; * </code></pre> */ private void createUniqueConstraint() { createUniqueConstraint( null ); } /** * Effectively: * * <pre><code> * CREATE CONSTRAINT ON (n:Cybermen) assert n.name is unique * ; * </code></pre> * * Also counts down the given latch prior to creating the constraint. */ private void createUniqueConstraint( CountDownLatch preCreateLatch ) { try ( Transaction tx = db.beginTx() ) { if ( preCreateLatch != null ) { preCreateLatch.countDown(); } db.schema().constraintFor( label ).assertPropertyIsUnique( property ).create(); tx.success(); } } /** * Effectively: * * <pre><code> * return single( db.findNodesByLabelAndProperty( label, property, value ), null ); * </code></pre> */ private Node lookUpNode( Object value ) { return single( db.findNodesByLabelAndProperty( label, property, value ), null ); } // -- Set Up: Transaction handling public void transaction( Action... actions ) { int progress = 0; try ( Transaction tx = db.beginTx() ) { for ( Action action : actions ) { action.apply( tx ); progress++; } } catch ( Throwable ex ) { StringBuilder sb = new StringBuilder( "Transaction failed:\n\n" ); for ( int i = 0; i < actions.length; i++ ) { String mark = progress == i? " failed --> " : " "; sb.append( mark ).append( actions[i] ).append( '\n' ); } ex.addSuppressed( new AssertionError( sb.toString() ) ); throw ex; } } private abstract class Action implements Function<Transaction,Void> { private final String name; protected Action( String name ) { this.name = name; } @Override public String toString() { return name; } } private final Action success = new Action( "tx.success();" ) { @Override public Void apply( Transaction transaction ) { transaction.success(); // We also call close() here, because some validations and checks don't run until commit transaction.close(); return null; } }; private Action createNode( final Object propertyValue ) { return new Action( "Node node = db.createNode( label ); " + "node.setProperty( property, " + reprValue( propertyValue ) + " );" ) { @Override public Void apply( Transaction transaction ) { Node node = db.createNode( label ); node.setProperty( property, propertyValue ); return null; } }; } private Action setProperty( final Node node, final Object value ) { return new Action( reprNode( node ) + ".setProperty( property, " + reprValue( value ) + " );") { @Override public Void apply( Transaction transaction ) { node.setProperty( property, value ); return null; } }; } private Action removeProperty( final Node node ) { return new Action( reprNode( node ) + ".removeProperty( property );") { @Override public Void apply( Transaction transaction ) { node.removeProperty( property ); return null; } }; } private Action addLabel( final Node node, final Label label ) { return new Action( reprNode( node ) + ".addLabel( " + label + " );" ) { @Override public Void apply( Transaction transaction ) { node.addLabel( label ); return null; } }; } private Action fail( final String message ) { return new Action( "fail( \"" + message + "\" );") { @Override public Void apply( Transaction transaction ) { Assert.fail( message ); return null; } }; } private Action assertLookupNode( final Object propertyValue, final Matcher<Node> matcher ) { return new Action( "assertThat( lookUpNode( " + reprValue( propertyValue ) + " ), " + matcher + " );" ) { @Override public Void apply( Transaction transaction ) { assertThat( lookUpNode( propertyValue ), matcher ); return null; } }; } private String reprValue( Object value ) { return value instanceof String? "\"" + value + "\"" : String.valueOf( value ); } private String reprNode( Node node ) { return node == a? "a" : node == b? "b" : node == c? "c" : node == d? "d" : "n"; } // -- Set Up: Advanced transaction handling private final Map<Transaction, javax.transaction.Transaction> txMap = new IdentityHashMap<>(); private void suspend( Transaction tx ) throws Exception { TransactionManager txManager = getTransactionManager(); txMap.put( tx, txManager.suspend() ); } private void resume( Transaction tx ) throws Exception { TransactionManager txManager = getTransactionManager(); txManager.resume( txMap.remove( tx ) ); } private TransactionManager getTransactionManager() { return resolveInternalDependency( TransactionManager.class ); } // -- Set Up: Misc. sharp tools /** * Locks controlling concurrent access to the store files. */ private LockService getLockService() { return resolveInternalDependency( LockService.class ); } private <T> T resolveInternalDependency( Class<T> type ) { @SuppressWarnings("deprecation") GraphDatabaseAPI api = (GraphDatabaseAPI) db; DependencyResolver resolver = api.getDependencyResolver(); return resolver.resolveDependency( type ); } private static void awaitUninterruptibly( CountDownLatch latch ) { try { latch.await(); } catch ( InterruptedException e ) { throw new AssertionError( "Interrupted", e ); } } // -- Set Up: Environment parts @Rule public TargetDirectory.TestDirectory testDirectory = TargetDirectory.testDirForTest( getClass() ); @Before public void setUp() { String storeDir = testDirectory.absolutePath(); TestGraphDatabaseFactory dbfactory = new TestGraphDatabaseFactory(); dbfactory.addKernelExtension( new PredefinedSchemaIndexProviderFactory( indexProvider ) ); db = dbfactory.newImpermanentDatabase( storeDir ); } @After public void tearDown() { db.shutdown(); } private static class PredefinedSchemaIndexProviderFactory extends KernelExtensionFactory<PredefinedSchemaIndexProviderFactory.NoDeps> { private final SchemaIndexProvider indexProvider; @Override public Lifecycle newKernelExtension( NoDeps noDeps ) throws Throwable { return indexProvider; } public static interface NoDeps { } public PredefinedSchemaIndexProviderFactory( SchemaIndexProvider indexProvider ) { super( indexProvider.getClass().getSimpleName() ); this.indexProvider = indexProvider; } } }
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_UniqueConstraintCompatibility.java
4,755
class Adapter implements IndexPopulator { @Override public void create() throws IOException { } @Override public void drop() throws IOException { } @Override public void add( long nodeId, Object propertyValue ) throws IndexEntryConflictException, IOException { } @Override public void verifyDeferredConstraints( PropertyAccessor accessor ) throws IndexEntryConflictException, IOException { } @Override public IndexUpdater newPopulatingUpdater( PropertyAccessor accessor ) { return SwallowingIndexUpdater.INSTANCE; } @Override public void close( boolean populationCompletedSuccessfully ) throws IOException { } @Override public void markAsFailed( String failure ) { } }
false
community_kernel_src_main_java_org_neo4j_kernel_api_index_IndexPopulator.java
4,756
public abstract class IndexEntryConflictException extends Exception { public IndexEntryConflictException( String message ) { super( message ); } protected static String quote( Object propertyValue ) { if ( propertyValue instanceof String ) { return format( "'%s'", propertyValue ); } else if ( propertyValue.getClass().isArray() ) { Class<?> type = propertyValue.getClass().getComponentType(); if ( type == Boolean.TYPE ) { return Arrays.toString( (boolean[]) propertyValue ); } else if ( type == Byte.TYPE ) { return Arrays.toString( (byte[]) propertyValue ); } else if ( type == Short.TYPE ) { return Arrays.toString( (short[]) propertyValue ); } else if ( type == Character.TYPE ) { return Arrays.toString( (char[]) propertyValue ); } else if ( type == Integer.TYPE ) { return Arrays.toString( (int[]) propertyValue ); } else if ( type == Long.TYPE ) { return Arrays.toString( (long[]) propertyValue ); } else if ( type == Float.TYPE ) { return Arrays.toString( (float[]) propertyValue ); } else if ( type == Double.TYPE ) { return Arrays.toString( (double[]) propertyValue ); } return Arrays.toString( (Object[]) propertyValue ); } return valueOf( propertyValue ); } /** * Use this method in cases where {@link org.neo4j.kernel.api.index.IndexEntryConflictException} was caught but it should not have been * allowed to be thrown in the first place. Typically where the index we performed an operation on is not a * unique index. */ public RuntimeException notAllowed( int labelId, int propertyKeyId ) { return new IllegalStateException( String.format( "Index for label:%s propertyKey:%s should not require unique values.", labelId, propertyKeyId ), this ); } public RuntimeException notAllowed( IndexDescriptor descriptor ) { return notAllowed( descriptor.getLabelId(), descriptor.getPropertyKeyId() ); } public abstract Object getPropertyValue(); public abstract String evidenceMessage( String labelName, String propertyKey ); }
false
community_kernel_src_main_java_org_neo4j_kernel_api_index_IndexEntryConflictException.java
4,757
public class IndexDescriptor { private final int labelId; private final int propertyKeyId; public IndexDescriptor( int labelId, int propertyKeyId ) { this.labelId = labelId; this.propertyKeyId = propertyKeyId; } @Override public boolean equals( Object obj ) { if ( this == obj ) { return true; } if ( obj != null && getClass() == obj.getClass() ) { IndexDescriptor that = (IndexDescriptor) obj; return this.labelId == that.labelId && this.propertyKeyId == that.propertyKeyId; } return false; } @Override public int hashCode() { int result = labelId; result = 31 * result + propertyKeyId; return result; } public int getLabelId() { return labelId; } public int getPropertyKeyId() { return propertyKeyId; } @Override public String toString() { return format( ":label[%d](property[%d])", labelId, propertyKeyId ); } public String userDescription( TokenNameLookup tokenNameLookup ) { return format( ":%s(%s)", tokenNameLookup.labelGetName( labelId ), tokenNameLookup.propertyKeyGetName( propertyKeyId ) ); } }
false
community_kernel_src_main_java_org_neo4j_kernel_api_index_IndexDescriptor.java
4,758
public class IndexConfiguration { private final boolean unique; public IndexConfiguration( boolean unique ) { this.unique = unique; } public boolean isUnique() { return unique; } @Override public boolean equals( Object o ) { return this == o || !(o == null || getClass() != o.getClass()) && unique == ((IndexConfiguration) o).unique; } @Override public int hashCode() { return (unique ? 1 : 0); } }
false
community_kernel_src_main_java_org_neo4j_kernel_api_index_IndexConfiguration.java
4,759
{ @Override protected boolean matchesSafely( List<?> item ) { return item.size() == size; } @Override public void describeTo( Description description ) { description.appendText( "List with size=" ).appendValue( size ); } };
false
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_UniqueIndexApplicationIT.java
4,760
@RunWith(Parameterized.class) public class UniqueIndexApplicationIT { public final @Rule DatabaseRule db = new ImpermanentDatabaseRule(); @Parameterized.Parameters(name = "{0}") public static List<Object[]> indexTypes() { return asList( createIndex( index( label( "Label1" ), "key1" ) ), createIndex( uniquenessConstraint( label( "Label1" ), "key1" ) ) ); } private final Function<GraphDatabaseService, ?> createIndex; @Before public void given() throws Exception { db.executeAndCommit( createIndex ); db.executeAndCommit( awaitIndexesOnline( 5, SECONDS ) ); } @Test public void tx_createNode_addLabel_setProperty() throws Exception { db.when( db.tx( createNode().then( addLabel( label( "Label1" ) ).then( setProperty( "key1", "value1" ) ) ) ) ); } @Test public void tx_createNode_tx_addLabel_setProperty() throws Exception { db.when( db.tx( createNode() ).then( db.tx( addLabel( label( "Label1" ) ).then( setProperty( "key1", "value1" ) ) ) ) ); } @Test public void tx_createNode_addLabel_tx_setProperty() throws Exception { db.when( db.tx( createNode().then( addLabel( label( "Label1" ) ) ) ).then( db.tx( setProperty( "key1", "value1" ) ) ) ); } @Test public void tx_createNode_setProperty_tx_addLabel() throws Exception { db.when( db.tx( createNode().then( setProperty( "key1", "value1" ) ) ).then( db.tx( addLabel( label( "Label1" ) ) ) ) ); } @Test public void tx_createNode_tx_addLabel_tx_setProperty() throws Exception { db.when( db.tx( createNode() ).then( db.tx( addLabel( label( "Label1" ) ) ).then( db.tx( setProperty( "key1", "value1" ) ) ) ) ); } @Test public void tx_createNode_tx_setProperty_tx_addLabel() throws Exception { db.when( db.tx( createNode() ).then( db.tx( setProperty( "key1", "value1" ) ).then( db.tx( addLabel( label( "Label1" ) ) ) ) ) ); } @After public void then() throws Exception { assertThat( "Matching nodes from index lookup", db.when( db.tx( listNodeIdsFromIndexLookup( label( "Label1" ), "key1", "value1" ) ) ), hasSize( 1 ) ); } private static Matcher<List<?>> hasSize( final int size ) { return new TypeSafeMatcher<List<?>>() { @Override protected boolean matchesSafely( List<?> item ) { return item.size() == size; } @Override public void describeTo( Description description ) { description.appendText( "List with size=" ).appendValue( size ); } }; } private Function<GraphDatabaseService, List<Long>> listNodeIdsFromIndexLookup( final Label label, final String propertyKey, final Object value ) { return new Function<GraphDatabaseService, List<Long>>() { @Override public List<Long> apply( GraphDatabaseService graphDb ) { ArrayList<Long> ids = new ArrayList<>(); for ( Node node : graphDb.findNodesByLabelAndProperty( label, propertyKey, value ) ) { ids.add( node.getId() ); } return ids; } }; } public UniqueIndexApplicationIT( Function<GraphDatabaseService, ?> createIndex ) { this.createIndex = createIndex; } private static Object[] createIndex( Function<GraphDatabaseService, Void> createIndex ) { return new Object[]{createIndex}; } }
false
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_UniqueIndexApplicationIT.java
4,761
public class SchemaIndexAcceptanceTest { @Test public void creatingIndexOnExistingDataBuildsIndexWhichWillBeOnlineNextStartup() throws Exception { Transaction tx = db.beginTx(); Node node1 = createNode( label, "name", "One" ); Node node2 = createNode( label, "name", "Two" ); Node node3 = createNode( label, "name", "Three" ); tx.success(); tx.finish(); createIndex( db, label, propertyKey ); restart(); assertThat( findNodesByLabelAndProperty( label, "name", "One", db ), containsOnly( node1 ) ); assertThat( findNodesByLabelAndProperty( label, "name", "Two", db ), containsOnly( node2 ) ); assertThat( findNodesByLabelAndProperty( label, "name", "Three", db ), containsOnly( node3 ) ); } @Test public void shouldIndexArrays() throws Exception { long[] arrayPropertyValue = {42, 23, 87}; createIndex( db, label, propertyKey ); Transaction tx = db.beginTx(); Node node1 = createNode( label, propertyKey, arrayPropertyValue ); tx.success(); tx.finish(); restart(); assertThat( getIndexes( db, label ), inTx( db, haveState( db, IndexState.ONLINE ) )); assertThat( findNodesByLabelAndProperty( label, propertyKey, arrayPropertyValue, db ), containsOnly( node1 ) ); assertThat( findNodesByLabelAndProperty( label, propertyKey, new long[]{42, 23}, db ), isEmpty() ); assertThat( findNodesByLabelAndProperty( label, propertyKey, Arrays.toString( arrayPropertyValue ), db ), isEmpty() ); } @Test public void shouldIndexStringArrays() throws Exception { String[] arrayPropertyValue = {"A, B", "C"}; createIndex( db, label, propertyKey ); Transaction tx = db.beginTx(); Node node1 = createNode( label, propertyKey, arrayPropertyValue ); tx.success(); tx.finish(); restart(); assertThat( getIndexes( db, label ), inTx( db, haveState( db, IndexState.ONLINE ) ) ); assertThat( findNodesByLabelAndProperty( label, propertyKey, arrayPropertyValue, db ), containsOnly( node1 ) ); assertThat( findNodesByLabelAndProperty( label, propertyKey, new String[]{"A", "B, C"}, db ), isEmpty() ); assertThat( findNodesByLabelAndProperty( label, propertyKey, Arrays.toString( arrayPropertyValue ), db ), isEmpty() ); } @Test public void shouldIndexArraysPostPopulation() throws Exception { long[] arrayPropertyValue = {42, 23, 87}; Transaction tx = db.beginTx(); Node node1 = createNode( label, propertyKey, arrayPropertyValue ); tx.success(); tx.finish(); createIndex( db, label, propertyKey ); restart(); assertThat( getIndexes( db, label ), inTx( db, haveState( db, IndexState.ONLINE ) ) ); assertThat( findNodesByLabelAndProperty( label, propertyKey, arrayPropertyValue, db ), containsOnly( node1 ) ); assertThat( findNodesByLabelAndProperty( label, propertyKey, new long[]{42, 23}, db ), isEmpty() ); assertThat( findNodesByLabelAndProperty( label, propertyKey, Arrays.toString( arrayPropertyValue ), db ), isEmpty() ); } @Test public void recoveryAfterCreateAndDropIndex() throws Exception { // GIVEN IndexDefinition indexDefinition = createIndex( db, label, propertyKey ); createSomeData( label, propertyKey ); doStuff( db, label, propertyKey ); dropIndex( indexDefinition ); doStuff( db, label, propertyKey ); // WHEN crashAndRestart(); // THEN assertThat( getIndexes( db, label ), isEmpty() ); } private EphemeralFileSystemAbstraction fs = new EphemeralFileSystemAbstraction(); private GraphDatabaseService db; private final Label label = label( "PERSON" ); private final String propertyKey = "key"; @Before public void before() throws Exception { db = newDb(); } private GraphDatabaseService newDb() { return new TestGraphDatabaseFactory().setFileSystem( fs ).newImpermanentDatabase(); } private void crashAndRestart() { EphemeralFileSystemAbstraction snapshot = fs.snapshot(); db.shutdown(); fs.shutdown(); fs = snapshot; db = newDb(); } private void restart() { db.shutdown(); db = newDb(); } @After public void after() throws Exception { db.shutdown(); } private Node createNode( Label label, Object... properties ) { Node node = db.createNode( label ); for ( Map.Entry<String, Object> property : map( properties ).entrySet() ) { node.setProperty( property.getKey(), property.getValue() ); } return node; } private void dropIndex( IndexDefinition indexDefinition ) { Transaction tx = db.beginTx(); indexDefinition.drop(); tx.success(); tx.finish(); } private static void doStuff( GraphDatabaseService db, Label label, String propertyKey ) { Transaction tx = db.beginTx(); try { Iterable<Node> nodes = db.findNodesByLabelAndProperty( label, propertyKey, 3323 ); for ( Node node : nodes ) { count( node.getLabels() ); } } finally { tx.finish(); } } private void createSomeData( Label label, String propertyKey ) { Transaction tx = db.beginTx(); try { Node node = db.createNode( label ); node.setProperty( propertyKey, "yeah" ); tx.success(); } finally { tx.finish(); } } }
false
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_SchemaIndexAcceptanceTest.java
4,762
@RunWith(Parameterized.class) public class PageOfRangesIteratorTest { @Parameterized.Parameters(name = "{0} bits") public static List<Object[]> formats() { ArrayList<Object[]> parameters = new ArrayList<>(); for ( BitmapDocumentFormat format : BitmapDocumentFormat.values() ) { parameters.add( new Object[]{format} ); } return parameters; } private final BitmapDocumentFormat format; public PageOfRangesIteratorTest( BitmapDocumentFormat format ) { this.format = format; } @Test public void shouldReadPagesOfDocumentsFromSearcher() throws Exception { final int labelId = 7; final int pageSize = 2; // given Query query = mock( Query.class ); IndexSearcher searcher = mock( IndexSearcher.class ); ScoreDoc doc1 = new ScoreDoc( 37, 0.0f ); ScoreDoc doc2 = new ScoreDoc( 16, 0.0f ); ScoreDoc doc3 = new ScoreDoc( 11, 0.0f ); when( searcher.searchAfter( any( ScoreDoc.class ), same( query ), anyInt() ) ).thenReturn( docs( doc1, doc2 ), // page1 docs( doc3 ) // page2 ); when( searcher.doc( 37 ) ).thenReturn( document( format.rangeField( 0x1 ), format.labelField( labelId, 0x01 ) ) ); when( searcher.doc( 16 ) ).thenReturn( document( format.rangeField( 0x2 ), format.labelField( labelId, 0x03 ) ) ); when( searcher.doc( 11 ) ).thenReturn( document( format.rangeField( 0x3 ), format.labelField( labelId, 0x30 ) ) ); PrimitiveLongIterator iterator = flatten( new PageOfRangesIterator( format, searcher, pageSize, query, labelId ) ); // when List<Long> longs = primitivesList( iterator ); // then assertEquals( asList( /*doc1:*/(1L << format.bitmapFormat().shift), /*doc2:*/(2L << format.bitmapFormat().shift), (2L << format.bitmapFormat().shift) + 1, /*doc3:*/(3L << format.bitmapFormat().shift) + 4, (3L << format.bitmapFormat().shift) + 5 ), longs ); ArgumentCaptor<ScoreDoc> prefixCollector = ArgumentCaptor.forClass( ScoreDoc.class ); verify( searcher, times( 2 ) ).searchAfter( prefixCollector.capture(), same( query ), eq( 2 ) ); assertEquals( asList( null, doc2 ), prefixCollector.getAllValues() ); verify( searcher, times( 3 ) ).doc( anyInt() ); verifyNoMoreInteractions( searcher ); } static TopDocs docs( ScoreDoc... docs ) { return new TopDocs( docs.length, docs, 0.0f ); } static Document document( Fieldable... fields ) { Document document = new Document(); for ( Fieldable field : fields ) { document.add( field ); } return document; } }
false
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_PageOfRangesIteratorTest.java
4,763
class PageOfRangesIterator extends PrefetchingIterator<PrimitiveLongIterator> { private IndexSearcher searcher; private final Query query; private final BitmapDocumentFormat format; private final int rangesPerPage; private final int[] labels; private ScoreDoc lastDoc; PageOfRangesIterator( BitmapDocumentFormat format, IndexSearcher searcher, int rangesPerPage, Query query, int... labels ) { this.searcher = searcher; this.query = query; this.format = format; this.rangesPerPage = rangesPerPage; this.labels = labels; if (labels.length == 0) { throw new IllegalArgumentException( "At least one label required" ); } } @Override protected PrimitiveLongIterator fetchNextOrNull() { if ( searcher == null ) { return null; // we are done searching with this iterator } try { TopDocs docs = searcher.searchAfter( lastDoc, query, rangesPerPage ); lastDoc = null; int docCount = docs != null ? docs.scoreDocs.length : 0; if ( docCount == 0 ) { searcher = null; // avoid searching again return null; } lastDoc = docs.scoreDocs[docCount - 1]; long[] rangeMap = new long[docCount * 2]; for ( int i = 0; i < docCount; i++ ) { Document doc = searcher.doc( docs.scoreDocs[i].doc ); rangeMap[i * 2] = format.rangeOf( doc ); rangeMap[i * 2 + 1] = labeledBitmap( doc ); } if ( docCount < rangesPerPage ) // not a full page => this is the last page (optimization) { searcher = null; // avoid searching again } return new LongPageIterator( new BitmapExtractor( format.bitmapFormat(), rangeMap ) ); } catch ( IOException e ) { throw new RuntimeException( e ); // TODO: something better? } } private long labeledBitmap( Document doc ) { long bitmap = -1; for ( int label : labels ) { bitmap &= format.mapOf( doc, label ); } return bitmap; } }
false
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_PageOfRangesIterator.java
4,764
{ @Override public void process( NodePropertyUpdate update ) throws IOException, IndexEntryConflictException { updates.add( update ); } @Override public void close() throws IOException, IndexEntryConflictException { if ( updates.size() > queueThreshold ) { flush(); updates.clear(); } } @Override public void remove( Iterable<Long> nodeIds ) throws IOException { throw new UnsupportedOperationException( "Should not remove() from populating index." ); } };
false
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_NonUniqueLuceneIndexPopulator.java
4,765
class NonUniqueLuceneIndexPopulator extends LuceneIndexPopulator { static final int DEFAULT_QUEUE_THRESHOLD = 10000; private final int queueThreshold; private final List<NodePropertyUpdate> updates = new ArrayList<>(); NonUniqueLuceneIndexPopulator( int queueThreshold, LuceneDocumentStructure documentStructure, LuceneIndexWriterFactory indexWriterFactory, IndexWriterStatus writerStatus, DirectoryFactory dirFactory, File dirFile, FailureStorage failureStorage, long indexId ) { super( documentStructure, indexWriterFactory, writerStatus, dirFactory, dirFile, failureStorage, indexId ); this.queueThreshold = queueThreshold; } @Override public void add( long nodeId, Object propertyValue ) throws IOException { writer.addDocument( documentStructure.newDocumentRepresentingProperty( nodeId, propertyValue ) ); } @Override public void verifyDeferredConstraints( PropertyAccessor accessor ) throws IndexEntryConflictException, IOException { // no constraints to verify so do nothing } @Override public IndexUpdater newPopulatingUpdater( PropertyAccessor propertyAccessor ) throws IOException { return new IndexUpdater() { @Override public void process( NodePropertyUpdate update ) throws IOException, IndexEntryConflictException { updates.add( update ); } @Override public void close() throws IOException, IndexEntryConflictException { if ( updates.size() > queueThreshold ) { flush(); updates.clear(); } } @Override public void remove( Iterable<Long> nodeIds ) throws IOException { throw new UnsupportedOperationException( "Should not remove() from populating index." ); } }; } @Override protected void flush() throws IOException { for ( NodePropertyUpdate update : this.updates ) { long nodeId = update.getNodeId(); switch ( update.getUpdateMode() ) { case ADDED: case CHANGED: // We don't look at the "before" value, so adding and changing idempotently is done the same way. writer.updateDocument( documentStructure.newQueryForChangeOrRemove( nodeId ), documentStructure.newDocumentRepresentingProperty( nodeId, update.getValueAfter() ) ); break; case REMOVED: writer.deleteDocuments( documentStructure.newQueryForChangeOrRemove( nodeId ) ); break; default: throw new IllegalStateException( "Unknown update mode " + update.getUpdateMode() ); } } } }
false
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_NonUniqueLuceneIndexPopulator.java
4,766
class NonUniqueLuceneIndexAccessor extends LuceneIndexAccessor { NonUniqueLuceneIndexAccessor( LuceneDocumentStructure documentStructure, LuceneIndexWriterFactory indexWriterFactory, IndexWriterStatus writerStatus, DirectoryFactory dirFactory, File dirFile ) throws IOException { super( documentStructure, indexWriterFactory, writerStatus, dirFactory, dirFile ); } }
false
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_NonUniqueLuceneIndexAccessor.java
4,767
{ @Override protected boolean matchesSafely( Document item ) { return equal( fields( document ), fields( item ) ); } @Override public void describeTo( Description description ) { description.appendValue( document ); } private Map<String, Fieldable> fields( Document doc ) { Map<String, Fieldable> these = new HashMap<>(); for ( Fieldable field : doc.getFields() ) { these.put( field.name(), field ); } return these; } boolean equal( Map<String, Fieldable> these, Map<String, Fieldable> those ) { if ( !these.keySet().equals( those.keySet() ) ) { return false; } for ( Map.Entry<String, Fieldable> entry : these.entrySet() ) { if ( !equal( entry.getValue(), those.get( entry.getKey() ) ) ) { return false; } } return true; } boolean equal( Fieldable lhs, Fieldable rhs ) { if ( lhs.isBinary() && rhs.isBinary() ) { return Arrays.equals( lhs.getBinaryValue(), rhs.getBinaryValue() ); } return lhs.stringValue().equals( rhs.stringValue() ); } } );
false
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_NodeRangeDocumentLabelScanStorageStrategyTest.java
4,768
@RunWith(Parameterized.class) public class NodeRangeDocumentLabelScanStorageStrategyTest { @Parameterized.Parameters(name = "{0} bits") public static List<Object[]> formats() { ArrayList<Object[]> parameters = new ArrayList<>(); for ( BitmapDocumentFormat format : BitmapDocumentFormat.values() ) { parameters.add( new Object[]{format} ); } return parameters; } private final BitmapDocumentFormat format; public NodeRangeDocumentLabelScanStorageStrategyTest( BitmapDocumentFormat format ) { this.format = format; } @Test public void shouldCreateNewDocumentsForNewlyLabeledNodes() throws Exception { // given LabelScanStorageStrategy.StorageService storage = mock( LabelScanStorageStrategy.StorageService.class ); IndexSearcher searcher = mock( IndexSearcher.class ); when( storage.acquireSearcher() ).thenReturn( searcher ); when( searcher.search( new TermQuery( format.rangeTerm( 0 ) ), 1 ) ).thenReturn( docs() ); when( searcher.search( new TermQuery( format.rangeTerm( 1 ) ), 1 ) ).thenReturn( null ); LuceneLabelScanWriter writer = new LuceneLabelScanWriter(storage, format ); // when writer.write( labelChanges( 0, labels(), labels( 6, 7 ) ) ); writer.write( labelChanges( 1, labels(), labels( 6, 8 ) ) ); writer.write( labelChanges( 1 << format.bitmapFormat().shift, labels(), labels( 7 ) ) ); writer.close(); // then verify( storage ).acquireSearcher(); verify( storage ).releaseSearcher( searcher ); verify( storage ).updateDocument( eq( format.rangeTerm( 0 ) ), match( document( format.rangeField( 0 ), format.labelField( 6, 0x3 ), format.labelField( 7, 0x1 ), format.labelField( 8, 0x2 ), format.labelSearchField( 8 ) ) ) ); verify( storage ).updateDocument( eq( format.rangeTerm( 1 ) ), match( document( format.rangeField( 1 ), format.labelField( 7, 0x1 ), format.labelSearchField( 7 ) ) ) ); verify( storage ).refreshSearcher(); verifyNoMoreInteractions( storage ); } @Test public void shouldUpdateDocumentsForReLabeledNodes() throws Exception { // given LabelScanStorageStrategy.StorageService storage = storage( document( format.rangeField( 0 ), format.labelField( 7, 0x70 ) ) ); LuceneLabelScanWriter writer = new LuceneLabelScanWriter(storage, format ); // when writer.write( labelChanges( 0, labels(), labels( 7, 8 ) ) ); writer.close(); // then verify( storage ).updateDocument( eq( format.rangeTerm( 0 ) ), match( document( format.rangeField( 0 ), format.labelField( 7, 0x71 ), format.labelField( 8, 0x01 ), format.labelSearchField( 8 ) ) ) ); } @Test public void shouldRemoveLabelFieldsThatDoesNotRepresentAnyNodes() throws Exception { // given LabelScanStorageStrategy.StorageService storage = storage( document( format.rangeField( 0 ), format.labelField( 7, 0x1 ), format.labelField( 8, 0x1 ) ) ); LuceneLabelScanWriter writer = new LuceneLabelScanWriter(storage, format ); // when writer.write( labelChanges( 0, labels( 7, 8 ), labels( 8 ) ) ); writer.close(); // then verify( storage ).updateDocument( eq( format.rangeTerm( 0 ) ), match( document( format.rangeField( 0 ), format.labelField( 8, 0x01 ), format.labelSearchField( 8 ) ) ) ); } @Test public void shouldDeleteEmptyDocuments() throws Exception { // given LabelScanStorageStrategy.StorageService storage = storage( document( format.rangeField( 0 ), format.labelField( 7, 0x1 ) ) ); LuceneLabelScanWriter writer = new LuceneLabelScanWriter(storage, format ); // when writer.write( labelChanges( 0, labels( 7 ), labels() ) ); writer.close(); // then verify( storage ).deleteDocuments( format.rangeTerm( 0 ) ); } @Test public void shouldUpdateDocumentToReflectLabelsAfterRegardlessOfPreviousContent() throws Exception { // given LabelScanStorageStrategy.StorageService storage = storage( document( format.rangeField( 0 ), format.labelField( 6, 0x1 ), format.labelField( 7, 0x1 ) ) ); LuceneLabelScanWriter writer = new LuceneLabelScanWriter(storage, format ); // when writer.write( labelChanges( 0, labels( 7 ), labels( 7, 8 ) ) ); writer.close(); // then verify( storage ).updateDocument( eq( format.rangeTerm( 0 ) ), match( document( format.rangeField( 0 ), format.labelField( 7, 0x01 ), format.labelField( 8, 0x01 ), format.labelSearchField( 7 ), format.labelSearchField( 8 ) ) ) ); } @Test public void shouldStoreAnyNodeIdInRange() throws Exception { for ( int i = 0, max = 1 << format.bitmapFormat().shift; i < max; i++ ) { // given LabelScanStorageStrategy.StorageService storage = storage(); LuceneLabelScanWriter writer = new LuceneLabelScanWriter(storage, format ); // when writer.write( labelChanges( i, labels(), labels( 7 ) ) ); writer.close(); // then verify( storage ).updateDocument( eq( format.rangeTerm( 0 ) ), match( document( format.rangeField( 0 ), format.labelField( 7, 1L << i ), format.labelSearchField( 7 ) ) ) ); } } private LabelScanStorageStrategy.StorageService storage( Document... documents ) throws Exception { LabelScanStorageStrategy.StorageService storage = mock( LabelScanStorageStrategy.StorageService.class ); IndexSearcher searcher = mock( IndexSearcher.class ); when( storage.acquireSearcher() ).thenReturn( searcher ); for ( int i = 0; i < documents.length; i++ ) { when( searcher.search( new TermQuery( format.rangeTerm( documents[i] ) ), 1 ) ) .thenReturn( docs( new ScoreDoc( i, 0.0f ) ) ); when( searcher.doc( i ) ).thenReturn( documents[i] ); } return storage; } private static long[] labels( long... labels ) { return labels; } private static Document match( final Document document ) { return argThat( new TypeSafeMatcher<Document>() { @Override protected boolean matchesSafely( Document item ) { return equal( fields( document ), fields( item ) ); } @Override public void describeTo( Description description ) { description.appendValue( document ); } private Map<String, Fieldable> fields( Document doc ) { Map<String, Fieldable> these = new HashMap<>(); for ( Fieldable field : doc.getFields() ) { these.put( field.name(), field ); } return these; } boolean equal( Map<String, Fieldable> these, Map<String, Fieldable> those ) { if ( !these.keySet().equals( those.keySet() ) ) { return false; } for ( Map.Entry<String, Fieldable> entry : these.entrySet() ) { if ( !equal( entry.getValue(), those.get( entry.getKey() ) ) ) { return false; } } return true; } boolean equal( Fieldable lhs, Fieldable rhs ) { if ( lhs.isBinary() && rhs.isBinary() ) { return Arrays.equals( lhs.getBinaryValue(), rhs.getBinaryValue() ); } return lhs.stringValue().equals( rhs.stringValue() ); } } ); } }
false
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_NodeRangeDocumentLabelScanStorageStrategyTest.java
4,769
public class NodeRangeDocumentLabelScanStorageStrategy implements LabelScanStorageStrategy { // This must be high to avoid to many calls to the lucene searcher. Tweak using LabelScanBenchmark private static final int RANGES_PER_PAGE = 4096; private final BitmapDocumentFormat format; public NodeRangeDocumentLabelScanStorageStrategy() { this( BitmapDocumentFormat._32 ); } NodeRangeDocumentLabelScanStorageStrategy( BitmapDocumentFormat format ) { this.format = format; } @Override public String toString() { return String.format( "%s{%s}", getClass().getSimpleName(), format ); } @Override public PrimitiveLongIterator nodesWithLabel( IndexSearcher searcher, int labelId ) { return flatten( new PageOfRangesIterator( format, searcher, RANGES_PER_PAGE, format.labelQuery( labelId ), labelId ) ); } @Override public AllEntriesLabelScanReader newNodeLabelReader( SearcherManager searcherManager ) { return new LuceneAllEntriesLabelScanReader( new LuceneAllDocumentsReader( searcherManager ), format ); } @Override public Iterator<Long> labelsForNode( IndexSearcher searcher, long nodeId ) { try { TopDocs topDocs = searcher.search( format.rangeQuery( format.bitmapFormat().rangeOf( nodeId ) ), 1 ); if ( topDocs.scoreDocs.length < 1 ) { return emptyIterator(); } else if ( topDocs.scoreDocs.length > 1 ) { throw new RuntimeException( "This label scan store is corrupted" ); } int doc = topDocs.scoreDocs[0].doc; List<Long> labels = new ArrayList<>(); for ( Fieldable fields : searcher.doc( doc ).getFields() ) { if ( "range".equals( fields.name() ) ) { continue; } if ( fields instanceof NumericField ) { NumericField labelField = (NumericField) fields; Long bitmap = Long.decode( labelField.stringValue() ); if ( format.bitmapFormat().hasLabel( bitmap, nodeId ) ) { labels.add( Long.decode( labelField.name() ) ); } } } return labels.iterator(); } catch ( IOException e ) { throw new RuntimeException( e ); } } @Override public LabelScanWriter acquireWriter( final StorageService storage ) { return new LuceneLabelScanWriter( storage, format ); } }
false
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_NodeRangeDocumentLabelScanStorageStrategy.java
4,770
public class LuceneSnapshotterTest { private final File indexDir = new File("."); private SnapshotDeletionPolicy snapshotPolicy; private IndexCommit luceneSnapshot; private IndexWriter writer; @Before public void setup() throws IOException { writer = mock(IndexWriter.class); snapshotPolicy = mock(SnapshotDeletionPolicy.class); luceneSnapshot = mock(IndexCommit.class); IndexWriterConfig config = new IndexWriterConfig( Version.LUCENE_36, null ); config.setIndexDeletionPolicy( snapshotPolicy ); when( writer.getConfig() ).thenReturn( config ); when(snapshotPolicy.snapshot( anyString() )).thenReturn( luceneSnapshot ); } @Test public void shouldReturnRealSnapshotIfIndexAllowsIt() throws Exception { // Given LuceneSnapshotter snapshotter = new LuceneSnapshotter(); when(luceneSnapshot.getFileNames()).thenReturn( asList("a", "b") ); // When ResourceIterator<File> snapshot = snapshotter.snapshot( indexDir, writer ); // Then assertEquals( new File(indexDir, "a"), snapshot.next() ); assertEquals( new File(indexDir, "b"), snapshot.next() ); assertFalse( snapshot.hasNext() ); snapshot.close(); verify( snapshotPolicy ).release( anyString() ); } @Test public void shouldReturnEmptyIteratorWhenNoCommitsHaveBeenMade() throws Exception { // Given LuceneSnapshotter snapshotter = new LuceneSnapshotter(); when(luceneSnapshot.getFileNames()).thenThrow( new IllegalStateException( "No index commit to snapshot" )); // When ResourceIterator<File> snapshot = snapshotter.snapshot( indexDir, writer ); // Then assertFalse( snapshot.hasNext() ); snapshot.close(); verify( snapshotPolicy ).snapshot( anyString() ); verifyNoMoreInteractions( snapshotPolicy ); } }
false
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_LuceneSnapshotterTest.java
4,771
private class LuceneSnapshotIterator extends PrefetchingIterator<File> implements ResourceIterator<File> { private final File indexDirectory; private final SnapshotDeletionPolicy deletionPolicy; private Iterator<String> fileNames; LuceneSnapshotIterator( File indexDirectory, IndexCommit snapshotPoint, SnapshotDeletionPolicy deletionPolicy ) throws IOException { this.indexDirectory = indexDirectory; this.deletionPolicy = deletionPolicy; this.fileNames = snapshotPoint.getFileNames().iterator(); } @Override protected File fetchNextOrNull() { if ( !fileNames.hasNext() ) { return null; } return new File( indexDirectory, fileNames.next() ); } @Override public void close() { try { deletionPolicy.release( ID ); } catch ( IOException e ) { // TODO What to do here? throw new RuntimeException( "Unable to close lucene index snapshot", e ); } } }
false
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_LuceneSnapshotter.java
4,772
public class LuceneSnapshotter { private static final String NO_INDEX_COMMIT_TO_SNAPSHOT = "No index commit to snapshot"; private static final String ID = "backup"; ResourceIterator<File> snapshot( File indexDir, IndexWriter writer ) throws IOException { SnapshotDeletionPolicy deletionPolicy = (SnapshotDeletionPolicy) writer.getConfig().getIndexDeletionPolicy(); try { return new LuceneSnapshotIterator( indexDir, deletionPolicy.snapshot( ID ), deletionPolicy ); } catch(IllegalStateException e) { if(e.getMessage().equals( NO_INDEX_COMMIT_TO_SNAPSHOT )) { return emptyIterator(); } throw e; } } private class LuceneSnapshotIterator extends PrefetchingIterator<File> implements ResourceIterator<File> { private final File indexDirectory; private final SnapshotDeletionPolicy deletionPolicy; private Iterator<String> fileNames; LuceneSnapshotIterator( File indexDirectory, IndexCommit snapshotPoint, SnapshotDeletionPolicy deletionPolicy ) throws IOException { this.indexDirectory = indexDirectory; this.deletionPolicy = deletionPolicy; this.fileNames = snapshotPoint.getFileNames().iterator(); } @Override protected File fetchNextOrNull() { if ( !fileNames.hasNext() ) { return null; } return new File( indexDirectory, fileNames.next() ); } @Override public void close() { try { deletionPolicy.release( ID ); } catch ( IOException e ) { // TODO What to do here? throw new RuntimeException( "Unable to close lucene index snapshot", e ); } } } }
false
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_LuceneSnapshotter.java
4,773
public class LuceneSchemaIndexProviderTest extends IndexProviderCompatibilityTestSuite { @Override protected LuceneSchemaIndexProvider createIndexProvider() { return new LuceneSchemaIndexProvider( new DirectoryFactory.InMemoryDirectoryFactory(), new Config( stringMap( "store_dir", forTest( getClass() ).makeGraphDbDir().getAbsolutePath() ) ) ); } }
false
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_LuceneSchemaIndexProviderTest.java
4,774
@Service.Implementation(KernelExtensionFactory.class) public class LuceneSchemaIndexProviderFactory extends KernelExtensionFactory<LuceneSchemaIndexProviderFactory.Dependencies> { static final String KEY = "lucene"; public static final SchemaIndexProvider.Descriptor PROVIDER_DESCRIPTOR = new SchemaIndexProvider.Descriptor( KEY, "1.0" ); public interface Dependencies { Config getConfig(); FileSystemAbstraction getFileSystem(); } public LuceneSchemaIndexProviderFactory() { super( KEY ); } @Override public LuceneSchemaIndexProvider newKernelExtension( Dependencies dependencies ) throws Throwable { Config config = dependencies.getConfig(); FileSystemAbstraction fileSystem = dependencies.getFileSystem(); DirectoryFactory directoryFactory = directoryFactory( config, fileSystem ); return new LuceneSchemaIndexProvider( directoryFactory, config ); } }
false
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_LuceneSchemaIndexProviderFactory.java
4,775
public class LuceneSchemaIndexProvider extends SchemaIndexProvider { private final DirectoryFactory directoryFactory; private final LuceneDocumentStructure documentStructure = new LuceneDocumentStructure(); private final IndexWriterStatus writerStatus = new IndexWriterStatus(); private final File rootDirectory; private final FailureStorage failureStorage; private final FolderLayout folderLayout; private Map<Long, String> failures = new HashMap<>(); public LuceneSchemaIndexProvider( DirectoryFactory directoryFactory, Config config ) { super( LuceneSchemaIndexProviderFactory.PROVIDER_DESCRIPTOR, 1 ); this.directoryFactory = directoryFactory; this.rootDirectory = getRootDirectory( config, LuceneSchemaIndexProviderFactory.KEY ); this.folderLayout = new FolderLayout( rootDirectory ); this.failureStorage = new FailureStorage( folderLayout ); } @Override public IndexPopulator getPopulator( long indexId, IndexDescriptor descriptor, IndexConfiguration config ) { if ( config.isUnique() ) { return new DeferredConstraintVerificationUniqueLuceneIndexPopulator( documentStructure, standard(), writerStatus, directoryFactory, folderLayout.getFolder( indexId ), failureStorage, indexId, descriptor ); } else { return new NonUniqueLuceneIndexPopulator( NonUniqueLuceneIndexPopulator.DEFAULT_QUEUE_THRESHOLD, documentStructure, standard(), writerStatus, directoryFactory, folderLayout.getFolder( indexId ), failureStorage, indexId ); } } @Override public IndexAccessor getOnlineAccessor( long indexId, IndexConfiguration config ) throws IOException { if ( config.isUnique() ) { return new UniqueLuceneIndexAccessor( documentStructure, standard(), writerStatus, directoryFactory, folderLayout.getFolder( indexId ) ); } else { return new NonUniqueLuceneIndexAccessor( documentStructure, standard(), writerStatus, directoryFactory, folderLayout.getFolder( indexId ) ); } } @Override public void shutdown() throws Throwable { // Nothing to shut down } @Override public InternalIndexState getInitialState( long indexId ) { try { String failure = failureStorage.loadIndexFailure( indexId ); if ( failure != null ) { failures.put( indexId, failure ); return InternalIndexState.FAILED; } try ( Directory directory = directoryFactory.open( folderLayout.getFolder( indexId ) ) ) { boolean status = writerStatus.isOnline( directory ); return status ? InternalIndexState.ONLINE : InternalIndexState.POPULATING; } } catch( CorruptIndexException e ) { return InternalIndexState.FAILED; } catch( FileNotFoundException e ) { failures.put( indexId, "File not found: " + e.getMessage() ); return InternalIndexState.FAILED; } catch( EOFException e ) { failures.put( indexId, "EOF encountered: " + e.getMessage() ); return InternalIndexState.FAILED; } catch ( IOException e ) { throw new RuntimeException( e ); } } @Override public String getPopulationFailure( long indexId ) throws IllegalStateException { String failure = failureStorage.loadIndexFailure( indexId ); if ( failure == null ) { failure = failures.get( indexId ); } if ( failure == null ) { throw new IllegalStateException( "Index " + indexId + " isn't failed" ); } return failure; } }
false
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_LuceneSchemaIndexProvider.java
4,776
private static class Hit { private final Object value; private final Long[] nodeIds; Hit( Object value, Long... nodeIds ) { this.value = value; this.nodeIds = nodeIds; } }
false
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_LuceneSchemaIndexPopulatorTest.java
4,777
public class LuceneSchemaIndexPopulatorTest { @Test public void addingValuesShouldPersistThem() throws Exception { // WHEN index.add( 1, "First" ); index.add( 2, "Second" ); index.add( 3, (byte)1 ); index.add( 4, (short)2 ); index.add( 5, 3 ); index.add( 6, 4L ); index.add( 7, 5F ); index.add( 8, 6D ); // THEN assertIndexedValues( hit( "First", 1 ), hit( "Second", 2 ), hit( (byte)1, 3 ), hit( (short)2, 4 ), hit( 3, 5 ), hit( 4L, 6 ), hit( 5F, 7 ), hit( 6D, 8 ) ); } @Test public void multipleEqualValues() throws Exception { // WHEN index.add( 1, "value" ); index.add( 2, "value" ); index.add( 3, "value" ); // THEN assertIndexedValues( hit( "value", 1L, 2L, 3L ) ); } @Test public void multipleEqualValuesWithUpdateThatRemovesOne() throws Exception { // WHEN index.add( 1, "value" ); index.add( 2, "value" ); index.add( 3, "value" ); updatePopulator( index, asList( remove( 2, "value" ) ), indexStoreView ); // THEN assertIndexedValues( hit( "value", 1L, 3L ) ); } @Test public void changeUpdatesInterleavedWithAdds() throws Exception { // WHEN index.add( 1, "1" ); index.add( 2, "2" ); updatePopulator( index, asList( change( 1, "1", "1a" ) ), indexStoreView ); index.add( 3, "3" ); // THEN assertIndexedValues( no( "1" ), hit( "1a", 1 ), hit( "2", 2 ), hit( "3", 3 ) ); } @Test public void addUpdatesInterleavedWithAdds() throws Exception { // WHEN index.add( 1, "1" ); index.add( 2, "2" ); updatePopulator( index, asList( remove( 1, "1" ), add( 1, "1a" ) ), indexStoreView ); index.add( 3, "3" ); // THEN assertIndexedValues( hit( "1a", 1 ), hit( "2", 2 ), hit( "3", 3 ), no( "1" ) ); } @Test public void removeUpdatesInterleavedWithAdds() throws Exception { // WHEN index.add( 1, "1" ); index.add( 2, "2" ); updatePopulator( index, asList( remove( 2, "2" ) ), indexStoreView ); index.add( 3, "3" ); // THEN assertIndexedValues( hit( "1", 1 ), no( "2" ), hit( "3", 3 ) ); } @Test public void multipleInterleaves() throws Exception { // WHEN index.add( 1, "1" ); index.add( 2, "2" ); updatePopulator( index, asList( change( 1, "1", "1a" ), change( 2, "2", "2a" ) ), indexStoreView ); index.add( 3, "3" ); index.add( 4, "4" ); updatePopulator( index, asList( change( 1, "1a", "1b" ), change( 4, "4", "4a" ) ), indexStoreView ); // THEN assertIndexedValues( no( "1" ), no( "1a" ), hit( "1b", 1 ), no( "2" ), hit( "2a", 2 ), hit( "3", 3 ), no( "4" ), hit( "4a", 4 ) ); } private Hit hit( Object value, Long... nodeIds ) { return new Hit( value, nodeIds ); } private Hit hit( Object value, long nodeId ) { return new Hit( value, nodeId ); } private Hit no( Object value ) { return new Hit( value ); } private static class Hit { private final Object value; private final Long[] nodeIds; Hit( Object value, Long... nodeIds ) { this.value = value; this.nodeIds = nodeIds; } } private NodePropertyUpdate add( long nodeId, Object value ) { return NodePropertyUpdate.add( 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 NodePropertyUpdate remove( long nodeId, Object removedValue ) { return NodePropertyUpdate.remove( nodeId, 0, removedValue, new long[0] ); } private IndexDescriptor indexDescriptor; private IndexStoreView indexStoreView; private LuceneSchemaIndexProvider provider; private Directory directory; private IndexPopulator index; private IndexReader reader; private IndexSearcher searcher; private final long indexId = 0; private int propertyKeyId = 666; private final LuceneDocumentStructure documentLogic = new LuceneDocumentStructure(); @Before public void before() throws Exception { directory = new RAMDirectory(); DirectoryFactory directoryFactory = new DirectoryFactory.Single( new DirectoryFactory.UncloseableDirectory( directory ) ); provider = new LuceneSchemaIndexProvider( directoryFactory, new Config( stringMap( store_dir.name(), "target/whatever" ) ) ); indexDescriptor = new IndexDescriptor( 42, propertyKeyId ); indexStoreView = mock( IndexStoreView.class ); index = provider.getPopulator( indexId, indexDescriptor, new IndexConfiguration( false ) ); index.create(); } @After public void after() throws Exception { if ( reader != null ) reader.close(); directory.close(); } private void assertIndexedValues( Hit... expectedHits ) throws IOException { switchToVerification(); for ( Hit hit : expectedHits ) { TopDocs hits = searcher.search( documentLogic.newQuery( hit.value ), 10 ); assertEquals( "Unexpected number of index results from " + hit.value, hit.nodeIds.length, hits.totalHits ); Set<Long> foundNodeIds = new HashSet<>(); for ( int i = 0; i < hits.totalHits; i++ ) { Document document = searcher.doc( hits.scoreDocs[i].doc ); foundNodeIds.add( parseLong( document.get( "id" ) ) ); } assertEquals( asSet( hit.nodeIds ), foundNodeIds ); } } private void switchToVerification() throws IOException { index.close( true ); assertEquals( InternalIndexState.ONLINE, provider.getInitialState( indexId ) ); reader = IndexReader.open( directory ); searcher = new IndexSearcher( reader ); } private static void updatePopulator( IndexPopulator populator, Iterable<NodePropertyUpdate> updates, PropertyAccessor accessor ) throws IOException, IndexEntryConflictException { try ( IndexUpdater updater = populator.newPopulatingUpdater( accessor ) ) { for ( NodePropertyUpdate update : updates ) { updater.process( update ); } } } }
false
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_LuceneSchemaIndexPopulatorTest.java
4,778
{ @Override public List<Long> apply( GraphDatabaseService graphDb ) { ArrayList<Long> ids = new ArrayList<>(); for ( Node node : graphDb.findNodesByLabelAndProperty( label, propertyKey, value ) ) { ids.add( node.getId() ); } return ids; } };
false
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_UniqueIndexApplicationIT.java
4,779
class UniqueLuceneIndexAccessor extends LuceneIndexAccessor { public UniqueLuceneIndexAccessor( LuceneDocumentStructure documentStructure, LuceneIndexWriterFactory indexWriterFactory, IndexWriterStatus writerStatus, DirectoryFactory dirFactory, File dirFile ) throws IOException { super( documentStructure, indexWriterFactory, writerStatus, dirFactory, dirFile ); } @Override public IndexUpdater newUpdater( final IndexUpdateMode mode ) { if ( mode != IndexUpdateMode.RECOVERY ) { return new LuceneUniquePropertyIndexUpdater( super.newUpdater( mode ) ); } else { /* If we are in recovery, don't handle the business logic of validating uniqueness. */ return super.newUpdater( mode ); } } /* The fact that this is here is a sign of a design error, and we should revisit and * remove this later on. Specifically, this is here because the unique indexes do validation * of uniqueness, which they really shouldn't be doing. In fact, they shouldn't exist, the unique * indexes are just indexes, and the logic of how they are used is not the responsibility of the * storage system to handle, that should go in the kernel layer. * * Anyway, where was I.. right: The kernel depends on the unique indexes to handle the business * logic of verifying domain uniqueness, and if they did not do that, race conditions appear for * index creation (not online operations, note) where concurrent violation of a currently created * index may break uniqueness. * * Phew. So, unique indexes currently have to pick up the slack here. The problem is that while * they serve the role of business logic execution, they also happen to be indexes, which is part * of the storage layer. There is one golden rule in the storage layer, which must never ever be * violated: Operations are idempotent. All operations against the storage layer have to be * executable over and over and have the same result, this is the basis of data recovery and * system consistency. * * Clearly, the uniqueness indexes don't do this, and so they fail in fulfilling their primary * contract in order to pick up the slack for the kernel not fulfilling it's contract. We hack * around this issue by tracking state - we know that probably the only time the idempotent * requirement will be invoked is during recovery, and we know that by happenstance, recovery is * single-threaded. As such, when we are in recovery, we turn off the business logic part and * correctly fulfill our actual contract. As soon as the database is online, we flip back to * running business logic in the storage layer and incorrectly implementing the storage layer * contract. * * One day, we should fix this. */ private class LuceneUniquePropertyIndexUpdater extends UniquePropertyIndexUpdater { final IndexUpdater delegate; public LuceneUniquePropertyIndexUpdater( IndexUpdater delegate ) { this.delegate = delegate; } @Override protected void flushUpdates( Iterable<NodePropertyUpdate> updates ) throws IOException, IndexEntryConflictException { for ( NodePropertyUpdate update : updates ) { delegate.process( update ); } delegate.close(); } @Override public void remove( Iterable<Long> nodeIds ) throws IOException { delegate.remove( nodeIds ); } } }
false
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_UniqueLuceneIndexAccessor.java
4,780
private class LuceneUniquePropertyIndexUpdater extends UniquePropertyIndexUpdater { final IndexUpdater delegate; public LuceneUniquePropertyIndexUpdater( IndexUpdater delegate ) { this.delegate = delegate; } @Override protected void flushUpdates( Iterable<NodePropertyUpdate> updates ) throws IOException, IndexEntryConflictException { for ( NodePropertyUpdate update : updates ) { delegate.process( update ); } delegate.close(); } @Override public void remove( Iterable<Long> nodeIds ) throws IOException { delegate.remove( nodeIds ); } }
false
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_UniqueLuceneIndexAccessor.java
4,781
public class LongPageIteratorTest { @Test public void shouldIterateThroughEachLongInEachPage() throws Exception { // given LongPageIterator iterator = new LongPageIterator( asList( new long[]{1, 2, 3}, new long[]{4, 5} ).iterator() ); // then assertTrue( iterator.hasNext() ); assertEquals( 1, iterator.next() ); assertTrue( iterator.hasNext() ); assertEquals( 2, iterator.next() ); assertTrue( iterator.hasNext() ); assertEquals( 3, iterator.next() ); assertTrue( iterator.hasNext() ); assertEquals( 4, iterator.next() ); assertTrue( iterator.hasNext() ); assertEquals( 5, iterator.next() ); assertFalse( iterator.hasNext() ); } @Test public void shouldNotGetAnythingFromEmptySourceIterator() throws Exception { // given LongPageIterator iterator = new LongPageIterator( Collections.<long[]>emptyList().iterator() ); // then assertFalse( iterator.hasNext() ); } @Test public void shouldNotGetAnythingFromSourceIteratorOfEmptyLongArrays() throws Exception { // given LongPageIterator iterator = new LongPageIterator( asList( new long[]{}, new long[]{} ).iterator() ); // then assertFalse( iterator.hasNext() ); } }
false
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_bitmaps_LongPageIteratorTest.java
4,782
{ @Override public long maxCount() { return 0; } @Override public void close() throws IOException { } @Override public Iterator<Long> iterator() { return emptyIterator(); } };
false
community_kernel_src_main_java_org_neo4j_kernel_api_index_IndexAccessor.java
4,783
class Adapter implements IndexAccessor { @Override public void drop() { } @Override public IndexUpdater newUpdater( IndexUpdateMode mode ) { return SwallowingIndexUpdater.INSTANCE; } @Override public void force() { } @Override public void close() { } @Override public IndexReader newReader() { return IndexReader.EMPTY; } @Override public BoundedIterable<Long> newAllEntriesReader() { return new BoundedIterable<Long>() { @Override public long maxCount() { return 0; } @Override public void close() throws IOException { } @Override public Iterator<Long> iterator() { return emptyIterator(); } }; } @Override public ResourceIterator<File> snapshotFiles() { return emptyIterator(); } }
false
community_kernel_src_main_java_org_neo4j_kernel_api_index_IndexAccessor.java
4,784
public class InMemoryIndexIndexProviderApprovalTest extends SchemaIndexProviderApprovalTest { public InMemoryIndexIndexProviderApprovalTest( TestValue value ) { super( value ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_InMemoryIndexIndexProviderApprovalTest.java
4,785
public class InMemoryIndexConstraintProviderApprovalTest extends SchemaConstraintProviderApprovalTest { public InMemoryIndexConstraintProviderApprovalTest( TestValue value ) { super( value ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_InMemoryIndexConstraintProviderApprovalTest.java
4,786
public class DuplicateIndexEntryConflictExceptionTest { @Test public void messageShouldIncludePropertyValueAndNodeIds() throws Exception { // given DuplicateIndexEntryConflictException e = new DuplicateIndexEntryConflictException( "value1", asSet(11l, 22l, 33l) ); // then assertEquals( format( "Multiple nodes have property value 'value1':%n" + " node(11), node(22), node(33)" ), e.getMessage()); } @Test public void evidenceMessageShouldIncludeLabelAndPropertyKey() throws Exception { // given DuplicateIndexEntryConflictException e = new DuplicateIndexEntryConflictException( "value1", asSet(11l, 22l, 33l) ); // then assertEquals( format( "Multiple nodes with label `Label1` have property `propertyKey1` = 'value1':%n" + " node(11), node(22), node(33)" ), e.evidenceMessage( "Label1", "propertyKey1" )); } }
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_DuplicateIndexEntryConflictExceptionTest.java
4,787
public class DuplicateIndexEntryConflictException extends IndexEntryConflictException { private final Object propertyValue; private final Set<Long> conflictingNodeIds; public DuplicateIndexEntryConflictException( Object propertyValue, Set<Long> conflictingNodeIds ) { super( String.format( "Multiple nodes have property value %s:%n" + " %s", quote( propertyValue ), asNodeList( conflictingNodeIds ) ) ); this.propertyValue = propertyValue; this.conflictingNodeIds = conflictingNodeIds; } public Object getPropertyValue() { return propertyValue; } @Override public String evidenceMessage( String labelName, String propertyKey ) { return String.format( "Multiple nodes with label `%s` have property `%s` = %s:%n" + " %s", labelName, propertyKey, quote( propertyValue ), asNodeList(conflictingNodeIds) ); } public Set<Long> getConflictingNodeIds() { return conflictingNodeIds; } private static String asNodeList( Collection<Long> nodeIds ) { TreeSet<Long> ids = new TreeSet<Long>( nodeIds ); StringBuilder builder = new StringBuilder(); boolean first = true; for ( long nodeId : ids ) { if ( !first ) { builder.append( ", " ); } else { first = false; } builder.append( "node(" ).append( nodeId ).append( ")" ); } return builder.toString(); } }
false
community_kernel_src_main_java_org_neo4j_kernel_api_index_DuplicateIndexEntryConflictException.java
4,788
public class ArrayEncoderTest { @Test public void shouldEncodeArrays() throws Exception { assertEquals( "D1.0|2.0|3.0|", ArrayEncoder.encode( new int[]{1, 2, 3} ) ); assertEquals( "Ztrue|false|", ArrayEncoder.encode( new boolean[]{true, false} ) ); assertEquals( "LYWxp|YXJl|eW91|b2s=|", ArrayEncoder.encode( new String[]{"ali", "are", "you", "ok"} ) ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_api_index_ArrayEncoderTest.java
4,789
public class ArrayEncoder { private static final BASE64Encoder base64Encoder = new BASE64Encoder(); private static final BASE64Decoder base64Decoder = new BASE64Decoder(); public static String encode( Object array ) { if ( !array.getClass().isArray() ) { throw new IllegalArgumentException( "Only works with arrays" ); } StringBuilder builder = new StringBuilder(); int length = Array.getLength( array ); String type = ""; for ( int i = 0; i < length; i++ ) { Object o = Array.get( array, i ); if ( o instanceof Number ) { type = "D"; builder.append( ((Number) o).doubleValue() ); } else if ( o instanceof Boolean ) { type = "Z"; builder.append( o ); } else { type = "L"; String str = o.toString(); builder.append( base64Encoder.encode( str.getBytes( Charsets.UTF_8 ) ) ); } builder.append( "|" ); } return type + builder.toString(); } }
false
community_kernel_src_main_java_org_neo4j_kernel_api_index_ArrayEncoder.java
4,790
public class LongPageIterator implements PrimitiveLongIterator { private final Iterator<long[]> source; private long[] current; private int offset; public LongPageIterator( Iterator<long[]> source ) { this.source = source; } @Override public boolean hasNext() { while ( current == null || offset >= current.length ) { if ( !source.hasNext() ) { current = null; return false; } current = source.next(); offset = 0; } return true; } @Override public long next() { if ( !hasNext() ) { throw new NoSuchElementException(); } return current[offset++]; } }
false
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_bitmaps_LongPageIterator.java
4,791
public class UniqueLuceneIndexAccessorTest { private final DirectoryFactory directoryFactory = new DirectoryFactory.InMemoryDirectoryFactory(); private final File indexDirectory = new File( "index1" ); @Test public void shouldAddUniqueEntries() throws Exception { // given UniqueLuceneIndexAccessor accessor = createAccessor(); // when updateAndCommit( accessor, asList( add( 1l, "value1" ), add( 2l, "value2" ) ) ); updateAndCommit( accessor, asList( add( 3l, "value3" ) ) ); accessor.close(); // then assertEquals( asList( 1l ), getAllNodes( "value1" ) ); } @Test public void shouldUpdateUniqueEntries() throws Exception { // given UniqueLuceneIndexAccessor accessor = createAccessor(); // when updateAndCommit( accessor, asList( add( 1l, "value1" ) ) ); updateAndCommit( accessor, asList( change( 1l, "value1", "value2" ) ) ); accessor.close(); // then assertEquals( asList( 1l ), getAllNodes( "value2" ) ); assertEquals( emptyListOf( Long.class ), getAllNodes( "value1" ) ); } @Test public void shouldRemoveAndAddEntries() throws Exception { // given UniqueLuceneIndexAccessor accessor = createAccessor(); // when updateAndCommit( accessor, asList( add( 1l, "value1" ) ) ); updateAndCommit( accessor, asList( add( 2l, "value2" ) ) ); updateAndCommit( accessor, asList( add( 3l, "value3" ) ) ); updateAndCommit( accessor, asList( add( 4l, "value4" ) ) ); updateAndCommit( accessor, asList( remove( 1l, "value1" ) ) ); updateAndCommit( accessor, asList( remove( 2l, "value2" ) ) ); updateAndCommit( accessor, asList( remove( 3l, "value3" ) ) ); updateAndCommit( accessor, asList( add( 1l, "value1" ) ) ); updateAndCommit( accessor, asList( add( 3l, "value3b" ) ) ); accessor.close(); // then assertEquals( asList( 1l ), getAllNodes( "value1" ) ); assertEquals( emptyListOf( Long.class ), getAllNodes( "value2" ) ); assertEquals( emptyListOf( Long.class ), getAllNodes( "value3" ) ); assertEquals( asList( 3l ), getAllNodes( "value3b" ) ); assertEquals( asList( 4l ), getAllNodes( "value4" ) ); } @Test public void shouldConsiderWholeTransactionForValidatingUniqueness() throws Exception { // given UniqueLuceneIndexAccessor accessor = createAccessor(); // when updateAndCommit( accessor, asList( add( 1l, "value1" ) ) ); updateAndCommit( accessor, asList( add( 2l, "value2" ) ) ); updateAndCommit( accessor, asList( change( 1l, "value1", "value2" ), change( 2l, "value2", "value1" ) ) ); accessor.close(); // then assertEquals( asList( 2l ), getAllNodes( "value1" ) ); assertEquals( asList( 1l ), getAllNodes( "value2" ) ); } private UniqueLuceneIndexAccessor createAccessor() throws IOException { return new UniqueLuceneIndexAccessor( new LuceneDocumentStructure(), standard(), new IndexWriterStatus(), directoryFactory, indexDirectory ); } private NodePropertyUpdate add( long nodeId, Object propertyValue ) { return NodePropertyUpdate.add( nodeId, 100, propertyValue, new long[]{1000} ); } private NodePropertyUpdate change( long nodeId, Object oldValue, Object newValue ) { return NodePropertyUpdate.change( nodeId, 100, oldValue, new long[]{1000}, newValue, new long[]{1000} ); } private NodePropertyUpdate remove( long nodeId, Object oldValue) { return NodePropertyUpdate.remove( nodeId, 100, oldValue, new long[]{1000} ); } private List<Long> getAllNodes( String propertyValue ) throws IOException { return AllNodesCollector.getAllNodes( directoryFactory, indexDirectory, propertyValue ); } private void updateAndCommit( IndexAccessor accessor, Iterable<NodePropertyUpdate> updates ) throws IOException, IndexEntryConflictException { try ( IndexUpdater updater = accessor.newUpdater( IndexUpdateMode.ONLINE ) ) { for ( NodePropertyUpdate update : updates ) { updater.process( update ); } } } }
false
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_UniqueLuceneIndexAccessorTest.java
4,792
public class BitmapFormatTest { @Test public void shouldConvertRangeAndBitmapToArray_32() throws Exception { // given for ( int i = 0; i < 32; i++ ) { // when long[] longs = BitmapFormat._32.convertRangeAndBitmapToArray( 16, 1L << i ); // then assertArrayEquals( new long[]{(16 << 5) + i}, longs ); } // when long[] longs = BitmapFormat._32.convertRangeAndBitmapToArray( 13, -1L ); // then long[] expected = new long[32]; for ( int i = 0; i < expected.length; i++ ) { expected[i] = (13 << 5) + i; } assertArrayEquals( expected, longs ); } @Test public void shouldConvertRangeAndBitmapToArray_64() throws Exception { // given for ( int i = 0; i < 64; i++ ) { // when long[] longs = BitmapFormat._64.convertRangeAndBitmapToArray( 11, 1L << i ); // then assertArrayEquals( new long[]{(11 << 6) + i}, longs ); } // when long[] longs = BitmapFormat._64.convertRangeAndBitmapToArray( 19, -1L ); // then long[] expected = new long[64]; for ( int i = 0; i < expected.length; i++ ) { expected[i] = (19 << 6) + i; } assertArrayEquals( expected, longs ); } @Test public void shouldSetBitmap_32() throws Exception { Set<Long> bitmaps = new HashSet<>(); for ( int i = 0; i < 32; i++ ) { // given Bitmap bitmap = new Bitmap(); // when BitmapFormat._32.set( bitmap, i, true ); // then assertEquals( "set i=" + i, 1, Long.bitCount( bitmap.bitmap() ) ); bitmaps.add( bitmap.bitmap() ); // when BitmapFormat._32.set( bitmap, i, false ); // then assertEquals( "unset i=" + i, 0L, bitmap.bitmap() ); } // then assertEquals( "each value is unique", 32, bitmaps.size() ); } @Test public void shouldSetBitmap_64() throws Exception { Set<Long> bitmaps = new HashSet<>(); for ( int i = 0; i < 64; i++ ) { // given Bitmap bitmap = new Bitmap(); // when BitmapFormat._64.set( bitmap, i, true ); // then assertEquals( "set i=" + i, 1, Long.bitCount( bitmap.bitmap() ) ); bitmaps.add( bitmap.bitmap() ); // when BitmapFormat._64.set( bitmap, i, false ); // then assertEquals( "unset i=" + i, 0L, bitmap.bitmap() ); } // then assertEquals( "each value is unique", 64, bitmaps.size() ); } @Test public void shouldBeAbleToCheckIfASingleNodeIdIsSet_32() throws Exception { for ( int input = 0; input < 32; input++ ) { // given Bitmap bitmap = new Bitmap(); // when BitmapFormat._32.set( bitmap, input, true ); // then assertThat( BitmapFormat._32.hasLabel( bitmap.bitmap(), input ), is( true ) ); for ( int check = 0; check < 32; check++ ) { assertThat( BitmapFormat._32.hasLabel( bitmap.bitmap(), check ), is( input == check ) ); } } } @Test public void shouldBeAbleToCheckIfASingleNodeIdIsSet_64() throws Exception { for ( int input = 0; input < 64; input++ ) { // given Bitmap bitmap = new Bitmap(); // when BitmapFormat._64.set( bitmap, input, true ); // then assertThat( BitmapFormat._64.hasLabel( bitmap.bitmap(), input ), is( true ) ); for ( int check = 0; check < 64; check++ ) { assertThat( BitmapFormat._64.hasLabel( bitmap.bitmap(), check ), is( input == check ) ); } } } }
false
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_bitmaps_BitmapFormatTest.java
4,793
public class BitmapExtractorTest { @Test public void shouldIterateOverAllIdsInPage() throws Exception { // given BitmapExtractor pages = new BitmapExtractor( BitmapFormat._64, // first range 0x00L >> 6, -1L, // second range 0x80L >> 6, -1L ); // then long[] expected = new long[64]; for ( int i = 0; i < expected.length; i++ ) { expected[i] = i; } assertTrue( pages.hasNext() ); assertArrayEquals( expected, pages.next() ); for ( int i = 0; i < expected.length; i++ ) { expected[i] = 0x80 + i; } assertTrue( pages.hasNext() ); assertArrayEquals( expected, pages.next() ); assertFalse( pages.hasNext() ); } @Test public void shouldYieldNothingForEmptyPages() throws Exception { // given BitmapExtractor pages = new BitmapExtractor( BitmapFormat._64, 0, 0, // page 1 1, 0, // page 2 2, 0, // page 3 3, 0, // page 4 4, 0, // page 5 5, 0, // page 6 6, 0, // page 7 7, 0 );// page 8 // then assertFalse( pages.hasNext() ); } @Test public void shouldYieldCorrectBitFromEachPage() throws Exception { // given long[] rangeBitmap = new long[64 * 2]; for ( int i = 0; i < 64; i++ ) { rangeBitmap[i * 2] = i; rangeBitmap[i * 2 + 1] = 1L << i; } BitmapExtractor pages = new BitmapExtractor( BitmapFormat._64, rangeBitmap ); // then for ( int i = 0; i < 64; i++ ) { assertArrayEquals( "page:" + i, new long[]{64 * i + i}, pages.next() ); } assertFalse( pages.hasNext() ); } @Test public void shouldHandle32BitBitmaps() throws Exception { // given BitmapExtractor pages = new BitmapExtractor( BitmapFormat._32, 0xFFL, 0x0001_8000_0000L ); // then assertArrayEquals( new long[]{(0xFFL << 5) + 31}, pages.next() ); assertFalse( pages.hasNext() ); } }
false
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_bitmaps_BitmapExtractorTest.java
4,794
public class BitmapExtractor extends PrefetchingIterator<long[]> { private final BitmapFormat format; private final long[] rangeBitmap; private int offset; public BitmapExtractor( BitmapFormat format, long... rangeBitmap ) { this.format = format; this.rangeBitmap = rangeBitmap; } @Override protected long[] fetchNextOrNull() { while ( offset < rangeBitmap.length ) { long[] result = format.convertRangeAndBitmapToArray( rangeBitmap[offset], rangeBitmap[offset + 1] ); offset += 2; if ( result != null ) { return result; } } return null; } }
false
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_bitmaps_BitmapExtractor.java
4,795
public class Bitmap { long bitmap; public Bitmap() { } public Bitmap( long bitmap ) { this.bitmap = bitmap; } public long bitmap() { return bitmap; } public boolean hasContent() { return bitmap != 0; } }
false
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_bitmaps_Bitmap.java
4,796
public class WriterLogicTest { @Test public void forceShouldSetOnlineStatus() throws Exception { // GIVEN IndexWriter writer = newWriter(); writer.addDocument( newDocument() ); logic.commitAsOnline( writer ); // WHEN writer.close( true ); // THEN assertTrue( "Should have had online status set", logic.isOnline( directory ) ); } @Test public void forceShouldKeepOnlineStatus() throws Exception { // GIVEN IndexWriter writer = newWriter(); logic.commitAsOnline( writer ); // WHEN writer.addDocument( newDocument() ); logic.commitAsOnline( writer ); writer.close( true ); // THEN assertTrue( "Should have had online status set", logic.isOnline( directory ) ); } @Test public void otherWriterSessionShouldKeepOnlineStatusEvenIfNotForcingBeforeClosing() throws Exception { // GIVEN IndexWriter writer = newWriter(); logic.commitAsOnline( writer ); writer.close( true ); // WHEN writer = newWriter(); writer.addDocument( newDocument() ); writer.close( true ); // THEN assertTrue( "Should have had online status set", logic.isOnline( directory ) ); } private final IndexWriterStatus logic = new IndexWriterStatus(); private Directory directory; private DirectoryFactory.InMemoryDirectoryFactory dirFactory; @Before public void before() throws Exception { dirFactory = new DirectoryFactory.InMemoryDirectoryFactory(); directory = dirFactory.open( new File( "dir" ) ); } @After public void after() { dirFactory.close(); } private IndexWriter newWriter() throws IOException { return new IndexWriter( directory, new IndexWriterConfig( Version.LUCENE_35, KEYWORD_ANALYZER ) ); } private Document newDocument() { Document doc = new Document(); doc.add( new Field( "test", "test", Store.NO, Index.NOT_ANALYZED ) ); return doc; } }
false
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_WriterLogicTest.java
4,797
public class UniqueLuceneIndexPopulatorTest { @Test public void shouldAddUniqueUniqueLuceneIndexPopulatorTestEntries() throws Exception { // given DirectoryFactory.InMemoryDirectoryFactory directoryFactory = new DirectoryFactory.InMemoryDirectoryFactory(); File indexDirectory = new File( "target/whatever" ); final LuceneDocumentStructure documentStructure = new LuceneDocumentStructure(); UniqueLuceneIndexPopulator populator = new UniqueLuceneIndexPopulator( 100, documentStructure, standard(), new IndexWriterStatus(), directoryFactory, indexDirectory, failureStorage, indexId ); populator.create(); // when populator.add( 1, "value1" ); populator.add( 2, "value2" ); populator.close( true ); // then List<Long> nodeIds = getAllNodes( directoryFactory, indexDirectory, "value1" ); assertEquals( asList( 1l ), nodeIds ); } @Test public void shouldUpdateUniqueEntries() throws Exception { // given DirectoryFactory.InMemoryDirectoryFactory directoryFactory = new DirectoryFactory.InMemoryDirectoryFactory(); File indexDirectory = new File( "target/whatever" ); final LuceneDocumentStructure documentStructure = new LuceneDocumentStructure(); UniqueLuceneIndexPopulator populator = new UniqueLuceneIndexPopulator( 100, documentStructure, standard(), new IndexWriterStatus(), directoryFactory, indexDirectory, failureStorage, indexId ); populator.create(); int propertyKeyId = 100; // when populator.add( 1, "value1" ); populator.add( 2, "value2" ); PropertyAccessor propertyAccessor = mock( PropertyAccessor.class ); when( propertyAccessor.getProperty( 1, propertyKeyId ) ).thenReturn( stringProperty( propertyKeyId, "value1" ) ); when( propertyAccessor.getProperty( 2, propertyKeyId )).thenReturn( stringProperty( propertyKeyId, "value2" ) ); try ( IndexUpdater updater = populator.newPopulatingUpdater( propertyAccessor ) ) { updater.process( add( 3, propertyKeyId, "value3", new long[]{1000} ) ); } populator.close( true ); // then List<Long> nodeIds = getAllNodes( directoryFactory, indexDirectory, "value3" ); assertEquals( asList( 3l ), nodeIds ); } @Test public void shouldRejectEntryWithAlreadyIndexedValue() throws Exception { // given UniqueLuceneIndexPopulator populator = new UniqueLuceneIndexPopulator( 100, new LuceneDocumentStructure(), standard(), new IndexWriterStatus(), new DirectoryFactory.InMemoryDirectoryFactory(), new File( "target/whatever" ), failureStorage, indexId ); populator.create(); populator.add( 1, "value1" ); // when try { populator.add( 2, "value1" ); fail( "should have thrown exception" ); } // then catch ( PreexistingIndexEntryConflictException conflict ) { assertEquals( 1, conflict.getExistingNodeId() ); assertEquals( "value1", conflict.getPropertyValue() ); assertEquals( 2, conflict.getAddedNodeId() ); } } @Test public void shouldRejectEntryWithAlreadyIndexedValueFromPreviousBatch() throws Exception { DirectoryFactory.InMemoryDirectoryFactory directoryFactory = new DirectoryFactory.InMemoryDirectoryFactory(); File indexDirectory = new File( "target/whatever" ); final LuceneDocumentStructure documentLogic = new LuceneDocumentStructure(); UniqueLuceneIndexPopulator populator = new UniqueLuceneIndexPopulator( 2, documentLogic, standard(), new IndexWriterStatus(), directoryFactory, indexDirectory, failureStorage, indexId ); populator.create(); populator.add( 1, "value1" ); populator.add( 2, "value2" ); // when try { populator.add( 3, "value1" ); fail( "should have thrown exception" ); } // then catch ( PreexistingIndexEntryConflictException conflict ) { assertEquals( 1, conflict.getExistingNodeId() ); assertEquals( "value1", conflict.getPropertyValue() ); assertEquals( 3, conflict.getAddedNodeId() ); } } @Test public void shouldRejectUpdateWithAlreadyIndexedValue() throws Exception { // given UniqueLuceneIndexPopulator populator = new UniqueLuceneIndexPopulator( 100, new LuceneDocumentStructure(), standard(), new IndexWriterStatus(), new DirectoryFactory.InMemoryDirectoryFactory(), new File( "target/whatever" ), failureStorage, indexId ); populator.create(); populator.add( 1, "value1" ); populator.add( 2, "value2" ); int propertyKeyId = 100; PropertyAccessor propertyAccessor = mock( PropertyAccessor.class ); when( propertyAccessor.getProperty( 1, propertyKeyId ) ).thenReturn( stringProperty( propertyKeyId, "value1" ) ); when( propertyAccessor.getProperty( 2, propertyKeyId ) ).thenReturn( stringProperty( propertyKeyId, "value2" ) ); // when try { try ( IndexUpdater updater = populator.newPopulatingUpdater( propertyAccessor ) ) { updater.process( add( 2, propertyKeyId, "value1", new long[]{1000} ) ); } fail( "should have thrown exception" ); } // then catch ( PreexistingIndexEntryConflictException conflict ) { assertEquals( 1, conflict.getExistingNodeId() ); assertEquals( "value1", conflict.getPropertyValue() ); assertEquals( 2, conflict.getAddedNodeId() ); } } private final FailureStorage failureStorage = mock( FailureStorage.class ); private final long indexId = 1; }
false
community_lucene-index_src_test_java_org_neo4j_kernel_api_impl_index_UniqueLuceneIndexPopulatorTest.java
4,798
{ @Override public void process( NodePropertyUpdate update ) throws IOException, IndexEntryConflictException { add( update.getNodeId(), update.getValueAfter() ); } @Override public void close() throws IOException, IndexEntryConflictException { } @Override public void remove( Iterable<Long> nodeIds ) { throw new UnsupportedOperationException( "should not remove() from populating index" ); } };
false
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_UniqueLuceneIndexPopulator.java
4,799
@Deprecated class UniqueLuceneIndexPopulator extends LuceneIndexPopulator { static final int DEFAULT_BATCH_SIZE = 1024; private static final float LOAD_FACTOR = 0.75f; private final int batchSize; private SearcherManager searcherManager; private Map<Object, Long> currentBatch = newBatchMap(); UniqueLuceneIndexPopulator( int batchSize, LuceneDocumentStructure documentStructure, LuceneIndexWriterFactory indexWriterFactory, IndexWriterStatus writerStatus, DirectoryFactory dirFactory, File dirFile, FailureStorage failureStorage, long indexId ) { super( documentStructure, indexWriterFactory, writerStatus, dirFactory, dirFile, failureStorage, indexId ); this.batchSize = batchSize; } private HashMap<Object, Long> newBatchMap() { return new HashMap<>( (int) (batchSize / LOAD_FACTOR), LOAD_FACTOR ); } @Override public void create() throws IOException { super.create(); searcherManager = new SearcherManager( writer, true, new SearcherFactory() ); } @Override public void drop() { currentBatch.clear(); } @Override protected void flush() throws IOException { // no need to do anything yet. } @Override public void add( long nodeId, Object propertyValue ) throws IndexEntryConflictException, IOException { Long previousEntry = currentBatch.get( propertyValue ); if ( previousEntry == null ) { IndexSearcher searcher = searcherManager.acquire(); try { TopDocs docs = searcher.search( documentStructure.newQuery( propertyValue ), 1 ); if ( docs.totalHits > 0 ) { Document doc = searcher.getIndexReader().document( docs.scoreDocs[0].doc ); previousEntry = documentStructure.getNodeId( doc ); } } finally { searcherManager.release( searcher ); } } if ( previousEntry != null ) { if ( previousEntry != nodeId ) { throw new PreexistingIndexEntryConflictException( propertyValue, previousEntry, nodeId ); } } else { currentBatch.put( propertyValue, nodeId ); writer.addDocument( documentStructure.newDocumentRepresentingProperty( nodeId, propertyValue ) ); if ( currentBatch.size() >= batchSize ) { startNewBatch(); } } } @Override public void verifyDeferredConstraints( PropertyAccessor accessor ) throws IndexEntryConflictException, IOException { // constraints are checked in add() so do nothing } @Override public IndexUpdater newPopulatingUpdater( PropertyAccessor propertyAccessor ) throws IOException { return new IndexUpdater() { @Override public void process( NodePropertyUpdate update ) throws IOException, IndexEntryConflictException { add( update.getNodeId(), update.getValueAfter() ); } @Override public void close() throws IOException, IndexEntryConflictException { } @Override public void remove( Iterable<Long> nodeIds ) { throw new UnsupportedOperationException( "should not remove() from populating index" ); } }; } private void startNewBatch() throws IOException { searcherManager.maybeRefresh(); currentBatch = newBatchMap(); } }
false
community_lucene-index_src_main_java_org_neo4j_kernel_api_impl_index_UniqueLuceneIndexPopulator.java