Unnamed: 0
int64
0
6.7k
func
stringlengths
12
89.6k
target
bool
2 classes
project
stringlengths
45
151
5,800
class CommitContext { final LuceneDataSource dataSource; final IndexIdentifier identifier; final IndexType indexType; final Map<Long, DocumentContext> documents = new HashMap<Long, DocumentContext>(); final CommandList commandList; final boolean recovery; IndexReference searcher; IndexWriter writer; CommitContext( LuceneDataSource dataSource, IndexIdentifier identifier, IndexType indexType, CommandList commandList ) { this.dataSource = dataSource; this.identifier = identifier; this.indexType = indexType; this.commandList = commandList; this.recovery = commandList.isRecovery(); } void ensureWriterInstantiated() { if ( searcher == null ) { searcher = dataSource.getIndexSearcher( identifier ); writer = searcher.getWriter(); } } DocumentContext getDocument( Object entityId, boolean allowCreate ) { long id = entityId instanceof Long ? (Long) entityId : ( (RelationshipId) entityId ).id; DocumentContext context = documents.get( id ); if ( context != null ) { return context; } Document document = LuceneDataSource.findDocument( indexType, searcher.getSearcher(), id ); if ( document != null ) { context = new DocumentContext( document, true, id ); documents.put( id, context ); } else if ( allowCreate ) { context = new DocumentContext( identifier.entityType.newDocument( entityId ), false, id ); documents.put( id, context ); } return context; } public void close() { if ( searcher != null ) searcher.close(); } static class DocumentContext { final Document document; final boolean exists; final long entityId; DocumentContext( Document document, boolean exists, long entityId ) { this.document = document; this.exists = exists; this.entityId = entityId; } } }
false
community_lucene-index_src_main_java_org_neo4j_index_impl_lucene_CommitContext.java
5,801
public class CommitCommand implements WorkerCommand<CommandState, Void> { @Override public Void doWork( CommandState state ) { state.tx.success(); state.tx.finish(); return null; } }
false
community_lucene-index_src_test_java_org_neo4j_index_impl_lucene_CommitCommand.java
5,802
public class CommandState { final Index<Node> index; final GraphDatabaseService graphDb; public volatile Transaction tx; public volatile boolean alive = true; public volatile Node node; public CommandState( Index<Node> index, GraphDatabaseService graphDb, Node node ) { this.index = index; this.graphDb = graphDb; this.node = node; } }
false
community_lucene-index_src_test_java_org_neo4j_index_impl_lucene_CommandState.java
5,803
public class CombinedIndexHits<T> extends CombiningIterator<T> implements IndexHits<T> { private final Collection<IndexHits<T>> allIndexHits; private final int size; public CombinedIndexHits( Collection<IndexHits<T>> iterators ) { super( iterators ); this.allIndexHits = iterators; size = accumulatedSize( iterators ); } private int accumulatedSize( Collection<IndexHits<T>> iterators ) { int result = 0; for ( IndexHits<T> hits : iterators ) { result += hits.size(); } return result; } public IndexHits<T> iterator() { return this; } @Override protected IndexHits<T> currentIterator() { return (IndexHits<T>) super.currentIterator(); } public int size() { return size; } public void close() { for ( IndexHits<T> hits : allIndexHits ) { hits.close(); } allIndexHits.clear(); } public T getSingle() { try { return IteratorUtil.singleOrNull( (Iterator<T>) this ); } finally { close(); } } public float currentScore() { return currentIterator().currentScore(); } }
false
community_lucene-index_src_main_java_org_neo4j_index_impl_lucene_CombinedIndexHits.java
5,804
public class Cache { private final Map<IndexIdentifier, Map<String,LruCache<String,Collection<Long>>>> caching = Collections.synchronizedMap( new HashMap<IndexIdentifier, Map<String,LruCache<String,Collection<Long>>>>() ); public void setCapacity( IndexIdentifier identifier, String key, int size ) { Map<String, LruCache<String, Collection<Long>>> map = caching.get( identifier ); if ( map == null ) { map = new HashMap<String, LruCache<String,Collection<Long>>>(); caching.put( identifier, map ); } map.put( key, new LruCache<String, Collection<Long>>( key, size ) ); } public LruCache<String, Collection<Long>> get( IndexIdentifier identifier, String key ) { Map<String, LruCache<String, Collection<Long>>> map = caching.get( identifier ); return map != null ? map.get( key ) : null; } public void disable( IndexIdentifier identifier, String key ) { Map<String, LruCache<String, Collection<Long>>> map = caching.get( identifier ); if ( map != null ) { map.remove( key ); } } public void disable( IndexIdentifier identifier ) { Map<String, LruCache<String, Collection<Long>>> map = caching.get( identifier ); if ( map != null ) { map.clear(); } } }
false
community_lucene-index_src_main_java_org_neo4j_index_impl_lucene_Cache.java
5,805
public class BeginTransactionCommand implements WorkerCommand<CommandState, Void> { @Override public Void doWork( CommandState state ) { state.tx = state.graphDb.beginTx(); return null; } }
false
community_lucene-index_src_test_java_org_neo4j_index_impl_lucene_BeginTransactionCommand.java
5,806
public class BatchInsertionIT { @Rule public TargetDirectory.TestDirectory testDir = TargetDirectory.testDirForTest( BatchInsertionIT.class ); @Test public void shouldIndexNodesWithMultipleLabels() throws Exception { // Given BatchInserter inserter = BatchInserters.inserter( testDir.directory().getAbsolutePath() ); inserter.createNode( map("name", "Bob"), label( "User" ), label("Admin")); inserter.createDeferredSchemaIndex( label( "User" ) ).on( "name" ).create(); inserter.createDeferredSchemaIndex( label( "Admin" ) ).on( "name" ).create(); // When inserter.shutdown(); // Then GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase(testDir.directory().getAbsolutePath()); try(Transaction tx = db.beginTx()) { assertThat( count( db.findNodesByLabelAndProperty( label( "User" ), "name", "Bob" ) ), equalTo(1) ); assertThat( count( db.findNodesByLabelAndProperty( label( "Admin" ), "name", "Bob" ) ), equalTo(1) ); } finally { db.shutdown(); } } @Test public void shouldNotIndexNodesWithWrongLabel() throws Exception { // Given BatchInserter inserter = BatchInserters.inserter( testDir.directory().getAbsolutePath() ); inserter.createNode( map("name", "Bob"), label( "User" ), label("Admin")); inserter.createDeferredSchemaIndex( label( "Banana" ) ).on( "name" ).create(); // When inserter.shutdown(); // Then GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase(testDir.directory().getAbsolutePath()); try(Transaction tx = db.beginTx()) { assertThat( count( db.findNodesByLabelAndProperty( label( "Banana" ), "name", "Bob" ) ), equalTo(0) ); } finally { db.shutdown(); } } @Test public void shouldBeAbleToMakeRepeatedCallsToSetNodeProperty() throws Exception { BatchInserter inserter = BatchInserters.inserter( testDir.directory().getAbsolutePath() ); long nodeId = inserter.createNode( Collections.<String, Object>emptyMap() ); final Object finalValue = 87; inserter.setNodeProperty( nodeId, "a", "some property value" ); inserter.setNodeProperty( nodeId, "a", 42 ); inserter.setNodeProperty( nodeId, "a", 3.14 ); inserter.setNodeProperty( nodeId, "a", true ); inserter.setNodeProperty( nodeId, "a", finalValue ); inserter.shutdown(); GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase(testDir.directory().getAbsolutePath()); try(Transaction ignored = db.beginTx()) { assertThat( db.getNodeById( nodeId ).getProperty( "a" ), equalTo( finalValue ) ); } finally { db.shutdown(); } } @Test public void shouldBeAbleToMakeRepeatedCallsToSetNodePropertyWithMultiplePropertiesPerBlock() throws Exception { BatchInserter inserter = BatchInserters.inserter( testDir.directory().getAbsolutePath() ); long nodeId = inserter.createNode( Collections.<String, Object>emptyMap() ); final Object finalValue1 = 87; final Object finalValue2 = 3.14; inserter.setNodeProperty( nodeId, "a", "some property value" ); inserter.setNodeProperty( nodeId, "a", 42 ); inserter.setNodeProperty( nodeId, "b", finalValue2 ); inserter.setNodeProperty( nodeId, "a", finalValue2 ); inserter.setNodeProperty( nodeId, "a", true ); inserter.setNodeProperty( nodeId, "a", finalValue1 ); inserter.shutdown(); GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase(testDir.directory().getAbsolutePath()); try(Transaction ignored = db.beginTx()) { assertThat( db.getNodeById( nodeId ).getProperty( "a" ), equalTo( finalValue1 ) ); assertThat( db.getNodeById( nodeId ).getProperty( "b" ), equalTo( finalValue2 ) ); } finally { db.shutdown(); } } @Ignore @Test public void testInsertionSpeed() { BatchInserter inserter = BatchInserters.inserter( testDir.directory().getAbsolutePath() ); BatchInserterIndexProvider provider = new LuceneBatchInserterIndexProvider( inserter ); BatchInserterIndex index = provider.nodeIndex( "yeah", EXACT_CONFIG ); index.setCacheCapacity( "key", 1000000 ); long t = currentTimeMillis(); for ( int i = 0; i < 1000000; i++ ) { Map<String, Object> properties = map( "key", "value" + i ); long id = inserter.createNode( properties ); index.add( id, properties ); } System.out.println( "insert:" + ( currentTimeMillis() - t ) ); index.flush(); t = currentTimeMillis(); for ( int i = 0; i < 1000000; i++ ) { count( (Iterator<Long>) index.get( "key", "value" + i ) ); } System.out.println( "get:" + ( currentTimeMillis() - t ) ); } }
false
community_lucene-index_src_test_java_org_neo4j_index_impl_lucene_BatchInsertionIT.java
5,807
public class LuceneIndexImplementation implements IndexImplementation { static final String KEY_TYPE = "type"; static final String KEY_ANALYZER = "analyzer"; static final String KEY_TO_LOWER_CASE = "to_lower_case"; static final String KEY_SIMILARITY = "similarity"; public static final String SERVICE_NAME = "lucene"; public static final Map<String, String> EXACT_CONFIG = Collections.unmodifiableMap( MapUtil.stringMap( IndexManager.PROVIDER, SERVICE_NAME, KEY_TYPE, "exact" ) ); public static final Map<String, String> FULLTEXT_CONFIG = Collections.unmodifiableMap( MapUtil.stringMap( IndexManager.PROVIDER, SERVICE_NAME, KEY_TYPE, "fulltext", KEY_TO_LOWER_CASE, "true" ) ); public static final int DEFAULT_LAZY_THRESHOLD = 100; private final GraphDatabaseService graphDb; private IndexConnectionBroker<LuceneXaConnection> broker; private LuceneDataSource dataSource; final int lazynessThreshold; public LuceneIndexImplementation( GraphDatabaseService db, LuceneDataSource dataSource, IndexConnectionBroker<LuceneXaConnection> broker ) { this.graphDb = db; this.dataSource = dataSource; this.broker = broker; this.lazynessThreshold = DEFAULT_LAZY_THRESHOLD; } IndexConnectionBroker<LuceneXaConnection> broker() { return broker; } LuceneDataSource dataSource() { return dataSource; } @Override public Index<Node> nodeIndex( String indexName, Map<String, String> config ) { return dataSource.nodeIndex(indexName, graphDb, this); } @Override public RelationshipIndex relationshipIndex( String indexName, Map<String, String> config ) { return dataSource.relationshipIndex( indexName, graphDb, this ); } @Override public Map<String, String> fillInDefaults( Map<String, String> source ) { Map<String, String> result = source != null ? new HashMap<String, String>( source ) : new HashMap<String, String>(); String analyzer = result.get( KEY_ANALYZER ); if ( analyzer == null ) { // Type is only considered if "analyzer" isn't supplied String type = result.get( KEY_TYPE ); if ( type == null ) { type = "exact"; result.put( KEY_TYPE, type ); } if ( type.equals( "fulltext" ) && !result.containsKey( LuceneIndexImplementation.KEY_TO_LOWER_CASE ) ) { result.put( KEY_TO_LOWER_CASE, "true" ); } } return result; } @Override public boolean configMatches( Map<String, String> storedConfig, Map<String, String> config ) { return match( storedConfig, config, KEY_TYPE, null ) && match( storedConfig, config, KEY_TO_LOWER_CASE, "true" ) && match( storedConfig, config, KEY_ANALYZER, null ) && match( storedConfig, config, KEY_SIMILARITY, null ); } private boolean match( Map<String, String> storedConfig, Map<String, String> config, String key, String defaultValue ) { String value1 = storedConfig.get( key ); String value2 = config.get( key ); if ( value1 == null || value2 == null ) { if ( value1 == value2 ) { return true; } if ( defaultValue != null ) { value1 = value1 != null ? value1 : defaultValue; value2 = value2 != null ? value2 : defaultValue; return value1.equals( value2 ); } } else { return value1.equals( value2 ); } return false; } @Override public String getDataSourceName() { return LuceneDataSource.DEFAULT_NAME; } public boolean matches( GraphDatabaseService gdb ) { return this.graphDb.equals(gdb); } public void reset( LuceneDataSource dataSource, IndexConnectionBroker<LuceneXaConnection> broker) { this.broker = broker; this.dataSource = dataSource; } public GraphDatabaseService graphDb() { return graphDb; } }
false
community_lucene-index_src_main_java_org_neo4j_index_impl_lucene_LuceneIndexImplementation.java
5,808
class LuceneTransaction extends XaTransaction { private final Map<IndexIdentifier, TxDataBoth> txData = new HashMap<IndexIdentifier, TxDataBoth>(); private final LuceneDataSource dataSource; private final Map<IndexIdentifier,CommandList> commandMap = new HashMap<IndexIdentifier,CommandList>(); LuceneTransaction( XaLogicalLog xaLog, TransactionState state, LuceneDataSource luceneDs ) { super( xaLog, state ); this.dataSource = luceneDs; } <T extends PropertyContainer> void add( LuceneIndex<T> index, T entity, String key, Object value ) { value = value instanceof ValueContext ? ((ValueContext) value).getCorrectValue() : value.toString(); TxDataBoth data = getTxData( index, true ); insert( entity, key, value, data.added( true ), data.removed( false ) ); queueCommand( index.newAddCommand( entity, key, value ) ); } private Object getEntityId( PropertyContainer entity ) { return entity instanceof Node ? ((Node) entity).getId() : RelationshipId.of( (Relationship) entity ); } <T extends PropertyContainer> TxDataBoth getTxData( LuceneIndex<T> index, boolean createIfNotExists ) { IndexIdentifier identifier = index.getIdentifier(); TxDataBoth data = txData.get( identifier ); if ( data == null && createIfNotExists ) { data = new TxDataBoth( index ); txData.put( identifier, data ); } return data; } <T extends PropertyContainer> void remove( LuceneIndex<T> index, T entity, String key, Object value ) { value = value instanceof ValueContext ? ((ValueContext) value).getCorrectValue() : value.toString(); TxDataBoth data = getTxData( index, true ); insert( entity, key, value, data.removed( true ), data.added( false ) ); queueCommand( index.newRemoveCommand( entity, key, value ) ); } <T extends PropertyContainer> void remove( LuceneIndex<T> index, T entity, String key ) { TxDataBoth data = getTxData( index, true ); insert( entity, key, null, data.removed( true ), data.added( false ) ); queueCommand( index.newRemoveCommand( entity, key, null ) ); } <T extends PropertyContainer> void remove( LuceneIndex<T> index, T entity ) { TxDataBoth data = getTxData( index, true ); insert( entity, null, null, data.removed( true ), data.added( false ) ); queueCommand( index.newRemoveCommand( entity, null, null ) ); } <T extends PropertyContainer> void delete( LuceneIndex<T> index ) { txData.put( index.getIdentifier(), new DeletedTxDataBoth( index ) ); queueCommand( new DeleteCommand( index.getIdentifier() ) ); } private CommandList queueCommand( LuceneCommand command ) { IndexIdentifier indexId = command.indexId; CommandList commands = commandMap.get( indexId ); if ( commands == null ) { commands = new CommandList(); commandMap.put( indexId, commands ); } if ( command instanceof DeleteCommand ) { commands.clear(); } commands.add( command ); commands.incCounter( command ); return commands; } private <T extends PropertyContainer> void insert( T entity, String key, Object value, TxDataHolder insertInto, TxDataHolder removeFrom ) { Object id = getEntityId( entity ); if ( removeFrom != null ) { removeFrom.remove( id, key, value ); } insertInto.add( id, key, value ); } <T extends PropertyContainer> Collection<Long> getRemovedIds( LuceneIndex<T> index, Query query ) { TxDataHolder removed = removedTxDataOrNull( index ); if ( removed == null ) { return Collections.emptySet(); } Collection<Long> ids = removed.query( query, null ); return ids != null ? ids : Collections.<Long>emptySet(); } <T extends PropertyContainer> Collection<Long> getRemovedIds( LuceneIndex<T> index, String key, Object value ) { TxDataHolder removed = removedTxDataOrNull( index ); if ( removed == null ) { return Collections.emptySet(); } Collection<Long> ids = removed.get( key, value ); Collection<Long> orphanIds = removed.getOrphans( key ); return merge( ids, orphanIds ); } static Collection<Long> merge( Collection<Long> c1, Collection<Long> c2 ) { if ( c1 == null && c2 == null ) { return Collections.<Long>emptySet(); } else if ( c1 != null && c2 != null ) { if (c1.isEmpty()) { return c2; } if (c2.isEmpty()) { return c1; } Collection<Long> result = new HashSet<Long>( c1.size()+c2.size(), 1 ); result.addAll( c1 ); result.addAll( c2 ); return result; } else { return c1 != null ? c1 : c2; } } <T extends PropertyContainer> Collection<Long> getAddedIds( LuceneIndex<T> index, Query query, QueryContext contextOrNull ) { TxDataHolder added = addedTxDataOrNull( index ); if ( added == null ) { return Collections.emptySet(); } Collection<Long> ids = added.query( query, contextOrNull ); return ids != null ? ids : Collections.<Long>emptySet(); } <T extends PropertyContainer> Collection<Long> getAddedIds( LuceneIndex<T> index, String key, Object value ) { TxDataHolder added = addedTxDataOrNull( index ); if ( added == null ) { return Collections.emptySet(); } Collection<Long> ids = added.get( key, value ); return ids != null ? ids : Collections.<Long>emptySet(); } private <T extends PropertyContainer> TxDataHolder addedTxDataOrNull( LuceneIndex<T> index ) { TxDataBoth data = getTxData( index, false ); return data != null ? data.added( false ) : null; } private <T extends PropertyContainer> TxDataHolder removedTxDataOrNull( LuceneIndex<T> index ) { TxDataBoth data = getTxData( index, false ); return data != null ? data.removed( false ) : null; } @Override protected void doAddCommand( XaCommand command ) { // we override inject command and manage our own in memory command list } @Override protected void injectCommand( XaCommand command ) { queueCommand( ( LuceneCommand ) command ).incCounter( (LuceneCommand ) command ); } @Override protected void doCommit() { dataSource.getWriteLock(); try { for ( Map.Entry<IndexIdentifier, CommandList> entry : this.commandMap.entrySet() ) { if ( entry.getValue().isEmpty() ) { continue; } IndexIdentifier identifier = entry.getKey(); CommandList commandList = entry.getValue(); IndexType type = identifier == LuceneCommand.CreateIndexCommand.FAKE_IDENTIFIER || !commandList.containsWrites() ? null : dataSource.getType( identifier, isRecovered() ); // This is for an issue where there are changes to and index which in a later // transaction becomes deleted and crashes before the next rotation. // The next recovery process will then recover that log and do those changes // to the index, which at this point doesn't exist. So just don't do those // changes as it will be deleted "later" anyway. if ( type == null && isRecovered() ) { if ( commandList.isDeletion() ) { dataSource.removeExpectedFutureDeletion( identifier ); } else if ( commandList.containsWrites() ) { dataSource.addExpectedFutureDeletion( identifier ); continue; } } CommitContext context = null; try { context = new CommitContext( dataSource, identifier, type, commandList ); for ( LuceneCommand command : commandList.commands ) { command.perform( context ); } applyDocuments( context.writer, type, context.documents ); if ( context.writer != null ) { dataSource.invalidateIndexSearcher( identifier ); } } finally { if ( context != null ) { context.close(); } } } dataSource.setLastCommittedTxId( getCommitTxId() ); closeTxData(); } catch ( IOException e ) { throw new RuntimeException( e ); } finally { dataSource.releaseWriteLock(); } } private void applyDocuments( IndexWriter writer, IndexType type, Map<Long, DocumentContext> documents ) throws IOException { for ( Map.Entry<Long, DocumentContext> entry : documents.entrySet() ) { DocumentContext context = entry.getValue(); if ( context.exists ) { if ( LuceneDataSource.documentIsEmpty( context.document ) ) { writer.deleteDocuments( type.idTerm( context.entityId ) ); } else { writer.updateDocument( type.idTerm( context.entityId ), context.document ); } } else { writer.addDocument( context.document ); } } } private void closeTxData() { for ( TxDataBoth data : this.txData.values() ) { data.close(); } this.txData.clear(); } @Override protected void doPrepare() { boolean containsDeleteCommand = false; for ( CommandList list : commandMap.values() ) { for ( LuceneCommand command : list.commands ) { if ( command instanceof DeleteCommand ) { containsDeleteCommand = true; } addCommand( command ); } } if ( !containsDeleteCommand ) { // unless the entire index is deleted addAbandonedEntitiesToTheTx(); } // else: the DeleteCommand will clear abandonedIds } private void addAbandonedEntitiesToTheTx() { for ( Map.Entry<IndexIdentifier, TxDataBoth> entry : txData.entrySet() ) { Collection<Long> abandonedIds = entry.getValue().index.abandonedIds; if ( !abandonedIds.isEmpty() ) { CommandList commands = commandMap.get( entry.getKey() ); for ( Long id : abandonedIds ) { RemoveCommand command = new RemoveCommand( entry.getKey(), entry.getKey().entityTypeByte, id, null, null ); addCommand( command ); commands.add( command ); } abandonedIds.clear(); } } } @Override protected void doRollback() { commandMap.clear(); closeTxData(); } @Override public boolean isReadOnly() { return commandMap.isEmpty(); } // Bad name private class TxDataBoth { private TxDataHolder add; private TxDataHolder remove; final LuceneIndex index; public TxDataBoth( LuceneIndex index ) { this.index = index; } TxDataHolder added( boolean createIfNotExists ) { if ( this.add == null && createIfNotExists ) { this.add = new TxDataHolder( index, index.type.newTxData( index ) ); } return this.add; } TxDataHolder removed( boolean createIfNotExists ) { if ( this.remove == null && createIfNotExists ) { this.remove = new TxDataHolder( index, index.type.newTxData( index ) ); } return this.remove; } void close() { safeClose( add ); safeClose( remove ); } private void safeClose( TxDataHolder data ) { if ( data != null ) { data.close(); } } } private class DeletedTxDataBoth extends TxDataBoth { public DeletedTxDataBoth( LuceneIndex index ) { super( index ); } @Override TxDataHolder added( boolean createIfNotExists ) { throw illegalStateException(); } @Override TxDataHolder removed( boolean createIfNotExists ) { throw illegalStateException(); } private IllegalStateException illegalStateException() { throw new IllegalStateException( "This index (" + index.getIdentifier() + ") has been marked as deleted in this transaction" ); } } static class CommandList { private final List<LuceneCommand> commands = new ArrayList<LuceneCommand>(); private boolean containsWrites; void add( LuceneCommand command ) { this.commands.add( command ); } boolean containsWrites() { return containsWrites; } boolean isDeletion() { return commands.size() == 1 && commands.get( 0 ) instanceof DeleteCommand; } void clear() { commands.clear(); containsWrites = false; } void incCounter( LuceneCommand command ) { if ( command.isConsideredNormalWriteCommand() ) { containsWrites = true; } } boolean isEmpty() { return commands.isEmpty(); } boolean isRecovery() { return commands.get( 0 ).isRecovered(); } } void createIndex( Class<? extends PropertyContainer> entityType, String name, Map<String, String> config ) { byte entityTypeByte = 0; if ( entityType == Node.class ) { entityTypeByte = LuceneCommand.NODE; } else if ( entityType == Relationship.class ) { entityTypeByte = LuceneCommand.RELATIONSHIP; } else { throw new IllegalArgumentException( "Unknown entity typee " + entityType ); } queueCommand( new CreateIndexCommand( entityTypeByte, name, config ) ); } <T extends PropertyContainer> IndexSearcher getAdditionsAsSearcher( LuceneIndex<T> index, QueryContext context ) { TxDataHolder data = addedTxDataOrNull( index ); return data != null ? data.asSearcher( context ) : null; } }
false
community_lucene-index_src_main_java_org_neo4j_index_impl_lucene_LuceneTransaction.java
5,809
static class CommandList { private final List<LuceneCommand> commands = new ArrayList<LuceneCommand>(); private boolean containsWrites; void add( LuceneCommand command ) { this.commands.add( command ); } boolean containsWrites() { return containsWrites; } boolean isDeletion() { return commands.size() == 1 && commands.get( 0 ) instanceof DeleteCommand; } void clear() { commands.clear(); containsWrites = false; } void incCounter( LuceneCommand command ) { if ( command.isConsideredNormalWriteCommand() ) { containsWrites = true; } } boolean isEmpty() { return commands.isEmpty(); } boolean isRecovery() { return commands.get( 0 ).isRecovered(); } }
false
community_lucene-index_src_main_java_org_neo4j_index_impl_lucene_LuceneTransaction.java
5,810
@Service.Implementation( ManagementBeanProvider.class ) public final class PrimitivesBean extends ManagementBeanProvider { public PrimitivesBean() { super( Primitives.class ); } @Override protected Neo4jMBean createMBean( ManagementData management ) throws NotCompliantMBeanException { return new PrimitivesImpl( management ); } private static class PrimitivesImpl extends Neo4jMBean implements Primitives { PrimitivesImpl( ManagementData management ) throws NotCompliantMBeanException { super( management ); this.nodeManager = management.getKernelData().graphDatabase().getDependencyResolver() .resolveDependency( NodeManager.class ); } private final NodeManager nodeManager; public long getNumberOfNodeIdsInUse() { return nodeManager.getNumberOfIdsInUse( Node.class ); } public long getNumberOfRelationshipIdsInUse() { return nodeManager.getNumberOfIdsInUse( Relationship.class ); } public long getNumberOfPropertyIdsInUse() { return nodeManager.getNumberOfIdsInUse( PropertyStore.class ); } public long getNumberOfRelationshipTypeIdsInUse() { return nodeManager.getNumberOfIdsInUse( RelationshipType.class ); } } }
false
community_jmx_src_main_java_org_neo4j_jmx_impl_PrimitivesBean.java
5,811
public class ManagementSupport { final static ManagementSupport load() { ManagementSupport support = new ManagementSupport(); for ( ManagementSupport candidate : Service.load( ManagementSupport.class ) ) { // Can we know that there aren't going to be multiple instances? support = candidate; } return support; } protected MBeanServer getMBeanServer() { return getPlatformMBeanServer(); } /** * Create a proxy for the specified bean. * * @param <T> The type of the bean to create. * @param kernel the kernel that the proxy should be created for. * @param beanInterface the bean type to create the proxy for. * @return a new proxy for the specified bean. */ protected <T> T makeProxy( KernelBean kernel, ObjectName name, Class<T> beanInterface ) { throw new UnsupportedOperationException( "Cannot create management bean proxies." ); } final <T> Collection<T> getProxiesFor( Class<T> beanInterface, KernelBean kernel ) { Collection<T> result = new ArrayList<T>(); ObjectName query = createObjectNameQuery( kernel.getInstanceId(), beanInterface ); for ( ObjectName name : getMBeanServer().queryNames( query, null ) ) { result.add( makeProxy( kernel, name, beanInterface ) ); } return result; } protected boolean supportsMxBeans() { return false; } /** * Get the URI to which connections can be made to the {@link MBeanServer} * of this JVM. * * @param kernel the kernel that wishes to access the URI. * @return a URI that can be used for connecting to the {@link MBeanServer} * of this JVM. */ protected JMXServiceURL getJMXServiceURL( KernelData kernel ) { return null; } public final ObjectName createObjectName( String instanceId, Class<?> beanInterface, String... extraNaming ) { return createObjectName( instanceId, getBeanName( beanInterface ), false, extraNaming ); } private final ObjectName createObjectNameQuery( String instanceId, Class<?> beanInterface ) { return createObjectName( instanceId, getBeanName( beanInterface ), true ); } public final ObjectName createMBeanQuery( String instanceId ) { return createObjectName( instanceId, "*", false ); } protected String getBeanName( Class<?> beanInterface ) { return beanName( beanInterface ); } protected ObjectName createObjectName( String instanceId, String beanName, boolean query, String... extraNaming ) { Hashtable<String, String> properties = new Hashtable<String, String>(); properties.put( "instance", "kernel#" + instanceId ); properties.put( "name", beanName ); for ( int i = 0; i < extraNaming.length; i++ ) { properties.put( "name" + i, extraNaming[i] ); } try { return new ObjectName( "org.neo4j", properties ); } catch ( MalformedObjectNameException e ) { return null; } } static String beanName( Class<?> iface ) { if ( iface.isInterface() ) { ManagementInterface management = iface.getAnnotation( ManagementInterface.class ); if ( management != null ) { return management.name(); } } throw new IllegalArgumentException( iface + " is not a Neo4j Management Been interface" ); } }
false
community_jmx_src_main_java_org_neo4j_jmx_impl_ManagementSupport.java
5,812
public final class ManagementData { private final KernelData kernel; private final ManagementSupport support; final ManagementBeanProvider provider; ManagementData( ManagementBeanProvider provider, KernelData kernel, ManagementSupport support ) { this.provider = provider; this.kernel = kernel; this.support = support; } public KernelData getKernelData() { return kernel; } ObjectName getObjectName( String... extraNaming ) { ObjectName name = support.createObjectName( kernel.instanceId(), provider.beanInterface, extraNaming ); if ( name == null ) { throw new IllegalArgumentException( provider.beanInterface + " is not a Neo4j Management Bean interface" ); } return name; } void validate( Class<? extends Neo4jMBean> implClass ) { if ( !provider.beanInterface.isAssignableFrom( implClass ) ) { throw new IllegalStateException( implClass + " does not implement " + provider.beanInterface ); } } }
false
community_jmx_src_main_java_org_neo4j_jmx_impl_ManagementData.java
5,813
public abstract class ManagementBeanProvider extends Service { final Class<?> beanInterface; public ManagementBeanProvider( Class<?> beanInterface ) { super( ManagementSupport.beanName( beanInterface ) ); if ( DynamicMBean.class.isAssignableFrom( beanInterface ) ) beanInterface = DynamicMBean.class; this.beanInterface = beanInterface; } protected Iterable<? extends Neo4jMBean> createMBeans( ManagementData management ) throws NotCompliantMBeanException { return singletonOrNone( createMBean( management ) ); } protected Iterable<? extends Neo4jMBean> createMXBeans( ManagementData management ) throws NotCompliantMBeanException { Class<?> implClass; try { implClass = getClass().getDeclaredMethod( "createMBeans", ManagementData.class ).getDeclaringClass(); } catch ( Exception e ) { implClass = ManagementBeanProvider.class; // Assume no override } if ( implClass != ManagementBeanProvider.class ) { // if createMBeans is overridden, delegate to it return createMBeans( management ); } else { // otherwise delegate to the createMXBean method and create a list return singletonOrNone( createMXBean( management ) ); } } protected abstract Neo4jMBean createMBean( ManagementData management ) throws NotCompliantMBeanException; protected Neo4jMBean createMXBean( ManagementData management ) throws NotCompliantMBeanException { return createMBean( management ); } final Iterable<? extends Neo4jMBean> loadBeans( KernelData kernel, ManagementSupport support ) throws Exception { if ( support.supportsMxBeans() ) { return createMXBeans( new ManagementData( this, kernel, support ) ); } else { return createMBeans( new ManagementData( this, kernel, support ) ); } } private static Collection<? extends Neo4jMBean> singletonOrNone( Neo4jMBean mbean ) { if ( mbean == null ) return Collections.emptySet(); return Collections.singleton( mbean ); } }
false
community_jmx_src_main_java_org_neo4j_jmx_impl_ManagementBeanProvider.java
5,814
private class DataSourceInfo implements DataSourceRegistrationListener { @Override public void registeredDataSource( XaDataSource ds ) { if ( ds instanceof NeoStoreXaDataSource ) { NeoStoreXaDataSource datasource = (NeoStoreXaDataSource) ds; storeCreationDate = datasource.getCreationTime(); storeLogVersion = datasource.getCurrentLogVersion(); isReadOnly = datasource.isReadOnly(); storeId = datasource.getRandomIdentifier(); try { storeDir = new File( datasource.getStoreDir() ).getCanonicalFile().getAbsolutePath(); } catch ( IOException e ) { storeDir = new File( datasource.getStoreDir() ).getAbsolutePath(); } } } @Override public void unregisteredDataSource( XaDataSource ds ) { if ( ds instanceof NeoStoreXaDataSource ) { storeCreationDate = -1; storeLogVersion = -1; isReadOnly = false; storeId = -1; storeDir = null; } } }
false
community_jmx_src_main_java_org_neo4j_jmx_impl_KernelBean.java
5,815
public class KernelBean extends Neo4jMBean implements Kernel { private final long kernelStartTime; private final String kernelVersion; private final ObjectName query; private final String instanceId; private final DataSourceInfo dataSourceInfo; private boolean isReadOnly; private long storeCreationDate = -1; private long storeId = -1; private String storeDir = null; private long storeLogVersion; KernelBean( KernelData kernel, ManagementSupport support ) throws NotCompliantMBeanException { super( Kernel.class, kernel, support ); dataSourceInfo = new DataSourceInfo(); kernel.graphDatabase().getDependencyResolver().resolveDependency( XaDataSourceManager.class ) .addDataSourceRegistrationListener( dataSourceInfo ); this.kernelVersion = kernel.version().toString(); this.instanceId = kernel.instanceId(); this.query = support.createMBeanQuery( instanceId ); kernelStartTime = new Date().getTime(); } String getInstanceId() { return instanceId; } public ObjectName getMBeanQuery() { return query; } public Date getKernelStartTime() { return new Date( kernelStartTime ); } public Date getStoreCreationDate() { return new Date( storeCreationDate ); } public String getStoreId() { return Long.toHexString( storeId ); } public long getStoreLogVersion() { return storeLogVersion; } public String getKernelVersion() { return kernelVersion; } public boolean isReadOnly() { return isReadOnly; } public String getStoreDirectory() { return storeDir; } private class DataSourceInfo implements DataSourceRegistrationListener { @Override public void registeredDataSource( XaDataSource ds ) { if ( ds instanceof NeoStoreXaDataSource ) { NeoStoreXaDataSource datasource = (NeoStoreXaDataSource) ds; storeCreationDate = datasource.getCreationTime(); storeLogVersion = datasource.getCurrentLogVersion(); isReadOnly = datasource.isReadOnly(); storeId = datasource.getRandomIdentifier(); try { storeDir = new File( datasource.getStoreDir() ).getCanonicalFile().getAbsolutePath(); } catch ( IOException e ) { storeDir = new File( datasource.getStoreDir() ).getAbsolutePath(); } } } @Override public void unregisteredDataSource( XaDataSource ds ) { if ( ds instanceof NeoStoreXaDataSource ) { storeCreationDate = -1; storeLogVersion = -1; isReadOnly = false; storeId = -1; storeDir = null; } } } }
false
community_jmx_src_main_java_org_neo4j_jmx_impl_KernelBean.java
5,816
public class JmxKernelExtension implements Lifecycle { private KernelData kernelData; private StringLogger logger; private List<Neo4jMBean> beans; private MBeanServer mbs; private ManagementSupport support; private JMXServiceURL url; public JmxKernelExtension( KernelData kernelData, Logging logging ) { this.kernelData = kernelData; this.logger = logging.getMessagesLog( getClass() ); } @Override public void init() throws Throwable { support = ManagementSupport.load(); url = support.getJMXServiceURL( kernelData ); mbs = support.getMBeanServer(); beans = new LinkedList<Neo4jMBean>(); try { Neo4jMBean bean = new KernelBean( kernelData, support ); mbs.registerMBean( bean, bean.objectName ); beans.add( bean ); } catch ( Exception e ) { logger.info( "Failed to register Kernel JMX Bean" ); } for ( ManagementBeanProvider provider : Service.load( ManagementBeanProvider.class ) ) { try { for ( Neo4jMBean bean : provider.loadBeans( kernelData, support ) ) { mbs.registerMBean( bean, bean.objectName ); beans.add( bean ); } } catch ( Exception e ) { // Unexpected exception logger.info( "Failed to register JMX Bean " + provider + " (" + e + ")" ); } } try { Neo4jMBean bean = new ConfigurationBean( kernelData, support ); mbs.registerMBean( bean, bean.objectName ); beans.add( bean ); } catch ( Exception e ) { logger.info( "Failed to register Configuration JMX Bean" ); } } @Override public void start() throws Throwable { } @Override public void stop() throws Throwable { } @Override public void shutdown() throws Throwable { for ( Neo4jMBean bean : beans ) { try { mbs.unregisterMBean( bean.objectName ); } catch ( Exception e ) { logger.warn( "Could not unregister MBean " + bean.objectName.toString(), e ); } } } public JMXServiceURL getConnectionURL() { return url; } public final <T> T getSingleManagementBean( Class<T> type ) { Iterator<T> beans = getManagementBeans( type ).iterator(); if ( beans.hasNext() ) { T bean = beans.next(); if ( beans.hasNext() ) { throw new NotFoundException( "More than one management bean for " + type.getName() ); } return bean; } throw new NotFoundException( "No management bean found for "+type.getName() ); } public <T> Collection<T> getManagementBeans( Class<T> beanInterface ) { Collection<T> result = null; if ( support.getClass() != ManagementSupport.class && beans.size() > 0 && beans.get( 0 ) instanceof KernelBean ) { try { result = support.getProxiesFor( beanInterface, (KernelBean) beans.get( 0 ) ); } catch ( UnsupportedOperationException ignore ) { result = null; // go to fall back } } if ( result == null ) { // Fall back: if we cannot create proxy, we can search for instances result = new ArrayList<T>(); for ( Neo4jMBean bean : beans ) { if ( beanInterface.isInstance( bean ) ) { result.add( beanInterface.cast( bean ) ); } } } return result; } }
false
community_jmx_src_main_java_org_neo4j_jmx_impl_JmxKernelExtension.java
5,817
@Service.Implementation(KernelExtensionFactory.class) public final class JmxExtensionFactory extends KernelExtensionFactory<JmxExtensionFactory.Dependencies> { public interface Dependencies { KernelData getKernelData(); Logging getLogging(); } public static final String KEY = "kernel jmx"; public JmxExtensionFactory() { super( KEY ); } @Override public Lifecycle newKernelExtension( Dependencies dependencies ) throws Throwable { return new JmxKernelExtension( dependencies.getKernelData(), dependencies.getLogging() ); } }
false
community_jmx_src_main_java_org_neo4j_jmx_impl_JmxExtensionFactory.java
5,818
private class UpdatedConfigurationListener implements ConfigurationChangeListener { @Override public void notifyConfigurationChanges( Iterable<ConfigurationChange> change ) { for( ConfigurationChange configurationChange : change ) { config.put( configurationChange.getName(), configurationChange.getNewValue() ); } } }
false
community_jmx_src_main_java_org_neo4j_jmx_impl_ConfigurationBean.java
5,819
@Description( "The configuration parameters used to configure Neo4j" ) public final class ConfigurationBean extends Neo4jMBean { public static final String CONFIGURATION_MBEAN_NAME = "Configuration"; private final Map<String, String> config; private final Config configuration; private final Map<String, String> parameterDescriptions; ConfigurationBean( KernelData kernel, ManagementSupport support ) throws NotCompliantMBeanException { super( CONFIGURATION_MBEAN_NAME, kernel, support ); this.config = new HashMap<String, String>(kernel.getConfig().getParams()); this.configuration = kernel.getConfig(); configuration.addConfigurationChangeListener( new UpdatedConfigurationListener() ); Map<String, String> descriptions = new HashMap<String, String>(); for ( Class<?> settingsClass : configuration.getSettingsClasses() ) { for ( final Field field : settingsClass.getFields() ) { if ( Modifier.isStatic( field.getModifiers() ) && Modifier.isFinal( field.getModifiers() ) ) { final org.neo4j.graphdb.factory.Description documentation = field.getAnnotation( org.neo4j.graphdb.factory.Description.class ); if ( documentation == null || !Setting.class.isAssignableFrom(field.getType()) ) continue; try { if ( !field.isAccessible() ) field.setAccessible( true ); String description = documentation.value(); Setting setting = (Setting) field.get( null ); descriptions.put( setting.name(), description ); String value = configuration.getParams().get( setting.name() ); if (value == null) value = setting.getDefaultValue(); config.put( setting.name(), value ); } catch ( Exception e ) { continue; } } } } parameterDescriptions = Collections.unmodifiableMap( descriptions ); } private String describeConfigParameter( String param ) { String description = parameterDescriptions.get( param ); return description != null ? description : "Configuration attribute"; } private MBeanAttributeInfo[] keys() { List<MBeanAttributeInfo> keys = new ArrayList<MBeanAttributeInfo>(); for ( String key : config.keySet() ) { keys.add( new MBeanAttributeInfo( key, String.class.getName(), describeConfigParameter( key ), true, false, false ) ); } return keys.toArray( new MBeanAttributeInfo[keys.size()] ); } private MBeanOperationInfo[] methods() { List<MBeanOperationInfo> methods = new ArrayList<MBeanOperationInfo>(); try { methods.add( new MBeanOperationInfo( "Apply settings", getClass().getMethod( "apply" ) ) ); } catch( NoSuchMethodException e ) { e.printStackTrace( ); } return methods.toArray( new MBeanOperationInfo[methods.size()] ); } @Override public Object getAttribute( String attribute ) throws AttributeNotFoundException, MBeanException, ReflectionException { return config.get( attribute ); } @Override public AttributeList getAttributes( String[] attributes ) { AttributeList result = new AttributeList( attributes.length ); for ( String attribute : attributes ) { try { result.add( new Attribute( attribute, getAttribute( attribute ) ) ); } catch ( Exception e ) { throw new RuntimeException( e ); } } return result; } @Override public void setAttribute( Attribute attribute ) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { if (config.containsKey( attribute.getName() )) config.put( attribute.getName(), attribute.getValue().toString() ); } @Override public MBeanInfo getMBeanInfo() { Description description = getClass().getAnnotation( Description.class ); return new MBeanInfo( getClass().getName(), description != null ? description.value() : "Neo4j configuration", keys(), null, methods(), null ); } @Override public Object invoke( String s, Object[] objects, String[] strings ) throws MBeanException, ReflectionException { try { return getClass().getMethod( s ).invoke( this ); } catch( InvocationTargetException e ) { throw new MBeanException( (Exception) e.getTargetException() ); } catch( Exception e ) { throw new MBeanException( e ); } } public void apply() { // Apply new config try { System.out.println( "Apply new config" ); configuration.applyChanges( config ); } catch( Throwable e ) { e.printStackTrace(); } } private class UpdatedConfigurationListener implements ConfigurationChangeListener { @Override public void notifyConfigurationChanges( Iterable<ConfigurationChange> change ) { for( ConfigurationChange configurationChange : change ) { config.put( configurationChange.getName(), configurationChange.getNewValue() ); } } } }
false
community_jmx_src_main_java_org_neo4j_jmx_impl_ConfigurationBean.java
5,820
public class JmxUtils { private static final MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); public static ObjectName getObjectName( GraphDatabaseService db, String name ) { if(!(db instanceof GraphDatabaseAPI)) { throw new IllegalArgumentException( "Can only resolve object names for embedded Neo4j database " + "instances, eg. instances created by GraphDatabaseFactory or HighlyAvailableGraphDatabaseFactory." ); } ObjectName neoQuery = ((GraphDatabaseAPI)db).getDependencyResolver().resolveDependency( JmxKernelExtension.class ) .getSingleManagementBean( Kernel.class ).getMBeanQuery(); String instance = neoQuery.getKeyProperty( "instance" ); String domain = neoQuery.getDomain(); try { return new ObjectName( format( "%s:instance=%s,name=%s", domain, instance, name ) ); } catch ( MalformedObjectNameException e ) { throw new RuntimeException( e ); } } @SuppressWarnings("unchecked") public static <T> T getAttribute( ObjectName objectName, String attribute ) { try { return (T) mbeanServer.getAttribute( objectName, attribute ); } catch ( MBeanException e ) { throw new RuntimeException( e ); } catch ( AttributeNotFoundException e ) { throw new RuntimeException( e ); } catch ( InstanceNotFoundException e ) { throw new RuntimeException( e ); } catch ( ReflectionException e ) { throw new RuntimeException( e ); } } @SuppressWarnings("unchecked") public static <T> T invoke( ObjectName objectName, String attribute, Object[] params, String[] signatur ) { try { return (T) mbeanServer.invoke( objectName, attribute, params, signatur ); } catch ( MBeanException e ) { throw new RuntimeException( e ); } catch ( InstanceNotFoundException e ) { throw new RuntimeException( e ); } catch ( ReflectionException e ) { throw new RuntimeException( e ); } } }
false
community_jmx_src_main_java_org_neo4j_jmx_JmxUtils.java
5,821
public class DescriptionTest { private static GraphDatabaseService graphdb; @BeforeClass public static void startDb() { graphdb = new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().newGraphDatabase(); } @AfterClass public static void stopDb() { if ( graphdb != null ) { graphdb.shutdown(); } graphdb = null; } @Test public void canGetBeanDescriptionFromMBeanInterface() throws Exception { assertEquals( Kernel.class.getAnnotation( Description.class ).value(), kernelMBeanInfo().getDescription() ); } @Test public void canGetMethodDescriptionFromMBeanInterface() throws Exception { for ( MBeanAttributeInfo attr : kernelMBeanInfo().getAttributes() ) { try { assertEquals( Kernel.class.getMethod( "get" + attr.getName() ).getAnnotation( Description.class ).value(), attr.getDescription() ); } catch ( NoSuchMethodException ignored ) { assertEquals( Kernel.class.getMethod( "is" + attr.getName() ).getAnnotation( Description.class ).value(), attr.getDescription() ); } } } private MBeanInfo kernelMBeanInfo() throws Exception { Kernel kernel = ((GraphDatabaseAPI) graphdb).getDependencyResolver().resolveDependency( JmxKernelExtension .class ).getSingleManagementBean( Kernel.class ); ObjectName query = kernel.getMBeanQuery(); Hashtable<String, String> properties = new Hashtable<String, String>( query.getKeyPropertyList() ); properties.put( "name", Kernel.NAME ); MBeanInfo beanInfo = getPlatformMBeanServer().getMBeanInfo( new ObjectName( query.getDomain(), properties ) ); return beanInfo; } }
false
community_jmx_src_test_java_org_neo4j_jmx_DescriptionTest.java
5,822
{ @Override public int compare( Pair<PropertyContainer, Long> o1, Pair<PropertyContainer, Long> o2 ) { return !reversed ? o1.other().compareTo( o2.other() ) : o2.other().compareTo( o1.other() ); } } );
false
community_lucene-index_src_test_java_org_neo4j_index_timeline_TestTimeline.java
5,823
{ private final RelationshipType type = DynamicRelationshipType.withName( "whatever" ); @Override public Relationship create() { return db.createNode().createRelationshipTo( db.createNode(), type ); } };
false
community_lucene-index_src_test_java_org_neo4j_index_timeline_TestTimeline.java
5,824
{ @Override public Node create() { return db.createNode(); } };
false
community_lucene-index_src_test_java_org_neo4j_index_timeline_TestTimeline.java
5,825
public class TestTimeline { private GraphDatabaseService db; @Before public void before() throws Exception { db = new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().newGraphDatabase(); } @After public void after() { db.shutdown(); } private interface EntityCreator<T extends PropertyContainer> { T create(); } private EntityCreator<PropertyContainer> nodeCreator = new EntityCreator<PropertyContainer>() { @Override public Node create() { return db.createNode(); } }; private EntityCreator<PropertyContainer> relationshipCreator = new EntityCreator<PropertyContainer>() { private final RelationshipType type = DynamicRelationshipType.withName( "whatever" ); @Override public Relationship create() { return db.createNode().createRelationshipTo( db.createNode(), type ); } }; private TimelineIndex<PropertyContainer> nodeTimeline() { try( Transaction tx = db.beginTx() ) { Index<Node> nodeIndex = db.index().forNodes( "timeline" ); tx.success(); return new LuceneTimeline( db, nodeIndex ); } } private TimelineIndex<PropertyContainer> relationshipTimeline() { try( Transaction tx = db.beginTx() ) { RelationshipIndex relationshipIndex = db.index().forRelationships( "timeline" ); tx.success(); return new LuceneTimeline( db, relationshipIndex ); } } private LinkedList<Pair<PropertyContainer, Long>> createTimestamps( EntityCreator<PropertyContainer> creator, TimelineIndex<PropertyContainer> timeline, long... timestamps ) { try( Transaction tx = db.beginTx() ) { LinkedList<Pair<PropertyContainer, Long>> result = new LinkedList<>(); for ( long timestamp : timestamps ) { result.add( createTimestampedEntity( creator, timeline, timestamp ) ); } tx.success(); return result; } } private Pair<PropertyContainer, Long> createTimestampedEntity( EntityCreator<PropertyContainer> creator, TimelineIndex<PropertyContainer> timeline, long timestamp ) { PropertyContainer entity = creator.create(); timeline.add( entity, timestamp ); return Pair.of( entity, timestamp ); } private List<PropertyContainer> sortedEntities( LinkedList<Pair<PropertyContainer, Long>> timestamps, final boolean reversed ) { List<Pair<PropertyContainer, Long>> sorted = new ArrayList<Pair<PropertyContainer,Long>>( timestamps ); sort( sorted, new Comparator<Pair<PropertyContainer, Long>>() { @Override public int compare( Pair<PropertyContainer, Long> o1, Pair<PropertyContainer, Long> o2 ) { return !reversed ? o1.other().compareTo( o2.other() ) : o2.other().compareTo( o1.other() ); } } ); List<PropertyContainer> result = new ArrayList<PropertyContainer>(); for ( Pair<PropertyContainer, Long> timestamp : sorted ) { result.add( timestamp.first() ); } return result; } // ======== Tests, although private so that we can create two versions of each, // ======== one for nodes and one for relationships private void makeSureFirstAndLastAreReturnedCorrectly( EntityCreator<PropertyContainer> creator, TimelineIndex<PropertyContainer> timeline ) throws Exception { LinkedList<Pair<PropertyContainer, Long>> timestamps = createTimestamps( creator, timeline, 223456, 12345, 432234 ); try( Transaction tx = db.beginTx() ) { assertEquals( timestamps.get( 1 ).first(), timeline.getFirst() ); assertEquals( timestamps.getLast().first(), timeline.getLast() ); tx.success(); } } private void makeSureRangesAreReturnedInCorrectOrder( EntityCreator<PropertyContainer> creator, TimelineIndex<PropertyContainer> timeline ) throws Exception { LinkedList<Pair<PropertyContainer, Long>> timestamps = createTimestamps( creator, timeline, 300000, 200000, 400000, 100000, 500000, 600000, 900000, 800000 ); try( Transaction tx = db.beginTx() ) { assertEquals( sortedEntities( timestamps, false ), asCollection( timeline.getBetween( null, null ).iterator() ) ); tx.success(); } } private void makeSureRangesAreReturnedInCorrectReversedOrder( EntityCreator<PropertyContainer> creator, TimelineIndex<PropertyContainer> timeline ) throws Exception { LinkedList<Pair<PropertyContainer, Long>> timestamps = createTimestamps( creator, timeline, 300000, 200000, 199999, 400000, 100000, 500000, 600000, 900000, 800000 ); try( Transaction tx = db.beginTx() ) { assertEquals( sortedEntities( timestamps, true ), asCollection( timeline.getBetween( null, null, true ).iterator() ) ); tx.success(); } } private void makeSureWeCanQueryLowerDefaultThan1970( EntityCreator<PropertyContainer> creator, TimelineIndex<PropertyContainer> timeline ) throws Exception { LinkedList<Pair<PropertyContainer, Long>> timestamps = createTimestamps( creator, timeline, -10000, 0, 10000 ); try( Transaction tx = db.beginTx() ) { assertEquals( sortedEntities( timestamps, true ), asCollection( timeline.getBetween( null, 10000L, true ).iterator() ) ); tx.success(); } } private void makeSureUncommittedChangesAreSortedCorrectly( EntityCreator<PropertyContainer> creator, TimelineIndex<PropertyContainer> timeline ) throws Exception { LinkedList<Pair<PropertyContainer, Long>> timestamps = createTimestamps( creator, timeline, 300000, 100000, 500000, 900000, 800000 ); try( Transaction tx = db.beginTx() ) { timestamps.addAll( createTimestamps( creator, timeline, 40000, 70000, 20000 ) ); assertEquals( sortedEntities( timestamps, false ), asCollection( timeline.getBetween( null, null ).iterator() ) ); tx.success(); } try( Transaction ignore = db.beginTx() ) { assertEquals( sortedEntities( timestamps, false ), asCollection( timeline.getBetween( null, null ).iterator() ) ); } } // ======== The tests @Test public void makeSureFirstAndLastAreReturnedCorrectlyNode() throws Exception { makeSureFirstAndLastAreReturnedCorrectly( nodeCreator, nodeTimeline() ); } @Test public void makeSureFirstAndLastAreReturnedCorrectlyRelationship() throws Exception { makeSureFirstAndLastAreReturnedCorrectly( relationshipCreator, relationshipTimeline() ); } @Test public void makeSureRangesAreReturnedInCorrectOrderNode() throws Exception { makeSureRangesAreReturnedInCorrectOrder( nodeCreator, nodeTimeline() ); } @Test public void makeSureRangesAreReturnedInCorrectOrderRelationship() throws Exception { makeSureRangesAreReturnedInCorrectOrder( relationshipCreator, relationshipTimeline() ); } @Test public void makeSureRangesAreReturnedInCorrectReversedOrderNode() throws Exception { makeSureRangesAreReturnedInCorrectReversedOrder( nodeCreator, nodeTimeline() ); } @Test public void makeSureRangesAreReturnedInCorrectReversedOrderRelationship() throws Exception { makeSureRangesAreReturnedInCorrectReversedOrder( relationshipCreator, relationshipTimeline() ); } @Test public void makeSureUncommittedChangesAreSortedCorrectlyNode() throws Exception { makeSureUncommittedChangesAreSortedCorrectly( nodeCreator, nodeTimeline() ); } @Test public void makeSureUncommittedChangesAreSortedCorrectlyRelationship() throws Exception { makeSureUncommittedChangesAreSortedCorrectly( relationshipCreator, relationshipTimeline() ); } @Test public void makeSureWeCanQueryLowerDefaultThan1970Node() throws Exception { makeSureWeCanQueryLowerDefaultThan1970( nodeCreator, nodeTimeline() ); } @Test public void makeSureWeCanQueryLowerDefaultThan1970Relationship() throws Exception { makeSureWeCanQueryLowerDefaultThan1970( relationshipCreator, relationshipTimeline() ); } }
false
community_lucene-index_src_test_java_org_neo4j_index_timeline_TestTimeline.java
5,826
{ @Override public boolean accept( File pathName ) { String subPath = pathName.getAbsolutePath().substring( path.length() ).replace( File.separatorChar, '/' ); if ( "/lock".equals( subPath ) ) { return false; // since the db is running, exclude the 'lock' file } if ( subPath.startsWith( "/schema/index/lucene/" ) || subPath.startsWith( "/schema/label/lucene/" ) ) { return !subPath.endsWith( "/write.lock" ); // since the db is running, exclude lucene lock files } return true; } } );
false
community_lucene-index_src_test_java_org_neo4j_index_recovery_UniqueIndexRecoveryTests.java
5,827
@RunWith(Parameterized.class) public class UniqueIndexRecoveryTests { @Test public void shouldRecoverCreationOfUniquenessConstraintFollowedByDeletionOfThatSameConstraint() throws Exception { // given createUniqueConstraint(); dropConstraints(); // when - perform recovery restart( snapshot( storeDir.absolutePath() ) ); // then - just make sure the constraint is gone try ( Transaction tx = db.beginTx() ) { assertFalse( db.schema().getConstraints( LABEL ).iterator().hasNext() ); tx.success(); } } private void dropConstraints() { try ( Transaction tx = db.beginTx() ) { for ( ConstraintDefinition constraint : db.schema().getConstraints( LABEL ) ) { constraint.drop(); } tx.success(); } } @Test public void shouldRecoverWhenCommandsTemporarilyViolateConstraints() throws Exception { // GIVEN Node unLabeledNode = createUnLabeledNode(); Node labeledNode = createLabeledNode(); createUniqueConstraint(); rotateLog(); // snapshot setPropertyOnLabeledNode( labeledNode ); deletePropertyOnLabeledNode( labeledNode ); addLabelToUnLabeledNode( unLabeledNode ); flushAll(); // persist - recovery will do everything since last log rotate // WHEN recovery is triggered restart( snapshot( storeDir.absolutePath() ) ); // THEN // it should just not blow up! try ( Transaction tx = db.beginTx() ) { assertThat( single( db.findNodesByLabelAndProperty( LABEL, PROPERTY_KEY, PROPERTY_VALUE ) ), equalTo( unLabeledNode ) ); tx.success(); } } private void restart( File newStore ) { db.shutdown(); db = (GraphDatabaseAPI) factory.newEmbeddedDatabase( newStore.getAbsolutePath() ); } private File snapshot( final String path ) throws IOException { File snapshotDir = new File( path, "snapshot-" + new Random().nextInt() ); FileUtils.copyRecursively( new File( path ), snapshotDir, new FileFilter() { @Override public boolean accept( File pathName ) { String subPath = pathName.getAbsolutePath().substring( path.length() ).replace( File.separatorChar, '/' ); if ( "/lock".equals( subPath ) ) { return false; // since the db is running, exclude the 'lock' file } if ( subPath.startsWith( "/schema/index/lucene/" ) || subPath.startsWith( "/schema/label/lucene/" ) ) { return !subPath.endsWith( "/write.lock" ); // since the db is running, exclude lucene lock files } return true; } } ); return snapshotDir; } private void addLabelToUnLabeledNode( Node unLabeledNode ) { try ( Transaction tx = db.beginTx() ) { unLabeledNode.addLabel( LABEL ); tx.success(); } } private void setPropertyOnLabeledNode( Node labeledNode ) { try ( Transaction tx = db.beginTx() ) { labeledNode.setProperty( PROPERTY_KEY, PROPERTY_VALUE ); tx.success(); } } private void deletePropertyOnLabeledNode( Node labeledNode ) { try ( Transaction tx = db.beginTx() ) { labeledNode.removeProperty( PROPERTY_KEY ); tx.success(); } } private void createUniqueConstraint() { try ( Transaction tx = db.beginTx() ) { db.schema().constraintFor( LABEL ).assertPropertyIsUnique( PROPERTY_KEY ).create(); tx.success(); } } private Node createLabeledNode() { try ( Transaction tx = db.beginTx() ) { Node node = db.createNode( LABEL ); tx.success(); return node; } } private Node createUnLabeledNode() { try ( Transaction tx = db.beginTx() ) { Node node = db.createNode(); node.setProperty( PROPERTY_KEY, PROPERTY_VALUE ); tx.success(); return node; } } @Parameterized.Parameters(name = "{0}") public static Collection<Object[]> parameters() { return asList( new Object[]{new LuceneSchemaIndexProviderFactory()}, new Object[]{new InMemoryIndexProviderFactory()} ); } @Parameterized.Parameter(0) public KernelExtensionFactory<?> kernelExtensionFactory; @Rule public final TargetDirectory.TestDirectory storeDir = TargetDirectory.testDirForTest( UniqueIndexRecoveryTests.class ); private static final String PROPERTY_KEY = "key"; private static final String PROPERTY_VALUE = "value"; private static final Label LABEL = label( "label" ); private final TestGraphDatabaseFactory factory = new TestGraphDatabaseFactory(); private GraphDatabaseAPI db; @Before public void before() { List<KernelExtensionFactory<?>> extensionFactories = new ArrayList<>(); extensionFactories.add( kernelExtensionFactory ); factory.addKernelExtensions( extensionFactories ); db = (GraphDatabaseAPI) factory.newEmbeddedDatabase( storeDir.absolutePath() ); } @After public void after() { db.shutdown(); } private void rotateLog() { db.getDependencyResolver().resolveDependency( XaDataSourceManager.class ).rotateLogicalLogs(); } private void flushAll() { db.getDependencyResolver().resolveDependency( XaDataSourceManager.class ).getNeoStoreDataSource().getNeoStore().flushAll(); db.getDependencyResolver().resolveDependency( IndexingService.class ).flushAll(); } }
false
community_lucene-index_src_test_java_org_neo4j_index_recovery_UniqueIndexRecoveryTests.java
5,828
public class LuceneBatchInserterIndexProvider implements BatchInserterIndexProvider { private final BatchInserterIndexProvider provider; public LuceneBatchInserterIndexProvider( final BatchInserter inserter ) { provider = new LuceneBatchInserterIndexProviderNewImpl( inserter ); } @Override public BatchInserterIndex nodeIndex( String indexName, Map<String, String> config ) { return provider.nodeIndex( indexName, config ); } @Override public BatchInserterIndex relationshipIndex( String indexName, Map<String, String> config ) { return provider.relationshipIndex( indexName, config ); } @Override public void shutdown() { provider.shutdown(); } }
false
community_lucene-index_src_main_java_org_neo4j_index_lucene_unsafe_batchinsert_LuceneBatchInserterIndexProvider.java
5,829
public class ValueContext { private final Object value; private boolean indexNumeric; public ValueContext( Object value ) { this.value = value; } /** * @return the value object specified in the constructor. */ public Object getValue() { return value; } /** * Returns a ValueContext to be used with * {@link org.neo4j.graphdb.index.Index#add(org.neo4j.graphdb.PropertyContainer, String, Object)} * * @return a numeric ValueContext */ public ValueContext indexNumeric() { if ( !( this.value instanceof Number ) ) { throw new IllegalStateException( "Value should be a Number, is " + value + " (" + value.getClass() + ")" ); } this.indexNumeric = true; return this; } /** * Returns the string representation of the value given in the constructor, * or the unmodified value if {@link #indexNumeric()} has been called. * * @return the, by the user, intended value to index. */ public Object getCorrectValue() { return this.indexNumeric ? this.value : this.value.toString(); } @Override public String toString() { return value.toString(); } /** * Convience method to add a numeric value to an index. * @param value The value to add * @return A ValueContext that can be used with * {@link org.neo4j.graphdb.index.Index#add(org.neo4j.graphdb.PropertyContainer, String, Object)} */ public static ValueContext numeric(Number value) { return new ValueContext(value).indexNumeric(); } }
false
community_lucene-index_src_main_java_org_neo4j_index_lucene_ValueContext.java
5,830
public abstract class Neo4jMBean extends StandardMBean { final ObjectName objectName; protected Neo4jMBean( ManagementData management, boolean isMXBean, String... extraNaming ) { super( management.provider.beanInterface, isMXBean ); management.validate( getClass() ); this.objectName = management.getObjectName( extraNaming ); } protected Neo4jMBean( ManagementData management, String... extraNaming ) throws NotCompliantMBeanException { super( management.provider.beanInterface ); management.validate( getClass() ); this.objectName = management.getObjectName( extraNaming ); } /** Constructor for {@link KernelBean} */ Neo4jMBean( Class<Kernel> beanInterface, KernelData kernel, ManagementSupport support ) throws NotCompliantMBeanException { super( beanInterface ); this.objectName = support.createObjectName( kernel.instanceId(), beanInterface ); } /** Constructor for {@link ConfigurationBean} */ Neo4jMBean( String beanName, KernelData kernel, ManagementSupport support ) throws NotCompliantMBeanException { super( DynamicMBean.class ); this.objectName = support.createObjectName( kernel.instanceId(), beanName, false ); } @Override protected String getClassName( MBeanInfo info ) { final Class<?> iface = this.getMBeanInterface(); return iface == null ? super.getClassName( info ) : iface.getName(); } @Override protected String getDescription( MBeanInfo info ) { Description description = describeClass(); if ( description != null ) return description.value(); return super.getDescription( info ); } @Override protected String getDescription( MBeanAttributeInfo info ) { Description description = describeMethod( info, "get", "is" ); if ( description != null ) return description.value(); return super.getDescription( info ); } @Override protected String getDescription( MBeanOperationInfo info ) { Description description = describeMethod( info ); if ( description != null ) return description.value(); return super.getDescription( info ); } @Override protected int getImpact( MBeanOperationInfo info ) { Description description = describeMethod( info ); if ( description != null ) return description.impact(); return super.getImpact( info ); } private Description describeClass() { Description description = getClass().getAnnotation( Description.class ); if ( description == null ) { for ( Class<?> iface : getClass().getInterfaces() ) { description = iface.getAnnotation( Description.class ); if ( description != null ) break; } } return description; } private Description describeMethod( MBeanFeatureInfo info, String... prefixes ) { Description description = describeMethod( getClass(), info.getName(), prefixes ); if ( description == null ) { for ( Class<?> iface : getClass().getInterfaces() ) { description = describeMethod( iface, info.getName(), prefixes ); if ( description != null ) break; } } return description; } private static Description describeMethod( Class<?> type, String methodName, String[] prefixes ) { if ( prefixes == null || prefixes.length == 0 ) { try { return type.getMethod( methodName ).getAnnotation( Description.class ); } catch ( Exception e ) { return null; } } else { for ( String prefix : prefixes ) { try { return type.getMethod( prefix + methodName ).getAnnotation( Description.class ); } catch ( Exception e ) { // continue to next } } return null; } } }
false
community_jmx_src_main_java_org_neo4j_jmx_impl_Neo4jMBean.java
5,831
private static class PrimitivesImpl extends Neo4jMBean implements Primitives { PrimitivesImpl( ManagementData management ) throws NotCompliantMBeanException { super( management ); this.nodeManager = management.getKernelData().graphDatabase().getDependencyResolver() .resolveDependency( NodeManager.class ); } private final NodeManager nodeManager; public long getNumberOfNodeIdsInUse() { return nodeManager.getNumberOfIdsInUse( Node.class ); } public long getNumberOfRelationshipIdsInUse() { return nodeManager.getNumberOfIdsInUse( Relationship.class ); } public long getNumberOfPropertyIdsInUse() { return nodeManager.getNumberOfIdsInUse( PropertyStore.class ); } public long getNumberOfRelationshipTypeIdsInUse() { return nodeManager.getNumberOfIdsInUse( RelationshipType.class ); } }
false
community_jmx_src_main_java_org_neo4j_jmx_impl_PrimitivesBean.java
5,832
private class DeletedTxDataBoth extends TxDataBoth { public DeletedTxDataBoth( LuceneIndex index ) { super( index ); } @Override TxDataHolder added( boolean createIfNotExists ) { throw illegalStateException(); } @Override TxDataHolder removed( boolean createIfNotExists ) { throw illegalStateException(); } private IllegalStateException illegalStateException() { throw new IllegalStateException( "This index (" + index.getIdentifier() + ") has been marked as deleted in this transaction" ); } }
false
community_lucene-index_src_main_java_org_neo4j_index_impl_lucene_LuceneTransaction.java
5,833
@Service.Implementation(ManagementBeanProvider.class) public final class StoreFileBean extends ManagementBeanProvider { public StoreFileBean() { super( StoreFile.class ); } @Override protected Neo4jMBean createMBean( ManagementData management ) throws NotCompliantMBeanException { return new StoreFileImpl( management ); } private static class StoreFileImpl extends Neo4jMBean implements StoreFile { private static final String NODE_STORE = "neostore.nodestore.db"; private static final String RELATIONSHIP_STORE = "neostore.relationshipstore.db"; private static final String PROPERTY_STORE = "neostore.propertystore.db"; private static final String ARRAY_STORE = "neostore.propertystore.db.arrays"; private static final String STRING_STORE = "neostore.propertystore.db.strings"; private static final String LOGICAL_LOG1 = "nioneo_logical.log.1"; private static final String LOGICAL_LOG2 = "nioneo_logical.log.2"; private File storePath; StoreFileImpl( ManagementData management ) throws NotCompliantMBeanException { super( management ); XaDataSourceManager xaDataSourceManager = management.getKernelData().graphDatabase() .getDependencyResolver().resolveDependency( XaDataSourceManager.class ); xaDataSourceManager.addDataSourceRegistrationListener( new DataSourceRegistrationListener() { @Override public void registeredDataSource( XaDataSource ds ) { if ( ds instanceof NeoStoreXaDataSource ) { NeoStoreXaDataSource nioneodb = (NeoStoreXaDataSource) ds; File path; try { path = new File( nioneodb.getStoreDir() ).getCanonicalFile().getAbsoluteFile(); } catch ( IOException e ) { path = new File( nioneodb.getStoreDir() ).getAbsoluteFile(); } storePath = path; } } @Override public void unregisteredDataSource( XaDataSource ds ) { if ( ds instanceof NeoStoreXaDataSource ) { storePath = null; } } } ); } public long getTotalStoreSize() { return storePath == null ? 0 : sizeOf( storePath ); } public long getLogicalLogSize() { if ( storePath == null ) { return 0; } File logicalLog = new File( storePath, LOGICAL_LOG1 ); if ( !logicalLog.isFile() ) { logicalLog = new File( storePath, LOGICAL_LOG2 ); } return sizeOf( logicalLog ); } private static long sizeOf( File file ) { if ( file.isFile() ) { return file.length(); } else if ( file.isDirectory() ) { long size = 0; for ( File child : file.listFiles() ) { size += sizeOf( child ); } return size; } return 0; } private long sizeOf( String name ) { return sizeOf( new File( storePath, name ) ); } public long getArrayStoreSize() { if ( storePath == null ) { return 0; } return sizeOf( ARRAY_STORE ); } public long getNodeStoreSize() { if ( storePath == null ) { return 0; } return sizeOf( NODE_STORE ); } public long getPropertyStoreSize() { if ( storePath == null ) { return 0; } return sizeOf( PROPERTY_STORE ); } public long getRelationshipStoreSize() { if ( storePath == null ) { return 0; } return sizeOf( RELATIONSHIP_STORE ); } public long getStringStoreSize() { if ( storePath == null ) { return 0; } return sizeOf( STRING_STORE ); } } }
false
community_jmx_src_main_java_org_neo4j_jmx_impl_StoreFileBean.java
5,834
{ @Override public void available() { } @Override public void unavailable() { notified.set( true ); } };
false
community_kernel_src_test_java_org_neo4j_kernel_AvailabilityGuardTest.java
5,835
{ @Override public void available() { notified.set( true ); } @Override public void unavailable() { } };
false
community_kernel_src_test_java_org_neo4j_kernel_AvailabilityGuardTest.java
5,836
{ @Override public void run() { availabilityGuard.grant(REQUIREMENT); } } );
false
community_kernel_src_test_java_org_neo4j_kernel_AvailabilityGuardTest.java
5,837
{ @Override public String description() { return "Thing"; } };
false
community_kernel_src_test_java_org_neo4j_kernel_AvailabilityGuardTest.java
5,838
public class AvailabilityGuardTest { private final AvailabilityGuard.AvailabilityRequirement REQUIREMENT = new AvailabilityGuard.AvailabilityRequirement() { @Override public String description() { return "Thing"; } }; @Test public void givenAccessGuardWith2ConditionsWhenAwaitThenTimeoutAndReturnFalse() throws Exception { // Given TickingClock clock = new TickingClock( 0, 100 ); AvailabilityGuard availabilityGuard = new AvailabilityGuard( clock, 2 ); // When boolean result = availabilityGuard.isAvailable( 1000 ); // Then assertThat( result, equalTo( false ) ); } @Test public void givenAccessGuardWith2ConditionsWhenAwaitThenActuallyWaitGivenTimeout() throws Exception { // Given TickingClock clock = new TickingClock( 0, 100 ); AvailabilityGuard availabilityGuard = new AvailabilityGuard( clock, 2 ); // When long start = clock.currentTimeMillis(); boolean result = availabilityGuard.isAvailable( 1000 ); long end = clock.currentTimeMillis(); // Then long waitTime = end - start; assertThat( result, equalTo( false ) ); assertThat( waitTime, equalTo( 1200L ) ); } @Test public void givenAccessGuardWith2ConditionsWhenGrantOnceAndAwaitThenTimeoutAndReturnFalse() throws Exception { // Given TickingClock clock = new TickingClock( 0, 100 ); AvailabilityGuard availabilityGuard = new AvailabilityGuard( clock, 2 ); // When long start = clock.currentTimeMillis(); availabilityGuard.grant(REQUIREMENT); boolean result = availabilityGuard.isAvailable( 1000 ); long end = clock.currentTimeMillis(); // Then long waitTime = end - start; assertThat( result, equalTo( false ) ); assertThat( waitTime, equalTo( 1200L ) ); } @Test public void givenAccessGuardWith2ConditionsWhenGrantTwiceAndAwaitThenTrue() throws Exception { // Given TickingClock clock = new TickingClock( 0, 100 ); AvailabilityGuard availabilityGuard = new AvailabilityGuard( clock, 2 ); // When availabilityGuard.grant(REQUIREMENT); availabilityGuard.grant(REQUIREMENT); long start = clock.currentTimeMillis(); boolean result = availabilityGuard.isAvailable( 1000 ); long end = clock.currentTimeMillis(); // Then long waitTime = end - start; assertThat( result, equalTo( true ) ); assertThat( waitTime, equalTo( 100L ) ); } @Test public void givenAccessGuardWith2ConditionsWhenGrantTwiceAndDenyOnceAndAwaitThenTimeoutAndReturnFalse() throws Exception { // Given TickingClock clock = new TickingClock( 0, 100 ); AvailabilityGuard availabilityGuard = new AvailabilityGuard( clock, 2 ); // When availabilityGuard.grant(REQUIREMENT); availabilityGuard.grant(REQUIREMENT); availabilityGuard.deny(REQUIREMENT); long start = clock.currentTimeMillis(); boolean result = availabilityGuard.isAvailable( 1000 ); long end = clock.currentTimeMillis(); // Then long waitTime = end - start; assertThat( result, equalTo( false ) ); assertThat( waitTime, equalTo( 1200L ) ); } @Test public void givenAccessGuardWith2ConditionsWhenGrantOnceAndAwaitAndGrantAgainDuringAwaitThenReturnTrue() throws Exception { // Given TickingClock clock = new TickingClock( 0, 100 ); final AvailabilityGuard availabilityGuard = new AvailabilityGuard( clock, 2 ); // When clock.at( 500, new Runnable() { @Override public void run() { availabilityGuard.grant(REQUIREMENT); } } ); availabilityGuard.grant(REQUIREMENT); long start = clock.currentTimeMillis(); boolean result = availabilityGuard.isAvailable( 1000 ); long end = clock.currentTimeMillis(); // Then long waitTime = end - start; assertThat( result, equalTo( true ) ); assertThat( waitTime, equalTo( 600L ) ); } @Test public void givenAccessGuardWithConditionWhenGrantThenNotifyListeners() throws Exception { // Given TickingClock clock = new TickingClock( 0, 100 ); final AvailabilityGuard availabilityGuard = new AvailabilityGuard( clock, 1 ); final AtomicBoolean notified = new AtomicBoolean(); AvailabilityGuard.AvailabilityListener availabilityListener = new AvailabilityGuard.AvailabilityListener() { @Override public void available() { notified.set( true ); } @Override public void unavailable() { } }; availabilityGuard.addListener( availabilityListener ); // When availabilityGuard.grant(REQUIREMENT); // Then assertThat( notified.get(), equalTo( true ) ); } @Test public void givenAccessGuardWithConditionWhenGrantAndDenyThenNotifyListeners() throws Exception { // Given TickingClock clock = new TickingClock( 0, 100 ); final AvailabilityGuard availabilityGuard = new AvailabilityGuard( clock, 1 ); final AtomicBoolean notified = new AtomicBoolean(); AvailabilityGuard.AvailabilityListener availabilityListener = new AvailabilityGuard.AvailabilityListener() { @Override public void available() { } @Override public void unavailable() { notified.set( true ); } }; availabilityGuard.addListener( availabilityListener ); // When availabilityGuard.grant(REQUIREMENT); availabilityGuard.deny(REQUIREMENT); // Then assertThat( notified.get(), equalTo( true ) ); } @Test public void givenAccessGuardWithConditionWhenShutdownThenInstantlyDenyAccess() throws Exception { // Given TickingClock clock = new TickingClock( 0, 100 ); final AvailabilityGuard availabilityGuard = new AvailabilityGuard( clock, 1 ); // When availabilityGuard.shutdown(); // Then boolean result = availabilityGuard.isAvailable( 1000 ); assertThat( result, equalTo( false ) ); assertThat( clock.currentTimeMillis(), equalTo( 0L ) ); } @Test public void shouldExplainWhoIsBlockingAccess() throws Exception { // Given TickingClock clock = new TickingClock( 0, 100 ); AvailabilityGuard availabilityGuard = new AvailabilityGuard( clock, 0 ); // When availabilityGuard.deny(REQUIREMENT); availabilityGuard.deny(REQUIREMENT); // Then assertThat( availabilityGuard.describeWhoIsBlocking(), equalTo( "Blocking components (2): [Thing, Thing]" ) ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_AvailabilityGuardTest.java
5,839
{ @Override public String apply( AvailabilityRequirement availabilityRequirement ) { return availabilityRequirement.description(); } };
false
community_kernel_src_main_java_org_neo4j_kernel_AvailabilityGuard.java
5,840
{ @Override public void notify( AvailabilityListener listener ) { listener.unavailable(); } } );
false
community_kernel_src_main_java_org_neo4j_kernel_AvailabilityGuard.java
5,841
{ @Override public void notify( AvailabilityListener listener ) { listener.available(); } } );
false
community_kernel_src_main_java_org_neo4j_kernel_AvailabilityGuard.java
5,842
{ @Override public void notify( AvailabilityListener listener ) { listener.unavailable(); } } );
false
community_kernel_src_main_java_org_neo4j_kernel_AvailabilityGuard.java
5,843
public class AvailabilityGuard { public interface AvailabilityListener { void available(); void unavailable(); } /** * Represents a description of why someone is denying access to the database, to help debugging. Components * granting and revoking access should use the same denial reason for both method calls, as it is used to track * who is blocking access to the database. */ public interface AvailabilityRequirement { String description(); } private Iterable<AvailabilityListener> listeners = Listeners.newListeners(); private final AtomicInteger available; private final List<AvailabilityRequirement> blockingComponents = new CopyOnWriteArrayList<>(); private final Clock clock; public AvailabilityGuard( Clock clock, int conditionCount ) { this.clock = clock; available = new AtomicInteger( conditionCount ); } public void deny( AvailabilityRequirement requirementNotMet ) { int val; do { val = available.get(); if ( val == -1 ) { return; } } while ( !available.compareAndSet( val, val + 1 ) ); blockingComponents.add( requirementNotMet ); if ( val == 0 ) { notifyListeners( listeners, new Listeners.Notification<AvailabilityListener>() { @Override public void notify( AvailabilityListener listener ) { listener.unavailable(); } } ); } } public void grant( AvailabilityRequirement requirementNowMet ) { int val; do { val = available.get(); if ( val == -1 ) { return; } } while ( !available.compareAndSet( val, val - 1 ) ); blockingComponents.remove( requirementNowMet ); if ( val == 1 ) { notifyListeners( listeners, new Listeners.Notification<AvailabilityListener>() { @Override public void notify( AvailabilityListener listener ) { listener.available(); } } ); } } public void shutdown() { int val = available.getAndSet( -1 ); if ( val == 0 ) { notifyListeners( listeners, new Listeners.Notification<AvailabilityListener>() { @Override public void notify( AvailabilityListener listener ) { listener.unavailable(); } } ); } } /** * Determines if the database is available for transactions to use. * * @param millis to wait if not yet available. * @return true if it is available, otherwise false. Returns false immediately if shutdown. */ public boolean isAvailable( long millis ) { int val = available.get(); if ( val == 0 ) { return true; } else if ( val == -1 ) { return false; } else { long start = clock.currentTimeMillis(); while ( clock.currentTimeMillis() < start + millis ) { val = available.get(); if ( val == 0 ) { return true; } else if ( val == -1 ) { return false; } try { Thread.sleep( 10 ); } catch ( InterruptedException e ) { Thread.interrupted(); break; } Thread.yield(); } return false; } } public void addListener( AvailabilityListener listener ) { listeners = Listeners.addListener( listener, listeners ); } public void removeListener( AvailabilityListener listener ) { listeners = Listeners.removeListener( listener, listeners ); } /** Provide a textual description of what components, if any, are blocking access. */ public String describeWhoIsBlocking() { if(blockingComponents.size() > 0 || available.get() > 0) { String causes = join( ", ", Iterables.map( DESCRIPTION, blockingComponents ) ); return "Blocking components ("+available.get()+"): [" + causes + "]"; } return "No blocking components"; } public static final Function<AvailabilityRequirement,String> DESCRIPTION = new Function<AvailabilityRequirement, String>() { @Override public String apply( AvailabilityRequirement availabilityRequirement ) { return availabilityRequirement.description(); } }; }
false
community_kernel_src_main_java_org_neo4j_kernel_AvailabilityGuard.java
5,844
public class AutoConfiguratorTest { private static final long MiB = 1024 * 1024, GiB = 1024 * MiB; @Rule public final TestName testName = new TestName(); private File storeDir; @Before public void given() { storeDir = TargetDirectory.forTest( getClass() ).cleanDirectory( testName.getMethodName() ); } @Test public void shouldProvideDefaultAssignmentsForHugeFiles() throws Exception { // given FileSystemAbstraction fs = mock( FileSystemAbstraction.class ); mockFileSize( fs, "nodestore.db", 200 * GiB ); mockFileSize( fs, "relationshipstore.db", 200 * GiB ); mockFileSize( fs, "propertystore.db", 200 * GiB ); mockFileSize( fs, "propertystore.db.strings", 200 * GiB ); mockFileSize( fs, "propertystore.db.arrays", 200 * GiB ); long availableMem = 100000; // reverse the internal formula long physicalMemory = 2 * availableMem; long vmMemory = (long) Math.ceil( physicalMemory - (availableMem / 0.85) ); AutoConfigurator autoConf = new AutoConfigurator( fs, storeDir, true, physicalMemory * MiB, vmMemory * MiB, Mockito.mock(ConsoleLogger.class) ); // when Map<String, String> configuration = autoConf.configure(); // then assertMappedMemory( configuration, "75000M", "relationshipstore.db" ); assertMappedMemory( configuration, " 5000M", "nodestore.db" ); assertMappedMemory( configuration, "15000M", "propertystore.db" ); assertMappedMemory( configuration, " 3750M", "propertystore.db.strings" ); assertMappedMemory( configuration, " 1250M", "propertystore.db.arrays" ); } @Test public void shouldProvideDefaultAssignmentsForHugeFilesWhenMemoryMappingIsNotUsed() throws Exception { // given FileSystemAbstraction fs = mock( FileSystemAbstraction.class ); mockFileSize( fs, "nodestore.db", 200 * GiB ); mockFileSize( fs, "relationshipstore.db", 200 * GiB ); mockFileSize( fs, "propertystore.db", 200 * GiB ); mockFileSize( fs, "propertystore.db.strings", 200 * GiB ); mockFileSize( fs, "propertystore.db.arrays", 200 * GiB ); long availableMem = 100000; AutoConfigurator autoConf = new AutoConfigurator( fs, storeDir, false, 10000 * GiB, 2 * availableMem * MiB, Mockito.mock(ConsoleLogger.class) ); // when Map<String, String> configuration = autoConf.configure(); // then assertMappedMemory( configuration, "75000M", "relationshipstore.db" ); assertMappedMemory( configuration, " 5000M", "nodestore.db" ); assertMappedMemory( configuration, "15000M", "propertystore.db" ); assertMappedMemory( configuration, " 3750M", "propertystore.db.strings" ); assertMappedMemory( configuration, " 1250M", "propertystore.db.arrays" ); } @Test public void shouldProvideDefaultAssignmentsForEmptyFiles() throws Exception { // given FileSystemAbstraction fs = mock( FileSystemAbstraction.class ); mockFileSize( fs, "nodestore.db", 0 ); mockFileSize( fs, "relationshipstore.db", 0 ); mockFileSize( fs, "propertystore.db", 0 ); mockFileSize( fs, "propertystore.db.strings", 0 ); mockFileSize( fs, "propertystore.db.arrays", 0 ); long availableMem = 100000; // reverse the internal formula long physicalMemory = 2 * availableMem; long vmMemory = (long) Math.ceil( physicalMemory - (availableMem / 0.85) ); AutoConfigurator autoConf = new AutoConfigurator( fs, storeDir, true, physicalMemory * MiB, vmMemory * MiB, Mockito.mock(ConsoleLogger.class) ); // when Map<String, String> configuration = autoConf.configure(); // then assertMappedMemory( configuration, "15000M", "relationshipstore.db" ); assertMappedMemory( configuration, " 3400M", "nodestore.db" ); assertMappedMemory( configuration, "12240M", "propertystore.db" ); assertMappedMemory( configuration, "10404M", "propertystore.db.strings" ); assertMappedMemory( configuration, "11791M", "propertystore.db.arrays" ); } @Test public void shouldProvideDefaultAssignmentsForEmptyFilesWhenMemoryMappingIsNotUsed() throws Exception { // given FileSystemAbstraction fs = mock( FileSystemAbstraction.class ); mockFileSize( fs, "nodestore.db", 0 ); mockFileSize( fs, "relationshipstore.db", 0 ); mockFileSize( fs, "propertystore.db", 0 ); mockFileSize( fs, "propertystore.db.strings", 0 ); mockFileSize( fs, "propertystore.db.arrays", 0 ); long availableMem = 100000; AutoConfigurator autoConf = new AutoConfigurator( fs, storeDir, false, 10000 * GiB, 2 * availableMem * MiB, Mockito.mock(ConsoleLogger.class) ); // when Map<String, String> configuration = autoConf.configure(); // then assertMappedMemory( configuration, "15000M", "relationshipstore.db" ); assertMappedMemory( configuration, " 3400M", "nodestore.db" ); assertMappedMemory( configuration, "12240M", "propertystore.db" ); assertMappedMemory( configuration, "10404M", "propertystore.db.strings" ); assertMappedMemory( configuration, "11791M", "propertystore.db.arrays" ); } @Test public void shouldProvideZeroMappedMemoryWhenPhysicalLessThanJVMMemory() throws Exception { // given FileSystemAbstraction fs = mock( FileSystemAbstraction.class ); mockFileSize( fs, "nodestore.db", 0 ); mockFileSize( fs, "relationshipstore.db", 0 ); mockFileSize( fs, "propertystore.db", 0 ); mockFileSize( fs, "propertystore.db.strings", 0 ); mockFileSize( fs, "propertystore.db.arrays", 0 ); ConsoleLogger mock = Mockito.mock( ConsoleLogger.class ); AutoConfigurator autoConf = new AutoConfigurator( fs, storeDir, true, 128 * MiB, 256 * MiB, mock ); // when Map<String, String> configuration = autoConf.configure(); // then verify( mock ).log( startsWith( "WARNING!" ) ); assertMappedMemory( configuration, "0M", "relationshipstore.db" ); assertMappedMemory( configuration, "0M", "nodestore.db" ); assertMappedMemory( configuration, "0M", "propertystore.db" ); assertMappedMemory( configuration, "0M", "propertystore.db.strings" ); assertMappedMemory( configuration, "0M", "propertystore.db.arrays" ); } private void assertMappedMemory( Map<String, String> configuration, String expected, String store ) { assertEquals( store, expected.trim(), configuration.get( "neostore." + store + ".mapped_memory" ) ); } private void mockFileSize( FileSystemAbstraction fs, String file, long size ) { when( fs.getFileSize( new File( storeDir, "neostore." + file ) ) ).thenReturn( size ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_AutoConfiguratorTest.java
5,845
@Deprecated public class AutoConfigurator { private final int totalPhysicalMemMb; private final int maxVmUsageMb; private final File dbPath; private final boolean useMemoryMapped; private final ConsoleLogger logger; private final FileSystemAbstraction fs; public AutoConfigurator( FileSystemAbstraction fs, File dbPath, boolean useMemoryMapped, ConsoleLogger logger ) { this( fs, dbPath, useMemoryMapped, physicalMemory(), Runtime.getRuntime().maxMemory(), logger ); } AutoConfigurator( FileSystemAbstraction fs, File dbPath, boolean useMemoryMapped, long physicalMemory, long vmMemory, ConsoleLogger logger ) { if (physicalMemory < vmMemory) { logger.log( "WARNING! Physical memory("+(physicalMemory/(1024*1000))+"MB) is less than assigned JVM memory("+(vmMemory/(1024*1000))+"MB). Continuing but with available JVM memory set to available physical memory" ); vmMemory = physicalMemory; } this.fs = fs; this.dbPath = dbPath; this.useMemoryMapped = useMemoryMapped; this.logger = logger; if ( physicalMemory != -1 ) { totalPhysicalMemMb = (int) (physicalMemory / 1024 / 1024); } else { totalPhysicalMemMb = -1; } maxVmUsageMb = (int) (vmMemory / 1024 / 1024); } private static long physicalMemory() { OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); long mem; try { Class<?> beanClass = Thread.currentThread().getContextClassLoader() .loadClass( "com.sun.management.OperatingSystemMXBean" ); Method method = beanClass.getMethod( "getTotalPhysicalMemorySize" ); mem = (Long) method.invoke( osBean ); } catch ( Exception e ) { // ok we tried but probably 1.5 JVM or other class library implementation mem = -1; // Be explicit about how this error is handled. } catch ( LinkageError e ) { // ok we tried but probably 1.5 JVM or other class library implementation mem = -1; // Be explicit about how this error is handled. } return mem; } public String getNiceMemoryInformation() { return "Physical mem: " + totalPhysicalMemMb + "MB, Heap size: " + maxVmUsageMb + "MB"; } public Map<String, String> configure() { Map<String, String> autoConfiguredConfig = new HashMap<String, String>(); if ( totalPhysicalMemMb > 0 ) { if ( useMemoryMapped ) { int availableMem = (totalPhysicalMemMb - maxVmUsageMb); // leave 15% for OS and other progs availableMem -= (int) (availableMem * 0.15f); assignMemory( autoConfiguredConfig, availableMem ); } else { // use half of heap (if needed) for buffers assignMemory( autoConfiguredConfig, maxVmUsageMb / 2 ); } } return autoConfiguredConfig; } private int calculate( int memLeft, int storeSize, float use, float expand, boolean canExpand ) { int size; if ( storeSize > (memLeft * use) ) { size = (int) (memLeft * use); } else if ( canExpand ) { if ( storeSize * expand * 5 < memLeft * use ) { size = (int) (memLeft * use / 5); } else { size = (int) (memLeft * use); } } else { size = storeSize; } return size; } private void assignMemory( Map<String, String> config, int availableMem ) { int nodeStore = getFileSizeMb( "nodestore.db" ); int relStore = getFileSizeMb( "relationshipstore.db" ); int propStore = getFileSizeMb( "propertystore.db" ); int stringStore = getFileSizeMb( "propertystore.db.strings" ); int arrayStore = getFileSizeMb( "propertystore.db.arrays" ); int totalSize = nodeStore + relStore + propStore + stringStore + arrayStore; boolean expand = false; if ( totalSize * 1.15f < availableMem ) { expand = true; } int memLeft = availableMem; relStore = calculate( memLeft, relStore, 0.75f, 1.1f, expand ); memLeft -= relStore; nodeStore = calculate( memLeft, nodeStore, 0.2f, 1.1f, expand ); memLeft -= nodeStore; propStore = calculate( memLeft, propStore, 0.75f, 1.1f, expand ); memLeft -= propStore; stringStore = calculate( memLeft, stringStore, 0.75f, 1.1f, expand ); memLeft -= stringStore; arrayStore = calculate( memLeft, arrayStore, 1.0f, 1.1f, expand ); memLeft -= arrayStore; configPut( config, "nodestore.db", nodeStore ); configPut( config, "relationshipstore.db", relStore ); configPut( config, "propertystore.db", propStore ); configPut( config, "propertystore.db.strings", stringStore ); configPut( config, "propertystore.db.arrays", arrayStore ); } private void configPut( Map<String, String> config, String store, int size ) { // Don't overwrite explicit config String key = "neostore." + store + ".mapped_memory"; config.put( key, size + "M" ); } private int getFileSizeMb( String file ) { long length = fs.getFileSize( new File( dbPath, "neostore." + file ) ); int mb = (int) (length / 1024 / 1024); if ( mb > 0 ) { return mb; } // default return 1MB if small or empty file return 1; } }
false
community_kernel_src_main_java_org_neo4j_kernel_AutoConfigurator.java
5,846
public class AlternatingSelectorOrderer extends AbstractSelectorOrderer<Integer> { public AlternatingSelectorOrderer( BranchSelector startSelector, BranchSelector endSelector ) { super( startSelector, endSelector ); } @Override protected Integer initialState() { return 0; } @Override public TraversalBranch next( TraversalContext metadata ) { TraversalBranch branch = nextBranchFromNextSelector( metadata, true ); Integer previousDepth = getStateForCurrentSelector(); if ( branch != null && branch.length() == previousDepth.intValue() ) { return branch; } else { if ( branch != null ) setStateForCurrentSelector( branch.length() ); } return branch; } }
false
community_kernel_src_main_java_org_neo4j_kernel_AlternatingSelectorOrderer.java
5,847
{ @Override public TraversalBranch next( TraversalContext metadata ) { return null; } };
false
community_kernel_src_main_java_org_neo4j_kernel_AbstractSelectorOrderer.java
5,848
@Deprecated public abstract class AbstractSelectorOrderer<T> implements SideSelector { private static final BranchSelector EMPTY_SELECTOR = new BranchSelector() { @Override public TraversalBranch next( TraversalContext metadata ) { return null; } }; private final BranchSelector[] selectors; @SuppressWarnings( "unchecked" ) private final T[] states = (T[]) new Object[2]; private int selectorIndex; public AbstractSelectorOrderer( BranchSelector startSelector, BranchSelector endSelector ) { selectors = new BranchSelector[] { startSelector, endSelector }; states[0] = initialState(); states[1] = initialState(); } protected T initialState() { return null; } protected void setStateForCurrentSelector( T state ) { states[selectorIndex] = state; } protected T getStateForCurrentSelector() { return states[selectorIndex]; } protected TraversalBranch nextBranchFromCurrentSelector( TraversalContext metadata, boolean switchIfExhausted ) { return nextBranchFromSelector( metadata, selectors[selectorIndex], switchIfExhausted ); } protected TraversalBranch nextBranchFromNextSelector( TraversalContext metadata, boolean switchIfExhausted ) { return nextBranchFromSelector( metadata, nextSelector(), switchIfExhausted ); } private TraversalBranch nextBranchFromSelector( TraversalContext metadata, BranchSelector selector, boolean switchIfExhausted ) { TraversalBranch result = selector.next( metadata ); if ( result == null ) { selectors[selectorIndex] = EMPTY_SELECTOR; if ( switchIfExhausted ) { result = nextSelector().next( metadata ); if ( result == null ) { selectors[selectorIndex] = EMPTY_SELECTOR; } } } return result; } protected BranchSelector nextSelector() { selectorIndex = (selectorIndex+1)%2; BranchSelector selector = selectors[selectorIndex]; return selector; } @Override public Direction currentSide() { return selectorIndex == 0 ? Direction.OUTGOING : Direction.INCOMING; } }
false
community_kernel_src_main_java_org_neo4j_kernel_AbstractSelectorOrderer.java
5,849
@Deprecated public abstract class AbstractGraphDatabase implements GraphDatabaseService, GraphDatabaseAPI { /** * @deprecated This method is only for internal use. * Version 1.9 of Neo4j will be the last version to contain this method. */ @Deprecated public abstract boolean transactionRunning(); }
false
community_kernel_src_main_java_org_neo4j_kernel_AbstractGraphDatabase.java
5,850
public class TestJmxExtension extends KernelExtensionFactoryContractTest { public TestJmxExtension() { super( JmxExtensionFactory.KEY, JmxExtensionFactory.class ); } }
false
community_jmx_src_test_java_org_neo4j_jmx_impl_TestJmxExtension.java
5,851
{ @Override public void registeredDataSource( XaDataSource ds ) { if ( ds instanceof NeoStoreXaDataSource ) { NeoStoreXaDataSource nioneodb = (NeoStoreXaDataSource) ds; File path; try { path = new File( nioneodb.getStoreDir() ).getCanonicalFile().getAbsoluteFile(); } catch ( IOException e ) { path = new File( nioneodb.getStoreDir() ).getAbsoluteFile(); } storePath = path; } } @Override public void unregisteredDataSource( XaDataSource ds ) { if ( ds instanceof NeoStoreXaDataSource ) { storePath = null; } } } );
false
community_jmx_src_main_java_org_neo4j_jmx_impl_StoreFileBean.java
5,852
private static class StoreFileImpl extends Neo4jMBean implements StoreFile { private static final String NODE_STORE = "neostore.nodestore.db"; private static final String RELATIONSHIP_STORE = "neostore.relationshipstore.db"; private static final String PROPERTY_STORE = "neostore.propertystore.db"; private static final String ARRAY_STORE = "neostore.propertystore.db.arrays"; private static final String STRING_STORE = "neostore.propertystore.db.strings"; private static final String LOGICAL_LOG1 = "nioneo_logical.log.1"; private static final String LOGICAL_LOG2 = "nioneo_logical.log.2"; private File storePath; StoreFileImpl( ManagementData management ) throws NotCompliantMBeanException { super( management ); XaDataSourceManager xaDataSourceManager = management.getKernelData().graphDatabase() .getDependencyResolver().resolveDependency( XaDataSourceManager.class ); xaDataSourceManager.addDataSourceRegistrationListener( new DataSourceRegistrationListener() { @Override public void registeredDataSource( XaDataSource ds ) { if ( ds instanceof NeoStoreXaDataSource ) { NeoStoreXaDataSource nioneodb = (NeoStoreXaDataSource) ds; File path; try { path = new File( nioneodb.getStoreDir() ).getCanonicalFile().getAbsoluteFile(); } catch ( IOException e ) { path = new File( nioneodb.getStoreDir() ).getAbsoluteFile(); } storePath = path; } } @Override public void unregisteredDataSource( XaDataSource ds ) { if ( ds instanceof NeoStoreXaDataSource ) { storePath = null; } } } ); } public long getTotalStoreSize() { return storePath == null ? 0 : sizeOf( storePath ); } public long getLogicalLogSize() { if ( storePath == null ) { return 0; } File logicalLog = new File( storePath, LOGICAL_LOG1 ); if ( !logicalLog.isFile() ) { logicalLog = new File( storePath, LOGICAL_LOG2 ); } return sizeOf( logicalLog ); } private static long sizeOf( File file ) { if ( file.isFile() ) { return file.length(); } else if ( file.isDirectory() ) { long size = 0; for ( File child : file.listFiles() ) { size += sizeOf( child ); } return size; } return 0; } private long sizeOf( String name ) { return sizeOf( new File( storePath, name ) ); } public long getArrayStoreSize() { if ( storePath == null ) { return 0; } return sizeOf( ARRAY_STORE ); } public long getNodeStoreSize() { if ( storePath == null ) { return 0; } return sizeOf( NODE_STORE ); } public long getPropertyStoreSize() { if ( storePath == null ) { return 0; } return sizeOf( PROPERTY_STORE ); } public long getRelationshipStoreSize() { if ( storePath == null ) { return 0; } return sizeOf( RELATIONSHIP_STORE ); } public long getStringStoreSize() { if ( storePath == null ) { return 0; } return sizeOf( STRING_STORE ); } }
false
community_jmx_src_main_java_org_neo4j_jmx_impl_StoreFileBean.java
5,853
public class QueryContext { private final Object queryOrQueryObject; private Sort sorting; private Operator defaultOperator; private boolean tradeCorrectnessForSpeed; private int topHits; public QueryContext( Object queryOrQueryObject ) { this.queryOrQueryObject = queryOrQueryObject; } /** * @return the query (or query object) specified in the constructor. */ public Object getQueryOrQueryObject() { return queryOrQueryObject; } /** * Returns a QueryContext with sorting added to it. * * @param sorting The sorting to be used * @return A QueryContext with the sorting applied. */ public QueryContext sort( Sort sorting ) { this.sorting = sorting; return this; } /** * Returns a QueryContext with sorting added to it. * * @param key The key to sort on. * @param additionalKeys Any additional keys to sort on. * @return A QueryContext with sorting added to it. */ public QueryContext sort( String key, String... additionalKeys ) { SortField firstSortField = new SortField( key, SortField.STRING ); if ( additionalKeys.length == 0 ) { return sort( new Sort( firstSortField ) ); } SortField[] sortFields = new SortField[1+additionalKeys.length]; sortFields[0] = firstSortField; for ( int i = 0; i < additionalKeys.length; i++ ) { sortFields[1+i] = new SortField( additionalKeys[i], SortField.STRING ); } return sort( new Sort( sortFields ) ); } /** * @return a QueryContext with sorting by relevance, i.e. sorted after which * score each hit has. */ public QueryContext sortByScore() { return sort( Sort.RELEVANCE ); } /** * Sort the results of a numeric range query if the query in this context * is a {@link NumericRangeQuery}, see {@link #numericRange(String, Number, Number)}, * Otherwise an {@link IllegalStateException} will be thrown. * * @param key the key to sort on. * @param reversed if the sort order should be reversed or not. {@code true} * for lowest first (ascending), {@code false} for highest first (descending) * @return a QueryContext with sorting by numeric value. */ public QueryContext sortNumeric( String key, boolean reversed ) { if ( !( queryOrQueryObject instanceof NumericRangeQuery ) ) { throw new IllegalStateException( "Not a numeric range query" ); } Number number = ((NumericRangeQuery)queryOrQueryObject).getMin(); number = number != null ? number : ((NumericRangeQuery)queryOrQueryObject).getMax(); int fieldType = SortField.INT; if ( number instanceof Long ) { fieldType = SortField.LONG; } else if ( number instanceof Float ) { fieldType = SortField.FLOAT; } else if ( number instanceof Double ) { fieldType = SortField.DOUBLE; } sort( new Sort( new SortField( key, fieldType, reversed ) ) ); return this; } /** * Returns the sorting setting for this context. * * @return the sorting set with one of the sort methods, f.ex * {@link #sort(Sort)} or {@link #sortByScore()} */ public Sort getSorting() { return this.sorting; } /** * Changes the the default operator used between terms in compound queries, * default is OR. * * @param defaultOperator The new operator to use. * @return A QueryContext with the new default operator applied. */ public QueryContext defaultOperator( Operator defaultOperator ) { this.defaultOperator = defaultOperator; return this; } /** * Returns the default operator used between terms in compound queries. * * @return the default {@link Operator} specified with * {@link #defaultOperator} or "OR" if none specified. */ public Operator getDefaultOperator() { return this.defaultOperator; } /** * Adding to or removing from an index affects results from query methods * inside the same transaction, even before those changes are committed. * To let those modifications be visible in query results, some rather heavy * operations may have to be done, which can be slow to complete. * * The default behavior is that these modifications are visible, but using * this method will tell the query to not strive to include the absolutely * latest modifications, so that such a performance penalty can be avoided. * * @return A QueryContext which doesn't necessarily include the latest * transaction modifications in the results, but may perform faster. */ public QueryContext tradeCorrectnessForSpeed() { this.tradeCorrectnessForSpeed = true; return this; } /** * Returns {@code true} if this context is set to prioritize speed over * the inclusion of transactional state in the results. * @return whether or not {@link #tradeCorrectnessForSpeed()} has been called. */ public boolean getTradeCorrectnessForSpeed() { return tradeCorrectnessForSpeed; } /** * Makes use of {@link IndexSearcher#search(org.apache.lucene.search.Query, int)}, * alternatively {@link IndexSearcher#search(org.apache.lucene.search.Query, org.apache.lucene.search.Filter, int, Sort)} * where only the top {@code numberOfTopHits} hits are returned. Default * behavior is to return all hits, although lazily retrieved from lucene all * the way up to the {@link IndexHits} iterator. * * @param numberOfTopHits the maximum number of top hits to return. * @return A {@link QueryContext} with the number of top hits set. */ public QueryContext top( int numberOfTopHits ) { this.topHits = numberOfTopHits; return this; } /** * Return the max number of results to be returned. * * @return the top hits set with {@link #top(int)}. */ public int getTop() { return this.topHits; } /** * Will create a {@link QueryContext} with a query for numeric ranges, that is * values that have been indexed using {@link ValueContext#indexNumeric()}. * {@code from} (lower) and {@code to} (higher) bounds are inclusive. * It will match the type of numbers supplied to the type of values that * are indexed in the index, f.ex. long, int, float and double. * If both {@code from} and {@code to} is {@code null} then it will default * to int. * * @param key the property key to query. * @param from the low end of the range (inclusive) * @param to the high end of the range (inclusive) * @return a {@link QueryContext} to do numeric range queries with. */ public static QueryContext numericRange( String key, Number from, Number to ) { return numericRange( key, from, to, true, true ); } /** * Will create a {@link QueryContext} with a query for numeric ranges, that is * values that have been indexed using {@link ValueContext#indexNumeric()}. * It will match the type of numbers supplied to the type of values that * are indexed in the index, f.ex. long, int, float and double. * If both {@code from} and {@code to} is {@code null} then it will default * to int. * * @param key the property key to query. * @param from the low end of the range (inclusive) * @param to the high end of the range (inclusive) * @param includeFrom whether or not {@code from} (the lower bound) is inclusive * or not. * @param includeTo whether or not {@code to} (the higher bound) is inclusive * or not. * @return a {@link QueryContext} to do numeric range queries with. */ public static QueryContext numericRange( String key, Number from, Number to, boolean includeFrom, boolean includeTo ) { return new QueryContext( LuceneUtil.rangeQuery( key, from, to, includeFrom, includeTo ) ); } }
false
community_lucene-index_src_main_java_org_neo4j_index_lucene_QueryContext.java
5,854
public class LuceneTimeline<T extends PropertyContainer> implements TimelineIndex<T> { private static final String FIELD = "timestamp"; private final Index<T> index; public LuceneTimeline( GraphDatabaseService db, Index<T> index ) { assertIsLuceneIndex( db, index ); this.index = index; } private void assertIsLuceneIndex( GraphDatabaseService db, Index<T> index ) { Map<String, String> config = db.index().getConfiguration( index ); if ( !config.get( IndexManager.PROVIDER ).equals( "lucene" ) ) // Not so hard coded please { throw new IllegalArgumentException( index + " isn't a Lucene index" ); } } private T getSingle( boolean reversed ) { IndexHits<T> hits = index.query( sort( everythingQuery().top( 1 ), reversed ) ); return hits.getSingle(); } private QueryContext everythingQuery() { return new QueryContext( newLongRange( FIELD, 0L, MAX_VALUE, true, true ) ); } private QueryContext rangeQuery( Long startTimestampOrNull, Long endTimestampOrNull ) { long start = startTimestampOrNull != null ? startTimestampOrNull : -Long.MAX_VALUE; long end = endTimestampOrNull != null ? endTimestampOrNull : MAX_VALUE; return new QueryContext( newLongRange( FIELD, start, end, true, true ) ); } private QueryContext sort( QueryContext query, boolean reversed ) { return query.sort( new Sort( new SortField( FIELD, SortField.LONG, reversed ) ) ); } @Override public T getLast() { return getSingle( true ); } @Override public T getFirst() { return getSingle( false ); } @Override public void remove( T entity, long timestamp ) { index.remove( entity, FIELD, timestamp ); } @Override public void add( T entity, long timestamp ) { index.add( entity, FIELD, numeric( timestamp ) ); } @Override public IndexHits<T> getBetween( Long startTimestampOrNull, Long endTimestampOrNull ) { return getBetween( startTimestampOrNull, endTimestampOrNull, false ); } @Override public IndexHits<T> getBetween( Long startTimestampOrNull, Long endTimestampOrNull, boolean reversed ) { return index.query( sort( rangeQuery( startTimestampOrNull, endTimestampOrNull ), reversed ) ); } }
false
community_lucene-index_src_main_java_org_neo4j_index_lucene_LuceneTimeline.java
5,855
public class LuceneLabelScanStoreBuilder { private final String storeDir; private final NeoStoreProvider neoStoreProvider; private final FileSystemAbstraction fileSystem; private final SingleLoggingService logger; private LuceneLabelScanStore labelScanStore = null; public LuceneLabelScanStoreBuilder( String storeDir, NeoStore neoStore, FileSystemAbstraction fileSystem, StringLogger logger ) { this.storeDir = storeDir; this.neoStoreProvider = new SimpleNeoStoreProvider( neoStore ); this.fileSystem = fileSystem; this.logger = new SingleLoggingService( logger ); } public LabelScanStore build() { if ( null == labelScanStore ) { // TODO: Replace with kernel extension based lookup labelScanStore = new LuceneLabelScanStore( new NodeRangeDocumentLabelScanStorageStrategy(), DirectoryFactory.PERSISTENT, // <db>/schema/label/lucene new File( new File( new File( storeDir, "schema" ), "label" ), "lucene" ), fileSystem, IndexWriterFactories.standard(), fullStoreLabelUpdateStream( neoStoreProvider ), LuceneLabelScanStore.loggerMonitor( logger ) ); try { labelScanStore.init(); labelScanStore.start(); } catch ( IOException e ) { // Throw better exception throw new RuntimeException( e ); } } return labelScanStore; } }
false
community_lucene-index_src_main_java_org_neo4j_index_lucene_LuceneLabelScanStoreBuilder.java
5,856
public class LuceneKernelExtensionFactory extends KernelExtensionFactory<LuceneKernelExtensionFactory.Dependencies> { public interface Dependencies { Config getConfig(); GraphDatabaseService getDatabase(); TransactionManager getTxManager(); XaFactory getXaFactory(); FileSystemAbstraction getFileSystem(); XaDataSourceManager getXaDataSourceManager(); IndexProviders getIndexProviders(); IndexStore getIndexStore(); } public LuceneKernelExtensionFactory() { super( LuceneIndexImplementation.SERVICE_NAME ); } @Override public Lifecycle newKernelExtension( Dependencies dependencies ) throws Throwable { return new LuceneKernelExtension( dependencies.getConfig(), dependencies.getDatabase(), dependencies.getTxManager(), dependencies.getIndexStore(), dependencies.getXaFactory(), dependencies.getFileSystem(), dependencies.getXaDataSourceManager(), dependencies.getIndexProviders() ); } }
false
community_lucene-index_src_main_java_org_neo4j_index_lucene_LuceneKernelExtensionFactory.java
5,857
public class TestIndexCreation { private GraphDatabaseAPI db; @Before public void before() throws Exception { db = (GraphDatabaseAPI)new TestGraphDatabaseFactory().newImpermanentDatabase(); } @After public void after() throws Exception { db.shutdown(); } @Test public void indexCreationConfigRaceCondition() throws Exception { // Since this is a probability test and not a precise test run do the run // a couple of times to be sure. for ( int run = 0; run < 10; run++ ) { final int r = run; final CountDownLatch latch = new CountDownLatch( 1 ); ExecutorService executor = newCachedThreadPool(); for ( int thread = 0; thread < 10; thread++ ) { executor.submit( new Runnable() { @Override public void run() { Transaction tx = db.beginTx(); try { latch.await(); Index<Node> index = db.index().forNodes( "index" + r ); Node node = db.createNode(); index.add( node, "name", "Name" ); tx.success(); } catch ( InterruptedException e ) { Thread.interrupted(); } finally { tx.finish(); } } } ); } latch.countDown(); executor.shutdown(); executor.awaitTermination( 10, TimeUnit.SECONDS ); verifyThatIndexCreationTransactionIsTheFirstOne(); } } private void verifyThatIndexCreationTransactionIsTheFirstOne() throws Exception { XaDataSource ds = db.getDependencyResolver().resolveDependency( XaDataSourceManager.class ).getXaDataSource( LuceneDataSource.DEFAULT_NAME ); long version = ds.getCurrentLogVersion(); ds.rotateLogicalLog(); ReadableByteChannel log = ds.getLogicalLog( version ); ByteBuffer buffer = newLogReaderBuffer(); readLogHeader( buffer, log, true ); XaCommandFactory cf = new XaCommandFactory() { @Override public XaCommand readCommand( ReadableByteChannel byteChannel, ByteBuffer buffer ) throws IOException { return LuceneCommand.readCommand( byteChannel, buffer, null ); } }; int creationIdentifier = -1; for ( LogEntry entry; (entry = LogIoUtils.readEntry( buffer, log, cf )) != null; ) { if ( entry instanceof LogEntry.Command && ((LogEntry.Command) entry).getXaCommand() instanceof LuceneCommand.CreateIndexCommand ) { if ( creationIdentifier != -1 ) throw new IllegalArgumentException( "More than one creation command" ); creationIdentifier = entry.getIdentifier(); } if ( entry instanceof LogEntry.Commit ) { // The first COMMIT assertTrue( "Index creation transaction wasn't the first one", creationIdentifier != -1 ); assertEquals( "Index creation transaction wasn't the first one", creationIdentifier, entry.getIdentifier() ); return; } } fail( "Didn't find any commit record in log " + version ); } }
false
community_lucene-index_src_test_java_org_neo4j_index_impl_lucene_TestIndexCreation.java
5,858
public class TestAutoIndexing { private ImpermanentGraphDatabase graphDb; private Transaction tx; private Map<String, String> config; private void newTransaction() { if ( tx != null ) { tx.success(); tx.finish(); } tx = graphDb.beginTx(); } private Map<String, String> getConfig() { if ( config == null ) { config = new HashMap<>(); } return config; } @Before public void startDb() { graphDb = (ImpermanentGraphDatabase) new TestGraphDatabaseFactory(). newImpermanentDatabaseBuilder().setConfig( getConfig() ).newGraphDatabase(); } @After public void stopDb() { if ( tx != null ) { tx.finish(); } if ( graphDb != null ) { graphDb.shutdown(); } tx = null; config = null; graphDb = null; } @Test public void testNodeAutoIndexFromAPISanity() { AutoIndexer<Node> autoIndexer = graphDb.index().getNodeAutoIndexer(); autoIndexer.startAutoIndexingProperty( "test_uuid" ); autoIndexer.setEnabled( true ); assertEquals( 1, autoIndexer.getAutoIndexedProperties().size() ); assertTrue( autoIndexer.getAutoIndexedProperties().contains( "test_uuid" ) ); newTransaction(); Node node1 = graphDb.createNode(); node1.setProperty( "test_uuid", "node1" ); Node node2 = graphDb.createNode(); node2.setProperty( "test_uuid", "node2" ); newTransaction(); assertEquals( node1, autoIndexer.getAutoIndex().get( "test_uuid", "node1" ).getSingle() ); assertEquals( node2, autoIndexer.getAutoIndex().get( "test_uuid", "node2" ).getSingle() ); } @Test public void testAutoIndexesReportReadOnly() { AutoIndexer<Node> autoIndexer = graphDb.index().getNodeAutoIndexer(); assertFalse( autoIndexer.getAutoIndex().isWriteable() ); autoIndexer.startAutoIndexingProperty( "test_uuid" ); autoIndexer.setEnabled( true ); assertFalse( autoIndexer.getAutoIndex().isWriteable() ); } @Test public void testChangesAreVisibleInTransaction() { AutoIndexer<Node> autoIndexer = graphDb.index().getNodeAutoIndexer(); autoIndexer.startAutoIndexingProperty( "nodeProp" ); autoIndexer.setEnabled( true ); newTransaction(); Node node1 = graphDb.createNode(); node1.setProperty( "nodeProp", "nodePropValue" ); node1.setProperty( "nodePropNonIndexable", "valueWhatever" ); ReadableIndex<Node> nodeIndex = autoIndexer.getAutoIndex(); assertEquals( node1, nodeIndex.get( "nodeProp", "nodePropValue" ).getSingle() ); newTransaction(); Node node2 = graphDb.createNode(); node2.setProperty( "nodeProp", "nodePropValue2" ); assertEquals( node2, nodeIndex.get( "nodeProp", "nodePropValue2" ).getSingle() ); node2.setProperty( "nodeProp", "nodePropValue3" ); assertEquals( node2, nodeIndex.get( "nodeProp", "nodePropValue3" ).getSingle() ); node2.removeProperty( "nodeProp" ); assertFalse( nodeIndex.get( "nodeProp", "nodePropValue2" ).hasNext() ); assertFalse( nodeIndex.get( "nodeProp", "nodePropValue3" ).hasNext() ); newTransaction(); assertEquals( node1, nodeIndex.get( "nodeProp", "nodePropValue" ).getSingle() ); assertFalse( nodeIndex.get( "nodeProp", "nodePropValue2" ).hasNext() ); assertFalse( nodeIndex.get( "nodeProp", "nodePropValue3" ).hasNext() ); } @Test public void testRelationshipAutoIndexFromAPISanity() { final String propNameToIndex = "test"; AutoIndexer<Relationship> autoIndexer = graphDb.index().getRelationshipAutoIndexer(); autoIndexer.startAutoIndexingProperty( propNameToIndex ); autoIndexer.setEnabled( true ); newTransaction(); Node node1 = graphDb.createNode(); Node node2 = graphDb.createNode(); Node node3 = graphDb.createNode(); Relationship rel12 = node1.createRelationshipTo( node2, DynamicRelationshipType.withName( "DYNAMIC" ) ); Relationship rel23 = node2.createRelationshipTo( node3, DynamicRelationshipType.withName( "DYNAMIC" ) ); rel12.setProperty( propNameToIndex, "rel12" ); rel23.setProperty( propNameToIndex, "rel23" ); newTransaction(); assertEquals( rel12, autoIndexer.getAutoIndex().get( propNameToIndex, "rel12" ).getSingle() ); assertEquals( rel23, autoIndexer.getAutoIndex().get( propNameToIndex, "rel23" ).getSingle() ); } @Test public void testConfigAndAPICompatibility() { stopDb(); config = new HashMap<>(); config.put( GraphDatabaseSettings.node_keys_indexable.name(), "nodeProp1, nodeProp2" ); config.put( GraphDatabaseSettings.relationship_keys_indexable.name(), "relProp1, relProp2" ); config.put( GraphDatabaseSettings.node_auto_indexing.name(), "true" ); config.put( GraphDatabaseSettings.relationship_auto_indexing.name(), "true" ); startDb(); assertTrue( graphDb.index().getNodeAutoIndexer().isEnabled() ); assertTrue( graphDb.index().getRelationshipAutoIndexer().isEnabled() ); AutoIndexer<Node> autoNodeIndexer = graphDb.index().getNodeAutoIndexer(); // Start auto indexing a new and an already auto indexed autoNodeIndexer.startAutoIndexingProperty( "nodeProp1" ); autoNodeIndexer.startAutoIndexingProperty( "nodeProp3" ); assertEquals( 3, autoNodeIndexer.getAutoIndexedProperties().size() ); assertTrue( autoNodeIndexer.getAutoIndexedProperties().contains( "nodeProp1" ) ); assertTrue( autoNodeIndexer.getAutoIndexedProperties().contains( "nodeProp2" ) ); assertTrue( autoNodeIndexer.getAutoIndexedProperties().contains( "nodeProp3" ) ); } @Test public void testSmallGraphWithNonIndexableProps() throws Exception { stopDb(); config = new HashMap<>(); config.put( GraphDatabaseSettings.node_keys_indexable.name(), "nodeProp1, nodeProp2" ); config.put( GraphDatabaseSettings.relationship_keys_indexable.name(), "relProp1, relProp2" ); config.put( GraphDatabaseSettings.node_auto_indexing.name(), "true" ); config.put( GraphDatabaseSettings.relationship_auto_indexing.name(), "true" ); startDb(); assertTrue( graphDb.index().getNodeAutoIndexer().isEnabled() ); assertTrue( graphDb.index().getRelationshipAutoIndexer().isEnabled() ); newTransaction(); // Build the graph, a 3-cycle Node node1 = graphDb.createNode(); Node node2 = graphDb.createNode(); Node node3 = graphDb.createNode(); Relationship rel12 = node1.createRelationshipTo( node2, DynamicRelationshipType.withName( "DYNAMIC" ) ); Relationship rel23 = node2.createRelationshipTo( node3, DynamicRelationshipType.withName( "DYNAMIC" ) ); Relationship rel31 = node3.createRelationshipTo( node1, DynamicRelationshipType.withName( "DYNAMIC" ) ); // Nodes node1.setProperty( "nodeProp1", "node1Value1" ); node1.setProperty( "nodePropNonIndexable1", "node1ValueNonIndexable" ); node2.setProperty( "nodeProp2", "node2Value1" ); node2.setProperty( "nodePropNonIndexable2", "node2ValueNonIndexable" ); node3.setProperty( "nodeProp1", "node3Value1" ); node3.setProperty( "nodeProp2", "node3Value2" ); node3.setProperty( "nodePropNonIndexable3", "node3ValueNonIndexable" ); // Relationships rel12.setProperty( "relProp1", "rel12Value1" ); rel12.setProperty( "relPropNonIndexable1", "rel12ValueNonIndexable" ); rel23.setProperty( "relProp2", "rel23Value1" ); rel23.setProperty( "relPropNonIndexable2", "rel23ValueNonIndexable" ); rel31.setProperty( "relProp1", "rel31Value1" ); rel31.setProperty( "relProp2", "rel31Value2" ); rel31.setProperty( "relPropNonIndexable3", "rel31ValueNonIndexable" ); newTransaction(); // Committed, time to check AutoIndexer<Node> autoNodeIndexer = graphDb.index().getNodeAutoIndexer(); assertEquals( node1, autoNodeIndexer.getAutoIndex().get( "nodeProp1", "node1Value1" ).getSingle() ); assertEquals( node2, autoNodeIndexer.getAutoIndex().get( "nodeProp2", "node2Value1" ).getSingle() ); assertEquals( node3, autoNodeIndexer.getAutoIndex().get( "nodeProp1", "node3Value1" ).getSingle() ); assertEquals( node3, autoNodeIndexer.getAutoIndex().get( "nodeProp2", "node3Value2" ).getSingle() ); assertFalse( autoNodeIndexer.getAutoIndex().get( "nodePropNonIndexable1", "node1ValueNonIndexable" ).hasNext() ); assertFalse( autoNodeIndexer.getAutoIndex().get( "nodePropNonIndexable2", "node2ValueNonIndexable" ).hasNext() ); assertFalse( autoNodeIndexer.getAutoIndex().get( "nodePropNonIndexable3", "node3ValueNonIndexable" ).hasNext() ); AutoIndexer<Relationship> autoRelIndexer = graphDb.index().getRelationshipAutoIndexer(); assertEquals( rel12, autoRelIndexer.getAutoIndex().get( "relProp1", "rel12Value1" ).getSingle() ); assertEquals( rel23, autoRelIndexer.getAutoIndex().get( "relProp2", "rel23Value1" ).getSingle() ); assertEquals( rel31, autoRelIndexer.getAutoIndex().get( "relProp1", "rel31Value1" ).getSingle() ); assertEquals( rel31, autoRelIndexer.getAutoIndex().get( "relProp2", "rel31Value2" ).getSingle() ); assertFalse( autoRelIndexer.getAutoIndex().get( "relPropNonIndexable1", "rel12ValueNonIndexable" ).hasNext() ); assertFalse( autoRelIndexer.getAutoIndex().get( "relPropNonIndexable2", "rel23ValueNonIndexable" ).hasNext() ); assertFalse( autoRelIndexer.getAutoIndex().get( "relPropNonIndexable3", "rel31ValueNonIndexable" ).hasNext() ); } @Test public void testDefaultIsOff() { newTransaction(); Node node1 = graphDb.createNode(); node1.setProperty( "testProp", "node1" ); newTransaction(); AutoIndexer<Node> autoIndexer = graphDb.index().getNodeAutoIndexer(); assertFalse( autoIndexer.getAutoIndex().get( "testProp", "node1" ).hasNext() ); } @Test public void testDefaulIfOffIsForEverything() { graphDb.index().getNodeAutoIndexer().setEnabled( true ); newTransaction(); Node node1 = graphDb.createNode(); node1.setProperty( "testProp", "node1" ); node1.setProperty( "testProp1", "node1" ); Node node2 = graphDb.createNode(); node2.setProperty( "testProp", "node2" ); node2.setProperty( "testProp1", "node2" ); newTransaction(); AutoIndexer<Node> autoIndexer = graphDb.index().getNodeAutoIndexer(); assertFalse( autoIndexer.getAutoIndex().get( "testProp", "node1" ).hasNext() ); assertFalse( autoIndexer.getAutoIndex().get( "testProp1", "node1" ).hasNext() ); assertFalse( autoIndexer.getAutoIndex().get( "testProp", "node2" ).hasNext() ); assertFalse( autoIndexer.getAutoIndex().get( "testProp1", "node2" ).hasNext() ); } @Test public void testDefaultIsOffIfExplicit() throws Exception { stopDb(); config = new HashMap<>(); config.put( GraphDatabaseSettings.node_keys_indexable.name(), "nodeProp1, nodeProp2" ); config.put( GraphDatabaseSettings.relationship_keys_indexable.name(), "relProp1, relProp2" ); config.put( GraphDatabaseSettings.node_auto_indexing.name(), "false" ); config.put( GraphDatabaseSettings.relationship_auto_indexing.name(), "false" ); startDb(); AutoIndexer<Node> autoIndexer = graphDb.index().getNodeAutoIndexer(); autoIndexer.startAutoIndexingProperty( "testProp" ); newTransaction(); Node node1 = graphDb.createNode(); node1.setProperty( "nodeProp1", "node1" ); node1.setProperty( "nodeProp2", "node1" ); node1.setProperty( "testProp", "node1" ); newTransaction(); assertFalse( autoIndexer.getAutoIndex().get( "nodeProp1", "node1" ).hasNext() ); assertFalse( autoIndexer.getAutoIndex().get( "nodeProp2", "node1" ).hasNext() ); assertFalse( autoIndexer.getAutoIndex().get( "testProp", "node1" ).hasNext() ); } @Test public void testDefaultsAreSeparateForNodesAndRelationships() throws Exception { stopDb(); config = new HashMap<>(); config.put( GraphDatabaseSettings.node_keys_indexable.name(), "propName" ); config.put( GraphDatabaseSettings.node_auto_indexing.name(), "true" ); // Now only node properties named propName should be indexed. startDb(); newTransaction(); Node node1 = graphDb.createNode(); Node node2 = graphDb.createNode(); node1.setProperty( "propName", "node1" ); node2.setProperty( "propName", "node2" ); node2.setProperty( "propName_", "node2" ); Relationship rel = node1.createRelationshipTo( node2, DynamicRelationshipType.withName( "DYNAMIC" ) ); rel.setProperty( "propName", "rel1" ); newTransaction(); ReadableIndex<Node> autoIndex = graphDb.index().getNodeAutoIndexer().getAutoIndex(); assertEquals( node1, autoIndex.get( "propName", "node1" ).getSingle() ); assertEquals( node2, autoIndex.get( "propName", "node2" ).getSingle() ); assertFalse( graphDb.index().getRelationshipAutoIndexer().getAutoIndex().get( "propName", "rel1" ).hasNext() ); } @Test public void testStartStopAutoIndexing() throws Exception { stopDb(); config = new HashMap<>(); config.put( GraphDatabaseSettings.node_keys_indexable.name(), "propName" ); config.put( GraphDatabaseSettings.node_auto_indexing.name(), "true" ); // Now only node properties named propName should be indexed. startDb(); AutoIndexer<Node> autoIndexer = graphDb.index().getNodeAutoIndexer(); assertTrue( autoIndexer.isEnabled() ); autoIndexer.setEnabled( false ); assertFalse( autoIndexer.isEnabled() ); newTransaction(); Node node1 = graphDb.createNode(); Node node2 = graphDb.createNode(); node1.setProperty( "propName", "node" ); newTransaction(); assertFalse( autoIndexer.getAutoIndex().get( "nodeProp1", "node1" ).hasNext() ); autoIndexer.setEnabled( true ); node2.setProperty( "propName", "node" ); newTransaction(); assertEquals( node2, autoIndexer.getAutoIndex().get( "propName", "node" ).getSingle() ); } @Test public void testStopMonitoringProperty() { AutoIndexer<Node> autoIndexer = graphDb.index().getNodeAutoIndexer(); autoIndexer.setEnabled( true ); autoIndexer.startAutoIndexingProperty( "propName" ); newTransaction(); Node node1 = graphDb.createNode(); Node node2 = graphDb.createNode(); node1.setProperty( "propName", "node" ); newTransaction(); assertEquals( node1, autoIndexer.getAutoIndex().get( "propName", "node" ).getSingle() ); newTransaction(); // Setting just another property to autoindex autoIndexer.startAutoIndexingProperty( "propName2" ); autoIndexer.stopAutoIndexingProperty( "propName" ); node2.setProperty( "propName", "propValue" ); Node node3 = graphDb.createNode(); node3.setProperty( "propName2", "propValue" ); newTransaction(); // Now node2 must be not there, node3 must be there and node1 should not have been touched assertEquals( node1, autoIndexer.getAutoIndex().get( "propName", "node" ).getSingle() ); assertEquals( node3, autoIndexer.getAutoIndex().get( "propName2", "propValue" ).getSingle() ); // Now, since only propName2 is autoindexed, every other should be // removed when touched, such as node1's propName node1.setProperty( "propName", "newValue" ); newTransaction(); assertFalse( autoIndexer.getAutoIndex().get( "propName", "newValue" ).hasNext() ); } @Test public void testMutations() throws Exception { graphDb.index().getNodeAutoIndexer().startAutoIndexingProperty( "nodeProp1" ); graphDb.index().getNodeAutoIndexer().startAutoIndexingProperty( "nodeProp2" ); graphDb.index().getNodeAutoIndexer().setEnabled( true ); Transaction tx = graphDb.beginTx(); Node node1 = null, node2 = null, node3 = null, node4 = null; try { // Create the primitives node1 = graphDb.createNode(); node2 = graphDb.createNode(); node3 = graphDb.createNode(); node4 = graphDb.createNode(); // Add indexable and non-indexable properties node1.setProperty( "nodeProp1", "nodeProp1Value" ); node2.setProperty( "nodeProp2", "nodeProp2Value" ); node3.setProperty( "nodeProp1", "nodeProp3Value" ); node4.setProperty( "nodeProp2", "nodeProp4Value" ); // Make things persistent tx.success(); } finally { tx.finish(); } /* * Here both nodes are indexed. To demonstrate removal, we stop * auto-indexing nodeProp1. */ AutoIndexer<Node> nodeAutoIndexer = graphDb.index().getNodeAutoIndexer(); nodeAutoIndexer.stopAutoIndexingProperty( "nodeProp1" ); tx = graphDb.beginTx(); try { /* * nodeProp1 is no longer auto indexed. It will be * removed regardless. Note that node3 will remain. */ node1.setProperty( "nodeProp1", "nodeProp1Value2" ); /* * node2 will be auto updated */ node2.setProperty( "nodeProp2", "nodeProp2Value2" ); /* * remove node4 property nodeProp2 from index. */ node4.removeProperty( "nodeProp2" ); // Make things persistent tx.success(); } catch ( Exception e ) { tx.failure(); } finally { tx.finish(); } Transaction transaction = graphDb.beginTx(); // Verify ReadableIndex<Node> nodeAutoIndex = nodeAutoIndexer.getAutoIndex(); // node1 is completely gone assertFalse( nodeAutoIndex.get( "nodeProp1", "nodeProp1Value" ).hasNext() ); assertFalse( nodeAutoIndex.get( "nodeProp1", "nodeProp1Value2" ).hasNext() ); // node2 is updated assertFalse( nodeAutoIndex.get( "nodeProp2", "nodeProp2Value" ).hasNext() ); assertEquals( node2, nodeAutoIndex.get( "nodeProp2", "nodeProp2Value2" ).getSingle() ); /* * node3 is still there, despite its nodeProp1 property not being monitored * any more because it was not touched, contrary to node1. */ assertEquals( node3, nodeAutoIndex.get( "nodeProp1", "nodeProp3Value" ).getSingle() ); // Finally, node4 is removed because the property was removed. assertFalse( nodeAutoIndex.get( "nodeProp2", "nodeProp4Value" ).hasNext() ); // END SNIPPET: Mutations transaction.finish(); } @Test public void testGettingAutoIndexByNameReturnsSomethingReadOnly() { // Create the node and relationship auto-indexes graphDb.index().getNodeAutoIndexer().setEnabled( true ); graphDb.index().getNodeAutoIndexer().startAutoIndexingProperty( "nodeProp" ); graphDb.index().getRelationshipAutoIndexer().setEnabled( true ); graphDb.index().getRelationshipAutoIndexer().startAutoIndexingProperty( "relProp" ); newTransaction(); Node node1 = graphDb.createNode(); Node node2 = graphDb.createNode(); Relationship rel = node1.createRelationshipTo( node2, DynamicRelationshipType.withName( "FOO" ) ); node1.setProperty( "nodeProp", "nodePropValue" ); rel.setProperty( "relProp", "relPropValue" ); newTransaction(); assertEquals( 1, graphDb.index().nodeIndexNames().length ); assertEquals( 1, graphDb.index().relationshipIndexNames().length ); assertEquals( "node_auto_index", graphDb.index().nodeIndexNames()[0] ); assertEquals( "relationship_auto_index", graphDb.index().relationshipIndexNames()[0] ); Index<Node> nodeIndex = graphDb.index().forNodes( "node_auto_index" ); RelationshipIndex relIndex = graphDb.index().forRelationships( "relationship_auto_index" ); assertEquals( node1, nodeIndex.get( "nodeProp", "nodePropValue" ).getSingle() ); assertEquals( rel, relIndex.get( "relProp", "relPropValue" ).getSingle() ); try { nodeIndex.add( null, null, null ); fail("Auto indexes should not allow external manipulation"); } catch ( UnsupportedOperationException e ) { // good } try { relIndex.add( null, null, null ); fail( "Auto indexes should not allow external manipulation" ); } catch ( UnsupportedOperationException e ) { // good } } @Test public void testRemoveUnloadedHeavyProperty() { /* * Checks a bug where removing non-cached heavy properties * would cause NPE in auto indexer. */ graphDb.index().getNodeAutoIndexer().setEnabled( true ); graphDb.index().getNodeAutoIndexer().startAutoIndexingProperty( "nodeProp" ); newTransaction(); Node node1 = graphDb.createNode(); // Large array, needed for making sure this is a heavy property node1.setProperty( "nodeProp", new int[] { -1, 2, 3, 4, 5, 6, 1, 1, 1, 1 } ); newTransaction(); graphDb.getDependencyResolver().resolveDependency( NodeManager.class ).clearCache(); node1.removeProperty( "nodeProp" ); newTransaction(); assertFalse( node1.hasProperty( "nodeProp" ) ); } @Test public void testRemoveRelationshipRemovesDocument() { AutoIndexer<Relationship> autoIndexer = graphDb.index().getRelationshipAutoIndexer(); autoIndexer.startAutoIndexingProperty( "foo" ); autoIndexer.setEnabled( true ); newTransaction(); Node node1 = graphDb.createNode(); Node node2 = graphDb.createNode(); Relationship rel = node1.createRelationshipTo( node2, DynamicRelationshipType.withName( "foo" ) ); rel.setProperty( "foo", "bar" ); newTransaction(); assertThat( graphDb.index().forRelationships( "relationship_auto_index" ).query( "_id_:*" ).size(), equalTo( 1 ) ); newTransaction(); rel.delete(); newTransaction(); assertThat( graphDb.index().forRelationships( "relationship_auto_index" ).query( "_id_:*" ).size(), equalTo( 0 ) ); } }
false
community_lucene-index_src_test_java_org_neo4j_index_impl_lucene_TestAutoIndexing.java
5,859
public class RollbackCommand implements WorkerCommand<CommandState, Void> { @Override public Void doWork( CommandState state ) { state.tx.failure(); state.tx.finish(); state.tx = null; return null; } }
false
community_lucene-index_src_test_java_org_neo4j_index_impl_lucene_RollbackCommand.java
5,860
public class RemoveFromIndexCommand implements WorkerCommand<CommandState, Void> { private String key; private String value; public RemoveFromIndexCommand( String key, String value ) { this.key = key; this.value = value; } @Override public Void doWork( CommandState state ) { state.index.remove( state.node, key, value ); return null; } }
false
community_lucene-index_src_test_java_org_neo4j_index_impl_lucene_RemoveFromIndexCommand.java
5,861
class RelationshipId { final long id; final long startNode; final long endNode; RelationshipId( long id, long startNode, long endNode ) { this.id = id; this.startNode = startNode; this.endNode = endNode; } public static RelationshipId of( Relationship rel ) { return new RelationshipId( rel.getId(), rel.getStartNode().getId(), rel.getEndNode().getId() ); } @Override public boolean equals( Object obj ) { return ((RelationshipId) obj).id == id; } @Override public int hashCode() { return (int) id; } }
false
community_lucene-index_src_main_java_org_neo4j_index_impl_lucene_RelationshipId.java
5,862
public class RecoveryIT { @Test public void testHardCoreRecovery() throws Exception { String path = "target/hcdb"; FileUtils.deleteRecursively( new File( path ) ); Process process = Runtime.getRuntime().exec( new String[]{ "java", "-cp", System.getProperty( "java.class.path" ), Inserter.class.getName(), path } ); // Let it run for a while and then kill it, and wait for it to die awaitFile( new File( path, "started" ) ); Thread.sleep( 5000 ); process.destroy(); process.waitFor(); GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase(path ); Transaction transaction = db.beginTx(); try { assertTrue( db.index().existsForNodes( "myIndex" ) ); Index<Node> index = db.index().forNodes( "myIndex" ); for ( Node node : GlobalGraphOperations.at( db ).getAllNodes() ) { for ( String key : node.getPropertyKeys() ) { String value = (String) node.getProperty( key ); boolean found = false; for ( Node indexedNode : index.get( key, value ) ) { if ( indexedNode.equals( node ) ) { found = true; break; } } if ( !found ) { throw new IllegalStateException( node + " has property '" + key + "'='" + value + "', but not in index" ); } } } } finally { transaction.finish(); db.shutdown(); } } private void awaitFile( File file ) throws InterruptedException { long end = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis( 30 ); while ( !file.exists() && System.currentTimeMillis() < end ) { Thread.sleep( 100 ); } if ( !file.exists() ) { fail( "The inserter doesn't seem to have run properly" ); } } }
false
community_lucene-index_src_test_java_org_neo4j_index_impl_lucene_RecoveryIT.java
5,863
public class QueryNotPossibleException extends RuntimeException { public QueryNotPossibleException() { super(); } public QueryNotPossibleException( String message, Throwable cause ) { super( message, cause ); } public QueryNotPossibleException( String message ) { super( message ); } public QueryNotPossibleException( Throwable cause ) { super( cause ); } }
false
community_lucene-index_src_main_java_org_neo4j_index_impl_lucene_QueryNotPossibleException.java
5,864
public class QueryIndexCommand implements WorkerCommand<CommandState, IndexHits<Node>> { private String key; private Object value; public QueryIndexCommand( String key, Object value ) { this.key = key; this.value = value; } @Override public IndexHits<Node> doWork( CommandState state ) { return state.index.get( key, value ); } }
false
community_lucene-index_src_test_java_org_neo4j_index_impl_lucene_QueryIndexCommand.java
5,865
public class PutIfAbsentCommand implements WorkerCommand<CommandState, Node> { private final String key; private final Object value; private final Node node; public PutIfAbsentCommand( Node node, String key, Object value ) { this.node = node; this.key = key; this.value = value; } @Override public Node doWork( CommandState state ) { return state.index.putIfAbsent( node, key, value ); } }
false
community_lucene-index_src_test_java_org_neo4j_index_impl_lucene_PutIfAbsentCommand.java
5,866
{ @Override public void run() { try { for ( int i = 0; i < count; i+=group ) { if ( halt.get() ) break; Transaction tx = graphDb.beginTx(); try { for ( int ii = 0; ii < group; ii++ ) { Node node = graphDb.createNode(); index.get( "key", "value" + System.currentTimeMillis()%count ).getSingle(); index.add( node, "key", "value" + id.getAndIncrement() ); } tx.success(); } finally { tx.finish(); } if ( i%100 == 0 ) System.out.println( threadId + ": " + i ); } } catch ( Exception e ) { e.printStackTrace( System.out ); halt.set( true ); } } };
false
community_lucene-index_src_test_java_org_neo4j_index_impl_lucene_PerformanceAndSanityIT.java
5,867
{ @Override public void run() { for ( int i = 0; System.currentTimeMillis() - time < 60*1000*2; i++ ) { if ( i%10 == 0 ) { if ( i%100 == 0 ) { int type = (int)(System.currentTimeMillis()%3); if ( type == 0 ) { IndexHits<Node> itr = index.get( "key", "value5" ); try { itr.getSingle(); } catch ( NoSuchElementException e ) { // For when there are multiple hits } } else if ( type == 1 ) { IndexHits<Node> itr = index.get( "key", "value5" ); for ( int size = 0; itr.hasNext() && size < 5; size++ ) { itr.next(); } itr.close(); } else { IndexHits<Node> itr = index.get( "key", "crap value" ); /* Will return 0 hits */ // Iterate over the hits sometimes (it's always gonna be 0 sized) if ( System.currentTimeMillis() % 10 > 5 ) { IteratorUtil.count( (Iterator<Node>) itr ); } } } else { IteratorUtil.count( (Iterator<Node>) index.get( "key", "value5" ) ); } } else { Transaction tx = graphDb.beginTx(); try { for ( int ii = 0; ii < 20; ii++ ) { Node node = graphDb.createNode(); index.add( node, "key", "value" + ii ); } tx.success(); } finally { tx.finish(); } } } } } );
false
community_lucene-index_src_test_java_org_neo4j_index_impl_lucene_PerformanceAndSanityIT.java
5,868
public class PerformanceAndSanityIT extends AbstractLuceneIndexTest { @Ignore @Test public void testNodeInsertionSpeed() { testInsertionSpeed( nodeIndex( "insertion-speed", LuceneIndexImplementation.EXACT_CONFIG ), NODE_CREATOR ); } @Ignore @Test public void testNodeFulltextInsertionSpeed() { testInsertionSpeed( nodeIndex( "insertion-speed-full", LuceneIndexImplementation.FULLTEXT_CONFIG ), NODE_CREATOR ); } @Ignore @Test public void testRelationshipInsertionSpeed() { testInsertionSpeed( relationshipIndex( "insertion-speed", LuceneIndexImplementation.EXACT_CONFIG ), new FastRelationshipCreator() ); } private <T extends PropertyContainer> void testInsertionSpeed( Index<T> index, EntityCreator<T> creator ) { long t = currentTimeMillis(); int max = 500000; for ( int i = 0; i < max; i++ ) { T entity = creator.create(); if ( i % 5000 == 5 ) { index.query( new TermQuery( new Term( "name", "The name " + i ) ) ); } lastOrNull( (Iterable<T>) index.query( new QueryContext( new TermQuery( new Term( "name", "The name " + i ) ) ).tradeCorrectnessForSpeed() ) ); lastOrNull( (Iterable<T>) index.get( "name", "The name " + i ) ); index.add( entity, "name", "The name " + i ); index.add( entity, "title", "Some title " + i ); index.add( entity, "something", i + "Nothing" ); index.add( entity, "else", i + "kdfjkdjf" + i ); if ( i % 30000 == 0 ) { restartTx(); System.out.println( i ); } } finishTx( true ); out.println( "insert:" + ( currentTimeMillis() - t ) ); t = currentTimeMillis(); int count = 2000000; int resultCount = 0; for ( int i = 0; i < count; i++ ) { resultCount += count( (Iterator<T>) index.get( "name", "The name " + i%max ) ); } out.println( "get(" + resultCount + "):" + (double)( currentTimeMillis() - t ) / (double)count ); t = currentTimeMillis(); resultCount = 0; for ( int i = 0; i < count; i++ ) { resultCount += count( (Iterator<T>) index.get( "something", i%max + "Nothing" ) ); } out.println( "get(" + resultCount + "):" + (double)( currentTimeMillis() - t ) / (double)count ); } /** * Starts multiple threads which updates and queries an index concurrently * during a long period of time just to make sure that number of file handles doesn't grow. * @throws Exception */ @Test @Ignore public void makeSureFilesAreClosedProperly() throws Exception { commitTx(); graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(TargetDirectory.forTest( getClass() ).cleanDirectory( "filesClosedProperty" ).getAbsolutePath() ); final Index<Node> index = nodeIndex( "open-files", LuceneIndexImplementation.EXACT_CONFIG ); final long time = System.currentTimeMillis(); final CountDownLatch latch = new CountDownLatch( 30 ); int coreCount = Runtime.getRuntime().availableProcessors(); ExecutorService pool = Executors.newFixedThreadPool( coreCount ); for ( int t = 0; t < latch.getCount(); t++ ) { pool.execute( new Runnable() { @Override public void run() { for ( int i = 0; System.currentTimeMillis() - time < 60*1000*2; i++ ) { if ( i%10 == 0 ) { if ( i%100 == 0 ) { int type = (int)(System.currentTimeMillis()%3); if ( type == 0 ) { IndexHits<Node> itr = index.get( "key", "value5" ); try { itr.getSingle(); } catch ( NoSuchElementException e ) { // For when there are multiple hits } } else if ( type == 1 ) { IndexHits<Node> itr = index.get( "key", "value5" ); for ( int size = 0; itr.hasNext() && size < 5; size++ ) { itr.next(); } itr.close(); } else { IndexHits<Node> itr = index.get( "key", "crap value" ); /* Will return 0 hits */ // Iterate over the hits sometimes (it's always gonna be 0 sized) if ( System.currentTimeMillis() % 10 > 5 ) { IteratorUtil.count( (Iterator<Node>) itr ); } } } else { IteratorUtil.count( (Iterator<Node>) index.get( "key", "value5" ) ); } } else { Transaction tx = graphDb.beginTx(); try { for ( int ii = 0; ii < 20; ii++ ) { Node node = graphDb.createNode(); index.add( node, "key", "value" + ii ); } tx.success(); } finally { tx.finish(); } } } } } ); } pool.shutdown(); pool.awaitTermination( 10, TimeUnit.DAYS ); graphDb.shutdown(); graphDb = new TestGraphDatabaseFactory().newImpermanentDatabase(); } @Ignore @Test public void testPerformanceForManySmallTransactions() throws Exception { final Index<Node> index = nodeIndex( "index", LuceneIndexImplementation.EXACT_CONFIG ); final int count = 5000; final int group = 1; final int threads = 3; final Collection<Thread> threadList = new ArrayList<Thread>(); final AtomicInteger id = new AtomicInteger(); final AtomicBoolean halt = new AtomicBoolean(); long t = System.currentTimeMillis(); for ( int h = 0; h < threads; h++ ) { final int threadId = h; Thread thread = new Thread() { @Override public void run() { try { for ( int i = 0; i < count; i+=group ) { if ( halt.get() ) break; Transaction tx = graphDb.beginTx(); try { for ( int ii = 0; ii < group; ii++ ) { Node node = graphDb.createNode(); index.get( "key", "value" + System.currentTimeMillis()%count ).getSingle(); index.add( node, "key", "value" + id.getAndIncrement() ); } tx.success(); } finally { tx.finish(); } if ( i%100 == 0 ) System.out.println( threadId + ": " + i ); } } catch ( Exception e ) { e.printStackTrace( System.out ); halt.set( true ); } } }; threadList.add( thread ); thread.start(); } for ( Thread aThread : threadList ) { aThread.join(); } long t1 = System.currentTimeMillis()-t; // System.out.println( "2" ); // t = System.currentTimeMillis(); // for ( int i = 0; i < count; i++ ) // { // Transaction tx = db.beginTx(); // try // { // Node node = index.get( "key", "value" + i ).getSingle(); // node.setProperty( "something", "sjdkjk" ); // tx.success(); // } // finally // { // tx.finish(); // } // if ( i%100 == 0 && i > 0 ) System.out.println( i ); // } // long t2 = System.currentTimeMillis()-t; System.out.println( t1 + ", " + (double)t1/(double)count ); } }
false
community_lucene-index_src_test_java_org_neo4j_index_impl_lucene_PerformanceAndSanityIT.java
5,869
public final class MyStandardAnalyzer extends Analyzer { private final Analyzer actual; public MyStandardAnalyzer() { actual = new StandardAnalyzer( Version.LUCENE_31, new HashSet<String>( Arrays.asList( "just", "some", "words" ) ) ); } @Override public TokenStream tokenStream( String fieldName, Reader reader ) { return actual.tokenStream( fieldName, reader ); } }
false
community_lucene-index_src_test_java_org_neo4j_index_impl_lucene_MyStandardAnalyzer.java
5,870
public class MultipleBackupDeletionPolicy extends SnapshotDeletionPolicy { static final String SNAPSHOT_ID = "backup"; private IndexCommit snapshot; private int snapshotUsers; public MultipleBackupDeletionPolicy() { super( new KeepOnlyLastCommitDeletionPolicy() ); } @Override public synchronized IndexCommit snapshot( String id ) throws IOException { if ( snapshotUsers == 0 ) { snapshot = super.snapshot( id ); } // Incremented after the call to super.snapshot() so that it wont get incremented // if an exception (IllegalStateException if empty index) is thrown snapshotUsers++; return snapshot; } @Override public synchronized void release( String id ) throws IOException { if ( (--snapshotUsers) > 0 ) { return; } super.release( id ); snapshot = null; if ( snapshotUsers < 0 ) { snapshotUsers = 0; throw new IllegalStateException( "Cannot release snapshot, no snapshot held" ); } } }
false
community_lucene-index_src_main_java_org_neo4j_index_impl_lucene_MultipleBackupDeletionPolicy.java
5,871
public class MonitoringTest { @Test public void shouldCountCommittedTransactions() throws Exception { GraphDatabaseService db = new TestGraphDatabaseFactory().newImpermanentDatabase(); Monitors monitors = ((GraphDatabaseAPI) db).getDependencyResolver().resolveDependency( Monitors.class ); EideticTransactionMonitor monitor = new EideticTransactionMonitor(); monitors.addMonitorListener( monitor, XaResourceManager.class.getName(), LuceneDataSource.DEFAULT_NAME ); Transaction tx = db.beginTx(); db.index().forNodes( "foo" ).add( db.createNode(), "a string", "a value" ); tx.success(); tx.finish(); assertEquals( 2, monitor.getCommitCount() ); assertEquals( 0, monitor.getInjectOnePhaseCommitCount() ); assertEquals( 0, monitor.getInjectTwoPhaseCommitCount() ); } @Test public void shouldNotCountRolledBackTransactions() throws Exception { GraphDatabaseService db = new TestGraphDatabaseFactory().newImpermanentDatabase(); Monitors monitors = ((GraphDatabaseAPI) db).getDependencyResolver().resolveDependency( Monitors.class ); EideticTransactionMonitor monitor = new EideticTransactionMonitor(); monitors.addMonitorListener( monitor, XaResourceManager.class.getName(), LuceneDataSource.DEFAULT_NAME ); Transaction tx = db.beginTx(); db.createNode(); tx.failure(); tx.finish(); assertEquals( 0, monitor.getCommitCount() ); assertEquals( 0, monitor.getInjectOnePhaseCommitCount() ); assertEquals( 0, monitor.getInjectTwoPhaseCommitCount() ); } }
false
community_lucene-index_src_test_java_org_neo4j_index_impl_lucene_MonitoringTest.java
5,872
private static class LuceneXaResource extends XaResourceHelpImpl { private final Object identifier; LuceneXaResource( Object identifier, XaResourceManager xaRm, byte[] branchId ) { super( xaRm, branchId ); this.identifier = identifier; } @Override public boolean isSameRM( XAResource xares ) { if ( xares instanceof LuceneXaResource ) { return identifier.equals( ((LuceneXaResource) xares).identifier ); } return false; } }
false
community_lucene-index_src_main_java_org_neo4j_index_impl_lucene_LuceneXaConnection.java
5,873
public class LuceneXaConnection extends XaConnectionHelpImpl implements IndexXaConnection { private final LuceneXaResource xaResource; LuceneXaConnection( Object identifier, XaResourceManager xaRm, byte[] branchId ) { super( xaRm ); xaResource = new LuceneXaResource( identifier, xaRm, branchId ); } @Override public XAResource getXaResource() { return xaResource; } private static class LuceneXaResource extends XaResourceHelpImpl { private final Object identifier; LuceneXaResource( Object identifier, XaResourceManager xaRm, byte[] branchId ) { super( xaRm, branchId ); this.identifier = identifier; } @Override public boolean isSameRM( XAResource xares ) { if ( xares instanceof LuceneXaResource ) { return identifier.equals( ((LuceneXaResource) xares).identifier ); } return false; } } private LuceneTransaction luceneTx; LuceneTransaction getLuceneTx() { if ( luceneTx == null ) { try { luceneTx = ( LuceneTransaction ) getTransaction(); } catch ( XAException e ) { throw new RuntimeException( "Unable to get lucene tx", e ); } } return luceneTx; } <T extends PropertyContainer> void add( LuceneIndex<T> index, T entity, String key, Object value ) { getLuceneTx().add( index, entity, key, value ); } <T extends PropertyContainer> void remove( LuceneIndex<T> index, T entity, String key, Object value ) { getLuceneTx().remove( index, entity, key, value ); } <T extends PropertyContainer> void remove( LuceneIndex<T> index, T entity, String key ) { getLuceneTx().remove( index, entity, key ); } <T extends PropertyContainer> void remove( LuceneIndex<T> index, T entity ) { getLuceneTx().remove( index, entity ); } <T extends PropertyContainer> void deleteIndex( LuceneIndex<T> index ) { getLuceneTx().delete( index ); } @Override public void createIndex( Class<? extends PropertyContainer> entityType, String name, Map<String, String> config ) { getLuceneTx().createIndex( entityType, name, config ); } }
false
community_lucene-index_src_main_java_org_neo4j_index_impl_lucene_LuceneXaConnection.java
5,874
public abstract class LuceneUtil { static void close( IndexWriter writer ) { close( (Object) writer ); } static void close( IndexSearcher searcher ) { close( (Object) searcher ); } private static void close( Object object ) { if ( object == null ) { return; } try { if ( object instanceof IndexWriter ) { ((IndexWriter) object).close(); } else if ( object instanceof IndexSearcher ) { ((IndexSearcher) object).close(); } } catch ( IOException e ) { throw new RuntimeException( e ); } } static void strictAddDocument( IndexWriter writer, Document document ) { try { writer.addDocument( document ); } catch ( IOException e ) { throw new RuntimeException( e ); } } static void strictRemoveDocument( IndexWriter writer, Query query ) { try { writer.deleteDocuments( query ); } catch ( IOException e ) { throw new RuntimeException( e ); } } /** * Will create a {@link Query} with a query for numeric ranges, that is * values that have been indexed using {@link ValueContext#indexNumeric()}. * It will match the type of numbers supplied to the type of values that * are indexed in the index, f.ex. long, int, float and double. * If both {@code from} and {@code to} is {@code null} then it will default * to int. * * @param key the property key to query. * @param from the low end of the range (inclusive) * @param to the high end of the range (inclusive) * @param includeFrom whether or not {@code from} (the lower bound) is inclusive * or not. * @param includeTo whether or not {@code to} (the higher bound) is inclusive * or not. * @return a {@link Query} to do numeric range queries with. */ public static Query rangeQuery( String key, Number from, Number to, boolean includeFrom, boolean includeTo ) { if ( from instanceof Long || to instanceof Long ) { return NumericRangeQuery.newLongRange( key, from != null ? from.longValue() : 0, to != null ? to.longValue() : Long.MAX_VALUE, includeFrom, includeTo ); } else if ( from instanceof Double || to instanceof Double ) { return NumericRangeQuery.newDoubleRange( key, from != null ? from.doubleValue() : 0, to != null ? to.doubleValue() : Double.MAX_VALUE, includeFrom, includeTo ); } else if ( from instanceof Float || to instanceof Float ) { return NumericRangeQuery.newFloatRange( key, from != null ? from.floatValue() : 0, to != null ? to.floatValue() : Float.MAX_VALUE, includeFrom, includeTo ); } else { return NumericRangeQuery.newIntRange( key, from != null ? from.intValue() : 0, to != null ? to.intValue() : Integer.MAX_VALUE, includeFrom, includeTo ); } } }
false
community_lucene-index_src_main_java_org_neo4j_index_impl_lucene_LuceneUtil.java
5,875
private class TxDataBoth { private TxDataHolder add; private TxDataHolder remove; final LuceneIndex index; public TxDataBoth( LuceneIndex index ) { this.index = index; } TxDataHolder added( boolean createIfNotExists ) { if ( this.add == null && createIfNotExists ) { this.add = new TxDataHolder( index, index.type.newTxData( index ) ); } return this.add; } TxDataHolder removed( boolean createIfNotExists ) { if ( this.remove == null && createIfNotExists ) { this.remove = new TxDataHolder( index, index.type.newTxData( index ) ); } return this.remove; } void close() { safeClose( add ); safeClose( remove ); } private void safeClose( TxDataHolder data ) { if ( data != null ) { data.close(); } } }
false
community_lucene-index_src_main_java_org_neo4j_index_impl_lucene_LuceneTransaction.java
5,876
{ @Override public void run() { Transaction tx = db.beginTx(); try { latch.await(); Index<Node> index = db.index().forNodes( "index" + r ); Node node = db.createNode(); index.add( node, "name", "Name" ); tx.success(); } catch ( InterruptedException e ) { Thread.interrupted(); } finally { tx.finish(); } } } );
false
community_lucene-index_src_test_java_org_neo4j_index_impl_lucene_TestIndexCreation.java
5,877
{ @Override public XaCommand readCommand( ReadableByteChannel byteChannel, ByteBuffer buffer ) throws IOException { return LuceneCommand.readCommand( byteChannel, buffer, null ); } };
false
community_lucene-index_src_test_java_org_neo4j_index_impl_lucene_TestIndexCreation.java
5,878
public class TestIndexDelectionFs { private static GraphDatabaseService db; @BeforeClass public static void doBefore() throws IOException { FileUtils.deleteRecursively( new File( "target/test-data/deletion" ) ); db = new GraphDatabaseFactory().newEmbeddedDatabase( "target/test-data/deletion" ); } @AfterClass public static void doAfter() { db.shutdown(); } @Test public void indexDeleteShouldDeleteDirectory() { String indexName = "index"; String otherIndexName = "other-index"; StringBuffer tempPath = new StringBuffer( ((GraphDatabaseAPI)db).getStoreDir()) .append(File.separator).append("index").append(File.separator) .append("lucene").append(File.separator).append("node") .append(File.separator); File pathToLuceneIndex = new File( tempPath.toString() + indexName ); File pathToOtherLuceneIndex = new File( tempPath.toString() + otherIndexName ); Transaction tx = db.beginTx(); Index<Node> index; try { index = db.index().forNodes( indexName ); Index<Node> otherIndex = db.index().forNodes( otherIndexName ); Node node = db.createNode(); index.add( node, "someKey", "someValue" ); otherIndex.add( node, "someKey", "someValue" ); assertFalse( pathToLuceneIndex.exists() ); assertFalse( pathToOtherLuceneIndex.exists() ); tx.success(); } finally { tx.finish(); } // Here "index" and "other-index" indexes should exist assertTrue( pathToLuceneIndex.exists() ); assertTrue( pathToOtherLuceneIndex.exists() ); tx = db.beginTx(); try { index.delete(); assertTrue( pathToLuceneIndex.exists() ); assertTrue( pathToOtherLuceneIndex.exists() ); tx.success(); } finally { tx.finish(); } // Here only "other-index" should exist assertFalse( pathToLuceneIndex.exists() ); assertTrue( pathToOtherLuceneIndex.exists() ); } }
false
community_lucene-index_src_test_java_org_neo4j_index_impl_lucene_TestIndexDelectionFs.java
5,879
class TxDataHolder { final LuceneIndex index; private TxData data; TxDataHolder( LuceneIndex index, TxData initialData ) { this.index = index; this.data = initialData; } void add( Object entityId, String key, Object value ) { this.data.add( this, entityId, key, value ); } void remove( Object entityId, String key, Object value ) { this.data.remove( this, entityId, key, value ); } Collection<Long> query( Query query, QueryContext contextOrNull ) { return this.data.query( this, query, contextOrNull ); } Collection<Long> get( String key, Object value ) { return this.data.get( this, key, value ); } Collection<Long> getOrphans( String key ) { return this.data.getOrphans( key ); } void close() { this.data.close(); } IndexSearcher asSearcher( QueryContext context ) { return this.data.asSearcher( this, context ); } void set( TxData newData ) { this.data = newData; } }
false
community_lucene-index_src_main_java_org_neo4j_index_impl_lucene_TxDataHolder.java
5,880
public static abstract class Configuration { public static final Setting<Boolean> read_only = GraphDatabaseSettings.read_only; }
false
community_lucene-index_src_main_java_org_neo4j_index_lucene_LuceneKernelExtension.java
5,881
public class LuceneKernelExtension extends LifecycleAdapter { private final Config config; private final GraphDatabaseService gdb; private final TransactionManager txManager; private final IndexStore indexStore; private final XaFactory xaFactory; private final FileSystemAbstraction fileSystemAbstraction; private final XaDataSourceManager xaDataSourceManager; private final IndexProviders indexProviders; public static abstract class Configuration { public static final Setting<Boolean> read_only = GraphDatabaseSettings.read_only; } public LuceneKernelExtension( Config config, GraphDatabaseService gdb, TransactionManager txManager, IndexStore indexStore, XaFactory xaFactory, FileSystemAbstraction fileSystemAbstraction, XaDataSourceManager xaDataSourceManager, IndexProviders indexProviders ) { this.config = config; this.gdb = gdb; this.txManager = txManager; this.indexStore = indexStore; this.xaFactory = xaFactory; this.fileSystemAbstraction = fileSystemAbstraction; this.xaDataSourceManager = xaDataSourceManager; this.indexProviders = indexProviders; } @Override public void start() throws Throwable { LuceneDataSource luceneDataSource = new LuceneDataSource( config, indexStore, fileSystemAbstraction, xaFactory, txManager ); xaDataSourceManager.registerDataSource( luceneDataSource ); IndexConnectionBroker<LuceneXaConnection> broker = config.get( Configuration.read_only ) ? new ReadOnlyIndexConnectionBroker<LuceneXaConnection>( txManager ) : new ConnectionBroker( txManager, luceneDataSource ); LuceneIndexImplementation indexImplementation = new LuceneIndexImplementation( gdb, luceneDataSource, broker ); indexProviders.registerIndexProvider( LuceneIndexImplementation.SERVICE_NAME, indexImplementation ); } @Override public void stop() throws Throwable { xaDataSourceManager.unregisterDataSource( LuceneDataSource.DEFAULT_NAME ); indexProviders.unregisterIndexProvider( LuceneIndexImplementation.SERVICE_NAME ); } }
false
community_lucene-index_src_main_java_org_neo4j_index_lucene_LuceneKernelExtension.java
5,882
public class ConstraintIndexFailureIT { public final @Rule TargetDirectory.TestDirectory storeDir = testDirForTest( ConstraintIndexFailureIT.class ); @Test public void shouldFailToValidateConstraintsIfUnderlyingIndexIsFailed() throws Exception { // given dbWithConstraint(); storeIndexFailure( "Injected failure" ); // when GraphDatabaseService db = startDatabase(); try { Transaction tx = db.beginTx(); try { db.createNode( label( "Label1" ) ).setProperty( "key1", "value1" ); fail( "expected exception" ); } // then catch ( ConstraintViolationException e ) { assertThat( e.getCause(), instanceOf( UnableToValidateConstraintKernelException.class ) ); assertThat( e.getCause().getCause().getMessage(), equalTo( "The index is in a failed state: 'Injected failure'.") ); } finally { tx.finish(); } } finally { db.shutdown(); } } private GraphDatabaseService startDatabase() { return new GraphDatabaseFactory().newEmbeddedDatabase( storeDir.directory().getAbsolutePath() ); } private void dbWithConstraint() { GraphDatabaseService db = startDatabase(); try { Transaction tx = db.beginTx(); try { db.schema().constraintFor( label( "Label1" ) ).assertPropertyIsUnique( "key1" ).create(); tx.success(); } finally { tx.finish(); } } finally { db.shutdown(); } } private void storeIndexFailure( String failure ) throws IOException { File luceneRootDirectory = new File( storeDir.directory(), "schema/index/lucene" ); new FailureStorage( new FolderLayout( luceneRootDirectory ) ) .storeIndexFailure( singleIndexId( luceneRootDirectory ), failure ); } private int singleIndexId( File luceneRootDirectory ) { List<Integer> indexIds = new ArrayList<>(); for ( String file : luceneRootDirectory.list() ) { try { indexIds.add( Integer.parseInt( file ) ); } catch ( NumberFormatException e ) { // do nothing } } return IteratorUtil.single( indexIds ); } }
false
community_lucene-index_src_test_java_org_neo4j_index_lucene_ConstraintIndexFailureIT.java
5,883
{ @Override public Object doWork( CommandState state ) { return entity.getProperty( key ); } } );
false
community_lucene-index_src_test_java_org_neo4j_index_impl_lucene_WorkThread.java
5,884
{ @Override protected void initialize( Node node, Map<String, Object> properties ) { node.setProperty( key, initialValue ); } };
false
community_lucene-index_src_test_java_org_neo4j_index_impl_lucene_WorkThread.java
5,885
{ @Override public Node doWork( CommandState state ) { UniqueFactory.UniqueNodeFactory factory = new UniqueFactory.UniqueNodeFactory( state.index ) { @Override protected void initialize( Node node, Map<String, Object> properties ) { node.setProperty( key, initialValue ); } }; return factory.getOrCreate( key, value ); } } );
false
community_lucene-index_src_test_java_org_neo4j_index_impl_lucene_WorkThread.java
5,886
{ @Override public Void doWork( CommandState state ) { state.index.add( node, key, value ); return null; } } );
false
community_lucene-index_src_test_java_org_neo4j_index_impl_lucene_WorkThread.java
5,887
public class WorkThread extends OtherThreadExecutor<CommandState> { private volatile boolean txOngoing; public WorkThread( String name, Index<Node> index, GraphDatabaseService graphDb, Node node ) { super( name, new CommandState( index, graphDb, node ) ); } public void createNodeAndIndexBy( String key, String value ) throws Exception { execute( new CreateNodeAndIndexByCommand( key, value ) ); } public void deleteIndex() throws Exception { execute( new DeleteIndexCommand() ); } public IndexHits<Node> queryIndex( String key, Object value ) throws Exception { return execute( new QueryIndexCommand( key, value ) ); } public void commit() throws Exception { execute( new CommitCommand() ); txOngoing = false; } public void beginTransaction() throws Exception { assert !txOngoing; execute( new BeginTransactionCommand() ); txOngoing = true; } public void removeFromIndex( String key, String value ) throws Exception { execute( new RemoveFromIndexCommand( key, value ) ); } public void rollback() throws Exception { if ( !txOngoing ) return; execute( new RollbackCommand() ); txOngoing = false; } public void die() throws Exception { execute( new DieCommand() ); } public Future<Node> putIfAbsent( Node node, String key, Object value ) throws Exception { return executeDontWait( new PutIfAbsentCommand( node, key, value ) ); } public void add( final Node node, final String key, final Object value ) throws Exception { execute( new WorkerCommand<CommandState, Void>() { @Override public Void doWork( CommandState state ) { state.index.add( node, key, value ); return null; } } ); } public Future<Node> getOrCreate( final String key, final Object value, final Object initialValue ) throws Exception { return executeDontWait( new WorkerCommand<CommandState, Node>() { @Override public Node doWork( CommandState state ) { UniqueFactory.UniqueNodeFactory factory = new UniqueFactory.UniqueNodeFactory( state.index ) { @Override protected void initialize( Node node, Map<String, Object> properties ) { node.setProperty( key, initialValue ); } }; return factory.getOrCreate( key, value ); } } ); } public Object getProperty( final PropertyContainer entity, final String key ) throws Exception { return execute( new WorkerCommand<CommandState, Object>() { @Override public Object doWork( CommandState state ) { return entity.getProperty( key ); } } ); } }
false
community_lucene-index_src_test_java_org_neo4j_index_impl_lucene_WorkThread.java
5,888
abstract class TxData { final LuceneIndex index; TxData( LuceneIndex index ) { this.index = index; } abstract void add( TxDataHolder holder, Object entityId, String key, Object value ); abstract void remove( TxDataHolder holder, Object entityId, String key, Object value ); abstract Collection<Long> query( TxDataHolder holder, Query query, QueryContext contextOrNull ); abstract Collection<Long> get( TxDataHolder holder, String key, Object value ); abstract Collection<Long> getOrphans( String key ); abstract void close(); abstract IndexSearcher asSearcher( TxDataHolder holder, QueryContext context ); }
false
community_lucene-index_src_main_java_org_neo4j_index_impl_lucene_TxData.java
5,889
public class TestIndexDeletion { private static final String INDEX_NAME = "index"; private static GraphDatabaseService graphDb; private Index<Node> index; private Transaction tx; private String key; private Node node; private String value; private List<WorkThread> workers; @BeforeClass public static void setUpStuff() { graphDb = new TestGraphDatabaseFactory().newImpermanentDatabase(); } @AfterClass public static void tearDownStuff() { graphDb.shutdown(); } @After public void commitTx() throws Exception { finishTx( true ); for ( WorkThread worker : workers ) { worker.rollback(); worker.die(); worker.close(); } } public void rollbackTx() { finishTx( false ); } public void finishTx( boolean success ) { if ( tx != null ) { if ( success ) { tx.success(); } tx.finish(); tx = null; } } @Before public void createInitialData() { beginTx(); index = graphDb.index().forNodes( INDEX_NAME ); index.delete(); restartTx(); index = graphDb.index().forNodes( INDEX_NAME ); key = "key"; value = "my own value"; node = graphDb.createNode(); index.add( node, key, value ); workers = new ArrayList<>(); } public void beginTx() { if ( tx == null ) { tx = graphDb.beginTx(); } } void restartTx() { finishTx( true ); beginTx(); } @Test public void shouldBeAbleToDeleteAndRecreateIndex() { restartTx(); assertContains( index.query( key, "own" ) ); index.delete(); restartTx(); Index<Node> recreatedIndex = graphDb.index().forNodes( INDEX_NAME, LuceneIndexImplementation.FULLTEXT_CONFIG ); assertNull( recreatedIndex.get( key, value ).getSingle() ); recreatedIndex.add( node, key, value ); restartTx(); assertContains( recreatedIndex.query( key, "own" ), node ); recreatedIndex.delete(); } @Test public void shouldNotBeDeletedWhenDeletionRolledBack() { restartTx(); index.delete(); rollbackTx(); beginTx(); index.get( key, value ); } @Test( expected = IllegalStateException.class ) public void shouldThrowIllegalStateForActionsAfterDeletedOnIndex() { restartTx(); index.delete(); restartTx(); index.query( key, "own" ); } @Test( expected = IllegalStateException.class ) public void shouldThrowIllegalStateForActionsAfterDeletedOnIndex2() { restartTx(); index.delete(); restartTx(); index.add( node, key, value ); } @Test( expected = IllegalStateException.class ) public void shouldThrowIllegalStateForActionsAfterDeletedOnIndex3() { restartTx(); index.delete(); index.query( key, "own" ); } @Test( expected = IllegalStateException.class ) public void shouldThrowIllegalStateForActionsAfterDeletedOnIndex4() { restartTx(); index.delete(); Index<Node> newIndex = graphDb.index().forNodes( INDEX_NAME ); newIndex.query( key, "own" ); } @Test public void deleteInOneTxShouldNotAffectTheOther() throws Exception { index.delete(); WorkThread firstTx = createWorker( "Single" ); firstTx.beginTransaction(); firstTx.createNodeAndIndexBy( key, "another value" ); firstTx.commit(); } @Test public void deleteAndCommitShouldBePublishedToOtherTransaction2() throws Exception { WorkThread firstTx = createWorker( "First" ); WorkThread secondTx = createWorker( "Second" ); firstTx.beginTransaction(); secondTx.beginTransaction(); firstTx.createNodeAndIndexBy(key, "some value"); secondTx.createNodeAndIndexBy(key, "some other value"); firstTx.deleteIndex(); firstTx.commit(); try { secondTx.queryIndex( key, "some other value" ); fail( "Should throw exception" ); } catch ( ExecutionException e ) { assertThat( e.getCause(), instanceOf( IllegalStateException.class ) ); assertThat( e.getCause().getMessage(), is( "This index (Index[index,Node]) has been deleted" ) ); } secondTx.rollback(); // Since $Before will start a tx, add a value and keep tx open and // workers will delete the index so this test will fail in @After // if we don't rollback this tx rollbackTx(); } @Test public void indexDeletesShouldNotByVisibleUntilCommit() throws Exception { commitTx(); WorkThread firstTx = createWorker( "First" ); firstTx.beginTransaction(); firstTx.removeFromIndex( key, value ); Transaction transaction = graphDb.beginTx(); IndexHits<Node> indexHits = index.get( key, value ); assertThat( indexHits, contains( node ) ); transaction.finish(); firstTx.rollback(); } @Test public void canDeleteIndexEvenIfEntitiesAreFoundToBeAbandonedInTheSameTx() throws Exception { // create and index a node Index<Node> nodeIndex = graphDb.index().forNodes( "index" ); Node node = graphDb.createNode(); nodeIndex.add( node, "key", "value" ); // make sure to commit the creation of the entry restartTx(); // delete the node to abandon the index entry node.delete(); restartTx(); // iterate over all nodes indexed with the key to discover abandoned for ( @SuppressWarnings( "unused" ) Node hit : nodeIndex.get( "key", "value" ) ); nodeIndex.delete(); restartTx(); } private WorkThread createWorker( String name ) { WorkThread workThread = new WorkThread( name, index, graphDb, node ); workers.add( workThread ); return workThread; } }
false
community_lucene-index_src_test_java_org_neo4j_index_impl_lucene_TestIndexDeletion.java
5,890
class TopDocsIterator extends AbstractIndexHits<Document> { private final Iterator<ScoreDoc> iterator; private ScoreDoc currentDoc; private final int size; private final IndexSearcher searcher; TopDocsIterator( Query query, QueryContext context, IndexSearcher searcher ) throws IOException { TopDocs docs = toTopDocs( query, context, searcher ); this.size = docs.scoreDocs.length; this.iterator = new ArrayIterator<ScoreDoc>( docs.scoreDocs ); this.searcher = searcher; } private TopDocs toTopDocs( Query query, QueryContext context, IndexSearcher searcher ) throws IOException { Sort sorting = context != null ? context.getSorting() : null; TopDocs topDocs; if ( sorting == null && context != null ) { topDocs = searcher.search( query, context.getTop() ); } else { if ( context == null || !context.getTradeCorrectnessForSpeed() ) { TopFieldCollector collector = LuceneDataSource.scoringCollector( sorting, context.getTop() ); searcher.search( query, collector ); topDocs = collector.topDocs(); } else { topDocs = searcher.search( query, null, context.getTop(), sorting ); } } return topDocs; } @Override protected Document fetchNextOrNull() { if ( !iterator.hasNext() ) { return null; } currentDoc = iterator.next(); try { return searcher.doc( currentDoc.doc ); } catch ( IOException e ) { throw new RuntimeException( e ); } } public float currentScore() { return currentDoc.score; } public int size() { return this.size; } }
false
community_lucene-index_src_main_java_org_neo4j_index_impl_lucene_TopDocsIterator.java
5,891
public class TestRecovery { private File getDbPath() { return new File("target/var/recovery"); } private GraphDatabaseService newGraphDbService() { File path = getDbPath(); Neo4jTestCase.deleteFileOrDirectory( path ); return new GraphDatabaseFactory().newEmbeddedDatabase( path.getPath() ); } @Test public void testRecovery() throws Exception { GraphDatabaseService graphDb = newGraphDbService(); Transaction transaction = graphDb.beginTx(); try { Node node = graphDb.createNode(); Node otherNode = graphDb.createNode(); Relationship rel = node.createRelationshipTo( otherNode, withName( "recovery" ) ); graphDb.index().forNodes( "node-index" ).add( node, "key1", "string value" ); graphDb.index().forNodes( "node-index" ).add( node, "key2", 12345 ); graphDb.index().forRelationships( "rel-index" ).add( rel, "key1", "string value" ); graphDb.index().forRelationships( "rel-index" ).add( rel, "key2", 12345 ); transaction.success(); } finally { transaction.finish(); graphDb.shutdown(); } // Start up and let it recover new GraphDatabaseFactory().newEmbeddedDatabase( getDbPath().getPath() ).shutdown(); } @Test public void testAsLittleAsPossibleRecoveryScenario() throws Exception { GraphDatabaseService db = newGraphDbService(); Transaction transaction = db.beginTx(); try { db.index().forNodes( "my-index" ).add( db.createNode(), "key", "value" ); transaction.success(); } finally { transaction.finish(); db.shutdown(); } // This doesn't seem to trigger recovery... it really should new GraphDatabaseFactory().newEmbeddedDatabase( getDbPath().getPath() ).shutdown(); } @Test public void testIndexDeleteIssue() throws Exception { createIndex(); Process process = Runtime.getRuntime().exec( new String[]{ "java", "-cp", System.getProperty( "java.class.path" ), AddDeleteQuit.class.getName(), getDbPath().getPath() } ); assertEquals( 0, new ProcessStreamHandler( process, true ).waitForResult() ); new GraphDatabaseFactory().newEmbeddedDatabase( getDbPath().getPath() ).shutdown(); } @Test public void recoveryForRelationshipCommandsOnly() throws Exception { File path = getDbPath(); Neo4jTestCase.deleteFileOrDirectory( path ); Process process = Runtime.getRuntime().exec( new String[]{ "java", "-Xdebug", "-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005", "-cp", System.getProperty( "java.class.path" ), AddRelToIndex.class.getName(), getDbPath().getPath() } ); assertEquals( 0, new ProcessStreamHandler( process, false ).waitForResult() ); // I would like to do this, but there's no exception propagated out from the constructor // if the recovery fails. // new GraphDatabaseFactory().newEmbeddedDatabase( getDbPath() ).shutdown(); // Instead I have to do this FileSystemAbstraction fileSystemAbstraction = new DefaultFileSystemAbstraction(); FileSystemAbstraction fileSystem = fileSystemAbstraction; Map<String, String> params = MapUtil.stringMap( "store_dir", getDbPath().getPath() ); Config config = new Config( params, GraphDatabaseSettings.class ); LuceneDataSource ds = new LuceneDataSource( config, new IndexStore( getDbPath(), fileSystem ), fileSystem, new XaFactory( config, TxIdGenerator.DEFAULT, new PlaceboTm( null, null ), fileSystemAbstraction, new Monitors(), new DevNullLoggingService(), RecoveryVerifier.ALWAYS_VALID, LogPruneStrategies.NO_PRUNING, mock( KernelHealth.class ) ), null ); ds.start(); ds.stop(); } @Test public void recoveryOnDeletedIndex() throws Exception { createIndex(); Process process = Runtime.getRuntime().exec( new String[]{ "java", "-cp", System.getProperty( "java.class.path" ), AddThenDeleteInAnotherTxAndQuit.class.getName(), getDbPath().getPath() } ); assertEquals( 0, new ProcessStreamHandler( process, false ).waitForResult() ); GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase( getDbPath().getPath() ); Transaction transaction = db.beginTx(); assertFalse( db.index().existsForNodes( "index" ) ); assertNotNull( db.index().forNodes( "index2" ).get( "key", "value" ).getSingle() ); transaction.finish(); db.shutdown(); } private void createIndex() { GraphDatabaseService db = newGraphDbService(); Transaction transaction = db.beginTx(); try { db.index().forNodes( "index" ); transaction.success(); } finally { transaction.finish(); db.shutdown(); } } }
false
community_lucene-index_src_test_java_org_neo4j_index_impl_lucene_TestRecovery.java
5,892
public class TestMigration { @Test public void canReadAndUpgradeOldIndexStoreFormat() throws Exception { String path = "target/var/old-index-store"; Neo4jTestCase.deleteFileOrDirectory( new File( path ) ); GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase( path ); db.shutdown(); InputStream stream = getClass().getClassLoader().getResourceAsStream( "old-index.db" ); writeFile( stream, new File( path, "index.db" ) ); db = new GraphDatabaseFactory().newEmbeddedDatabase( path ); Transaction transaction = db.beginTx(); try { assertTrue( db.index().existsForNodes( "indexOne" ) ); Index<Node> indexOne = db.index().forNodes( "indexOne" ); verifyConfiguration( db, indexOne, LuceneIndexImplementation.EXACT_CONFIG ); assertTrue( db.index().existsForNodes( "indexTwo" ) ); Index<Node> indexTwo = db.index().forNodes( "indexTwo" ); verifyConfiguration( db, indexTwo, LuceneIndexImplementation.FULLTEXT_CONFIG ); assertTrue( db.index().existsForRelationships( "indexThree" ) ); Index<Relationship> indexThree = db.index().forRelationships( "indexThree" ); verifyConfiguration( db, indexThree, LuceneIndexImplementation.EXACT_CONFIG ); } finally { transaction.finish(); } db.shutdown(); } @Test @Ignore( "These upgrade tests only work for one version difference" ) public void canUpgradeFromPreviousVersion() throws Exception { GraphDatabaseService db = unpackDbFrom( "db-with-v3.0.1.zip" ); Index<Node> index = db.index().forNodes( "v3.0.1" ); Node node = index.get( "key", "value" ).getSingle(); assertNotNull( node ); db.shutdown(); } private GraphDatabaseService unpackDbFrom( String file ) throws IOException { File path = new File( "target/var/zipup" ); FileUtils.deleteRecursively( path ); path.mkdirs(); ZipInputStream zip = new ZipInputStream( getClass().getClassLoader().getResourceAsStream( file ) ); ZipEntry entry = null; byte[] buffer = new byte[2048]; while ( (entry = zip.getNextEntry()) != null ) { if ( entry.isDirectory() ) { new File( path, entry.getName() ).mkdirs(); continue; } FileOutputStream fos = new FileOutputStream( new File( path, entry.getName() ) ); BufferedOutputStream bos = new BufferedOutputStream( fos, buffer.length ); int size; while ( (size = zip.read( buffer, 0, buffer.length )) != -1 ) { bos.write( buffer, 0, size ); } bos.flush(); bos.close(); } return new GraphDatabaseFactory().newEmbeddedDatabase( path.getAbsolutePath() ); } private void verifyConfiguration( GraphDatabaseService db, Index<? extends PropertyContainer> index, Map<String, String> config ) { assertEquals( config, db.index().getConfiguration( index ) ); } private void writeFile( InputStream stream, File file ) throws Exception { file.delete(); OutputStream out = new FileOutputStream( file ); byte[] bytes = new byte[1024]; int bytesRead = 0; while ( (bytesRead = stream.read( bytes )) >= 0 ) { out.write( bytes, 0, bytesRead ); } out.close(); } @Test public void providerGetsFilledInAutomatically() { Map<String, String> correctConfig = MapUtil.stringMap( "type", "exact", IndexManager.PROVIDER, "lucene" ); File storeDir = new File( "target/var/index" ); Neo4jTestCase.deleteFileOrDirectory( storeDir ); GraphDatabaseService graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( storeDir.getPath() ); Transaction transaction = graphDb.beginTx(); try { assertEquals( correctConfig, graphDb.index().getConfiguration( graphDb.index().forNodes( "default" ) ) ); assertEquals( correctConfig, graphDb.index().getConfiguration( graphDb.index().forNodes( "wo-provider", MapUtil.stringMap( "type", "exact" ) ) ) ); assertEquals( correctConfig, graphDb.index().getConfiguration( graphDb.index().forNodes( "w-provider", MapUtil.stringMap( "type", "exact", IndexManager.PROVIDER, "lucene" ) ) ) ); assertEquals( correctConfig, graphDb.index().getConfiguration( graphDb.index().forRelationships( "default" ) ) ); assertEquals( correctConfig, graphDb.index().getConfiguration( graphDb.index().forRelationships( "wo-provider", MapUtil.stringMap( "type", "exact" ) ) ) ); assertEquals( correctConfig, graphDb.index().getConfiguration( graphDb.index().forRelationships( "w-provider", MapUtil.stringMap( "type", "exact", IndexManager.PROVIDER, "lucene" ) ) ) ); transaction.success(); } finally { transaction.finish(); } graphDb.shutdown(); removeProvidersFromIndexDbFile( storeDir ); graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( storeDir.getPath() ); transaction = graphDb.beginTx(); try { // Getting the index w/o exception means that the provider has been reinstated assertEquals( correctConfig, graphDb.index().getConfiguration( graphDb.index().forNodes( "default" ) ) ); assertEquals( correctConfig, graphDb.index().getConfiguration( graphDb.index().forNodes( "wo-provider", MapUtil.stringMap( "type", "exact" ) ) ) ); assertEquals( correctConfig, graphDb.index().getConfiguration( graphDb.index().forNodes( "w-provider", MapUtil.stringMap( "type", "exact", IndexManager.PROVIDER, "lucene" ) ) ) ); assertEquals( correctConfig, graphDb.index().getConfiguration( graphDb.index().forRelationships( "default" ) ) ); assertEquals( correctConfig, graphDb.index().getConfiguration( graphDb.index().forRelationships( "wo-provider", MapUtil.stringMap( "type", "exact" ) ) ) ); assertEquals( correctConfig, graphDb.index().getConfiguration( graphDb.index().forRelationships( "w-provider", MapUtil.stringMap( "type", "exact", IndexManager.PROVIDER, "lucene" ) ) ) ); } finally { transaction.finish(); } graphDb.shutdown(); removeProvidersFromIndexDbFile( storeDir ); graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( storeDir.getPath() ); transaction = graphDb.beginTx(); try { // Getting the index w/o exception means that the provider has been reinstated assertEquals( correctConfig, graphDb.index().getConfiguration( graphDb.index().forNodes( "default" ) ) ); assertEquals( correctConfig, graphDb.index().getConfiguration( graphDb.index().forNodes( "wo-provider" ) ) ); assertEquals( correctConfig, graphDb.index().getConfiguration( graphDb.index().forNodes( "w-provider" ) ) ); assertEquals( correctConfig, graphDb.index().getConfiguration( graphDb.index().forRelationships( "default" ) ) ); assertEquals( correctConfig, graphDb.index().getConfiguration( graphDb.index().forRelationships( "wo-provider" ) ) ); assertEquals( correctConfig, graphDb.index().getConfiguration( graphDb.index().forRelationships( "w-provider" ) ) ); } finally { transaction.finish(); } graphDb.shutdown(); } private void removeProvidersFromIndexDbFile( File storeDir ) { IndexStore indexStore = new IndexStore( storeDir, new DefaultFileSystemAbstraction() ); for ( Class<? extends PropertyContainer> cls : new Class[] {Node.class, Relationship.class} ) { for ( String name : indexStore.getNames( cls ) ) { Map<String, String> config = indexStore.get( cls, name ); config = new HashMap<String, String>( config ); config.remove( IndexManager.PROVIDER ); indexStore.set( Node.class, name, config ); } } } }
false
community_lucene-index_src_test_java_org_neo4j_index_impl_lucene_TestMigration.java
5,893
{ @Override protected Relationship create( Map<String, Object> properties ) { assertEquals( value, properties.get( key ) ); assertEquals( 1, properties.size() ); return root.createRelationshipTo( graphDatabase().createNode(), type ); } };
false
community_lucene-index_src_test_java_org_neo4j_index_impl_lucene_TestLuceneIndex.java
5,894
{ @Override protected void initialize( Node node, Map<String, Object> properties ) { assertEquals( value, properties.get( key ) ); assertEquals( 1, properties.size() ); node.setProperty( property, counter.getAndIncrement() ); } };
false
community_lucene-index_src_test_java_org_neo4j_index_impl_lucene_TestLuceneIndex.java
5,895
public class TestLuceneIndex extends AbstractLuceneIndexTest { @SuppressWarnings( "unchecked" ) private <T extends PropertyContainer> void makeSureAdditionsCanBeRead( Index<T> index, EntityCreator<T> entityCreator ) { String key = "name"; String value = "Mattias"; assertThat( index.get( key, value ).getSingle(), is( nullValue() ) ); assertThat( index.get( key, value ), isEmpty() ); assertThat( index.query( key, "*" ), isEmpty() ); T entity1 = entityCreator.create(); T entity2 = entityCreator.create(); index.add( entity1, key, value ); for ( int i = 0; i < 2; i++ ) { assertThat( index.get( key, value ), contains( entity1 ) ); assertThat( index.query( key, "*" ), contains( entity1 ) ); assertThat( index.get( key, value ), contains( entity1 ) ); restartTx(); } index.add( entity2, key, value ); assertThat( index.get( key, value ), contains( entity1, entity2 ) ); restartTx(); assertThat( index.get( key, value ), contains( entity1, entity2 ) ); index.delete(); } @Test public void makeSureYouGetLatestTxModificationsInQueryByDefault() { Index<Node> index = nodeIndex( LuceneIndexImplementation.FULLTEXT_CONFIG ); Node node = graphDb.createNode(); index.add( node, "key", "value" ); assertThat( index.query( "key:value" ), contains( node ) ); } @Test public void makeSureLuceneIndexesReportAsWriteable() { Index<Node> index = nodeIndex( LuceneIndexImplementation.FULLTEXT_CONFIG ); Node node = graphDb.createNode(); index.add( node, "key", "value" ); assertTrue( index.isWriteable() ); } @Test public void makeSureAdditionsCanBeReadNodeExact() { makeSureAdditionsCanBeRead( nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ), NODE_CREATOR ); } @Test public void makeSureAdditionsCanBeReadNodeFulltext() { makeSureAdditionsCanBeRead( nodeIndex( LuceneIndexImplementation.FULLTEXT_CONFIG ), NODE_CREATOR ); } @Test public void makeSureAdditionsCanBeReadRelationshipExact() { makeSureAdditionsCanBeRead( relationshipIndex( LuceneIndexImplementation.EXACT_CONFIG ), RELATIONSHIP_CREATOR ); } @Test public void makeSureAdditionsCanBeReadRelationshipFulltext() { makeSureAdditionsCanBeRead( relationshipIndex( LuceneIndexImplementation.FULLTEXT_CONFIG ), RELATIONSHIP_CREATOR ); } @Test public void makeSureAdditionsCanBeRemovedInSameTx() { makeSureAdditionsCanBeRemoved( false ); } @Test @Ignore public void makeSureYouCanAskIfAnIndexExistsOrNot() { String name = currentIndexName(); assertFalse( graphDb.index().existsForNodes( name ) ); graphDb.index().forNodes( name ); assertTrue( graphDb.index().existsForNodes( name ) ); assertFalse( graphDb.index().existsForRelationships( name ) ); graphDb.index().forRelationships( name ); assertTrue( graphDb.index().existsForRelationships( name ) ); } private void makeSureAdditionsCanBeRemoved( boolean restartTx ) { Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ); String key = "name"; String value = "Mattias"; assertNull( index.get( key, value ).getSingle() ); Node node = graphDb.createNode(); index.add( node, key, value ); if ( restartTx ) { restartTx(); } assertEquals( node, index.get( key, value ).getSingle() ); index.remove( node, key, value ); assertNull( index.get( key, value ).getSingle() ); restartTx(); assertNull( index.get( key, value ).getSingle() ); node.delete(); index.delete(); } @Test public void makeSureAdditionsCanBeRemoved() { makeSureAdditionsCanBeRemoved( true ); } private void makeSureSomeAdditionsCanBeRemoved( boolean restartTx ) { Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ); String key1 = "name"; String key2 = "title"; String value1 = "Mattias"; assertNull( index.get( key1, value1 ).getSingle() ); assertNull( index.get( key2, value1 ).getSingle() ); Node node = graphDb.createNode(); Node node2 = graphDb.createNode(); index.add( node, key1, value1 ); index.add( node, key2, value1 ); index.add( node2, key1, value1 ); if ( restartTx ) { restartTx(); } index.remove( node, key1, value1 ); index.remove( node, key2, value1 ); assertEquals( node2, index.get( key1, value1 ).getSingle() ); assertNull( index.get( key2, value1 ).getSingle() ); assertEquals( node2, index.get( key1, value1 ).getSingle() ); assertNull( index.get( key2, value1 ).getSingle() ); node.delete(); index.delete(); } @Test public void makeSureSomeAdditionsCanBeRemovedInSameTx() { makeSureSomeAdditionsCanBeRemoved( false ); } @Test public void makeSureSomeAdditionsCanBeRemoved() { makeSureSomeAdditionsCanBeRemoved( true ); } @Test public void makeSureThereCanBeMoreThanOneValueForAKeyAndEntity() { makeSureThereCanBeMoreThanOneValueForAKeyAndEntity( false ); } @Test public void makeSureThereCanBeMoreThanOneValueForAKeyAndEntitySameTx() { makeSureThereCanBeMoreThanOneValueForAKeyAndEntity( true ); } private void makeSureThereCanBeMoreThanOneValueForAKeyAndEntity( boolean restartTx ) { Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ); String key = "name"; String value1 = "Lucene"; String value2 = "Index"; String value3 = "Rules"; assertThat( index.query( key, "*" ), isEmpty() ); Node node = graphDb.createNode(); index.add( node, key, value1 ); index.add( node, key, value2 ); if ( restartTx ) { restartTx(); } index.add( node, key, value3 ); for ( int i = 0; i < 2; i++ ) { assertThat( index.get( key, value1 ), contains( node ) ); assertThat( index.get( key, value2 ), contains( node ) ); assertThat( index.get( key, value3 ), contains( node ) ); assertThat( index.get( key, "whatever" ), isEmpty() ); restartTx(); } index.delete(); } @Test public void indexHitsFromQueryingRemovedDoesNotReturnNegativeCount() { Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ); Node theNode = graphDb.createNode(); index.remove( theNode ); IndexHits<Node> hits = index.query( "someRandomKey", theNode.getId() ); assertTrue( hits.size() >= 0 ); } @Test public void shouldNotGetLatestTxModificationsWhenChoosingSpeedQueries() { Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ); Node node = graphDb.createNode(); index.add( node, "key", "value" ); QueryContext queryContext = new QueryContext( "value" ).tradeCorrectnessForSpeed(); assertThat( index.query( "key", queryContext ), isEmpty() ); assertThat( index.query( "key", "value" ), contains( node ) ); } @Test public void makeSureArrayValuesAreSupported() { Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ); String key = "name"; String value1 = "Lucene"; String value2 = "Index"; String value3 = "Rules"; assertThat( index.query( key, "*" ), isEmpty() ); Node node = graphDb.createNode(); index.add( node, key, new String[]{value1, value2, value3} ); for ( int i = 0; i < 2; i++ ) { assertThat( index.get( key, value1 ), contains( node ) ); assertThat( index.get( key, value2 ), contains( node ) ); assertThat( index.get( key, value3 ), contains( node ) ); assertThat( index.get( key, "whatever" ), isEmpty() ); restartTx(); } index.remove( node, key, new String[]{value2, value3} ); for ( int i = 0; i < 2; i++ ) { assertThat( index.get( key, value1 ), contains( node ) ); assertThat( index.get( key, value2 ), isEmpty() ); assertThat( index.get( key, value3 ), isEmpty() ); restartTx(); } index.delete(); } @Test public void makeSureWildcardQueriesCanBeAsked() { Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ); String key = "name"; String value1 = "neo4j"; String value2 = "nescafe"; Node node1 = graphDb.createNode(); Node node2 = graphDb.createNode(); index.add( node1, key, value1 ); index.add( node2, key, value2 ); for ( int i = 0; i < 2; i++ ) { assertThat( index.query( key, "neo*" ), contains( node1 ) ); assertThat( index.query( key, "n?o4j" ), contains( node1 ) ); assertThat( index.query( key, "ne*" ), contains( node1, node2 ) ); assertThat( index.query( key + ":neo4j" ), contains( node1 ) ); assertThat( index.query( key + ":neo*" ), contains( node1 ) ); assertThat( index.query( key + ":n?o4j" ), contains( node1 ) ); assertThat( index.query( key + ":ne*" ), contains( node1, node2 ) ); restartTx(); } index.delete(); } @Test public void makeSureCompositeQueriesCanBeAsked() { Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ); Node neo = graphDb.createNode(); Node trinity = graphDb.createNode(); index.add( neo, "username", "neo@matrix" ); index.add( neo, "sex", "male" ); index.add( trinity, "username", "trinity@matrix" ); index.add( trinity, "sex", "female" ); for ( int i = 0; i < 2; i++ ) { assertThat( index.query( "username:*@matrix AND sex:male" ), contains( neo ) ); assertThat( index.query( new QueryContext( "username:*@matrix sex:male" ).defaultOperator( Operator.AND ) ), contains( neo ) ); assertThat( index.query( "username:*@matrix OR sex:male" ), contains( neo, trinity ) ); assertThat( index.query( new QueryContext( "username:*@matrix sex:male" ).defaultOperator( Operator.OR ) ), contains( neo, trinity ) ); restartTx(); } index.delete(); } @SuppressWarnings( "unchecked" ) private <T extends PropertyContainer> void doSomeRandomUseCaseTestingWithExactIndex( Index<T> index, EntityCreator<T> creator ) { String name = "name"; String mattias = "Mattias Persson"; String title = "title"; String hacker = "Hacker"; assertThat( index.get( name, mattias ), isEmpty() ); T entity1 = creator.create(); T entity2 = creator.create(); assertNull( index.get( name, mattias ).getSingle() ); index.add( entity1, name, mattias ); assertThat( index.get( name, mattias ), contains( entity1 ) ); assertContains( index.query( name, "\"" + mattias + "\"" ), entity1 ); assertContains( index.query( "name:\"" + mattias + "\"" ), entity1 ); assertEquals( entity1, index.get( name, mattias ).getSingle() ); assertContains( index.query( "name", "Mattias*" ), entity1 ); commitTx(); beginTx(); assertThat( index.get( name, mattias ), contains( entity1 ) ); assertThat( index.query( name, "\"" + mattias + "\"" ), contains( entity1 ) ); assertThat( index.query( "name:\"" + mattias + "\"" ), contains( entity1 ) ); assertEquals( entity1, index.get( name, mattias ).getSingle() ); assertThat( index.query( "name", "Mattias*" ), contains( entity1 ) ); commitTx(); beginTx(); index.add( entity2, title, hacker ); index.add( entity1, title, hacker ); assertThat( index.get( name, mattias ), contains( entity1 ) ); assertThat( index.get( title, hacker ), contains( entity1, entity2 ) ); assertContains( index.query( "name:\"" + mattias + "\" OR title:\"" + hacker + "\"" ), entity1, entity2 ); commitTx(); beginTx(); assertThat( index.get( name, mattias ), contains( entity1 ) ); assertThat( index.get( title, hacker ), contains( entity1, entity2 ) ); assertThat( index.query( "name:\"" + mattias + "\" OR title:\"" + hacker + "\"" ), contains( entity1, entity2 ) ); assertThat( index.query( "name:\"" + mattias + "\" AND title:\"" + hacker + "\"" ), contains( entity1 ) ); commitTx(); beginTx(); index.remove( entity2, title, hacker ); assertThat( index.get( name, mattias ), contains( entity1 ) ); assertThat( index.get( title, hacker ), contains( entity1 ) ); assertContains( index.query( "name:\"" + mattias + "\" OR title:\"" + hacker + "\"" ), entity1 ); commitTx(); beginTx(); assertThat( index.get( name, mattias ), contains( entity1 ) ); assertThat( index.get( title, hacker ), contains( entity1 ) ); assertThat( index.query( "name:\"" + mattias + "\" OR title:\"" + hacker + "\"" ), contains( entity1 ) ); commitTx(); beginTx(); index.remove( entity1, title, hacker ); index.remove( entity1, name, mattias ); index.delete(); commitTx(); } @Test public void doSomeRandomUseCaseTestingWithExactNodeIndex() { doSomeRandomUseCaseTestingWithExactIndex( nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ), NODE_CREATOR ); } @Test public void doSomeRandomUseCaseTestingWithExactRelationshipIndex() { doSomeRandomUseCaseTestingWithExactIndex( relationshipIndex( LuceneIndexImplementation.EXACT_CONFIG ), RELATIONSHIP_CREATOR ); } @SuppressWarnings( "unchecked" ) private <T extends PropertyContainer> void doSomeRandomTestingWithFulltextIndex( Index<T> index, EntityCreator<T> creator ) { T entity1 = creator.create(); T entity2 = creator.create(); String key = "name"; index.add( entity1, key, "The quick brown fox" ); index.add( entity2, key, "brown fox jumped over" ); for ( int i = 0; i < 2; i++ ) { assertThat( index.get( key, "The quick brown fox" ), contains( entity1 ) ); assertThat( index.get( key, "brown fox jumped over" ), contains( entity2 ) ); assertThat( index.query( key, "quick" ), contains( entity1 ) ); assertThat( index.query( key, "brown" ), contains( entity1, entity2 ) ); assertThat( index.query( key, "quick OR jumped" ), contains( entity1, entity2 ) ); assertThat( index.query( key, "brown AND fox" ), contains( entity1, entity2 ) ); restartTx(); } index.delete(); } @Test public void doSomeRandomTestingWithNodeFulltextInde() { doSomeRandomTestingWithFulltextIndex( nodeIndex( LuceneIndexImplementation.FULLTEXT_CONFIG ), NODE_CREATOR ); } @Test public void doSomeRandomTestingWithRelationshipFulltextInde() { doSomeRandomTestingWithFulltextIndex( relationshipIndex( LuceneIndexImplementation.FULLTEXT_CONFIG ), RELATIONSHIP_CREATOR ); } @Test public void testNodeLocalRelationshipIndex() { RelationshipIndex index = relationshipIndex( LuceneIndexImplementation.EXACT_CONFIG ); RelationshipType type = DynamicRelationshipType.withName( "YO" ); Node startNode = graphDb.createNode(); Node endNode1 = graphDb.createNode(); Node endNode2 = graphDb.createNode(); Relationship rel1 = startNode.createRelationshipTo( endNode1, type ); Relationship rel2 = startNode.createRelationshipTo( endNode2, type ); index.add( rel1, "name", "something" ); index.add( rel2, "name", "something" ); for ( int i = 0; i < 2; i++ ) { assertThat( index.query( "name:something" ), contains( rel1, rel2 ) ); assertThat( index.query( "name:something", null, endNode1 ), contains( rel1 ) ); assertThat( index.query( "name:something", startNode, endNode2 ), contains( rel2 ) ); assertThat( index.query( null, startNode, endNode1 ), contains( rel1 ) ); assertThat( index.get( "name", "something", null, endNode1 ), contains( rel1 ) ); assertThat( index.get( "name", "something", startNode, endNode2 ), contains( rel2 ) ); assertThat( index.get( null, null, startNode, endNode1 ), contains( rel1 ) ); restartTx(); } rel2.delete(); rel1.delete(); startNode.delete(); endNode1.delete(); endNode2.delete(); index.delete(); } @Test public void testSortByRelevance() { Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ); Node node1 = graphDb.createNode(); Node node2 = graphDb.createNode(); Node node3 = graphDb.createNode(); index.add( node1, "name", "something" ); index.add( node2, "name", "something" ); index.add( node2, "foo", "yes" ); index.add( node3, "name", "something" ); index.add( node3, "foo", "yes" ); index.add( node3, "bar", "yes" ); restartTx(); IndexHits<Node> hits = index.query( new QueryContext( "+name:something foo:yes bar:yes" ).sort( Sort.RELEVANCE ) ); assertEquals( node3, hits.next() ); assertEquals( node2, hits.next() ); assertEquals( node1, hits.next() ); assertFalse( hits.hasNext() ); index.delete(); node1.delete(); node2.delete(); node3.delete(); } @Test public void testSorting() { Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ); String name = "name"; String title = "title"; String other = "other"; String sex = "sex"; Node adam = graphDb.createNode(); Node adam2 = graphDb.createNode(); Node jack = graphDb.createNode(); Node eva = graphDb.createNode(); index.add( adam, name, "Adam" ); index.add( adam, title, "Software developer" ); index.add( adam, sex, "male" ); index.add( adam, other, "aaa" ); index.add( adam2, name, "Adam" ); index.add( adam2, title, "Blabla" ); index.add( adam2, sex, "male" ); index.add( adam2, other, "bbb" ); index.add( jack, name, "Jack" ); index.add( jack, title, "Apple sales guy" ); index.add( jack, sex, "male" ); index.add( jack, other, "ccc" ); index.add( eva, name, "Eva" ); index.add( eva, title, "Secretary" ); index.add( eva, sex, "female" ); index.add( eva, other, "ddd" ); for ( int i = 0; i < 2; i++ ) { assertContainsInOrder( index.query( new QueryContext( "name:*" ).sort( name, title ) ), adam2, adam, eva, jack ); assertContainsInOrder( index.query( new QueryContext( "name:*" ).sort( name, other ) ), adam, adam2, eva, jack ); assertContainsInOrder( index.query( new QueryContext( "name:*" ).sort( sex, title ) ), eva, jack, adam2, adam ); assertContainsInOrder( index.query( name, new QueryContext( "*" ).sort( sex, title ) ), eva, jack, adam2, adam ); assertContainsInOrder( index.query( new QueryContext( "name:*" ).sort( name, title ).top( 2 ) ), adam2, adam ); restartTx(); } } @Test public void testNumericValuesExactIndex() throws Exception { testNumericValues( nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ) ); } @Test public void testNumericValuesFulltextIndex() throws Exception { testNumericValues( nodeIndex( LuceneIndexImplementation.FULLTEXT_CONFIG ) ); } private void testNumericValues( Index<Node> index ) { Node node10 = graphDb.createNode(); Node node6 = graphDb.createNode(); Node node31 = graphDb.createNode(); String key = "key"; index.add( node10, key, numeric( 10 ) ); index.add( node6, key, numeric( 6 ) ); index.add( node31, key, numeric( 31 ) ); for ( int i = 0; i < 2; i++ ) { assertThat( index.query( NumericRangeQuery.newIntRange( key, 4, 40, true, true ) ), contains( node10, node6, node31 ) ); assertThat( index.query( NumericRangeQuery.newIntRange( key, 6, 15, true, true ) ), contains( node10, node6 ) ); assertThat( index.query( NumericRangeQuery.newIntRange( key, 6, 15, false, true ) ), contains( node10 ) ); restartTx(); } index.remove( node6, key, numeric( 6 ) ); assertThat( index.query( NumericRangeQuery.newIntRange( key, 4, 40, true, true ) ), contains( node10, node31 ) ); restartTx(); assertThat( index.query( NumericRangeQuery.newIntRange( key, 4, 40, true, true ) ), contains( node10, node31 ) ); } @Test public void testNumericValueArrays() { Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ); Node node1 = graphDb.createNode(); index.add( node1, "number", new ValueContext[]{ numeric( 45 ), numeric( 98 ) } ); Node node2 = graphDb.createNode(); index.add( node2, "number", new ValueContext[]{ numeric( 47 ), numeric( 100 ) } ); IndexHits<Node> indexResult1 = index.query( "number", newIntRange( "number", 47, 98, true, true ) ); assertThat( indexResult1, contains( node1, node2 ) ); assertThat( indexResult1.size(), is( 2 )); IndexHits<Node> indexResult2 = index.query( "number", newIntRange( "number", 44, 46, true, true ) ); assertThat( indexResult2, contains( node1 ) ); assertThat( indexResult2.size(), is( 1 ) ); IndexHits<Node> indexResult3 = index.query( "number", newIntRange( "number", 99, 101, true, true ) ); assertThat( indexResult3, contains( node2 ) ); assertThat( indexResult3.size(), is( 1 ) ); IndexHits<Node> indexResult4 = index.query( "number", newIntRange( "number", 47, 98, false, false ) ); assertThat( indexResult4, isEmpty() ); IndexHits<Node> indexResult5 = index.query( "number", numericRange( "number", null, 98, true, true ) ); assertContains( indexResult5, node1, node2 ); IndexHits<Node> indexResult6 = index.query( "number", numericRange( "number", 47, null, true, true ) ); assertContains( indexResult6, node1, node2 ); } @Test public void testRemoveNumericValues() { Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ); Node node1 = graphDb.createNode(); Node node2 = graphDb.createNode(); String key = "key"; index.add( node1, key, new ValueContext( 15 ).indexNumeric() ); index.add( node2, key, new ValueContext( 5 ).indexNumeric() ); index.remove( node1, key, new ValueContext( 15 ).indexNumeric() ); assertThat( index.query( NumericRangeQuery.newIntRange( key, 0, 20, false, false ) ), contains( node2 ) ); index.remove( node2, key, new ValueContext( 5 ).indexNumeric() ); assertThat( index.query( NumericRangeQuery.newIntRange( key, 0, 20, false, false ) ), isEmpty() ); restartTx(); assertThat( index.query( NumericRangeQuery.newIntRange( key, 0, 20, false, false ) ), isEmpty() ); index.add( node1, key, new ValueContext( 15 ).indexNumeric() ); index.add( node2, key, new ValueContext( 5 ).indexNumeric() ); restartTx(); assertThat( index.query( NumericRangeQuery.newIntRange( key, 0, 20, false, false ) ), contains( node1, node2 ) ); index.remove( node1, key, new ValueContext( 15 ).indexNumeric() ); assertThat( index.query( NumericRangeQuery.newIntRange( key, 0, 20, false, false ) ), contains( node2 ) ); restartTx(); assertThat( index.query( NumericRangeQuery.newIntRange( key, 0, 20, false, false ) ), contains( node2 ) ); } @Test public void sortNumericValues() throws Exception { Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ); Node node1 = graphDb.createNode(); Node node2 = graphDb.createNode(); Node node3 = graphDb.createNode(); String key = "key"; index.add( node1, key, numeric( 5 ) ); index.add( node2, key, numeric( 15 ) ); index.add( node3, key, numeric( 10 ) ); restartTx(); assertContainsInOrder( index.query( numericRange( key, 5, 15 ).sortNumeric( key, false ) ), node1, node3, node2 ); } @Test public void testIndexNumberAsString() { Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ); Node node1 = graphDb.createNode(); index.add( node1, "key", 10 ); for ( int i = 0; i < 2; i++ ) { assertEquals( node1, index.get( "key", 10 ).getSingle() ); assertEquals( node1, index.get( "key", "10" ).getSingle() ); assertEquals( node1, index.query( "key", 10 ).getSingle() ); assertEquals( node1, index.query( "key", "10" ).getSingle() ); restartTx(); } } @Test( expected = IllegalArgumentException.class ) public void makeSureIndexGetsCreatedImmediately() { // Since index creation is done outside of the normal transactions, // a rollback will not roll back index creation. nodeIndex( LuceneIndexImplementation.FULLTEXT_CONFIG ); assertTrue( graphDb.index().existsForNodes( currentIndexName() ) ); rollbackTx(); beginTx(); assertTrue( graphDb.index().existsForNodes( currentIndexName() ) ); nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ); rollbackTx(); } @Test public void makeSureFulltextConfigIsCaseInsensitiveByDefault() { Index<Node> index = nodeIndex( LuceneIndexImplementation.FULLTEXT_CONFIG ); Node node = graphDb.createNode(); String key = "name"; String value = "Mattias Persson"; index.add( node, key, value ); for ( int i = 0; i < 2; i++ ) { assertThat( index.query( "name", "[A TO Z]" ), contains( node ) ); assertThat( index.query( "name", "[a TO z]" ), contains( node ) ); assertThat( index.query( "name", "Mattias" ), contains( node ) ); assertThat( index.query( "name", "mattias" ), contains( node ) ); assertThat( index.query( "name", "Matt*" ), contains( node ) ); assertThat( index.query( "name", "matt*" ), contains( node ) ); restartTx(); } } @Test public void makeSureFulltextIndexCanBeCaseSensitive() { Index<Node> index = nodeIndex( MapUtil.stringMap( new HashMap<>( LuceneIndexImplementation.FULLTEXT_CONFIG ), "to_lower_case", "false" ) ); Node node = graphDb.createNode(); String key = "name"; String value = "Mattias Persson"; index.add( node, key, value ); for ( int i = 0; i < 2; i++ ) { assertThat( index.query( "name", "[A TO Z]" ), contains( node ) ); assertThat( index.query( "name", "[a TO z]" ), isEmpty() ); assertThat( index.query( "name", "Matt*" ), contains( node ) ); assertThat( index.query( "name", "matt*" ), isEmpty() ); assertThat( index.query( "name", "Persson" ), contains( node ) ); assertThat( index.query( "name", "persson" ), isEmpty() ); restartTx(); } } @Test public void makeSureCustomAnalyzerCanBeUsed() { CustomAnalyzer.called = false; Index<Node> index = nodeIndex( MapUtil.stringMap( IndexManager.PROVIDER, "lucene", "analyzer", org.neo4j.index.impl.lucene.CustomAnalyzer.class.getName(), "to_lower_case", "true" ) ); Node node = graphDb.createNode(); String key = "name"; String value = "The value"; index.add( node, key, value ); restartTx(); assertTrue( CustomAnalyzer.called ); assertThat( index.query( key, "[A TO Z]" ), contains( node ) ); } @Test public void makeSureCustomAnalyzerCanBeUsed2() { CustomAnalyzer.called = false; Index<Node> index = nodeIndex( "w-custom-analyzer-2", MapUtil.stringMap( IndexManager.PROVIDER, "lucene", "analyzer", org.neo4j.index.impl.lucene.CustomAnalyzer.class.getName(), "to_lower_case", "true", "type", "fulltext" ) ); Node node = graphDb.createNode(); String key = "name"; String value = "The value"; index.add( node, key, value ); restartTx(); assertTrue( CustomAnalyzer.called ); assertThat( index.query( key, "[A TO Z]" ), contains( node ) ); } @Test public void makeSureIndexNameAndConfigCanBeReachedFromIndex() { String indexName = "my-index-1"; Index<Node> nodeIndex = nodeIndex( indexName, LuceneIndexImplementation.EXACT_CONFIG ); assertEquals( indexName, nodeIndex.getName() ); assertEquals( LuceneIndexImplementation.EXACT_CONFIG, graphDb.index().getConfiguration( nodeIndex ) ); String indexName2 = "my-index-2"; Index<Relationship> relIndex = relationshipIndex( indexName2, LuceneIndexImplementation.FULLTEXT_CONFIG ); assertEquals( indexName2, relIndex.getName() ); assertEquals( LuceneIndexImplementation.FULLTEXT_CONFIG, graphDb.index().getConfiguration( relIndex ) ); } @Test public void testStringQueryVsQueryObject() { Index<Node> index = nodeIndex( LuceneIndexImplementation.FULLTEXT_CONFIG ); Node node = graphDb.createNode(); index.add( node, "name", "Mattias Persson" ); for ( int i = 0; i < 2; i++ ) { assertContains( index.query( "name:Mattias AND name:Per*" ), node ); assertContains( index.query( "name:mattias" ), node ); assertContains( index.query( new TermQuery( new Term( "name", "mattias" ) ) ), node ); restartTx(); } assertNull( index.query( new TermQuery( new Term( "name", "Mattias" ) ) ).getSingle() ); } @SuppressWarnings( "unchecked" ) private <T extends PropertyContainer> void testAbandonedIds( EntityCreator<T> creator, Index<T> index ) { // TODO This doesn't actually test that they are deleted, it just triggers it // so that you manually can inspect what's going on T a = creator.create(); T b = creator.create(); T c = creator.create(); String key = "name"; String value = "value"; index.add( a, key, value ); index.add( b, key, value ); index.add( c, key, value ); restartTx(); creator.delete( b ); restartTx(); IteratorUtil.count( (Iterator<Node>) index.get( key, value ) ); rollbackTx(); beginTx(); IteratorUtil.count( (Iterator<Node>) index.get( key, value ) ); index.add( c, "something", "whatever" ); restartTx(); IteratorUtil.count( (Iterator<Node>) index.get( key, value ) ); } @Test public void testAbandonedNodeIds() { testAbandonedIds( NODE_CREATOR, nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ) ); } @Test public void testAbandonedNodeIdsFulltext() { testAbandonedIds( NODE_CREATOR, nodeIndex( LuceneIndexImplementation.FULLTEXT_CONFIG ) ); } @Test public void testAbandonedRelIds() { testAbandonedIds( RELATIONSHIP_CREATOR, relationshipIndex( LuceneIndexImplementation.EXACT_CONFIG ) ); } @Test public void testAbandonedRelIdsFulltext() { testAbandonedIds( RELATIONSHIP_CREATOR, relationshipIndex( LuceneIndexImplementation.FULLTEXT_CONFIG ) ); } @Test public void makeSureYouCanRemoveFromRelationshipIndex() { Node n1 = graphDb.createNode(); Node n2 = graphDb.createNode(); Relationship r = n1.createRelationshipTo( n2, DynamicRelationshipType.withName( "foo" ) ); RelationshipIndex index = graphDb.index().forRelationships( "rel-index" ); String key = "bar"; index.remove( r, key, "value" ); index.add( r, key, "otherValue" ); for ( int i = 0; i < 2; i++ ) { assertThat( index.get( key, "value" ), isEmpty() ); assertThat( index.get( key, "otherValue" ), contains( r ) ); restartTx(); } } @Test public void makeSureYouCanGetEntityTypeFromIndex() { Index<Node> nodeIndex = nodeIndex( MapUtil.stringMap( IndexManager.PROVIDER, "lucene", "type", "exact" ) ); Index<Relationship> relIndex = relationshipIndex( MapUtil.stringMap( IndexManager.PROVIDER, "lucene", "type", "exact" ) ); assertEquals( Node.class, nodeIndex.getEntityType() ); assertEquals( Relationship.class, relIndex.getEntityType() ); } @Test public void makeSureConfigurationCanBeModified() { Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ); try { graphDb.index().setConfiguration( index, IndexManager.PROVIDER, "something" ); fail( "Shouldn't be able to modify provider" ); } catch ( IllegalArgumentException e ) { /* Good*/ } try { graphDb.index().removeConfiguration( index, IndexManager.PROVIDER ); fail( "Shouldn't be able to modify provider" ); } catch ( IllegalArgumentException e ) { /* Good*/ } String key = "my-key"; String value = "my-value"; String newValue = "my-new-value"; assertNull( graphDb.index().setConfiguration( index, key, value ) ); assertEquals( value, graphDb.index().getConfiguration( index ).get( key ) ); assertEquals( value, graphDb.index().setConfiguration( index, key, newValue ) ); assertEquals( newValue, graphDb.index().getConfiguration( index ).get( key ) ); assertEquals( newValue, graphDb.index().removeConfiguration( index, key ) ); assertNull( graphDb.index().getConfiguration( index ).get( key ) ); } @Test public void makeSureSlightDifferencesInIndexConfigCanBeSupplied() { Map<String, String> config = MapUtil.stringMap( IndexManager.PROVIDER, "lucene", "type", "fulltext" ); String name = currentIndexName(); nodeIndex( name, config ); nodeIndex( name, MapUtil.stringMap( new HashMap<>( config ), "to_lower_case", "true" ) ); try { nodeIndex( name, MapUtil.stringMap( new HashMap<>( config ), "to_lower_case", "false" ) ); fail( "Shouldn't be able to get index with these kinds of differences in config" ); } catch ( IllegalArgumentException e ) { /* */ } nodeIndex( name, MapUtil.stringMap( new HashMap<>( config ), "whatever", "something" ) ); } @Test public void testScoring() { Index<Node> index = nodeIndex( LuceneIndexImplementation.FULLTEXT_CONFIG ); Node node1 = graphDb.createNode(); Node node2 = graphDb.createNode(); String key = "text"; // Where the heck did I get this sentence from? index.add( node1, key, "a time where no one was really awake" ); index.add( node2, key, "once upon a time there was" ); restartTx(); IndexHits<Node> hits = index.query( key, new QueryContext( "once upon a time was" ).sort( Sort.RELEVANCE ) ); Node hit1 = hits.next(); float score1 = hits.currentScore(); Node hit2 = hits.next(); float score2 = hits.currentScore(); assertEquals( node2, hit1 ); assertEquals( node1, hit2 ); assertTrue( score1 > score2 ); } @Test public void testTopHits() { Index<Relationship> index = relationshipIndex( LuceneIndexImplementation.FULLTEXT_CONFIG ); EntityCreator<Relationship> creator = RELATIONSHIP_CREATOR; String key = "text"; Relationship rel1 = creator.create( key, "one two three four five six seven eight nine ten" ); Relationship rel2 = creator.create( key, "one two three four five six seven eight other things" ); Relationship rel3 = creator.create( key, "one two three four five six some thing else" ); Relationship rel4 = creator.create( key, "one two three four five what ever" ); Relationship rel5 = creator.create( key, "one two three four all that is good and bad" ); Relationship rel6 = creator.create( key, "one two three hill or something" ); Relationship rel7 = creator.create( key, "one two other time than this" ); index.add( rel2, key, rel2.getProperty( key ) ); index.add( rel1, key, rel1.getProperty( key ) ); index.add( rel3, key, rel3.getProperty( key ) ); index.add( rel7, key, rel7.getProperty( key ) ); index.add( rel5, key, rel5.getProperty( key ) ); index.add( rel4, key, rel4.getProperty( key ) ); index.add( rel6, key, rel6.getProperty( key ) ); String query = "one two three four five six seven"; for ( int i = 0; i < 2; i++ ) { assertContainsInOrder( index.query( key, new QueryContext( query ).top( 3 ).sort( Sort.RELEVANCE ) ), rel1, rel2, rel3 ); restartTx(); } } @Test public void testSimilarity() { Index<Node> index = nodeIndex( MapUtil.stringMap( IndexManager.PROVIDER, "lucene", "type", "fulltext", "similarity", DefaultSimilarity.class.getName() ) ); Node node = graphDb.createNode(); index.add( node, "key", "value" ); restartTx(); assertContains( index.get( "key", "value" ), node ); } @Test public void testCombinedHitsSizeProblem() { Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ); Node node1 = graphDb.createNode(); Node node2 = graphDb.createNode(); Node node3 = graphDb.createNode(); String key = "key"; String value = "value"; index.add( node1, key, value ); index.add( node2, key, value ); restartTx(); index.add( node3, key, value ); IndexHits<Node> hits = index.get( key, value ); assertEquals( 3, hits.size() ); } @SuppressWarnings( "unchecked" ) private <T extends PropertyContainer> void testRemoveWithoutKey( EntityCreator<T> creator, Index<T> index ) throws Exception { String key1 = "key1"; String key2 = "key2"; String value = "value"; T entity1 = creator.create(); index.add( entity1, key1, value ); index.add( entity1, key2, value ); T entity2 = creator.create(); index.add( entity2, key1, value ); index.add( entity2, key2, value ); restartTx(); assertContains( index.get( key1, value ), entity1, entity2 ); assertContains( index.get( key2, value ), entity1, entity2 ); index.remove( entity1, key2 ); assertContains( index.get( key1, value ), entity1, entity2 ); assertContains( index.get( key2, value ), entity2 ); index.add( entity1, key2, value ); for ( int i = 0; i < 2; i++ ) { assertContains( index.get( key1, value ), entity1, entity2 ); assertContains( index.get( key2, value ), entity1, entity2 ); restartTx(); } } @Test public void testRemoveWithoutKeyNodes() throws Exception { testRemoveWithoutKey( NODE_CREATOR, nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ) ); } @Test public void testRemoveWithoutKeyRelationships() throws Exception { testRemoveWithoutKey( RELATIONSHIP_CREATOR, relationshipIndex( LuceneIndexImplementation.EXACT_CONFIG ) ); } @SuppressWarnings( "unchecked" ) private <T extends PropertyContainer> void testRemoveWithoutKeyValue( EntityCreator<T> creator, Index<T> index ) throws Exception { String key1 = "key1"; String value1 = "value1"; String key2 = "key2"; String value2 = "value2"; T entity1 = creator.create(); index.add( entity1, key1, value1 ); index.add( entity1, key2, value2 ); T entity2 = creator.create(); index.add( entity2, key1, value1 ); index.add( entity2, key2, value2 ); restartTx(); assertContains( index.get( key1, value1 ), entity1, entity2 ); assertContains( index.get( key2, value2 ), entity1, entity2 ); index.remove( entity1 ); assertContains( index.get( key1, value1 ), entity2 ); assertContains( index.get( key2, value2 ), entity2 ); index.add( entity1, key1, value1 ); for ( int i = 0; i < 2; i++ ) { assertContains( index.get( key1, value1 ), entity1, entity2 ); assertContains( index.get( key2, value2 ), entity2 ); restartTx(); } } @Test public void testRemoveWithoutKeyValueNodes() throws Exception { testRemoveWithoutKeyValue( NODE_CREATOR, nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ) ); } @Test public void testRemoveWithoutKeyValueRelationships() throws Exception { testRemoveWithoutKeyValue( RELATIONSHIP_CREATOR, relationshipIndex( LuceneIndexImplementation.EXACT_CONFIG ) ); } @SuppressWarnings( "unchecked" ) private <T extends PropertyContainer> void testRemoveWithoutKeyFulltext( EntityCreator<T> creator, Index<T> index ) throws Exception { String key1 = "key1"; String key2 = "key2"; String value1 = "value one"; String value2 = "other value"; String value = "value"; T entity1 = creator.create(); index.add( entity1, key1, value1 ); index.add( entity1, key2, value1 ); index.add( entity1, key2, value2 ); T entity2 = creator.create(); index.add( entity2, key1, value1 ); index.add( entity2, key2, value1 ); index.add( entity2, key2, value2 ); restartTx(); assertContains( index.query( key1, value ), entity1, entity2 ); assertContains( index.query( key2, value ), entity1, entity2 ); index.remove( entity1, key2 ); assertContains( index.query( key1, value ), entity1, entity2 ); assertContains( index.query( key2, value ), entity2 ); index.add( entity1, key2, value1 ); for ( int i = 0; i < 2; i++ ) { assertContains( index.query( key1, value ), entity1, entity2 ); assertContains( index.query( key2, value ), entity1, entity2 ); restartTx(); } } @Test public void testRemoveWithoutKeyFulltextNode() throws Exception { testRemoveWithoutKeyFulltext( NODE_CREATOR, nodeIndex( LuceneIndexImplementation.FULLTEXT_CONFIG ) ); } @Test public void testRemoveWithoutKeyFulltextRelationship() throws Exception { testRemoveWithoutKeyFulltext( RELATIONSHIP_CREATOR, relationshipIndex( LuceneIndexImplementation.FULLTEXT_CONFIG ) ); } @SuppressWarnings( "unchecked" ) private <T extends PropertyContainer> void testRemoveWithoutKeyValueFulltext( EntityCreator<T> creator, Index<T> index ) throws Exception { String value = "value"; String key1 = "key1"; String value1 = value + " one"; String key2 = "key2"; String value2 = value + " two"; T entity1 = creator.create(); index.add( entity1, key1, value1 ); index.add( entity1, key2, value2 ); T entity2 = creator.create(); index.add( entity2, key1, value1 ); index.add( entity2, key2, value2 ); restartTx(); assertContains( index.query( key1, value ), entity1, entity2 ); assertContains( index.query( key2, value ), entity1, entity2 ); index.remove( entity1 ); assertContains( index.query( key1, value ), entity2 ); assertContains( index.query( key2, value ), entity2 ); index.add( entity1, key1, value1 ); for ( int i = 0; i < 2; i++ ) { assertContains( index.query( key1, value ), entity1, entity2 ); assertContains( index.query( key2, value ), entity2 ); restartTx(); } } @Test public void testRemoveWithoutKeyValueFulltextNode() throws Exception { testRemoveWithoutKeyValueFulltext( NODE_CREATOR, nodeIndex( LuceneIndexImplementation.FULLTEXT_CONFIG ) ); } @Test public void testRemoveWithoutKeyValueFulltextRelationship() throws Exception { testRemoveWithoutKeyValueFulltext( RELATIONSHIP_CREATOR, relationshipIndex( LuceneIndexImplementation.FULLTEXT_CONFIG ) ); } @Test public void testSortingWithTopHitsInPartCommittedPartLocal() { Index<Node> index = nodeIndex( LuceneIndexImplementation.FULLTEXT_CONFIG ); Node first = graphDb.createNode(); Node second = graphDb.createNode(); Node third = graphDb.createNode(); Node fourth = graphDb.createNode(); String key = "key"; index.add( third, key, "ccc" ); index.add( second, key, "bbb" ); restartTx(); index.add( fourth, key, "ddd" ); index.add( first, key, "aaa" ); assertContainsInOrder( index.query( key, new QueryContext( "*" ).sort( key ) ), first, second, third, fourth ); assertContainsInOrder( index.query( key, new QueryContext( "*" ).sort( key ).top( 2 ) ), first, second ); } @Test public void shouldNotFindValueDeletedInSameTx() { Index<Node> nodeIndex = graphDb.index().forNodes( "size-after-removal" ); Node node = graphDb.createNode(); nodeIndex.add( node, "key", "value" ); restartTx(); nodeIndex.remove( node ); for ( int i = 0; i < 2; i++ ) { IndexHits<Node> hits = nodeIndex.get( "key", "value" ); assertEquals( 0, hits.size() ); assertNull( hits.getSingle() ); hits.close(); restartTx(); } } @Test public void notAbleToIndexWithForbiddenKey() throws Exception { Index<Node> index = graphDb.index().forNodes( "check-for-null" ); Node node = graphDb.createNode(); try { index.add( node, null, "not allowed" ); fail( "Shouldn't be able to index something with null key" ); } catch ( IllegalArgumentException e ) { // OK } try { index.add( node, "_id_", "not allowed" ); fail( "Shouldn't be able to index something with null key" ); } catch ( IllegalArgumentException e ) { // OK } } private Node createAndIndexNode( Index<Node> index, String key, String value ) { Node node = graphDb.createNode(); node.setProperty( key, value ); index.add( node, key, value ); return node; } @Test public void testRemoveNodeFromIndex() { Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ); String key = "key"; String value = "MYID"; Node node = createAndIndexNode( index, key, value ); index.remove( node ); node.delete(); Node node2 = createAndIndexNode( index, key, value ); assertEquals( node2, index.get( key, value ).getSingle() ); } @Test public void canQueryWithWildcardEvenIfAlternativeRemovalMethodsUsedInSameTx1() throws Exception { Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ); Node node = graphDb.createNode(); index.add( node, "key", "value" ); restartTx(); index.remove( node, "key" ); assertNull( index.query( "key", "v*" ).getSingle() ); assertNull( index.query( "key", "*" ).getSingle() ); } @Test public void canQueryWithWildcardEvenIfAlternativeRemovalMethodsUsedInSameTx2() throws Exception { Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ); Node node = graphDb.createNode(); index.add( node, "key", "value" ); restartTx(); index.remove( node ); assertNull( index.query( "key", "v*" ).getSingle() ); assertNull( index.query( "key", "*" ).getSingle() ); } @Ignore( "TODO Exposes a bug. Fixed in Lucene 3.4.0" ) @Test public void updateIndex() throws Exception { String TEXT = "text"; String NUMERIC = "numeric"; String TEXT_1 = "text_1"; Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ); Node n = graphDb.createNode(); index.add(n, NUMERIC, new ValueContext(5).indexNumeric()); index.add(n, TEXT, "text"); index.add(n, TEXT_1, "text"); commitTx(); assertNotNull( index.query(QueryContext.numericRange(NUMERIC, 5, 5, true, true)).getSingle() ); assertNotNull( index.get(TEXT_1, "text").getSingle() ); beginTx(); // Following line may be commented, it's addition of node that causes the problem index.remove(n, TEXT, "text"); index.add(n, TEXT, "text 1"); commitTx(); assertNotNull( index.get(TEXT_1, "text").getSingle() ); // Test fails here assertNotNull( index.query(QueryContext.numericRange(NUMERIC, 5, 5, true, true)).getSingle() ); } @Test public void exactIndexWithCaseInsensitive() throws Exception { Index<Node> index = nodeIndex( stringMap( "analyzer", LowerCaseKeywordAnalyzer.class.getName() ) ); Node node = graphDb.createNode(); index.add( node, "name", "Thomas Anderson" ); assertContains( index.query( "name", "\"Thomas Anderson\"" ), node ); assertContains( index.query( "name", "\"thoMas ANDerson\"" ), node ); restartTx(); assertContains( index.query( "name", "\"Thomas Anderson\"" ), node ); assertContains( index.query( "name", "\"thoMas ANDerson\"" ), node ); } @Test public void exactIndexWithCaseInsensitiveWithBetterConfig() throws Exception { // START SNIPPET: exact-case-insensitive Index<Node> index = graphDb.index().forNodes( "exact-case-insensitive", stringMap( "type", "exact", "to_lower_case", "true" ) ); Node node = graphDb.createNode(); index.add( node, "name", "Thomas Anderson" ); assertContains( index.query( "name", "\"Thomas Anderson\"" ), node ); assertContains( index.query( "name", "\"thoMas ANDerson\"" ), node ); // END SNIPPET: exact-case-insensitive restartTx(); assertContains( index.query( "name", "\"Thomas Anderson\"" ), node ); assertContains( index.query( "name", "\"thoMas ANDerson\"" ), node ); } @Test public void notAbleToRemoveWithForbiddenKey() throws Exception { Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ); Node node = graphDb.createNode(); index.add( node, "name", "Mattias" ); restartTx(); try { index.remove( node, null ); fail( "Shouldn't be able to" ); } catch ( IllegalArgumentException e ) { // OK } try { index.remove( node, "_id_" ); fail( "Shouldn't be able to" ); } catch ( IllegalArgumentException e ) { // OK } } @Ignore( "an issue that should be fixed at some point" ) @Test( expected = NotFoundException.class ) public void shouldNotBeAbleToIndexNodeThatIsNotCommitted() throws Exception { Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ); Node node = graphDb.createNode(); String key = "noob"; String value = "Johan"; WorkThread thread = new WorkThread( "other thread", index, graphDb, node ); thread.beginTransaction(); try { thread.add( node, key, value ); } finally { thread.rollback(); } } @Test public void putIfAbsentSingleThreaded() { Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ); Node node = graphDb.createNode(); String key = "name"; String value = "Mattias"; String value2 = "Persson"; assertNull( index.putIfAbsent( node, key, value ) ); assertEquals( node, index.get( key, value ).getSingle() ); assertNotNull( index.putIfAbsent( node, key, value ) ); assertNull( index.putIfAbsent( node, key, value2 ) ); assertNotNull( index.putIfAbsent( node, key, value2 ) ); restartTx(); assertNotNull( index.putIfAbsent( node, key, value ) ); assertNotNull( index.putIfAbsent( node, key, value2 ) ); assertEquals( node, index.get( key, value ).getSingle() ); } @Test public void putIfAbsentMultiThreaded() throws Exception { Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ); Node node = graphDb.createNode(); commitTx(); String key = "name"; String value = "Mattias"; WorkThread t1 = new WorkThread( "t1", index, graphDb, node ); WorkThread t2 = new WorkThread( "t2", index, graphDb, node ); t1.beginTransaction(); t2.beginTransaction(); assertNull( t2.putIfAbsent( node, key, value ).get() ); Future<Node> futurePut = t1.putIfAbsent( node, key, value ); t1.waitUntilWaiting(); t2.commit(); assertNotNull( futurePut.get() ); t1.commit(); t1.close(); t2.close(); Transaction transaction = graphDb.beginTx(); assertEquals( node, index.get( key, value ).getSingle() ); transaction.finish(); } @Test public void putIfAbsentOnOtherValueInOtherThread() throws Exception { Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ); Node node = graphDb.createNode(); commitTx(); String key = "name"; String value = "Mattias"; String otherValue = "Tobias"; WorkThread t1 = new WorkThread( "t1", index, graphDb, node ); WorkThread t2 = new WorkThread( "t2", index, graphDb, node ); t1.beginTransaction(); t2.beginTransaction(); assertNull( t2.putIfAbsent( node, key, value ).get() ); Future<Node> futurePut = t1.putIfAbsent( node, key, otherValue ); t2.commit(); assertNull( futurePut.get() ); t1.commit(); t1.close(); t2.close(); Transaction transaction = graphDb.beginTx(); assertEquals( node, index.get( key, value ).getSingle() ); assertEquals( node, index.get( key, otherValue ).getSingle() ); transaction.finish(); } @Test public void putIfAbsentOnOtherKeyInOtherThread() throws Exception { Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ); Node node = graphDb.createNode(); commitTx(); String key = "name"; String otherKey = "friend"; String value = "Mattias"; WorkThread t1 = new WorkThread( "t1", index, graphDb, node ); WorkThread t2 = new WorkThread( "t2", index, graphDb, node ); t1.beginTransaction(); t2.beginTransaction(); assertNull( t2.putIfAbsent( node, key, value ).get() ); assertNull( t1.putIfAbsent( node, otherKey, value ).get() ); t2.commit(); t1.commit(); t1.close(); t2.close(); Transaction transaction = graphDb.beginTx(); assertEquals( node, index.get( key, value ).getSingle() ); assertEquals( node, index.get( otherKey, value ).getSingle() ); transaction.finish(); } @Test public void putIfAbsentShouldntBlockIfNotAbsent() throws Exception { Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ); Node node = graphDb.createNode(); String key = "key"; String value = "value"; index.add( node, key, value ); restartTx(); WorkThread otherThread = new WorkThread( "other thread", index, graphDb, node ); otherThread.beginTransaction(); // Should not grab lock index.putIfAbsent( node, key, value ); // Should be able to complete right away assertNotNull( otherThread.putIfAbsent( node, key, value ).get() ); otherThread.commit(); commitTx(); otherThread.close(); } @Test public void getOrCreateNodeWithUniqueFactory() throws Exception { final String key = "name"; final String value = "Mattias"; final String property = "counter"; final Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ); final AtomicInteger counter = new AtomicInteger(); UniqueFactory<Node> factory = new UniqueFactory.UniqueNodeFactory( index ) { @Override protected void initialize( Node node, Map<String, Object> properties ) { assertEquals( value, properties.get( key ) ); assertEquals( 1, properties.size() ); node.setProperty( property, counter.getAndIncrement() ); } }; Node unique = factory.getOrCreate( key, value ); assertNotNull( unique ); assertEquals( "not initialized", 0, unique.getProperty( property, null ) ); assertEquals( unique, index.get( key, value ).getSingle() ); assertEquals( unique, factory.getOrCreate( key, value ) ); assertEquals( "initialized more than once", 0, unique.getProperty( property ) ); assertEquals( unique, index.get( key, value ).getSingle() ); finishTx( false ); } @Test public void getOrCreateRelationshipWithUniqueFactory() throws Exception { final String key = "name"; final String value = "Mattias"; final Node root = graphDb.createNode(); final Index<Relationship> index = relationshipIndex( LuceneIndexImplementation.EXACT_CONFIG ); final DynamicRelationshipType type = DynamicRelationshipType.withName( "SINGLE" ); UniqueFactory<Relationship> factory = new UniqueFactory.UniqueRelationshipFactory( index ) { @Override protected Relationship create( Map<String, Object> properties ) { assertEquals( value, properties.get( key ) ); assertEquals( 1, properties.size() ); return root.createRelationshipTo( graphDatabase().createNode(), type ); } }; Relationship unique = factory.getOrCreate( key, value ); assertEquals( unique, root.getSingleRelationship( type, Direction.BOTH ) ); assertNotNull( unique ); assertEquals( unique, index.get( key, value ).getSingle() ); assertEquals( unique, factory.getOrCreate( key, value ) ); assertEquals( unique, root.getSingleRelationship( type, Direction.BOTH ) ); assertEquals( unique, index.get( key, value ).getSingle() ); finishTx( false ); } @Test public void getOrCreateMultiThreaded() throws Exception { Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ); String key = "name"; String value = "Mattias"; WorkThread t1 = new WorkThread( "t1", index, graphDb, null ); WorkThread t2 = new WorkThread( "t2", index, graphDb, null ); t1.beginTransaction(); t2.beginTransaction(); Node node = t2.getOrCreate( key, value, 0 ).get(); assertNotNull( node ); assertEquals( 0, t2.getProperty( node, key ) ); Future<Node> futurePut = t1.getOrCreate( key, value, 1 ); t1.waitUntilWaiting(); t2.commit(); assertEquals( node, futurePut.get() ); assertEquals( 0, t1.getProperty( node, key ) ); t1.commit(); assertEquals( node, index.get( key, value ).getSingle() ); t1.close(); t2.close(); } @Test public void useStandardAnalyzer() throws Exception { Index<Node> index = nodeIndex( stringMap( "analyzer", MyStandardAnalyzer.class.getName() ) ); Node node = graphDb.createNode(); index.add( node, "name", "Mattias" ); } @Test public void numericValueForGetInExactIndex() throws Exception { Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ); numericValueForGet( index ); } @Test public void numericValueForGetInFulltextIndex() throws Exception { Index<Node> index = nodeIndex( LuceneIndexImplementation.FULLTEXT_CONFIG ); numericValueForGet( index ); } private void numericValueForGet( Index<Node> index ) { Node node = graphDb.createNode(); long id = 100L; index.add( node, "name", ValueContext.numeric( id ) ); assertEquals( node, index.get( "name", ValueContext.numeric( id ) ).getSingle() ); restartTx(); assertEquals( node, index.get( "name", ValueContext.numeric( id ) ).getSingle() ); } @Test public void combinedNumericalQuery() throws Exception { Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG ); Node node = graphDb.createNode(); index.add( node, "start", ValueContext.numeric( 10 ) ); index.add( node, "end", ValueContext.numeric( 20 ) ); restartTx(); BooleanQuery q = new BooleanQuery(); q.add( LuceneUtil.rangeQuery( "start", 9, null, true, true ), Occur.MUST ); q.add( LuceneUtil.rangeQuery( "end", null, 30, true, true ), Occur.MUST ); assertContains( index.query( q ), node ); } @Test public void failureToCreateAnIndexShouldNotLeaveConfiguratiobBehind() throws Exception { // WHEN try { // StandardAnalyzer is invalid since it has no publi no-arg constructor nodeIndex( stringMap( "analyzer", StandardAnalyzer.class.getName() ) ); fail( "Should have failed" ); } catch ( RuntimeException e ) { assertThat( e.getMessage(), CoreMatchers.containsString( StandardAnalyzer.class.getName() ) ); } // THEN - assert that there's no index config about this index left behind assertFalse( "There should be no index config for index '" + currentIndexName() + "' left behind", ((GraphDatabaseAPI)graphDb).getDependencyResolver().resolveDependency( IndexStore.class ).has( Node.class, currentIndexName() ) ); } @Test public void shouldBeAbleToQueryAllMatchingDocsAfterRemovingWithWildcard() throws Exception { // GIVEN Index<Node> index = nodeIndex( EXACT_CONFIG ); Node node1 = graphDb.createNode(); index.add( node1, "name", "Mattias" ); finishTx( true ); beginTx(); // WHEN index.remove( node1, "name" ); Set<Node> nodes = asSet( (Iterable<Node>) index.query( "*:*" ) ); // THEN assertEquals( asSet(), nodes ); } }
false
community_lucene-index_src_test_java_org_neo4j_index_impl_lucene_TestLuceneIndex.java
5,896
public class TestLuceneDataSource { private final FileSystemAbstraction fileSystem = new DefaultFileSystemAbstraction(); private IndexStore indexStore; private LuceneDataSource dataSource; File dbPath = getDbPath(); private File getDbPath() { return new File("target/var/datasource" + System.currentTimeMillis()); } @Before public void setup() { dbPath.mkdirs(); indexStore = new IndexStore( dbPath, new DefaultFileSystemAbstraction() ); addIndex( "foo" ); } private void addIndex( String name ) { indexStore.set( Node.class, name, MapUtil.stringMap( IndexManager.PROVIDER, "lucene", "type", "fulltext" ) ); } private IndexIdentifier identifier( String name ) { return new IndexIdentifier( LuceneCommand.NODE, dataSource.nodeEntityType, name ); } @After public void teardown() throws IOException { dataSource.stop(); FileUtils.deleteRecursively( dbPath ); } @Test public void testShouldReturnIndexWriterFromLRUCache() throws InstantiationException { Config config = new Config( config(), GraphDatabaseSettings.class ); dataSource = new LuceneDataSource( config, indexStore, new DefaultFileSystemAbstraction(), new XaFactory( config, TxIdGenerator.DEFAULT, new PlaceboTm( null, null ), new DefaultFileSystemAbstraction(), new Monitors(), new DevNullLoggingService(), RecoveryVerifier.ALWAYS_VALID, LogPruneStrategies.NO_PRUNING, mock( KernelHealth.class ) ), null ); dataSource.start(); IndexIdentifier identifier = identifier( "foo" ); IndexWriter writer = dataSource.getIndexSearcher( identifier ).getWriter(); assertSame( writer, dataSource.getIndexSearcher( identifier ).getWriter() ); } @Test public void testShouldReturnIndexSearcherFromLRUCache() throws InstantiationException, IOException { Config config = new Config( config(), GraphDatabaseSettings.class ); dataSource = new LuceneDataSource( config, indexStore, new DefaultFileSystemAbstraction(), new XaFactory( config, TxIdGenerator.DEFAULT, new PlaceboTm( null, null ), new DefaultFileSystemAbstraction(), new Monitors(), new DevNullLoggingService(), RecoveryVerifier.ALWAYS_VALID, LogPruneStrategies.NO_PRUNING, mock( KernelHealth.class ) ), null ); dataSource.start(); IndexIdentifier identifier = identifier( "foo" ); IndexReference searcher = dataSource.getIndexSearcher( identifier ); assertSame( searcher, dataSource.getIndexSearcher( identifier ) ); searcher.close(); } @Test public void testClosesOldestIndexWriterWhenCacheSizeIsExceeded() throws InstantiationException { addIndex( "bar" ); addIndex( "baz" ); Map<String, String> config = config(); config.put( GraphDatabaseSettings.lucene_searcher_cache_size.name(), "2" ); Config config1 = new Config( config, GraphDatabaseSettings.class ); dataSource = new LuceneDataSource( config1, indexStore, new DefaultFileSystemAbstraction(), new XaFactory( config1, TxIdGenerator.DEFAULT, new PlaceboTm( null, null ), new DefaultFileSystemAbstraction(), new Monitors(), new DevNullLoggingService(), RecoveryVerifier.ALWAYS_VALID, LogPruneStrategies.NO_PRUNING, mock( KernelHealth.class ) ), null ); dataSource.start(); IndexIdentifier fooIdentifier = identifier( "foo" ); IndexIdentifier barIdentifier = identifier( "bar" ); IndexIdentifier bazIdentifier = identifier( "baz" ); IndexWriter fooIndexWriter = dataSource.getIndexSearcher( fooIdentifier ).getWriter(); dataSource.getIndexSearcher( barIdentifier ); assertFalse( IndexWriterAccessor.isClosed( fooIndexWriter ) ); dataSource.getIndexSearcher( bazIdentifier ); assertTrue( IndexWriterAccessor.isClosed( fooIndexWriter ) ); } @Test public void testClosesOldestIndexSearcherWhenCacheSizeIsExceeded() throws InstantiationException, IOException { addIndex( "bar" ); addIndex( "baz" ); Map<String, String> config = config(); config.put( GraphDatabaseSettings.lucene_searcher_cache_size.name(), "2" ); Config config1 = new Config( config, GraphDatabaseSettings.class ); dataSource = new LuceneDataSource( config1, indexStore, new DefaultFileSystemAbstraction(), new XaFactory( config1, TxIdGenerator.DEFAULT, new PlaceboTm( null, null ), fileSystem, new Monitors(), new DevNullLoggingService(), RecoveryVerifier.ALWAYS_VALID, LogPruneStrategies.NO_PRUNING, mock( KernelHealth.class ) ), null ); dataSource.start(); IndexIdentifier fooIdentifier = identifier( "foo" ); IndexIdentifier barIdentifier = identifier( "bar" ); IndexIdentifier bazIdentifier = identifier( "baz" ); IndexReference fooSearcher = dataSource.getIndexSearcher( fooIdentifier ); IndexReference barSearcher = dataSource.getIndexSearcher( barIdentifier ); assertFalse( fooSearcher.isClosed() ); IndexReference bazSearcher = dataSource.getIndexSearcher( bazIdentifier ); assertTrue( fooSearcher.isClosed() ); barSearcher.close(); bazSearcher.close(); } @Test public void testRecreatesSearcherWhenRequestedAgain() throws InstantiationException, IOException { addIndex( "bar" ); addIndex( "baz" ); Map<String, String> config = config(); config.put( GraphDatabaseSettings.lucene_searcher_cache_size.name(), "2" ); Config config1 = new Config( config, GraphDatabaseSettings.class ); dataSource = new LuceneDataSource( config1, indexStore, new DefaultFileSystemAbstraction(), new XaFactory( config1, TxIdGenerator.DEFAULT, new PlaceboTm( null, null ), new DefaultFileSystemAbstraction(), new Monitors(), new DevNullLoggingService(), RecoveryVerifier.ALWAYS_VALID, LogPruneStrategies.NO_PRUNING, mock( KernelHealth.class ) ), null ); dataSource.start(); IndexIdentifier fooIdentifier = identifier( "foo" ); IndexIdentifier barIdentifier = identifier( "bar" ); IndexIdentifier bazIdentifier = identifier( "baz" ); IndexReference oldFooSearcher = dataSource.getIndexSearcher( fooIdentifier ); IndexReference barSearcher = dataSource.getIndexSearcher( barIdentifier ); IndexReference bazSearcher = dataSource.getIndexSearcher( bazIdentifier ); IndexReference newFooSearcher = dataSource.getIndexSearcher( bazIdentifier ); assertNotSame( oldFooSearcher, newFooSearcher ); assertFalse( newFooSearcher.isClosed() ); oldFooSearcher.close(); barSearcher.close(); bazSearcher.close(); newFooSearcher.close(); } @Test public void testRecreatesWriterWhenRequestedAgainAfterCacheEviction() throws InstantiationException { addIndex( "bar" ); addIndex( "baz" ); Map<String, String> config = config(); config.put( GraphDatabaseSettings.lucene_searcher_cache_size.name(), "2" ); Config config1 = new Config( config, GraphDatabaseSettings.class ); dataSource = new LuceneDataSource( config1, indexStore, new DefaultFileSystemAbstraction(), new XaFactory( config1, TxIdGenerator.DEFAULT, new PlaceboTm( null, null ), new DefaultFileSystemAbstraction(), new Monitors(), new DevNullLoggingService(), RecoveryVerifier.ALWAYS_VALID, LogPruneStrategies.NO_PRUNING, mock( KernelHealth.class ) ), null ); dataSource.start(); IndexIdentifier fooIdentifier = identifier( "foo" ); IndexIdentifier barIdentifier = identifier( "bar" ); IndexIdentifier bazIdentifier = identifier( "baz" ); IndexWriter oldFooIndexWriter = dataSource.getIndexSearcher( fooIdentifier ).getWriter(); dataSource.getIndexSearcher( barIdentifier ); dataSource.getIndexSearcher( bazIdentifier ); IndexWriter newFooIndexWriter = dataSource.getIndexSearcher( fooIdentifier ).getWriter(); assertNotSame( oldFooIndexWriter, newFooIndexWriter ); assertFalse( IndexWriterAccessor.isClosed( newFooIndexWriter ) ); } @Ignore("No longer valid since Lucene 3.5") @Test public void testInvalidatingSearcherCreatesANewOne() throws InstantiationException, IOException { Config config = new Config( config(), GraphDatabaseSettings.class ); dataSource = new LuceneDataSource( config, indexStore, new DefaultFileSystemAbstraction(), new XaFactory( config, TxIdGenerator.DEFAULT, new PlaceboTm( null, null ), new DefaultFileSystemAbstraction(), new Monitors(), new DevNullLoggingService(), RecoveryVerifier.ALWAYS_VALID, LogPruneStrategies.NO_PRUNING, mock( KernelHealth.class ) ), null ); dataSource.start(); IndexIdentifier identifier = new IndexIdentifier( LuceneCommand.NODE, dataSource.nodeEntityType, "foo" ); IndexReference oldSearcher = dataSource.getIndexSearcher( identifier ); dataSource.invalidateIndexSearcher( identifier ); IndexReference newSearcher = dataSource.getIndexSearcher( identifier ); assertNotSame( oldSearcher, newSearcher ); assertTrue( oldSearcher.isClosed() ); assertFalse( newSearcher.isClosed() ); assertNotSame( oldSearcher.getSearcher(), newSearcher.getSearcher() ); newSearcher.close(); } private Map<String, String> config() { return MapUtil.stringMap("store_dir", getDbPath().getPath() ); } }
false
community_lucene-index_src_test_java_org_neo4j_index_impl_lucene_TestLuceneDataSource.java
5,897
public class TestIndexNames { private static GraphDatabaseService graphDb; private Transaction tx; @BeforeClass public static void setUpStuff() { graphDb = new TestGraphDatabaseFactory().newImpermanentDatabase(); } @AfterClass public static void tearDownStuff() { graphDb.shutdown(); } @After public void commitTx() { finishTx( true ); } public void finishTx( boolean success ) { if ( tx != null ) { if ( success ) { tx.success(); } tx.finish(); tx = null; } } public void beginTx() { if ( tx == null ) { tx = graphDb.beginTx(); } } void restartTx() { finishTx( true ); beginTx(); } @Test public void makeSureIndexNamesCanBeRead() { beginTx(); assertEquals( 0, graphDb.index().nodeIndexNames().length ); String name1 = "my-index-1"; Index<Node> nodeIndex1 = graphDb.index().forNodes( name1 ); assertContains( Arrays.asList( graphDb.index().nodeIndexNames() ), name1 ); String name2 = "my-index-2"; graphDb.index().forNodes( name2 ); assertContains( Arrays.asList( graphDb.index().nodeIndexNames() ), name1, name2 ); graphDb.index().forRelationships( name1 ); assertContains( Arrays.asList( graphDb.index().nodeIndexNames() ), name1, name2 ); assertContains( Arrays.asList( graphDb.index().relationshipIndexNames() ), name1 ); finishTx( true ); restartTx(); assertContains( Arrays.asList( graphDb.index().nodeIndexNames() ), name1, name2 ); assertContains( Arrays.asList( graphDb.index().relationshipIndexNames() ), name1 ); nodeIndex1.delete(); assertContains( Arrays.asList( graphDb.index().nodeIndexNames() ), name1, name2 ); assertContains( Arrays.asList( graphDb.index().relationshipIndexNames() ), name1 ); finishTx( true ); beginTx(); assertContains( Arrays.asList( graphDb.index().nodeIndexNames() ), name2 ); assertContains( Arrays.asList( graphDb.index().relationshipIndexNames() ), name1 ); finishTx( false ); } }
false
community_lucene-index_src_test_java_org_neo4j_index_impl_lucene_TestIndexNames.java
5,898
private static class ReadData implements Task { @Override public void run( GraphDatabaseAPI graphdb ) { try(Transaction ignored = graphdb.beginTx()) { Node node = graphdb.index().forNodes( "nodes" ).get( "value", "present" ).getSingle(); assertNotNull( "did not get the node from the index", node ); assertEquals( "present", node.getProperty( "value" ) ); } resumeThread(); } }
false
community_neo4j_src_test_java_visibility_TestPropertyReadOnNewEntityBeforeLockRelease.java
5,899
protected interface Representation<T> { String represent( T item ); }
false
community_graph-algo_src_test_java_common_AbstractTestBase.java