Unnamed: 0
int64 0
6.7k
| func
stringlengths 12
89.6k
| target
bool 2
classes | project
stringlengths 45
151
|
|---|---|---|---|
400
|
public class LegacyPropertyIndexStoreReader implements Closeable
{
public static final String FROM_VERSION = "PropertyIndexStore " + LegacyStore.LEGACY_VERSION;
public static final int RECORD_SIZE = 9;
private final StoreChannel fileChannel;
private final LegacyDynamicStringStoreReader nameStoreReader;
private final long maxId;
public LegacyPropertyIndexStoreReader( FileSystemAbstraction fs, File file ) throws IOException
{
fileChannel = fs.open( file, "r" );
int endHeaderSize = UTF8.encode( FROM_VERSION ).length;
maxId = (fileChannel.size() - endHeaderSize) / RECORD_SIZE;
nameStoreReader = new LegacyDynamicStringStoreReader( fs, new File( file.getPath() + KEYS_PART ),
"StringPropertyStore" );
}
public Token[] readTokens() throws IOException
{
ByteBuffer buffer = ByteBuffer.wrap( new byte[RECORD_SIZE] );
Collection<Token> tokens = new ArrayList<Token>();
for ( long id = 0; id < maxId; id++ )
{
readIntoBuffer( fileChannel, buffer, RECORD_SIZE );
byte inUseByte = buffer.get();
boolean inUse = (inUseByte == Record.IN_USE.byteValue());
if ( inUseByte != Record.IN_USE.byteValue() && inUseByte != Record.NOT_IN_USE.byteValue() )
{
throw new InvalidRecordException( "Record[" + id + "] unknown in use flag[" + inUse + "]" );
}
if ( !inUse )
{
continue;
}
buffer.getInt(); // unused "property count"
int nameId = buffer.getInt();
String name = nameStoreReader.readDynamicString( nameId );
tokens.add( new Token( name, (int) id ) );
}
return tokens.toArray( new Token[tokens.size()] );
}
@Override
public void close() throws IOException
{
nameStoreReader.close();
fileChannel.close();
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_storemigration_legacystore_LegacyPropertyIndexStoreReader.java
|
401
|
{
long id = 0;
ByteBuffer buffer = allocateDirect( RECORD_SIZE );
@Override
protected NodeRecord fetchNextOrNull()
{
NodeRecord nodeRecord = null;
while ( nodeRecord == null && id <= maxId )
{
readIntoBuffer( fileChannel, buffer, RECORD_SIZE );
long inUseByte = buffer.get();
boolean inUse = (inUseByte & 0x1) == Record.IN_USE.intValue();
if ( inUse )
{
long nextRel = LegacyStore.getUnsignedInt( buffer );
long relModifier = (inUseByte & 0xEL) << 31;
long nextProp = LegacyStore.getUnsignedInt( buffer );
long propModifier = (inUseByte & 0xF0L) << 28;
nodeRecord = new NodeRecord( id, longFromIntAndMod( nextRel, relModifier ), longFromIntAndMod( nextProp, propModifier ) );
}
else nodeRecord = new NodeRecord( id, Record.NO_NEXT_RELATIONSHIP.intValue(), Record.NO_NEXT_PROPERTY.intValue() );
nodeRecord.setInUse( inUse );
id++;
}
return nodeRecord;
}
@Override
public void remove()
{
throw new UnsupportedOperationException();
}
};
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_storemigration_legacystore_LegacyNodeStoreReader.java
|
402
|
public class LegacyNodeStoreReader implements Closeable
{
public static final String FROM_VERSION = "NodeStore " + LegacyStore.LEGACY_VERSION;
public static final int RECORD_SIZE = 9;
private final StoreChannel fileChannel;
private final long maxId;
public LegacyNodeStoreReader( FileSystemAbstraction fs, File fileName ) throws IOException
{
fileChannel = fs.open( fileName, "r" );
int endHeaderSize = UTF8.encode( FROM_VERSION ).length;
maxId = (fileChannel.size() - endHeaderSize) / RECORD_SIZE;
}
public long getMaxId()
{
return maxId;
}
public Iterator<NodeRecord> readNodeStore() throws IOException
{
return new PrefetchingIterator<NodeRecord>()
{
long id = 0;
ByteBuffer buffer = allocateDirect( RECORD_SIZE );
@Override
protected NodeRecord fetchNextOrNull()
{
NodeRecord nodeRecord = null;
while ( nodeRecord == null && id <= maxId )
{
readIntoBuffer( fileChannel, buffer, RECORD_SIZE );
long inUseByte = buffer.get();
boolean inUse = (inUseByte & 0x1) == Record.IN_USE.intValue();
if ( inUse )
{
long nextRel = LegacyStore.getUnsignedInt( buffer );
long relModifier = (inUseByte & 0xEL) << 31;
long nextProp = LegacyStore.getUnsignedInt( buffer );
long propModifier = (inUseByte & 0xF0L) << 28;
nodeRecord = new NodeRecord( id, longFromIntAndMod( nextRel, relModifier ), longFromIntAndMod( nextProp, propModifier ) );
}
else nodeRecord = new NodeRecord( id, Record.NO_NEXT_RELATIONSHIP.intValue(), Record.NO_NEXT_PROPERTY.intValue() );
nodeRecord.setInUse( inUse );
id++;
}
return nodeRecord;
}
@Override
public void remove()
{
throw new UnsupportedOperationException();
}
};
}
@Override
public void close() throws IOException
{
fileChannel.close();
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_storemigration_legacystore_LegacyNodeStoreReader.java
|
403
|
public class LegacyDynamicStringStoreReader
{
private final int blockSize;
private final StoreChannel fileChannel;
private final ByteBuffer blockBuffer;
private ByteBuffer chainBuffer;
public LegacyDynamicStringStoreReader( FileSystemAbstraction fs, File fileName, String fromVersion )
throws IOException
{
// Read version and block size (stored in the first record in the store)
fileChannel = fs.open( fileName, "r" );
long fileSize = fileChannel.size();
byte version[] = new byte[UTF8.encode( fromVersion ).length];
ByteBuffer buffer = ByteBuffer.wrap( version );
fileChannel.position( fileSize - version.length );
fileChannel.read( buffer );
buffer = ByteBuffer.allocate( 4 );
fileChannel.position( 0 );
fileChannel.read( buffer );
buffer.flip();
blockSize = buffer.getInt();
blockBuffer = ByteBuffer.allocate( blockSize );
chainBuffer = ByteBuffer.wrap( new byte[blockSize*3] ); // just a default, will grow on demand
}
public String readDynamicString( long startRecordId ) throws IOException
{
long blockId = startRecordId;
chainBuffer.clear();
while ( blockId != Record.NO_NEXT_BLOCK.intValue() )
{
fileChannel.position( blockId*blockSize );
readIntoBuffer( fileChannel, blockBuffer, blockSize );
ensureChainBufferBigEnough();
blockId = readRecord( blockId, blockBuffer );
}
return UTF8.decode( chainBuffer.array(), 0, chainBuffer.position() );
}
private void ensureChainBufferBigEnough()
{
if ( chainBuffer.remaining() < blockSize )
{
byte[] extendedBuffer = new byte[chainBuffer.capacity()*2];
System.arraycopy( chainBuffer.array(), 0, extendedBuffer, 0, chainBuffer.capacity() );
chainBuffer = ByteBuffer.wrap( extendedBuffer );
}
}
private long readRecord( long blockId, ByteBuffer recordData )
{
/*
* First 4b
* [x , ][ , ][ , ][ , ] 0: start record, 1: linked record
* [ x, ][ , ][ , ][ , ] inUse
* [ ,xxxx][ , ][ , ][ , ] high next block bits
* [ , ][xxxx,xxxx][xxxx,xxxx][xxxx,xxxx] nr of bytes in the data field in this record
*
*/
long firstInteger = getUnsignedInt( recordData );
long maskedInteger = firstInteger & ~0x80000000;
int highNibbleInMaskedInteger = (int) ( ( maskedInteger ) >> 28 );
boolean inUse = highNibbleInMaskedInteger == Record.IN_USE.intValue();
if ( !inUse )
{
throw new InvalidRecordException( "DynamicRecord not in use, blockId[" + blockId + "]" );
}
int nrOfBytes = (int) ( firstInteger & 0xFFFFFF );
long nextBlock = getUnsignedInt( recordData );
long nextModifier = ( firstInteger & 0xF000000L ) << 8;
long longNextBlock = longFromIntAndMod( nextBlock, nextModifier );
// Read the data into the chainBuffer
recordData.limit( recordData.position()+nrOfBytes );
chainBuffer.put( recordData );
return longNextBlock;
}
public void close() throws IOException
{
fileChannel.close();
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_storemigration_legacystore_LegacyDynamicStringStoreReader.java
|
404
|
public class UpgradeNotAllowedByConfigurationException extends StoreFailureException
{
public UpgradeNotAllowedByConfigurationException( String msg )
{
super( msg );
}
public UpgradeNotAllowedByConfigurationException()
{
super( String.format(
"Failed to start Neo4j with an older data store version. "
+ "To enable automatic upgrade, please set configuration parameter \"%s=true\"",
GraphDatabaseSettings.allow_store_upgrade.name() ) );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_storemigration_UpgradeNotAllowedByConfigurationException.java
|
405
|
public class UpgradableDatabaseTestIT
{
@Before
public void checkOperatingSystem() {
assumeTrue( !System.getProperty( "os.name" ).startsWith( "Windows" ) );
}
@Test
public void shouldAcceptTheStoresInTheSampleDatabaseAsBeingEligibleForUpgrade() throws IOException
{
URL legacyStoreResource = getClass().getResource( "legacystore/exampledb/neostore" );
File resourceDirectory = new File( legacyStoreResource.getFile() ).getParentFile();
File workingDirectory = new File( "target/" + UpgradableDatabaseTestIT.class.getSimpleName() );
FileUtils.deleteRecursively( workingDirectory );
assertTrue( workingDirectory.mkdirs() );
copyRecursively( resourceDirectory, workingDirectory );
assertTrue( new UpgradableDatabase( new StoreVersionCheck( fileSystem ) ).storeFilesUpgradeable( new File( workingDirectory, "neostore" ) ) );
}
@Test
public void shouldRejectStoresIfOneFileHasIncorrectVersion() throws IOException
{
URL legacyStoreResource = getClass().getResource( "legacystore/exampledb/neostore" );
File resourceDirectory = new File( legacyStoreResource.getFile() ).getParentFile();
File workingDirectory = new File( "target/" + UpgradableDatabaseTestIT.class.getSimpleName() );
FileUtils.deleteRecursively( workingDirectory );
assertTrue( workingDirectory.mkdirs() );
copyRecursively( resourceDirectory, workingDirectory );
changeVersionNumber( fileSystem, new File( workingDirectory, "neostore.nodestore.db" ), "v0.9.5" );
assertFalse( new UpgradableDatabase( new StoreVersionCheck( fileSystem ) ).storeFilesUpgradeable( new File( workingDirectory, "neostore" ) ) );
}
@Test
public void shouldRejectStoresIfOneFileHasNoVersionAsIfNotShutDownCleanly() throws IOException
{
URL legacyStoreResource = getClass().getResource( "legacystore/exampledb/neostore" );
File resourceDirectory = new File( legacyStoreResource.getFile() ).getParentFile();
File workingDirectory = new File( "target/" + UpgradableDatabaseTestIT.class.getSimpleName() );
FileUtils.deleteRecursively( workingDirectory );
assertTrue( workingDirectory.mkdirs() );
copyRecursively( resourceDirectory, workingDirectory );
truncateFile( fileSystem, new File( workingDirectory, "neostore.nodestore.db" ), "StringPropertyStore " + LEGACY_VERSION );
assertFalse( new UpgradableDatabase( new StoreVersionCheck( fileSystem ) ).storeFilesUpgradeable( new File( workingDirectory, "neostore" ) ) );
}
@Test
public void shouldRejectStoresIfOneFileShorterThanExpectedVersionString() throws IOException
{
URL legacyStoreResource = getClass().getResource( "legacystore/exampledb/neostore" );
File resourceDirectory = new File( legacyStoreResource.getFile() ).getParentFile();
File workingDirectory = new File( "target/" + UpgradableDatabaseTestIT.class.getSimpleName() );
FileUtils.deleteRecursively( workingDirectory );
assertTrue( workingDirectory.mkdirs() );
copyRecursively( resourceDirectory, workingDirectory );
int shortFileLength = 5 /* (RelationshipTypeStore.RECORD_SIZE) */ * 3;
assertTrue( shortFileLength < UTF8.encode( "StringPropertyStore " + LEGACY_VERSION ).length );
truncateToFixedLength( fileSystem, new File( workingDirectory, "neostore.relationshiptypestore.db" ), shortFileLength );
assertFalse( new UpgradableDatabase( new StoreVersionCheck( fileSystem ) ).storeFilesUpgradeable( new File( workingDirectory, "neostore" ) ) );
}
private final FileSystemAbstraction fileSystem = new DefaultFileSystemAbstraction();
@Test
public void shouldCommunicateWhatCausesInabilityToUpgrade() throws IOException
{
URL legacyStoreResource = getClass().getResource( "legacystore/exampledb/neostore" );
File resourceDirectory = new File( legacyStoreResource.getFile() ).getParentFile();
File workingDirectory = new File( "target/" + UpgradableDatabaseTestIT.class.getSimpleName() );
FileUtils.deleteRecursively( workingDirectory );
assertTrue( workingDirectory.mkdirs() );
copyRecursively( resourceDirectory, workingDirectory );
changeVersionNumber( fileSystem, new File( workingDirectory, "neostore.nodestore.db" ), "v0.9.5" );
try
{
new UpgradableDatabase( new StoreVersionCheck( fileSystem ) ).checkUpgradeable(
new File( workingDirectory, "neostore" ) );
fail( "should not have been able to upgrade" );
}
catch (StoreUpgrader.UnexpectedUpgradingStoreVersionException e)
{
assertThat( e.getMessage(), is("'neostore.nodestore.db' has a store version number that we cannot upgrade " +
"from. Expected 'NodeStore " + LEGACY_VERSION + "' but file is version 'NodeStore v0.9.5'.") );
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_storemigration_UpgradableDatabaseTestIT.java
|
406
|
public class UpgradableDatabase
{
private final StoreVersionCheck storeVersionCheck;
public UpgradableDatabase( StoreVersionCheck storeVersionCheck )
{
this.storeVersionCheck = storeVersionCheck;
}
public boolean storeFilesUpgradeable( File neoStoreFile )
{
try
{
checkUpgradeable( neoStoreFile );
return true;
}
catch ( StoreUpgrader.UnableToUpgradeException e )
{
return false;
}
}
public void checkUpgradeable( File neoStoreFile )
{
File storeDirectory = neoStoreFile.getParentFile();
for ( StoreFile store : StoreFile.legacyStoreFiles() )
{
String expectedVersion = store.legacyVersion();
File storeFile = new File( storeDirectory, store.storeFileName() );
Pair<Outcome, String> outcome = storeVersionCheck.hasVersion( storeFile, expectedVersion );
if ( !outcome.first().isSuccessful() )
{
switch ( outcome.first() )
{
case missingStoreFile:
throw new StoreUpgrader.UpgradeMissingStoreFilesException( storeFile.getName() );
case storeVersionNotFound:
throw new StoreUpgrader.UpgradingStoreVersionNotFoundException( storeFile.getName() );
case unexpectedUpgradingStoreVersion:
throw new StoreUpgrader.UnexpectedUpgradingStoreVersionException(
storeFile.getName(), expectedVersion, outcome.other() );
default:
throw new IllegalArgumentException( outcome.first().name() );
}
}
}
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_storemigration_UpgradableDatabase.java
|
407
|
public class StoreVersionCheckTest
{
@Test
public void shouldReportMissingFileDoesNotHaveSpecifiedVersion()
{
// given
File missingFile = new File("/you/will/never/find/me");
StoreVersionCheck storeVersionCheck = new StoreVersionCheck(new EphemeralFileSystemAbstraction());
// then
assertFalse( storeVersionCheck.hasVersion( missingFile, "version" ).first().isSuccessful() );
}
@Test
public void shouldReportShortFileDoesNotHaveSpecifiedVersion() throws IOException
{
// given
EphemeralFileSystemAbstraction fs = new EphemeralFileSystemAbstraction();
File shortFile = fileContaining( fs, "a" );
StoreVersionCheck storeVersionCheck = new StoreVersionCheck( fs );
// then
assertFalse( storeVersionCheck.hasVersion( shortFile, "version" ).first().isSuccessful() );
}
@Test
public void shouldReportFileWithIncorrectVersion() throws IOException
{
// given
EphemeralFileSystemAbstraction fs = new EphemeralFileSystemAbstraction();
File shortFile = fileContaining( fs, "versionWhichIsIncorrect" );
StoreVersionCheck storeVersionCheck = new StoreVersionCheck( fs );
// then
assertFalse( storeVersionCheck.hasVersion( shortFile, "correctVersion 1" ).first().isSuccessful() );
}
@Test
public void shouldReportFileWithCorrectVersion() throws IOException
{
// given
EphemeralFileSystemAbstraction fs = new EphemeralFileSystemAbstraction();
File shortFile = fileContaining( fs, "correctVersion 1" );
StoreVersionCheck storeVersionCheck = new StoreVersionCheck( fs );
// then
assertTrue( storeVersionCheck.hasVersion( shortFile, "correctVersion 1" ).first().isSuccessful() );
}
private File fileContaining( EphemeralFileSystemAbstraction fs, String content ) throws IOException
{
File shortFile = new File( "shortFile" );
OutputStream outputStream = fs.openAsOutputStream( shortFile, true );
outputStream.write( content.getBytes() );
outputStream.close();
return shortFile;
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_storemigration_StoreVersionCheckTest.java
|
408
|
public class StoreVersionCheck
{
private final FileSystemAbstraction fs;
public StoreVersionCheck( FileSystemAbstraction fs )
{
this.fs = fs;
}
public Pair<Outcome,String> hasVersion( File storeFile, String expectedVersion )
{
StoreChannel fileChannel = null;
byte[] expectedVersionBytes = UTF8.encode( expectedVersion );
try
{
if ( !fs.fileExists( storeFile ) )
{
return Pair.of( Outcome.missingStoreFile, null );
}
fileChannel = fs.open( storeFile, "r" );
if ( fileChannel.size() < expectedVersionBytes.length )
{
return Pair.of( Outcome.storeVersionNotFound, null );
}
String actualVersion = readVersion( fileChannel, expectedVersionBytes.length );
if ( !actualVersion.startsWith( typeDescriptor( expectedVersion ) ) )
{
return Pair.of( Outcome.storeVersionNotFound, actualVersion );
}
if ( !expectedVersion.equals( actualVersion ) )
{
return Pair.of( Outcome.unexpectedUpgradingStoreVersion, actualVersion );
}
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
finally
{
if ( fileChannel != null )
{
try
{
fileChannel.close();
}
catch ( IOException e )
{
// Ignore exception on close
}
}
}
return Pair.of( Outcome.ok, null );
}
private String typeDescriptor( String expectedVersion )
{
int spaceIndex = expectedVersion.indexOf( ' ' );
if ( spaceIndex == -1 )
{
throw new IllegalArgumentException( "Unexpected version " + expectedVersion );
}
return expectedVersion.substring( 0, spaceIndex );
}
private String readVersion( StoreChannel fileChannel, int bytesToRead ) throws IOException
{
fileChannel.position( fileChannel.size() - bytesToRead );
byte[] foundVersionBytes = new byte[bytesToRead];
fileChannel.read( ByteBuffer.wrap( foundVersionBytes ) );
return UTF8.decode( foundVersionBytes );
}
public static enum Outcome
{
ok( true ),
missingStoreFile( false ),
storeVersionNotFound( false ),
unexpectedUpgradingStoreVersion( false );
private final boolean success;
private Outcome( boolean success )
{
this.success = success;
}
public boolean isSuccessful()
{
return this.success;
}
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_storemigration_StoreVersionCheck.java
|
409
|
public abstract class XaCommandFactory
{
/**
* Reads the data from a commad previosly written to the logical log and
* creates the command again.
* <p>
* The implementation has to guard against the command beeing corrupt and
* not completly written to the logical log. When unable to read the command
* <CODE>null</CODE> should be returned. <CODE>IOException</CODE> should
* only be thrown in case of real IO failure. The <CODE>null</CODE> return
* is a signal to the recovery mechanism to stop scaning for more entries.
*
* @param fileChannel
* The channel to read the command data from
* @param buffer
* A small buffer that can be used to read data into
* @return The command or null if unable to read command
* @throws IOException
* In case of real IO failure
*/
public abstract XaCommand readCommand( ReadableByteChannel byteChannel,
ByteBuffer buffer ) throws IOException;
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_XaCommandFactory.java
|
410
|
private static class ResourceTransaction
{
private Xid xid;
private final XaTransaction xaTx;
ResourceTransaction( XaTransaction xaTx )
{
this.xaTx = xaTx;
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_XaResourceManager.java
|
411
|
public class XaContainer
{
private XaLogicalLog log;
private XaResourceManager rm;
/**
* Creates a XaContainer.
*
* @param log
*/
public XaContainer(XaResourceManager rm, XaLogicalLog log)
{
this.rm = rm;
this.log = log;
}
/**
* Opens the logical log. If the log doesn't exist a new log will be
* created. If the log exists it will be scaned and non completed
* transactions will be recovered.
* <p>
* This method is only valid to invoke once after the container has been
* created. Invoking this method again could cause the logical log to be
* corrupted.
*/
public void openLogicalLog() throws IOException
{
log.open();
}
/**
* Closes the logical log and nulls out all instances.
*/
public void close()
{
try
{
if ( log != null )
{
log.close();
}
}
catch ( IOException e )
{
System.out.println( "Unable to close logical log" );
e.printStackTrace();
}
log = null;
rm = null;
}
public XaLogicalLog getLogicalLog()
{
return log;
}
public XaResourceManager getResourceManager()
{
return rm;
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_XaContainer.java
|
412
|
NODE
{
@Override
public String toString( String resourceId )
{
return "Node[" + resourceId + "]";
}
},
| false
|
community_kernel_src_main_java_org_neo4j_kernel_info_ResourceType.java
|
413
|
public final class LockInfo
{
private final String resource;
private final ResourceType type;
private final int readCount;
private final int writeCount;
private final List<WaitingThread> waitingThreads;
private final List<LockingTransaction> lockingTransactions;
@ConstructorProperties( { "resourceType", "resourceId", "readCount", "writeCount", "lockingTransactions",
"waitingThreads" } )
public LockInfo( ResourceType type, String resourceId, int readCount, int writeCount,
List<LockingTransaction> lockingTransactions, List<WaitingThread> waitingThreads )
{
this.type = type;
this.resource = resourceId;
this.readCount = readCount;
this.writeCount = writeCount;
this.lockingTransactions = new ArrayList<LockingTransaction>( lockingTransactions );
this.waitingThreads = new ArrayList<WaitingThread>( waitingThreads );
}
public LockInfo( ResourceType type, String resourceId, int readCount, int writeCount,
Collection<LockingTransaction> locking )
{
this.type = type;
this.resource = resourceId;
this.readCount = readCount;
this.writeCount = writeCount;
this.waitingThreads = new ArrayList<WaitingThread>();
this.lockingTransactions = new ArrayList<LockingTransaction>( locking );
for ( LockingTransaction tx : lockingTransactions )
{
if ( tx instanceof WaitingThread )
{
waitingThreads.add( (WaitingThread) tx );
}
}
}
@Override
public String toString()
{
StringBuilder builder = new StringBuilder( );
builder.append( "Total lock count: readCount=" + this.getReadCount() + " writeCount="
+ this.getWriteCount() + " for "
+ this.getResourceType().toString( this.getResourceId() ) ).append( "\n" );
builder.append( "Lock holders:\n" );
for ( LockingTransaction tle : this.getLockingTransactions() )
{
builder.append( tle ).append( "\n" );
}
builder.append( "Waiting list:" ).append( "\n" );
StringBuilder waitList = new StringBuilder();
String sep = "";
for ( WaitingThread we : this.getWaitingThreads() )
{
waitList.append( sep ).append( we );
sep = ", ";
}
builder.append( waitList ).append( "\n" );
return builder.toString();
}
public ResourceType getResourceType()
{
return type;
}
public String getResourceId()
{
return resource;
}
public int getWriteCount()
{
return writeCount;
}
public int getReadCount()
{
return readCount;
}
public int getWaitingThreadsCount()
{
return waitingThreads.size();
}
public List<WaitingThread> getWaitingThreads()
{
return Collections.unmodifiableList( waitingThreads );
}
public List<LockingTransaction> getLockingTransactions()
{
return Collections.unmodifiableList( lockingTransactions );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_info_LockInfo.java
|
414
|
public class JvmMetadataRepository
{
public String getJavaVmName()
{
return System.getProperty( "java.vm.name" );
}
public String getJavaVersion()
{
return System.getProperty( "java.version" );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_info_JvmMetadataRepository.java
|
415
|
public class JvmChecker
{
public static final String INCOMPATIBLE_JVM_WARNING = "You are using an unsupported Java runtime. Please" +
" use Oracle(R) Java(TM) Runtime Environment 7.";
public static final String INCOMPATIBLE_JVM_VERSION_WARNING = "You are using an unsupported version of " +
"the Java runtime. Please use Oracle(R) Java(TM) Runtime Environment 7.";
private final StringLogger stringLogger;
private final JvmMetadataRepository jvmMetadataRepository;
public JvmChecker( StringLogger stringLogger, JvmMetadataRepository jvmMetadataRepository )
{
this.stringLogger = stringLogger;
this.jvmMetadataRepository = jvmMetadataRepository;
}
public void checkJvmCompatibilityAndIssueWarning()
{
String javaVmName = jvmMetadataRepository.getJavaVmName();
String javaVersion = jvmMetadataRepository.getJavaVersion();
if ( !javaVmName.matches( "Java HotSpot\\(TM\\) (64-Bit Server|Server|Client) VM" ) )
{
stringLogger.warn( INCOMPATIBLE_JVM_WARNING );
}
else if ( !javaVersion.matches( "^1\\.7.*" ) )
{
stringLogger.warn( INCOMPATIBLE_JVM_VERSION_WARNING );
}
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_info_JvmChecker.java
|
416
|
public class JVMCheckerTest
{
@Test
public void shouldNotIssueWarningWhenUsingHotspotServerVmVersion7() throws Exception
{
BufferingLogger bufferingLogger = new BufferingLogger();
new JvmChecker( bufferingLogger, new CannedJvmMetadataRepository( "Java HotSpot(TM) 64-Bit Server VM",
"1.7.0-b147" ) ).checkJvmCompatibilityAndIssueWarning();
assertTrue( bufferingLogger.toString().isEmpty() );
}
@Test
public void shouldNotIssueWarningWhenUsingHotspotServerVmVersion7InThe32BitVersion() throws Exception
{
BufferingLogger bufferingLogger = new BufferingLogger();
new JvmChecker( bufferingLogger, new CannedJvmMetadataRepository( "Java HotSpot(TM) Server VM",
"1.7.0_25-b15" ) ).checkJvmCompatibilityAndIssueWarning();
assertTrue( bufferingLogger.toString().isEmpty() );
}
@Test
public void shouldIssueWarningWhenUsingUnsupportedJvm() throws Exception
{
BufferingLogger bufferingLogger = new BufferingLogger();
new JvmChecker( bufferingLogger, new CannedJvmMetadataRepository( "OpenJDK 64-Bit Server VM",
"1.7" ) ).checkJvmCompatibilityAndIssueWarning();
assertThat( bufferingLogger.toString().trim(), is( INCOMPATIBLE_JVM_WARNING ) );
}
@Test
public void shouldIssueWarningWhenUsingUnsupportedJvmVersion() throws Exception
{
BufferingLogger bufferingLogger = new BufferingLogger();
new JvmChecker( bufferingLogger, new CannedJvmMetadataRepository( "Java HotSpot(TM) 64-Bit Server VM",
"1.6.42_87" ) ).checkJvmCompatibilityAndIssueWarning();
assertThat( bufferingLogger.toString().trim(), is( INCOMPATIBLE_JVM_VERSION_WARNING ) );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_info_JVMCheckerTest.java
|
417
|
STOPPED
{
@Override
boolean shutdown( DiagnosticsManager manager )
{
return false;
}
};
| false
|
community_kernel_src_main_java_org_neo4j_kernel_info_DiagnosticsManager.java
|
418
|
INITIAL
{
@Override
boolean startup( DiagnosticsManager manager )
{
manager.state = STARTED;
return true;
}
},
| false
|
community_kernel_src_main_java_org_neo4j_kernel_info_DiagnosticsManager.java
|
419
|
private static class ExtractedVisitableDiagnosticsProvider<T> extends ExtractedDiagnosticsProvider<T>
{
ExtractedVisitableDiagnosticsProvider( VisitableDiagnostics<T> extractor, T source )
{
super( extractor, source );
}
@Override
public void acceptDiagnosticsVisitor( Object visitor )
{
( (DiagnosticsExtractor.VisitableDiagnostics<T>) extractor ).dispatchDiagnosticsVisitor( source, visitor );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_info_DiagnosticsManager.java
|
420
|
private static class ExtractedDiagnosticsProvider<T> implements DiagnosticsProvider
{
final DiagnosticsExtractor<T> extractor;
final T source;
ExtractedDiagnosticsProvider( DiagnosticsExtractor<T> extractor, T source )
{
this.extractor = extractor;
this.source = source;
}
@Override
public String getDiagnosticsIdentifier()
{
return extractor.toString();
}
@Override
public void acceptDiagnosticsVisitor( Object visitor )
{
// nobody visits the source of this
}
@Override
public void dump( DiagnosticsPhase phase, StringLogger log )
{
extractor.dumpDiagnostics( source, phase, log );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_info_DiagnosticsManager.java
|
421
|
{
@Override
protected String underlyingObjectToObject( DiagnosticsProvider provider )
{
return provider.getDiagnosticsIdentifier();
}
}, true );
| false
|
community_kernel_src_main_java_org_neo4j_kernel_info_DiagnosticsManager.java
|
422
|
{
@Override
public String getDiagnosticsIdentifier()
{
return DiagnosticsManager.this.getClass().getName();
}
@Override
public void dump( DiagnosticsPhase phase, final StringLogger log )
{
if ( phase.isInitialization() || phase.isExplicitlyRequested() )
{
log.logLongMessage( "Diagnostics providers:", new IterableWrapper<String, DiagnosticsProvider>(
providers )
{
@Override
protected String underlyingObjectToObject( DiagnosticsProvider provider )
{
return provider.getDiagnosticsIdentifier();
}
}, true );
}
}
@Override
public void acceptDiagnosticsVisitor( Object visitor )
{
Visitor<? super DiagnosticsProvider, ? extends RuntimeException> target =
Visitor.SafeGenerics.castOrNull( DiagnosticsProvider.class, RuntimeException.class, visitor );
if ( target != null ) for ( DiagnosticsProvider provider : providers )
{
target.visit( provider );
}
}
} );
| false
|
community_kernel_src_main_java_org_neo4j_kernel_info_DiagnosticsManager.java
|
423
|
{
@Override
public void run()
{
dumpAll( DiagnosticsPhase.LOG_ROTATION );
}
} );
| false
|
community_kernel_src_main_java_org_neo4j_kernel_info_DiagnosticsManager.java
|
424
|
public final class DiagnosticsManager implements Iterable<DiagnosticsProvider>, Lifecycle
{
private final List<DiagnosticsProvider> providers = new CopyOnWriteArrayList<DiagnosticsProvider>();
private final StringLogger logger;
private volatile State state = State.INITIAL;
public DiagnosticsManager( StringLogger logger )
{
( this.logger = logger ).addRotationListener( new Runnable()
{
@Override
public void run()
{
dumpAll( DiagnosticsPhase.LOG_ROTATION );
}
} );
providers.add( new DiagnosticsProvider(/*self*/)
{
@Override
public String getDiagnosticsIdentifier()
{
return DiagnosticsManager.this.getClass().getName();
}
@Override
public void dump( DiagnosticsPhase phase, final StringLogger log )
{
if ( phase.isInitialization() || phase.isExplicitlyRequested() )
{
log.logLongMessage( "Diagnostics providers:", new IterableWrapper<String, DiagnosticsProvider>(
providers )
{
@Override
protected String underlyingObjectToObject( DiagnosticsProvider provider )
{
return provider.getDiagnosticsIdentifier();
}
}, true );
}
}
@Override
public void acceptDiagnosticsVisitor( Object visitor )
{
Visitor<? super DiagnosticsProvider, ? extends RuntimeException> target =
Visitor.SafeGenerics.castOrNull( DiagnosticsProvider.class, RuntimeException.class, visitor );
if ( target != null ) for ( DiagnosticsProvider provider : providers )
{
target.visit( provider );
}
}
} );
SystemDiagnostics.registerWith( this );
}
@Override
public void init()
throws Throwable
{
synchronized ( providers )
{
@SuppressWarnings( "hiding" ) State state = this.state;
if ( !state.startup( this ) ) return;
}
dumpAll( DiagnosticsPhase.INITIALIZED);
}
public void start()
{
synchronized ( providers )
{
@SuppressWarnings( "hiding" ) State state = this.state;
if ( !state.startup( this ) ) return;
}
dumpAll( DiagnosticsPhase.STARTED);
}
@Override
public void stop()
throws Throwable
{
synchronized ( providers )
{
@SuppressWarnings( "hiding" ) State state = this.state;
if ( !state.shutdown( this ) ) return;
}
dumpAll( DiagnosticsPhase.STOPPING );
providers.clear();
}
public void shutdown()
{
synchronized ( providers )
{
@SuppressWarnings( "hiding" ) State state = this.state;
if ( !state.shutdown( this ) ) return;
}
dumpAll( DiagnosticsPhase.SHUTDOWN );
providers.clear();
}
private enum State
{
INITIAL
{
@Override
boolean startup( DiagnosticsManager manager )
{
manager.state = STARTED;
return true;
}
},
STARTED,
STOPPED
{
@Override
boolean shutdown( DiagnosticsManager manager )
{
return false;
}
};
boolean startup( DiagnosticsManager manager )
{
return false;
}
boolean shutdown( DiagnosticsManager manager )
{
manager.state = STOPPED;
return true;
}
}
public StringLogger getTargetLog()
{
return logger;
}
public void dumpAll()
{
dumpAll( DiagnosticsPhase.REQUESTED );
}
public void dump( String identifier )
{
extract( identifier, logger );
}
public void dumpAll( StringLogger log )
{
for ( DiagnosticsProvider provider : providers )
{
dump( provider, DiagnosticsPhase.EXPLICIT, log );
}
}
public void extract( String identifier, StringLogger log )
{
for ( DiagnosticsProvider provider : providers )
{
if ( identifier.equals( provider.getDiagnosticsIdentifier() ) )
{
dump( provider, DiagnosticsPhase.EXPLICIT, log );
return;
}
}
}
public void visitAll( Object visitor )
{
for ( DiagnosticsProvider provider : providers )
{
provider.acceptDiagnosticsVisitor( visitor );
}
}
private void dumpAll( DiagnosticsPhase phase )
{
phase.emitStart( logger );
for ( DiagnosticsProvider provider : providers )
{
dump( provider, phase, logger );
}
phase.emitDone( logger );
}
public <T> void register( DiagnosticsExtractor<T> extractor, T source )
{
appendProvider( extractedProvider( extractor, source ) );
}
public <T> T tryAppendProvider( T protentialProvider )
{
if ( protentialProvider instanceof DiagnosticsProvider )
{
appendProvider( (DiagnosticsProvider) protentialProvider );
}
return protentialProvider;
}
public <T, E extends Enum<E> & DiagnosticsExtractor<T>> void registerAll( Class<E> extractorEnum, T source )
{
for ( DiagnosticsExtractor<T> extractor : extractorEnum.getEnumConstants() )
{
register( extractor, source );
}
}
public void prependProvider( DiagnosticsProvider provider )
{
@SuppressWarnings( "hiding" ) State state = this.state;
if ( state == State.STOPPED ) return;
providers.add( 0, provider );
if ( state == State.STARTED ) dump( DiagnosticsPhase.STARTED, provider );
}
public void appendProvider( DiagnosticsProvider provider )
{
@SuppressWarnings( "hiding" ) State state = this.state;
if ( state == State.STOPPED ) return;
providers.add( provider );
if ( state == State.STARTED ) dump( DiagnosticsPhase.STARTED, provider );
}
private void dump( DiagnosticsPhase phase, DiagnosticsProvider provider )
{
phase.emitStart( logger, provider );
dump( provider, phase, logger );
phase.emitDone( logger, provider );
}
private static void dump( DiagnosticsProvider provider, DiagnosticsPhase phase, StringLogger logger )
{
try
{
provider.dump( phase, logger );
}
catch ( Exception cause )
{
logger.error( "Failure while logging diagnostics for " + provider, cause );
}
}
@Override
public Iterator<DiagnosticsProvider> iterator()
{
return providers.iterator();
}
static <T> DiagnosticsProvider extractedProvider( DiagnosticsExtractor<T> extractor, T source )
{
if ( extractor instanceof DiagnosticsExtractor.VisitableDiagnostics<?> )
{
return new ExtractedVisitableDiagnosticsProvider<T>(
(DiagnosticsExtractor.VisitableDiagnostics<T>) extractor, source );
}
else
{
return new ExtractedDiagnosticsProvider<T>( extractor, source );
}
}
private static class ExtractedDiagnosticsProvider<T> implements DiagnosticsProvider
{
final DiagnosticsExtractor<T> extractor;
final T source;
ExtractedDiagnosticsProvider( DiagnosticsExtractor<T> extractor, T source )
{
this.extractor = extractor;
this.source = source;
}
@Override
public String getDiagnosticsIdentifier()
{
return extractor.toString();
}
@Override
public void acceptDiagnosticsVisitor( Object visitor )
{
// nobody visits the source of this
}
@Override
public void dump( DiagnosticsPhase phase, StringLogger log )
{
extractor.dumpDiagnostics( source, phase, log );
}
}
private static class ExtractedVisitableDiagnosticsProvider<T> extends ExtractedDiagnosticsProvider<T>
{
ExtractedVisitableDiagnosticsProvider( VisitableDiagnostics<T> extractor, T source )
{
super( extractor, source );
}
@Override
public void acceptDiagnosticsVisitor( Object visitor )
{
( (DiagnosticsExtractor.VisitableDiagnostics<T>) extractor ).dispatchDiagnosticsVisitor( source, visitor );
}
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_info_DiagnosticsManager.java
|
425
|
public class CannedJvmMetadataRepository extends JvmMetadataRepository
{
private final String javaVmName;
private final String javaVersion;
public CannedJvmMetadataRepository( String javaVmName, String javaVersion )
{
this.javaVmName = javaVmName;
this.javaVersion = javaVersion;
}
@Override
public String getJavaVmName()
{
return javaVmName;
}
@Override
public String getJavaVersion()
{
return javaVersion;
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_info_CannedJvmMetadataRepository.java
|
426
|
private static class PutIfAbsent implements WorkerCommand<HighlyAvailableGraphDatabase, Node>
{
private final long node;
private final String key;
private final String value;
public PutIfAbsent( long node, String key, String value )
{
this.node = node;
this.key = key;
this.value = value;
}
@Override
public Node doWork( HighlyAvailableGraphDatabase state )
{
return state.index().forNodes( key ).putIfAbsent( state.getNodeById( node ), key, value );
}
}
| false
|
enterprise_ha_src_test_java_org_neo4j_kernel_index_IndexOperationsIT.java
|
427
|
public class IndexOperationsIT extends AbstractClusterTest
{
@Test
public void index_modifications_are_propagated() throws Exception
{
// GIVEN
// -- a slave
cluster.await( allSeesAllAsAvailable() );
String key = "name";
String value = "Mattias";
HighlyAvailableGraphDatabase author = cluster.getAnySlave();
// WHEN
// -- it creates a node associated with indexing in a transaction
long node = createNode( author, key, value, true );
// THEN
// -- all instances should see it after pulling updates
for ( HighlyAvailableGraphDatabase db : cluster.getAllMembers() )
{
db.getDependencyResolver().resolveDependency( UpdatePuller.class ).pullUpdates();
assertNodeAndIndexingExists( db, node, key, value );
}
}
@Test
public void index_objects_can_be_reused_after_role_switch() throws Exception
{
// GIVEN
// -- an existing index
cluster.await( allSeesAllAsAvailable() );
String key = "key", value = "value";
HighlyAvailableGraphDatabase master = cluster.getMaster();
long nodeId = createNode( master, key, value, true );
cluster.sync();
// -- get Index and IndexManager references to all dbs
Map<HighlyAvailableGraphDatabase,IndexManager> indexManagers = new HashMap<>();
Map<HighlyAvailableGraphDatabase,Index<Node>> indexes = new HashMap<>();
for ( HighlyAvailableGraphDatabase db : cluster.getAllMembers() )
{
Transaction transaction = db.beginTx();
try
{
indexManagers.put( db, db.index() );
indexes.put( db, db.index().forNodes( key ) );
transaction.success();
}
finally
{
transaction.finish();
}
}
// WHEN
// -- there's a master switch
cluster.shutdown( master );
indexManagers.remove( master );
indexes.remove( master );
cluster.await( ClusterManager.masterAvailable( master ) );
cluster.await( ClusterManager.masterSeesSlavesAsAvailable( 1 ) );
// THEN
// -- the index instances should still be viable to use
for ( Map.Entry<HighlyAvailableGraphDatabase, IndexManager> entry : indexManagers.entrySet() )
{
HighlyAvailableGraphDatabase db = entry.getKey();
Transaction transaction = db.beginTx();
try
{
IndexManager indexManager = entry.getValue();
assertTrue( indexManager.existsForNodes( key ) );
assertEquals( nodeId, indexManager.forNodes( key ).get( key, value ).getSingle().getId() );
}
finally
{
transaction.finish();
}
}
for ( Map.Entry<HighlyAvailableGraphDatabase, Index<Node>> entry : indexes.entrySet() )
{
HighlyAvailableGraphDatabase db = entry.getKey();
Transaction transaction = db.beginTx();
try
{
Index<Node> index = entry.getValue();
assertEquals( nodeId, index.get( key, value ).getSingle().getId() );
}
finally
{
transaction.finish();
}
}
}
@Test
public void put_if_absent_works_across_instances() throws Exception
{
// GIVEN
// -- two instances, each begin a transaction
cluster.await( allSeesAllAsAvailable() );
String key = "key", value = "value";
HighlyAvailableGraphDatabase db1 = cluster.getMaster(), db2 = cluster.getAnySlave();
long node = createNode( db1, key, value, false );
cluster.sync();
OtherThreadExecutor<HighlyAvailableGraphDatabase> w1 = new OtherThreadExecutor<>( "w1", db1 );
OtherThreadExecutor<HighlyAvailableGraphDatabase> w2 = new OtherThreadExecutor<>( "w2", db2 );
Transaction tx1 = w1.execute( new BeginTx() );
Transaction tx2 = w2.execute( new BeginTx() );
// WHEN
// -- second instance does putIfAbsent --> null
assertNull( w2.execute( new PutIfAbsent( node, key, value ) ) );
// -- get a future to first instance putIfAbsent. Wait for it to go and await the lock
Future<Node> w1Future = w1.executeDontWait( new PutIfAbsent( node, key, value ) );
w1.waitUntilWaiting();
// -- second instance completes tx
w2.execute( new FinishTx( tx2, true ) );
tx2.success();
tx2.finish();
// THEN
// -- first instance can complete the future with a non-null result
assertNotNull( w1Future.get() );
w1.execute( new FinishTx( tx1, true ) );
// -- assert the index has got one entry and both instances have the same data
assertNodeAndIndexingExists( db1, node, key, value );
assertNodeAndIndexingExists( db2, node, key, value );
cluster.sync();
assertNodeAndIndexingExists( cluster.getAnySlave( db1, db2 ), node, key, value );
w2.close();
w1.close();
}
private long createNode( HighlyAvailableGraphDatabase author, String key, Object value, boolean index )
{
Transaction tx = author.beginTx();
try
{
Node node = author.createNode();
node.setProperty( key, value );
if ( index )
author.index().forNodes( key ).add( node, key, value );
tx.success();
return node.getId();
}
finally
{
tx.finish();
}
}
private void assertNodeAndIndexingExists( HighlyAvailableGraphDatabase db, long nodeId, String key, Object value )
{
Transaction transaction = db.beginTx();
try
{
Node node = db.getNodeById( nodeId );
assertEquals( value, node.getProperty( key ) );
assertTrue( db.index().existsForNodes( key ) );
assertEquals( node, db.index().forNodes( key ).get( key, value ).getSingle() );
}
finally
{
transaction.finish();
}
}
private static class PutIfAbsent implements WorkerCommand<HighlyAvailableGraphDatabase, Node>
{
private final long node;
private final String key;
private final String value;
public PutIfAbsent( long node, String key, String value )
{
this.node = node;
this.key = key;
this.value = value;
}
@Override
public Node doWork( HighlyAvailableGraphDatabase state )
{
return state.index().forNodes( key ).putIfAbsent( state.getNodeById( node ), key, value );
}
}
}
| false
|
enterprise_ha_src_test_java_org_neo4j_kernel_index_IndexOperationsIT.java
|
428
|
{
@Override
protected void config( GraphDatabaseBuilder builder, String clusterName, int serverId )
{
builder.setConfig( "jmx.port", "" + (9912+serverId) );
builder.setConfig( HaSettings.ha_server, ":" + (1136+serverId) );
}
};
| false
|
enterprise_ha_src_test_java_org_neo4j_kernel_index_AutoIndexConfigIT.java
|
429
|
public class AutoIndexConfigIT
{
private static final TargetDirectory dir = TargetDirectory.forTest( AutoIndexConfigIT.class );
private ClusterManager.ManagedCluster cluster;
private ClusterManager clusterManager;
public void startCluster( int size ) throws Throwable
{
clusterManager = new ClusterManager( clusterOfSize( size ), dir.cleanDirectory( "dbs" ), MapUtil.stringMap() )
{
@Override
protected void config( GraphDatabaseBuilder builder, String clusterName, int serverId )
{
builder.setConfig( "jmx.port", "" + (9912+serverId) );
builder.setConfig( HaSettings.ha_server, ":" + (1136+serverId) );
}
};
clusterManager.start();
cluster = clusterManager.getDefaultCluster();
}
@After
public void stopCluster() throws Throwable
{
clusterManager.stop();
}
@Test
public void programmaticConfigShouldSurviveMasterSwitches() throws Throwable
{
String propertyToIndex = "programmatic-property";
// Given
startCluster( 3 );
HighlyAvailableGraphDatabase slave = cluster.getAnySlave();
AutoIndexer<Node> originalAutoIndex = slave.index().getNodeAutoIndexer();
originalAutoIndex.setEnabled( true );
originalAutoIndex.startAutoIndexingProperty( propertyToIndex );
// When
cluster.shutdown( cluster.getMaster() );
cluster.await( masterAvailable() );
// Then
AutoIndexer<Node> newAutoIndex = slave.index().getNodeAutoIndexer();
assertThat(newAutoIndex.isEnabled(), is(true));
assertThat( newAutoIndex.getAutoIndexedProperties(), hasItem( propertyToIndex ) );
}
}
| false
|
enterprise_ha_src_test_java_org_neo4j_kernel_index_AutoIndexConfigIT.java
|
430
|
public class ThreadLocalWithSize<T> extends ThreadLocal<T>
{
private final AtomicInteger size = new AtomicInteger();
@Override
public void set( T value )
{
super.set( value );
size.incrementAndGet();
}
@Override
public void remove()
{
super.remove();
size.decrementAndGet();
}
public int size()
{
return size.get();
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_util_ThreadLocalWithSize.java
|
431
|
public class TestTestLogger
{
@Test
public void shouldPassExactAssertions() throws Exception
{
// Given
TestLogger logger = new TestLogger();
Throwable cause = new Throwable("This is a throwable!");
logger.debug( "Debug" );
logger.debug( "Debug", cause );
logger.info( "Info" );
logger.info( "Info", cause );
logger.warn( "Warn" );
logger.warn( "Warn", cause );
logger.error( "Error" );
logger.error( "Error", cause );
// When
logger.assertExactly(
debug( "Debug" ),
debug( "Debug", cause ),
info( "Info" ),
info( "Info", cause ),
warn( "Warn" ),
warn( "Warn", cause ),
error( "Error" ),
error( "Error", cause )
);
// Then no assertion should have failed
}
@Test
public void shouldFailNicelyIfTooManyLogCalls() throws Exception
{
// Given
TestLogger logger = new TestLogger();
logger.debug( "Debug" );
logger.debug( "Debug 2" );
// When
try {
logger.assertExactly( debug( "Debug" ) );
fail("Should have failed.");
} catch(AssertionError e)
{
// Then
assertThat( e.getMessage(), equalTo("Got more log calls than expected. The remaining log calls were: \n" +
"LogCall{ DEBUG, message='Debug 2', cause=null}\n") );
}
}
@Test
public void shouldFailIfTooFewLogCalls() throws Exception
{
// Given
TestLogger logger = new TestLogger();
// When
try {
logger.assertExactly( debug( "Debug" ) );
fail("Should have failed.");
} catch(AssertionError e)
{
// Then
assertThat( e.getMessage(), equalTo("Got fewer log calls than expected. The missing log calls were: \n" +
"LogCall{ DEBUG, message='Debug', cause=null}\n") );
}
}
@Test
public void shouldPassIfContains() throws Exception
{
// Given
TestLogger logger = new TestLogger();
logger.debug( "Debug 1" );
logger.debug( "Debug 2" );
logger.debug( "Debug 3" );
// When
logger.assertAtLeastOnce(
debug( "Debug 2" ),
debug( "Debug 1" ) );
// Then no assertion should have failed
}
@Test
public void shouldFailIfDoesntContain() throws Exception
{
// Given
TestLogger logger = new TestLogger();
logger.debug( "Debug 1" );
logger.debug( "Debug 3" );
// When
try
{
logger.assertAtLeastOnce(
debug( "Debug 2" ),
debug( "Debug 1" ) );
} catch(AssertionError e)
{
assertThat( e.getMessage(), equalTo( "These log calls were expected, but never occurred: \n" +
"LogCall{ DEBUG, message='Debug 2', cause=null}\n" ) );
}
}
@Test
public void shouldPassOnEmptyAsserters() throws Exception
{
// Given
TestLogger logger = new TestLogger();
// When
logger.assertNoDebugs();
logger.assertNoInfos();
logger.assertNoWarnings();
logger.assertNoErrors();
logger.assertNoLoggingOccurred();
// Then no assertions should have failed
}
@Test
public void shouldFailOnNonEmptyAsserters() throws Exception
{
TestLogger logger = new TestLogger();
// Debug
try
{
logger.debug( "Debug" );
logger.assertNoErrors();
logger.assertNoWarnings();
logger.assertNoInfos();
logger.assertNoDebugs();
fail( "Should have failed" );
} catch(AssertionError e)
{
assertThat( e.getMessage(), equalTo( "Expected no messages with level DEBUG. But found: \n" +
"LogCall{ DEBUG, message='Debug', cause=null}\n" ) );
}
// Info
try
{
logger.info( "Info" );
logger.assertNoErrors();
logger.assertNoWarnings();
logger.assertNoInfos();
fail( "Should have failed" );
} catch(AssertionError e)
{
assertThat( e.getMessage(), equalTo( "Expected no messages with level INFO. But found: \n" +
"LogCall{ INFO, message='Info', cause=null}\n" ) );
}
// Warn
try
{
logger.warn( "Warn" );
logger.assertNoErrors();
logger.assertNoWarnings();
fail( "Should have failed" );
} catch(AssertionError e)
{
assertThat( e.getMessage(), equalTo( "Expected no messages with level WARN. But found: \n" +
"LogCall{ WARN, message='Warn', cause=null}\n" ) );
}
// Errors
try
{
logger.error( "Error" );
logger.assertNoErrors();
fail( "Should have failed" );
} catch(AssertionError e)
{
assertThat( e.getMessage(), equalTo( "Expected no messages with level ERROR. But found: \n" +
"LogCall{ ERROR, message='Error', cause=null}\n" ) );
}
// All
try
{
logger.assertNoLoggingOccurred();
fail( "Should have failed" );
} catch(AssertionError e)
{
assertThat( e.getMessage(), equalTo( "Expected no log messages at all, but got:\n" +
"LogCall{ DEBUG, message='Debug', cause=null}\n" +
"LogCall{ INFO, message='Info', cause=null}\n" +
"LogCall{ WARN, message='Warn', cause=null}\n" +
"LogCall{ ERROR, message='Error', cause=null}\n") );
}
// Specific message
try
{
logger.debug( "This is a message." );
logger.debug( "This is a message." );
logger.assertNo(debug("This is a message."));
fail( "Should have failed" );
} catch(AssertionError e)
{
assertThat( e.getMessage(), equalTo( "Expected no occurrence of " +
"LogCall{ DEBUG, message='This is a message.', cause=null}, but it was in fact logged 2 times.") );
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_util_TestTestLogger.java
|
432
|
public class LockingTransaction implements Serializable
{
private static final long serialVersionUID = 1L;
private final String transaction;
private final int readCount;
private final int writeCount;
@ConstructorProperties( { "transaction", "readCount", "writeCount" } )
public LockingTransaction( String transaction, int readCount, int writeCount )
{
this.transaction = transaction;
this.readCount = readCount;
this.writeCount = writeCount;
}
@Override
public String toString()
{
return transaction+"{" +"readCount=" + readCount + ", writeCount=" + writeCount + "}";
}
public String getTransaction()
{
return transaction;
}
public int getReadCount()
{
return readCount;
}
public int getWriteCount()
{
return writeCount;
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_info_LockingTransaction.java
|
433
|
RELATIONSHIP
{
@Override
public String toString( String resourceId )
{
return "Relationship[" + resourceId + "]";
}
},
| false
|
community_kernel_src_main_java_org_neo4j_kernel_info_ResourceType.java
|
434
|
public abstract class XaDataSource implements Lifecycle
{
private byte[] branchId = null;
private String name = null;
/**
* Constructor used by the Neo4j kernel to create datasources.
*
*/
public XaDataSource(byte branchId[], String name)
{
this.branchId = branchId;
this.name = name;
}
/**
* Creates a XA connection to the resource this data source represents.
*
* @return A connection to an XA resource
*/
public abstract XaConnection getXaConnection();
/**
* Returns any assigned or default branch id for this data source.
*
* @return the branch id
*/
public byte[] getBranchId()
{
return this.branchId;
}
/**
* Returns a timestamp when this data source was created. Note this is not
* the timestamp for the creation of the data source object instance, if
* the data source is for example a database timestamp is meant to be when
* the database was created.
* <p>
* Creation time together with random identifier can be used to uniqley
* identify a data source (since it is possible to have multiple sources
* of same type).
*
* @return timestamp when this datasource was created
*/
public long getCreationTime()
{
throw new UnsupportedOperationException( getClass().getName() );
}
public File getFileName( long version )
{
throw new UnsupportedOperationException( getClass().getName() );
}
/**
* Returns a random identifier that gets generated when the data source is
* created. Note with "created" we mean first time data source is created
* and not object creation.
* <p>
* Creation time together with the random identifier can be used to uniquely
* identify a data source (since it is possible to have multiple sources of
* the same type).
*
* @return random identifier for this data source
*/
public long getRandomIdentifier()
{
throw new UnsupportedOperationException( getClass().getName() );
}
/**
* Returns the current version of this data source. A invoke to the
* {@link #rotateLogicalLog()} when keepLogicalLogs(boolean) is
* set to <code>true</code> will result in a log with that version created.
*
* @return the current version of the logical log
*/
public long getCurrentLogVersion()
{
throw new UnsupportedOperationException( getClass().getName() );
}
/**
* Rotates this logical log. Active transactions get copied to a new logical log.
*
* @return the last transaction id of the produced logical log.
* @throws IOException if unable to read old log or write to new one
*/
public long rotateLogicalLog() throws IOException
{
throw new UnsupportedOperationException( getClass().getName() );
}
/**
* Returns a readable byte channel of the specified logical log.
*
* @param version version of the logical log
* @return readable byte channel of the logical log
* @throws IOException if no such log exist
*/
public ReadableByteChannel getLogicalLog( long version ) throws IOException
{
throw new UnsupportedOperationException( getClass().getName() );
}
/**
* Tests if a specific logical log exists.
*
* @param version the version of the logical log
* @return <CODE>true</CODE> if the log exists
*/
public boolean hasLogicalLog( long version )
{
throw new UnsupportedOperationException( getClass().getName() );
}
public long getLogicalLogLength( long version )
{
throw new UnsupportedOperationException( getClass().getName() );
}
/**
* Deletes a log specific logical log.
*
* @param version version of log to delete
*
* @return true if the log existed and was deleted
*/
public boolean deleteLogicalLog( long version )
{
throw new UnsupportedOperationException( getClass().getName() );
}
/**
* Returns the assigned name of this resource.
*
* @return the assigned name of this resource
*/
public String getName()
{
return name;
}
/**
* Turns off/on auto rotate of logical logs. Default is <CODE>true</CODE>.
*
* @param rotate <CODE>true</CODE> to turn on
* @deprecated in favor of {@link GraphDatabaseSettings#logical_log_rotation_threshold}
*/
@Deprecated
public void setAutoRotate( boolean rotate )
{
throw new UnsupportedOperationException( getClass().getName() );
}
/**
* Sets the target size of the logical log that will cause a rotation of
* the log if {@link #setAutoRotate(boolean)} is set to <CODE>true</CODE>.
*
* @param size target size in bytes
* @deprecated in favor of setting {@link GraphDatabaseSettings#logical_log_rotation_threshold} to {@code 0}.
*/
@Deprecated
public void setLogicalLogTargetSize( long size )
{
throw new UnsupportedOperationException( getClass().getName() );
}
public ReadableByteChannel getPreparedTransaction( int identifier ) throws IOException
{
throw new UnsupportedOperationException( getClass().getName() );
}
public void getPreparedTransaction( int identifier, LogBuffer targetBuffer ) throws IOException
{
throw new UnsupportedOperationException( getClass().getName() );
}
public void applyCommittedTransaction( long txId, ReadableByteChannel transaction ) throws IOException
{
getXaContainer().getResourceManager().applyCommittedTransaction( transaction, txId );
}
public long applyPreparedTransaction( ReadableByteChannel transaction ) throws IOException
{
return getXaContainer().getResourceManager().applyPreparedTransaction( transaction );
}
public long getLastCommittedTxId()
{
throw new UnsupportedOperationException( getClass().getName() );
}
public void setLastCommittedTxId( long txId )
{
throw new UnsupportedOperationException( getClass().getName() );
}
public XaContainer getXaContainer()
{
throw new UnsupportedOperationException( getClass().getName() );
}
public Pair<Integer,Long> getMasterForCommittedTx( long txId ) throws IOException
{
throw new UnsupportedOperationException( getClass().getName() );
}
public ResourceIterator<File> listStoreFiles( boolean includeLogicalLogs ) throws IOException
{
throw new UnsupportedOperationException( getClass().getName() );
}
public ResourceIterator<File> listStoreFiles() throws IOException
{
throw new UnsupportedOperationException( getClass().getName() );
}
public ResourceIterator<File> listLogicalLogs( ) throws IOException
{
throw new UnsupportedOperationException( getClass().getName() );
}
/**
* Should return a log writer that remains usable after this {@link XaDataSource} has been shut down.
* This log writer is guaranteed to not be used against any existing store locations while this data source
* is running.
*/
public LogBufferFactory createLogBufferFactory()
{
throw new UnsupportedOperationException( getClass().getName() );
}
@Override
public void init() throws Throwable
{
}
@Override
public void start() throws Throwable
{
}
@Override
public void stop() throws Throwable
{
}
@Override
public void shutdown() throws Throwable
{
}
/**
* Returns previous value
*/
public boolean setRecovered( boolean recovered )
{
return false;
}
public LogExtractor getLogExtractor( long startTxId, long endTxIdHint ) throws IOException
{
throw new UnsupportedOperationException( getClass().getName() );
}
public void recoveryCompleted() throws IOException
{
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_XaDataSource.java
|
435
|
OTHER
{
@Override
public String toString( String resourceId )
{
return resourceId;
}
};
| false
|
community_kernel_src_main_java_org_neo4j_kernel_info_ResourceType.java
|
436
|
private class LifecycleInstance
implements Lifecycle
{
Lifecycle instance;
LifecycleStatus currentStatus = LifecycleStatus.NONE;
private LifecycleInstance( Lifecycle instance )
{
this.instance = instance;
}
@Override
public void init()
throws LifecycleException
{
if ( currentStatus == LifecycleStatus.NONE )
{
currentStatus = changedStatus( instance, currentStatus, LifecycleStatus.INITIALIZING );
try
{
instance.init();
currentStatus = changedStatus( instance, currentStatus, LifecycleStatus.STOPPED );
}
catch ( Throwable e )
{
currentStatus = changedStatus( instance, currentStatus, LifecycleStatus.NONE );
throw new LifecycleException( instance, LifecycleStatus.NONE, LifecycleStatus.STOPPED, e );
}
}
}
@Override
public void start()
throws LifecycleException
{
if ( currentStatus == LifecycleStatus.NONE )
{
init();
}
if ( currentStatus == LifecycleStatus.STOPPED )
{
currentStatus = changedStatus( instance, currentStatus, LifecycleStatus.STARTING );
try
{
instance.start();
currentStatus = changedStatus( instance, currentStatus, LifecycleStatus.STARTED );
}
catch ( Throwable e )
{
currentStatus = changedStatus( instance, currentStatus, LifecycleStatus.STOPPED );
throw new LifecycleException( instance, LifecycleStatus.STOPPED, LifecycleStatus.STARTED, e );
}
}
}
@Override
public void stop()
throws LifecycleException
{
if ( currentStatus == LifecycleStatus.STARTED )
{
currentStatus = changedStatus( instance, currentStatus, LifecycleStatus.STOPPING );
try
{
instance.stop();
}
catch ( Throwable e )
{
log.error( "Exception when stopping " + instance, e );
throw new LifecycleException( instance, LifecycleStatus.STARTED, LifecycleStatus.STOPPED, e );
}
finally
{
currentStatus = changedStatus( instance, currentStatus, LifecycleStatus.STOPPED );
}
}
}
@Override
public void shutdown()
throws LifecycleException
{
if ( currentStatus == LifecycleStatus.STARTED )
{
stop();
}
if ( currentStatus == LifecycleStatus.STOPPED )
{
currentStatus = changedStatus( instance, currentStatus, LifecycleStatus.SHUTTING_DOWN );
try
{
instance.shutdown();
}
catch ( Throwable e )
{
throw new LifecycleException( instance, LifecycleStatus.STOPPED, LifecycleStatus.SHUTTING_DOWN, e );
}
finally
{
currentStatus = changedStatus( instance, currentStatus, LifecycleStatus.SHUTDOWN );
}
}
}
@Override
public String toString()
{
return instance.toString() + ": " + currentStatus.name();
}
public boolean isInstance( Object instance )
{
return this.instance == instance;
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_lifecycle_LifeSupport.java
|
437
|
{
@Override
public boolean visit( StringLogger.LineLogger element )
{
for ( LifecycleInstance instance : instances )
{
element.logLine( instance.toString() );
}
return true;
}
}, true
| false
|
community_kernel_src_main_java_org_neo4j_kernel_lifecycle_LifeSupport.java
|
438
|
{
@Override
public Lifecycle apply( LifecycleInstance lifecycleInstance )
{
return lifecycleInstance.instance;
}
}, new ArrayList<>(instances) );
| false
|
community_kernel_src_main_java_org_neo4j_kernel_lifecycle_LifeSupport.java
|
439
|
public class LifeSupport
implements Lifecycle
{
private volatile List<LifecycleInstance> instances = new ArrayList<LifecycleInstance>();
private volatile LifecycleStatus status = LifecycleStatus.NONE;
private final List<LifecycleListener> listeners = new ArrayList<LifecycleListener>();
private final StringLogger log;
public LifeSupport()
{
this( StringLogger.SYSTEM_ERR );
}
public LifeSupport( StringLogger log )
{
this.log = log;
}
/**
* Initialize all registered instances, transitioning from status NONE to STOPPED.
* <p/>
* If transition fails, then it goes to STOPPED and then SHUTDOWN, so it cannot be restarted again.
*/
@Override
public synchronized void init()
throws LifecycleException
{
if ( status == LifecycleStatus.NONE )
{
status = changedStatus( this, status, LifecycleStatus.INITIALIZING );
for ( LifecycleInstance instance : instances )
{
try
{
instance.init();
}
catch ( LifecycleException e )
{
status = changedStatus( this, status, LifecycleStatus.STOPPED );
try
{
shutdown();
}
catch ( LifecycleException e1 )
{
throw causedBy( e1, e );
}
throw e;
}
}
status = changedStatus( this, status, LifecycleStatus.STOPPED );
}
}
/**
* Start all registered instances, transitioning from STOPPED to STARTED.
* <p/>
* If it was previously not initialized, it will be initialized first.
* <p/>
* If any instance fails to start, the already started instances will be stopped, so
* that the overall status is STOPPED.
*
* @throws LifecycleException
*/
@Override
public synchronized void start()
throws LifecycleException
{
init();
if ( status == LifecycleStatus.STOPPED )
{
status = changedStatus( this, status, LifecycleStatus.STARTING );
for ( LifecycleInstance instance : instances )
{
try
{
instance.start();
}
catch ( LifecycleException e )
{
// TODO perhaps reconsider chaining of exceptions coming from LifeSupports?
status = changedStatus( this, status, LifecycleStatus.STARTED );
try
{
stop();
}
catch ( LifecycleException e1 )
{
throw causedBy( e1, e );
}
throw e;
}
}
status = changedStatus( this, status, LifecycleStatus.STARTED );
}
}
/**
* Stop all registered instances, transitioning from STARTED to STOPPED.
* <p/>
* If any instance fails to stop, the rest of the instances will still be stopped,
* so that the overall status is STOPPED.
*/
@Override
public synchronized void stop()
throws LifecycleException
{
if ( status == LifecycleStatus.STARTED )
{
status = changedStatus( this, status, LifecycleStatus.STOPPING );
LifecycleException ex = null;
for ( int i = instances.size() - 1; i >= 0; i-- )
{
LifecycleInstance lifecycleInstance = instances.get( i );
try
{
lifecycleInstance.stop();
}
catch ( LifecycleException e )
{
ex = causedBy( e, ex );
}
}
status = changedStatus( this, status, LifecycleStatus.STOPPED );
if ( ex != null )
{
throw ex;
}
}
}
/**
* Shutdown all registered instances, transitioning from either STARTED or STOPPED to SHUTDOWN.
* <p/>
* If any instance fails to shutdown, the rest of the instances will still be shut down,
* so that the overall status is SHUTDOWN.
*/
@Override
public synchronized void shutdown()
throws LifecycleException
{
LifecycleException ex = null;
try
{
stop();
}
catch ( LifecycleException e )
{
ex = e;
}
if ( status == LifecycleStatus.STOPPED )
{
status = changedStatus( this, status, LifecycleStatus.SHUTTING_DOWN );
for ( int i = instances.size() - 1; i >= 0; i-- )
{
LifecycleInstance lifecycleInstance = instances.get( i );
try
{
lifecycleInstance.shutdown();
}
catch ( LifecycleException e )
{
ex = causedBy( e, ex );
}
}
status = changedStatus( this, status, LifecycleStatus.SHUTDOWN );
if ( ex != null )
{
throw ex;
}
}
}
/**
* Restart an individual instance. All instances "after" the instance will be stopped first,
* so that they don't try to use it during the restart. A restart is effectively a stop followed
* by a start.
*
* @throws LifecycleException if any start or stop fails
* @throws IllegalArgumentException if instance is not registered
*/
public synchronized void restart( Lifecycle instance )
throws LifecycleException, IllegalArgumentException
{
if ( status == LifecycleStatus.STARTED )
{
boolean foundRestartingInstance = false;
List<LifecycleInstance> restartingInstances = new ArrayList<LifecycleInstance>();
for ( LifecycleInstance lifecycleInstance : instances )
{
if ( lifecycleInstance.instance == instance )
{
foundRestartingInstance = true;
}
if ( foundRestartingInstance )
{
restartingInstances.add( lifecycleInstance );
}
}
if ( !foundRestartingInstance )
{
throw new IllegalArgumentException( "Instance is not registered" );
}
// Stop instances
status = changedStatus( this, status, LifecycleStatus.STOPPING );
LifecycleException ex = null;
for ( int i = restartingInstances.size() - 1; i >= 0; i-- )
{
LifecycleInstance lifecycleInstance = restartingInstances.get( i );
try
{
lifecycleInstance.stop();
}
catch ( LifecycleException e )
{
ex = causedBy( e, ex );
}
}
// Failed stop - stop the whole thing to be safe
if ( ex != null )
{
status = changedStatus( this, status, LifecycleStatus.STARTED );
try
{
stop();
throw ex;
}
catch ( LifecycleException e )
{
throw causedBy( e, ex );
}
}
// Start instances
try
{
for ( int i = 0; i < restartingInstances.size(); i++ )
{
LifecycleInstance lifecycle = restartingInstances.get( i );
lifecycle.start();
}
status = changedStatus( this, status, LifecycleStatus.STARTED );
}
catch ( LifecycleException e )
{
// Failed restart - stop the whole thing to be safe
status = changedStatus( this, status, LifecycleStatus.STARTED );
try
{
stop();
throw e;
}
catch ( LifecycleException e1 )
{
throw causedBy( e1, e );
}
}
}
}
/**
* Add a new Lifecycle instance. It will immediately be transitioned
* to the state of this LifeSupport.
*
* @param instance the Lifecycle instance to add
* @param <T> type of the instance
* @return the instance itself
* @throws LifecycleException if the instance could not be transitioned properly
*/
public synchronized <T> T add( T instance )
throws LifecycleException
{
if ( instance instanceof Lifecycle )
{
LifecycleInstance newInstance = new LifecycleInstance( (Lifecycle) instance );
List<LifecycleInstance> tmp = new ArrayList<>( instances );
tmp.add(newInstance);
instances = tmp;
bringToState( newInstance );
}
return instance;
}
public synchronized boolean remove( Object instance )
{
for ( int i = 0; i < instances.size(); i++ )
{
if ( instances.get( i ).isInstance( instance ) )
{
List<LifecycleInstance> tmp = new ArrayList<>( instances );
LifecycleInstance lifecycleInstance = tmp.remove( i );
lifecycleInstance.shutdown();
instances = tmp;
return true;
}
}
return false;
}
public Iterable<Lifecycle> getLifecycleInstances()
{
return Iterables.map( new Function<LifecycleInstance, Lifecycle>()
{
@Override
public Lifecycle apply( LifecycleInstance lifecycleInstance )
{
return lifecycleInstance.instance;
}
}, new ArrayList<>(instances) );
}
/**
* Shutdown and throw away all the current instances. After
* this you can add new instances. This method does not change
* the status of the LifeSupport (i.e. if it was started it will remain started)
*/
public synchronized void clear()
{
for ( LifecycleInstance instance : instances )
{
instance.shutdown();
}
instances = new ArrayList<>( );
}
public LifecycleStatus getStatus()
{
return status;
}
public synchronized void addLifecycleListener( LifecycleListener listener )
{
listeners.add( listener );
}
public synchronized void removeLifecycleListener( LifecycleListener listener )
{
listeners.remove( listener );
}
public synchronized void dump( StringLogger logger )
{
logger.logLongMessage( "Lifecycle status:" + status.name(), new Visitor<StringLogger.LineLogger,
RuntimeException>()
{
@Override
public boolean visit( StringLogger.LineLogger element )
{
for ( LifecycleInstance instance : instances )
{
element.logLine( instance.toString() );
}
return true;
}
}, true
);
}
private void bringToState( LifecycleInstance instance )
throws LifecycleException
{
switch ( status )
{
case STARTED:
instance.start();
break;
case STOPPED:
instance.init();
break;
case SHUTDOWN:
break;
}
}
private LifecycleException causedBy( LifecycleException exception, LifecycleException chainedLifecycleException )
{
if ( chainedLifecycleException == null )
{
return exception;
}
log.error( "Lifecycle exception", exception );
log.error( "Chained lifecycle exception", chainedLifecycleException );
Throwable current = exception;
while ( current.getCause() != null )
{
current = current.getCause();
}
current.initCause( chainedLifecycleException );
return exception;
}
private LifecycleStatus changedStatus( Lifecycle instance,
LifecycleStatus oldStatus,
LifecycleStatus newStatus
)
{
for ( LifecycleListener listener : listeners )
{
listener.notifyStatusChanged( instance, oldStatus, newStatus );
}
return newStatus;
}
public boolean isRunning()
{
return status == LifecycleStatus.STARTED;
}
private class LifecycleInstance
implements Lifecycle
{
Lifecycle instance;
LifecycleStatus currentStatus = LifecycleStatus.NONE;
private LifecycleInstance( Lifecycle instance )
{
this.instance = instance;
}
@Override
public void init()
throws LifecycleException
{
if ( currentStatus == LifecycleStatus.NONE )
{
currentStatus = changedStatus( instance, currentStatus, LifecycleStatus.INITIALIZING );
try
{
instance.init();
currentStatus = changedStatus( instance, currentStatus, LifecycleStatus.STOPPED );
}
catch ( Throwable e )
{
currentStatus = changedStatus( instance, currentStatus, LifecycleStatus.NONE );
throw new LifecycleException( instance, LifecycleStatus.NONE, LifecycleStatus.STOPPED, e );
}
}
}
@Override
public void start()
throws LifecycleException
{
if ( currentStatus == LifecycleStatus.NONE )
{
init();
}
if ( currentStatus == LifecycleStatus.STOPPED )
{
currentStatus = changedStatus( instance, currentStatus, LifecycleStatus.STARTING );
try
{
instance.start();
currentStatus = changedStatus( instance, currentStatus, LifecycleStatus.STARTED );
}
catch ( Throwable e )
{
currentStatus = changedStatus( instance, currentStatus, LifecycleStatus.STOPPED );
throw new LifecycleException( instance, LifecycleStatus.STOPPED, LifecycleStatus.STARTED, e );
}
}
}
@Override
public void stop()
throws LifecycleException
{
if ( currentStatus == LifecycleStatus.STARTED )
{
currentStatus = changedStatus( instance, currentStatus, LifecycleStatus.STOPPING );
try
{
instance.stop();
}
catch ( Throwable e )
{
log.error( "Exception when stopping " + instance, e );
throw new LifecycleException( instance, LifecycleStatus.STARTED, LifecycleStatus.STOPPED, e );
}
finally
{
currentStatus = changedStatus( instance, currentStatus, LifecycleStatus.STOPPED );
}
}
}
@Override
public void shutdown()
throws LifecycleException
{
if ( currentStatus == LifecycleStatus.STARTED )
{
stop();
}
if ( currentStatus == LifecycleStatus.STOPPED )
{
currentStatus = changedStatus( instance, currentStatus, LifecycleStatus.SHUTTING_DOWN );
try
{
instance.shutdown();
}
catch ( Throwable e )
{
throw new LifecycleException( instance, LifecycleStatus.STOPPED, LifecycleStatus.SHUTTING_DOWN, e );
}
finally
{
currentStatus = changedStatus( instance, currentStatus, LifecycleStatus.SHUTDOWN );
}
}
}
@Override
public String toString()
{
return instance.toString() + ": " + currentStatus.name();
}
public boolean isInstance( Object instance )
{
return this.instance == instance;
}
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_lifecycle_LifeSupport.java
|
440
|
{
@Override
public void evaluate() throws Throwable
{
try
{
base.evaluate();
}
finally
{
LifeRule.this.shutdown();
}
}
};
| false
|
community_kernel_src_test_java_org_neo4j_kernel_lifecycle_LifeRule.java
|
441
|
public class LifeRule extends LifeSupport implements TestRule
{
@Override
public Statement apply( final Statement base, Description description )
{
return new Statement()
{
@Override
public void evaluate() throws Throwable
{
try
{
base.evaluate();
}
finally
{
LifeRule.this.shutdown();
}
}
};
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_lifecycle_LifeRule.java
|
442
|
public class GitHub1304Test
{
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Test
public void givenBatchInserterWhenArrayPropertyUpdated4TimesThenShouldNotFail()
{
BatchInserter batchInserter = BatchInserters.inserter( folder.getRoot().getAbsolutePath() );
long nodeId = batchInserter.createNode( Collections.<String, Object>emptyMap() );
for ( int i = 0; i < 4; i++ )
{
batchInserter.setNodeProperty( nodeId, "array", new byte[]{2, 3, 98, 1, 43, 50, 3, 33, 51, 55, 116, 16, 23,
56, 9, -10, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1} );
}
batchInserter.getNodeProperties( nodeId ); //fails here
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_lifecycle_GitHub1304Test.java
|
443
|
public final class WaitingThread extends LockingTransaction
{
public static WaitingThread create( String transaction, int readCount, int writeCount, Thread thread,
long waitingSince, boolean isWriteLock )
{
return new WaitingThread( transaction, readCount, writeCount, thread.getId(), thread.getName(), waitingSince,
isWriteLock );
}
private static final long serialVersionUID = 1L;
private final boolean writeLock;
private final long threadId;
private final String threadName;
private final long waitingSince;
@ConstructorProperties({"transaction", "readCount", "writeCount", "threadId", "threadName", "waitingSince",
"waitingOnWriteLock"})
public WaitingThread( String transaction, int readCount, int writeCount, long threadId, String threadName,
long waitingSince, boolean writeLock )
{
super( transaction, readCount, writeCount );
this.threadId = threadId;
this.threadName = threadName;
this.waitingSince = waitingSince;
this.writeLock = writeLock;
}
@Override
public String toString()
{
StringBuilder builder = new StringBuilder();
builder.append( "\"" ).append( getThreadName() ).append( "\" " ).append( " (" ).append( getTransaction() ).
append( ") " ).append( "[tid=" ).append( getThreadId() ).append( "(" ).append(
getReadCount() ).append( "r," ).append( getWriteCount() ).append( "w )," ).append(
isWaitingOnWriteLock() ? "Write" : "Read" ).append( "Lock]" );
return builder.toString();
}
public boolean isWaitingOnReadLock()
{
return !writeLock;
}
public boolean isWaitingOnWriteLock()
{
return writeLock;
}
public long getThreadId()
{
return threadId;
}
public String getThreadName()
{
return threadName;
}
public long getWaitingSince()
{
return waitingSince;
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_info_WaitingThread.java
|
444
|
NETWORK( "Network information:" )
{
@Override
void dump( LineLogger logger )
{
try
{
Enumeration<NetworkInterface> networkInterfaces = getNetworkInterfaces();
while ( networkInterfaces.hasMoreElements() )
{
NetworkInterface iface = networkInterfaces.nextElement();
logger.logLine( String.format( "Interface %s:", iface.getDisplayName() ) );
Enumeration<InetAddress> addresses = iface.getInetAddresses();
while ( addresses.hasMoreElements() )
{
InetAddress address = addresses.nextElement();
String hostAddress = address.getHostAddress();
logger.logLine( String.format( " address: %s", hostAddress ) );
}
}
} catch ( SocketException e )
{
logger.logLine( "ERROR: failed to inspect network interfaces and addresses: " + e.getMessage() );
}
}
},
| false
|
community_kernel_src_main_java_org_neo4j_kernel_info_SystemDiagnostics.java
|
445
|
{
@Override
public boolean accept( File path )
{
return path.isDirectory();
}
} ) )
| false
|
community_kernel_src_main_java_org_neo4j_kernel_info_SystemDiagnostics.java
|
446
|
LINUX_SCHEDULERS( "Linux scheduler information:" )
{
private final File SYS_BLOCK = new File( "/sys/block" );
@Override
boolean isApplicable()
{
return SYS_BLOCK.isDirectory();
}
@Override
void dump( StringLogger.LineLogger logger )
{
for ( File subdir : SYS_BLOCK.listFiles( new java.io.FileFilter()
{
@Override
public boolean accept( File path )
{
return path.isDirectory();
}
} ) )
{
File scheduler = new File( subdir, "queue/scheduler" );
if ( scheduler.isFile() )
{
try
{
BufferedReader reader = newBufferedFileReader( scheduler, UTF_8 );
try
{
for ( String line; null != ( line = reader.readLine() ); )
logger.logLine( line );
}
finally
{
reader.close();
}
}
catch ( IOException e )
{
// ignore
}
}
}
}
},
| false
|
community_kernel_src_main_java_org_neo4j_kernel_info_SystemDiagnostics.java
|
447
|
SYSTEM_PROPERTIES( "System.properties:" )
{
@Override
void dump( StringLogger.LineLogger logger )
{
for ( Object property : System.getProperties().keySet() )
{
if ( property instanceof String )
{
String key = (String) property;
if ( key.startsWith( "java." ) || key.startsWith( "os." ) || key.endsWith( ".boot.class.path" )
|| key.equals( "line.separator" ) ) continue;
logger.logLine( key + " = " + System.getProperty( key ) );
}
}
}
},
| false
|
community_kernel_src_main_java_org_neo4j_kernel_info_SystemDiagnostics.java
|
448
|
LIBRARY_PATH( "Library path:" )
{
@Override
void dump( StringLogger.LineLogger logger )
{
RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
for ( String path : runtime.getLibraryPath().split( File.pathSeparator ) )
{
logger.logLine( canonicalize( path ) );
}
}
},
| false
|
community_kernel_src_main_java_org_neo4j_kernel_info_SystemDiagnostics.java
|
449
|
CLASSPATH( "Java classpath:" )
{
@Override
void dump( StringLogger.LineLogger logger )
{
RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
Collection<String> classpath;
if ( runtime.isBootClassPathSupported() )
{
classpath = buildClassPath( getClass().getClassLoader(),
new String[] { "bootstrap", "classpath" },
runtime.getBootClassPath(), runtime.getClassPath() );
}
else
{
classpath = buildClassPath( getClass().getClassLoader(),
new String[] { "classpath" }, runtime.getClassPath() );
}
for ( String path : classpath )
{
logger.logLine( path );
}
}
private Collection<String> buildClassPath( ClassLoader loader, String[] pathKeys, String... classPaths )
{
Map<String, String> paths = new HashMap<String, String>();
assert pathKeys.length == classPaths.length;
for ( int i = 0; i < classPaths.length; i++ )
for ( String path : classPaths[i].split( File.pathSeparator ) )
paths.put( canonicalize( path ), pathValue( paths, pathKeys[i], path ) );
for ( int level = 0; loader != null; level++ )
{
if ( loader instanceof URLClassLoader )
{
URLClassLoader urls = (URLClassLoader) loader;
for ( URL url : urls.getURLs() )
if ( "file".equalsIgnoreCase( url.getProtocol() ) )
paths.put( url.toString(), pathValue( paths, "loader." + level, url.getPath() ) );
}
loader = loader.getParent();
}
List<String> result = new ArrayList<String>( paths.size() );
for ( Map.Entry<String, String> path : paths.entrySet() )
{
result.add( " [" + path.getValue() + "] " + path.getKey() );
}
return result;
}
private String pathValue( Map<String, String> paths, String key, String path )
{
String value;
if ( null != ( value = paths.remove( canonicalize( path ) ) ) )
{
value += " + " + key;
}
else
{
value = key;
}
return value;
}
},
| false
|
community_kernel_src_main_java_org_neo4j_kernel_info_SystemDiagnostics.java
|
450
|
JAVA_VIRTUAL_MACHINE( "JVM information:" )
{
@Override
void dump( StringLogger.LineLogger logger )
{
RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
logger.logLine( "VM Name: " + runtime.getVmName() );
logger.logLine( "VM Vendor: " + runtime.getVmVendor() );
logger.logLine( "VM Version: " + runtime.getVmVersion() );
CompilationMXBean compiler = ManagementFactory.getCompilationMXBean();
logger.logLine( "JIT compiler: " + ( ( compiler == null ) ? "unknown" : compiler.getName() ) );
logger.logLine( "VM Arguments: " + runtime.getInputArguments() );
}
},
| false
|
community_kernel_src_main_java_org_neo4j_kernel_info_SystemDiagnostics.java
|
451
|
OPERATING_SYSTEM( "Operating system information:" )
{
private static final String SUN_UNIX_BEAN = "com.sun.management.UnixOperatingSystemMXBean";
@Override
void dump( StringLogger.LineLogger logger )
{
OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
logger.logLine( String.format( "Operating System: %s; version: %s; arch: %s; cpus: %s", os.getName(),
os.getVersion(), os.getArch(), os.getAvailableProcessors() ) );
logBeanProperty( logger, "Max number of file descriptors: ", os, SUN_UNIX_BEAN, "getMaxFileDescriptorCount" );
logBeanProperty( logger, "Number of open file descriptors: ", os, SUN_UNIX_BEAN, "getOpenFileDescriptorCount" );
logger.logLine( "Process id: " + runtime.getName() );
logger.logLine( "Byte order: " + ByteOrder.nativeOrder() );
logger.logLine( "Local timezone: " + getLocalTimeZone() );
}
private String getLocalTimeZone()
{
TimeZone tz = Calendar.getInstance().getTimeZone();
return tz.getID();
}
private void logBeanProperty( StringLogger.LineLogger logger, String message, Object bean, String type, String method )
{
Object value = getBeanProperty( bean, type, method, null );
if ( value != null ) logger.logLine( message + value );
}
},
| false
|
community_kernel_src_main_java_org_neo4j_kernel_info_SystemDiagnostics.java
|
452
|
JAVA_MEMORY( "JVM memory information:" )
{
@Override
void dump( StringLogger.LineLogger logger )
{
logger.logLine( "Free memory: " + bytes( Runtime.getRuntime().freeMemory() ) );
logger.logLine( "Total memory: " + bytes( Runtime.getRuntime().totalMemory() ) );
logger.logLine( "Max memory: " + bytes( Runtime.getRuntime().maxMemory() ) );
for ( GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans() )
{
logger.logLine( "Garbage Collector: " + gc.getName() + ": " + Arrays.toString( gc.getMemoryPoolNames() ) );
}
for ( MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans() )
{
MemoryUsage usage = pool.getUsage();
logger.logLine( String.format( "Memory Pool: %s (%s): committed=%s, used=%s, max=%s, threshold=%s",
pool.getName(), pool.getType(), usage == null ? "?" : bytes( usage.getCommitted() ),
usage == null ? "?" : bytes( usage.getUsed() ), usage == null ? "?" : bytes( usage.getMax() ),
pool.isUsageThresholdSupported() ? bytes( pool.getUsageThreshold() ) : "?" ) );
}
}
},
| false
|
community_kernel_src_main_java_org_neo4j_kernel_info_SystemDiagnostics.java
|
453
|
{
@Override
public boolean visit( LineLogger logger )
{
dump( logger );
return false;
}
}, true );
| false
|
community_kernel_src_main_java_org_neo4j_kernel_info_SystemDiagnostics.java
|
454
|
SYSTEM_MEMORY( "System memory information:" )
{
private static final String SUN_OS_BEAN = "com.sun.management.OperatingSystemMXBean";
private static final String IBM_OS_BEAN = "com.ibm.lang.management.OperatingSystemMXBean";
@Override
void dump( StringLogger.LineLogger logger )
{
OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
logBeanBytesProperty( logger, "Total Physical memory: ", os, SUN_OS_BEAN, "getTotalPhysicalMemorySize" );
logBeanBytesProperty( logger, "Free Physical memory: ", os, SUN_OS_BEAN, "getFreePhysicalMemorySize" );
logBeanBytesProperty( logger, "Committed virtual memory: ", os, SUN_OS_BEAN, "getCommittedVirtualMemorySize" );
logBeanBytesProperty( logger, "Total swap space: ", os, SUN_OS_BEAN, "getTotalSwapSpaceSize" );
logBeanBytesProperty( logger, "Free swap space: ", os, SUN_OS_BEAN, "getFreeSwapSpaceSize" );
logBeanBytesProperty( logger, "Total physical memory: ", os, IBM_OS_BEAN, "getTotalPhysicalMemory" );
logBeanBytesProperty( logger, "Free physical memory: ", os, IBM_OS_BEAN, "getFreePhysicalMemorySize" );
}
private void logBeanBytesProperty( StringLogger.LineLogger logger, String message, Object bean, String type,
String method )
{
Object value = getBeanProperty( bean, type, method, null );
if ( value instanceof Number ) logger.logLine( message + bytes( ( (Number) value ).longValue() ) );
}
},
| false
|
community_kernel_src_main_java_org_neo4j_kernel_info_SystemDiagnostics.java
|
455
|
public class TestMultipleCauseException
{
@Test
public void shouldBeAbleToAddCauses()
{
Throwable cause = new Throwable();
MultipleCauseException exception = new MultipleCauseException( "Hello", cause );
assertThat( exception.getMessage(), is( "Hello" ) );
assertThat( exception.getCause(), is( cause ) );
assertThat( exception.getCauses(), is( not( nullValue() ) ) );
assertThat( exception.getCauses().size(), is( 1 ) );
assertThat( exception.getCauses().get( 0 ), is( cause ) );
}
@Test
public void stackTraceShouldContainAllCauses()
{
Throwable cause1 = new Throwable( "Message 1" );
MultipleCauseException exception = new MultipleCauseException( "Hello", cause1 );
Throwable cause2 = new Throwable( "Message 2" );
exception.addCause( cause2 );
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintWriter out = new PrintWriter( baos );
// When
exception.printStackTrace( out );
out.flush();
String stackTrace = baos.toString();
// Then
assertThat( "Stack trace contains exception one as cause.",
stackTrace.contains( "Caused by: java.lang.Throwable: Message 1" ), is( true ) );
assertThat( "Stack trace contains exception one as cause.",
stackTrace.contains( "Also caused by: java.lang.Throwable: Message 2" ), is( true ) );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_util_TestMultipleCauseException.java
|
456
|
public class TestLogging implements Logging
{
private Map<Class, TestLogger> loggers = new HashMap<>();
@Override
public TestLogger getMessagesLog( Class loggingClass )
{
if(!loggers.containsKey( loggingClass ))
{
loggers.put( loggingClass, new TestLogger() );
}
return loggers.get( loggingClass );
}
@Override
public ConsoleLogger getConsoleLog( Class loggingClass )
{
return new ConsoleLogger( getMessagesLog( loggingClass ) );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_util_TestLogging.java
|
457
|
public static final class LogCall
{
protected final Level level;
protected final String message;
protected final Throwable cause;
protected final boolean flush;
private LogCall( Level level, String message, Throwable cause, boolean flush )
{
this.level = level;
this.message = message;
this.cause = cause;
this.flush = flush;
}
// DSL sugar methods to use when writing assertions.
public static LogCall debug(String msg) { return new LogCall(Level.DEBUG, msg, null, false); }
public static LogCall info(String msg) { return new LogCall(Level.INFO, msg, null, false); }
public static LogCall warn(String msg) { return new LogCall(Level.WARN, msg, null, false); }
public static LogCall error(String msg) { return new LogCall(Level.ERROR, msg, null, false); }
public static LogCall debug(String msg, Throwable c) { return new LogCall(Level.DEBUG, msg, c, false); }
public static LogCall info(String msg, Throwable c) { return new LogCall(Level.INFO, msg, c, false); }
public static LogCall warn(String msg, Throwable c) { return new LogCall(Level.WARN, msg, c, false); }
public static LogCall error(String msg, Throwable c) { return new LogCall(Level.ERROR, msg, c, false); }
@Override
public String toString()
{
return "LogCall{ " + level +
", message='" + message + '\'' +
", cause=" + cause +
'}';
}
@Override
public boolean equals( Object o )
{
if ( this == o )
return true;
if ( o == null || getClass() != o.getClass() )
return false;
LogCall logCall = (LogCall) o;
return flush == logCall.flush && level == logCall.level &&
message.equals( logCall.message ) &&
!(cause != null ? !cause.equals( logCall.cause ) : logCall.cause != null);
}
@Override
public int hashCode()
{
int result = level.hashCode();
result = 31 * result + message.hashCode();
result = 31 * result + (cause != null ? cause.hashCode() : 0);
result = 31 * result + (flush ? 1 : 0);
return result;
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_util_TestLogger.java
|
458
|
return new Predicate<LogCall>(){
@Override
public boolean accept( LogCall item )
{
return item.level == level;
}
};
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_util_TestLogger.java
|
459
|
public static final ResourceIterator EMPTY_ITERATOR = new ResourceIterator(){
@Override
public void close()
{
}
@Override
public boolean hasNext()
{
return false;
}
@Override
public Object next()
{
return null;
}
@Override
public void remove()
{
}
};
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_util_ResourceIterators.java
|
460
|
public class ResourceIterators
{
public static final ResourceIterator EMPTY_ITERATOR = new ResourceIterator(){
@Override
public void close()
{
}
@Override
public boolean hasNext()
{
return false;
}
@Override
public Object next()
{
return null;
}
@Override
public void remove()
{
}
};
public static <T> ResourceIterator<T> emptyResourceIterator( Class<T> clazz )
{
return EMPTY_ITERATOR;
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_util_ResourceIterators.java
|
461
|
public class RelIdArrayWithLoops extends RelIdArray
{
private IdBlock lastLoopBlock;
public RelIdArrayWithLoops( int type )
{
super( type );
}
@Override
public int sizeOfObjectInBytesIncludingOverhead()
{
return super.sizeOfObjectInBytesIncludingOverhead() + sizeOfBlockWithReference( lastLoopBlock );
}
protected RelIdArrayWithLoops( RelIdArray from )
{
super( from );
lastLoopBlock = from.getLastLoopBlock();
}
protected RelIdArrayWithLoops( int type, IdBlock out, IdBlock in, IdBlock loop )
{
super( type, out, in );
this.lastLoopBlock = loop;
}
@Override
protected IdBlock getLastLoopBlock()
{
return this.lastLoopBlock;
}
@Override
protected void setLastLoopBlock( IdBlock block )
{
this.lastLoopBlock = block;
}
@Override
public RelIdArray upgradeIfNeeded( RelIdArray capabilitiesToMatch )
{
return this;
}
@Override
public RelIdArray downgradeIfPossible()
{
return lastLoopBlock == null ? new RelIdArray( this ) : this;
}
@Override
public RelIdArray newSimilarInstance()
{
return new RelIdArrayWithLoops( getType() );
}
@Override
protected boolean accepts( RelIdArray source )
{
return true;
}
@Override
public boolean couldBeNeedingUpdate()
{
return true;
}
@Override
public RelIdArray shrink()
{
IdBlock lastOutBlock = DirectionWrapper.OUTGOING.getBlock( this );
IdBlock lastInBlock = DirectionWrapper.INCOMING.getBlock( this );
IdBlock shrunkOut = lastOutBlock != null ? lastOutBlock.shrink() : null;
IdBlock shrunkIn = lastInBlock != null ? lastInBlock.shrink() : null;
IdBlock shrunkLoop = lastLoopBlock != null ? lastLoopBlock.shrink() : null;
return shrunkOut == lastOutBlock && shrunkIn == lastInBlock && shrunkLoop == lastLoopBlock ? this :
new RelIdArrayWithLoops( getType(), shrunkOut, shrunkIn, shrunkLoop );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_util_RelIdArrayWithLoops.java
|
462
|
public static class RelIdIteratorImpl implements RelIdIterator
{
private final DirectionWrapper[] directions;
private int directionPosition = -1;
private DirectionWrapper currentDirection;
private IteratorState currentState;
private final IteratorState[] states;
private long nextElement;
private boolean nextElementDetermined;
private RelIdArray ids;
RelIdIteratorImpl( RelIdArray ids, DirectionWrapper[] directions )
{
this.ids = ids;
this.directions = directions;
this.states = new IteratorState[directions.length];
// Find the initial block which isn't null. There can be directions
// which have a null block currently, but could potentially be set
// after the next getMoreRelationships.
IdBlock block = null;
while ( block == null && directionPosition+1 < directions.length )
{
currentDirection = directions[++directionPosition];
block = currentDirection.getBlock( ids );
}
if ( block != null )
{
currentState = new IteratorState( block, 0 );
states[directionPosition] = currentState;
}
}
@Override
public int getType()
{
return ids.getType();
}
@Override
public RelIdIterator updateSource( RelIdArray newSource, DirectionWrapper direction )
{
if ( ids != newSource || newSource.couldBeNeedingUpdate() )
{
ids = newSource;
// Blocks may have gotten upgraded to support a linked list
// of blocks, so reestablish those references.
for ( int i = 0; i < states.length; i++ )
{
if ( states[i] != null )
{
states[i].update( directions[i].getBlock( ids ) );
}
}
}
return this;
}
@Override
public boolean hasNext()
{
if ( nextElementDetermined )
{
return nextElement != -1;
}
while ( true )
{
if ( currentState != null && currentState.hasNext() )
{
nextElement = currentState.next();
nextElementDetermined = true;
return true;
}
else
{
if ( !nextBlock() )
{
break;
}
}
}
// Keep this false since the next call could come after we've loaded
// some more relationships
nextElementDetermined = false;
nextElement = -1;
return false;
}
protected boolean nextBlock()
{
while ( directionPosition+1 < directions.length )
{
currentDirection = directions[++directionPosition];
IteratorState nextState = states[directionPosition];
if ( nextState != null )
{
currentState = nextState;
return true;
}
IdBlock block = currentDirection.getBlock( ids );
if ( block != null )
{
currentState = new IteratorState( block, 0 );
states[directionPosition] = currentState;
return true;
}
}
return false;
}
@Override
public void doAnotherRound()
{
directionPosition = -1;
nextBlock();
}
@Override
public long next()
{
if ( !hasNext() )
{
throw new NoSuchElementException();
}
nextElementDetermined = false;
return nextElement;
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_util_RelIdArray.java
|
463
|
private static class LowIdBlock extends IdBlock
{
// First element is the actual length w/o the slack
private int[] ids = new int[3];
@Override
public int sizeOfObjectInBytesIncludingOverhead()
{
return withObjectOverhead( withReference( withArrayOverhead( 4*ids.length ) ) );
}
public static boolean idIsLow( long id )
{
return (id & 0xFF00000000L) == 0;
}
@Override
protected boolean accepts( long id )
{
return idIsLow( id );
}
@Override
protected boolean accepts( IdBlock block )
{
return block instanceof LowIdBlock;
}
@Override
protected void append( IdBlock source, int targetStartIndex, int itemsToCopy )
{
if ( source instanceof LowIdBlock )
{
arraycopy( ((LowIdBlock)source).ids, 1, ids, targetStartIndex, itemsToCopy );
}
else
{
throw new IllegalArgumentException( source.toString() );
}
}
@Override
IdBlock upgradeToHighIdBlock()
{
return new HighIdBlock( this );
}
@Override
protected IdBlock copyAndShrink()
{
LowIdBlock copy = new LowIdBlock();
copy.ids = Arrays.copyOf( ids, length()+1 );
return copy;
}
@Override
protected void extendArrayTo( int numberOfItemsToCopy, int newLength )
{
int[] newIds = new int[newLength+1];
arraycopy( ids, 0, newIds, 0, numberOfItemsToCopy+1 );
ids = newIds;
}
@Override
protected int length()
{
return ids[0];
}
@Override
protected int capacity()
{
return ids.length-1;
}
@Override
protected void setLength( int length )
{
ids[0] = length;
}
@Override
protected long get( int index )
{
assert index >= 0 && index < length();
return ids[index+1]&0xFFFFFFFFL;
}
@Override
protected void set( long id, int index )
{
ids[index+1] = (int) id; // guarded from outside that this is indeed an int
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_util_RelIdArray.java
|
464
|
private static class IteratorState
{
private IdBlock block;
private int relativePosition;
public IteratorState( IdBlock block, int relativePosition )
{
this.block = block;
this.relativePosition = relativePosition;
}
boolean hasNext()
{
return relativePosition < block.length();
}
/*
* Only called if hasNext returns true
*/
long next()
{
long id = block.get( relativePosition++ );
return id;
}
public void update( IdBlock block )
{
this.block = block;
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_util_RelIdArray.java
|
465
|
public static abstract class IdBlock implements SizeOfObject
{
/**
* @return a shrunk version of itself. It returns itself if there is
* no need to shrink it or a {@link #copyAndShrink()} if there is slack in the array.
*/
IdBlock shrink()
{
return length() == capacity() ? this : copyAndShrink();
}
void add( long id )
{
int length = ensureSpace( 1 );
set( id, length );
setLength( length+1 );
}
void addAll( IdBlock block )
{
int otherBlockLength = block.length();
int length = ensureSpace( otherBlockLength+1 );
append( block, length+1, otherBlockLength );
setLength( otherBlockLength+length );
}
/**
* Returns the number of ids in the array, not the array size.
*/
int ensureSpace( int delta )
{
int length = length();
int newLength = length+delta;
int capacity = capacity();
if ( newLength >= capacity )
{ // We're out of space, try doubling the size
int calculatedLength = capacity*2;
if ( newLength > calculatedLength )
{ // Doubling the size wasn't enough, go with double what was required
calculatedLength = newLength*2;
}
extendArrayTo( length, calculatedLength );
}
return length;
}
protected abstract boolean accepts( long id );
protected abstract boolean accepts( IdBlock block );
protected abstract IdBlock copyAndShrink();
abstract IdBlock upgradeToHighIdBlock();
protected abstract void extendArrayTo( int numberOfItemsToCopy, int newLength );
protected abstract void setLength( int length );
protected abstract int length();
protected abstract int capacity();
protected abstract void append( IdBlock source, int targetStartIndex, int itemsToCopy );
protected abstract long get( int index );
protected abstract void set( long id, int index );
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_util_RelIdArray.java
|
466
|
private static class HighIdBlock extends IdBlock
{
// First element is the actual length w/o the slack
private int[] ids;
private byte[] highBits;
public HighIdBlock()
{
ids = new int[3];
highBits = new byte[3];
}
private HighIdBlock( LowIdBlock lowIdBlock )
{
ids = Arrays.copyOf( lowIdBlock.ids, lowIdBlock.ids.length );
highBits = new byte[ids.length];
}
@Override
public int sizeOfObjectInBytesIncludingOverhead()
{
return withObjectOverhead(
withReference( withArrayOverhead( 4*ids.length ) ) +
withReference( withArrayOverhead( ids.length ) ) );
}
@Override
protected boolean accepts( long id )
{
return true;
}
@Override
protected boolean accepts( IdBlock block )
{
return true;
}
@Override
protected void append( IdBlock source, int targetStartIndex, int itemsToCopy )
{
if ( source instanceof LowIdBlock )
{
arraycopy( ((LowIdBlock)source).ids, 1, ids, targetStartIndex, itemsToCopy );
}
else
{
arraycopy( ((HighIdBlock)source).ids, 1, ids, targetStartIndex, itemsToCopy );
arraycopy( ((HighIdBlock)source).highBits, 1, highBits, targetStartIndex, itemsToCopy );
}
}
@Override
IdBlock upgradeToHighIdBlock()
{
return this;
}
@Override
protected IdBlock copyAndShrink()
{
HighIdBlock copy = new HighIdBlock();
int itemsToCopy = length()+1;
copy.ids = Arrays.copyOf( ids, itemsToCopy );
copy.highBits = Arrays.copyOf( highBits, itemsToCopy );
return copy;
}
@Override
protected void extendArrayTo( int numberOfItemsToCopy, int newLength )
{
int[] newIds = new int[newLength+1];
byte[] newHighBits = new byte[newLength+1];
arraycopy( ids, 0, newIds, 0, numberOfItemsToCopy+1 );
arraycopy( highBits, 0, newHighBits, 0, numberOfItemsToCopy+1 );
ids = newIds;
highBits = newHighBits;
}
@Override
protected int length()
{
return ids[0];
}
@Override
protected int capacity()
{
return ids.length-1;
}
@Override
protected void setLength( int length )
{
ids[0] = length;
}
@Override
protected long get( int index )
{
return ((long)highBits[index+1] << 32) | ids[index+1]&0xFFFFFFFFL;
}
@Override
protected void set( long id, int index )
{
ids[index+1] = (int)id;
highBits[index+1] = (byte) ((id&0xFF00000000L) >>> 32);
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_util_RelIdArray.java
|
467
|
{
@Override
public boolean hasNext()
{
return false;
}
@Override
protected boolean nextBlock()
{
return false;
}
@Override
public void doAnotherRound()
{
}
@Override
public RelIdIterator updateSource( RelIdArray newSource, DirectionWrapper direction )
{
return direction.iterator( newSource );
}
};
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_util_RelIdArray.java
|
468
|
public static class EmptyRelIdArray extends RelIdArray
{
private static final DirectionWrapper[] EMPTY_DIRECTION_ARRAY = new DirectionWrapper[0];
private final RelIdIterator EMPTY_ITERATOR = new RelIdIteratorImpl( this, EMPTY_DIRECTION_ARRAY )
{
@Override
public boolean hasNext()
{
return false;
}
@Override
protected boolean nextBlock()
{
return false;
}
@Override
public void doAnotherRound()
{
}
@Override
public RelIdIterator updateSource( RelIdArray newSource, DirectionWrapper direction )
{
return direction.iterator( newSource );
}
};
private EmptyRelIdArray( int type )
{
super( type );
}
@Override
public RelIdIterator iterator( final DirectionWrapper direction )
{
return EMPTY_ITERATOR;
}
};
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_util_RelIdArray.java
|
469
|
BOTH( Direction.BOTH )
{
@Override
RelIdIterator iterator( RelIdArray ids )
{
return new RelIdIteratorImpl( ids, DIRECTIONS_FOR_BOTH );
}
@Override
IdBlock getBlock( RelIdArray ids )
{
return ids.getLastLoopBlock();
}
@Override
void setBlock( RelIdArray ids, IdBlock block )
{
ids.setLastLoopBlock( block );
}
};
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_util_RelIdArray.java
|
470
|
INCOMING( Direction.INCOMING )
{
@Override
RelIdIterator iterator( RelIdArray ids )
{
return new RelIdIteratorImpl( ids, DIRECTIONS_FOR_INCOMING );
}
@Override
IdBlock getBlock( RelIdArray ids )
{
return ids.inBlock;
}
@Override
void setBlock( RelIdArray ids, IdBlock block )
{
ids.inBlock = block;
}
},
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_util_RelIdArray.java
|
471
|
OUTGOING( Direction.OUTGOING )
{
@Override
RelIdIterator iterator( RelIdArray ids )
{
return new RelIdIteratorImpl( ids, DIRECTIONS_FOR_OUTGOING );
}
@Override
IdBlock getBlock( RelIdArray ids )
{
return ids.outBlock;
}
@Override
void setBlock( RelIdArray ids, IdBlock block )
{
ids.outBlock = block;
}
},
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_util_RelIdArray.java
|
472
|
public class RelIdArray implements SizeOfObject
{
private static final DirectionWrapper[] DIRECTIONS_FOR_OUTGOING =
new DirectionWrapper[] { DirectionWrapper.OUTGOING, DirectionWrapper.BOTH };
private static final DirectionWrapper[] DIRECTIONS_FOR_INCOMING =
new DirectionWrapper[] { DirectionWrapper.INCOMING, DirectionWrapper.BOTH };
private static final DirectionWrapper[] DIRECTIONS_FOR_BOTH =
new DirectionWrapper[] { DirectionWrapper.OUTGOING, DirectionWrapper.INCOMING, DirectionWrapper.BOTH };
public static class EmptyRelIdArray extends RelIdArray
{
private static final DirectionWrapper[] EMPTY_DIRECTION_ARRAY = new DirectionWrapper[0];
private final RelIdIterator EMPTY_ITERATOR = new RelIdIteratorImpl( this, EMPTY_DIRECTION_ARRAY )
{
@Override
public boolean hasNext()
{
return false;
}
@Override
protected boolean nextBlock()
{
return false;
}
@Override
public void doAnotherRound()
{
}
@Override
public RelIdIterator updateSource( RelIdArray newSource, DirectionWrapper direction )
{
return direction.iterator( newSource );
}
};
private EmptyRelIdArray( int type )
{
super( type );
}
@Override
public RelIdIterator iterator( final DirectionWrapper direction )
{
return EMPTY_ITERATOR;
}
};
public static RelIdArray empty( int type )
{
return new EmptyRelIdArray( type );
}
public static final RelIdArray EMPTY = new EmptyRelIdArray( -1 );
private final int type;
private IdBlock outBlock;
private IdBlock inBlock;
public RelIdArray( int type )
{
this.type = type;
}
@Override
public int sizeOfObjectInBytesIncludingOverhead()
{
return withObjectOverhead( 8 /*type (padded)*/ + sizeOfBlockWithReference( outBlock ) + sizeOfBlockWithReference( inBlock ) );
}
static int sizeOfBlockWithReference( IdBlock block )
{
return withReference( block != null ? block.sizeOfObjectInBytesIncludingOverhead() : 0 );
}
public int getType()
{
return type;
}
protected RelIdArray( RelIdArray from )
{
this( from.type );
this.outBlock = from.outBlock;
this.inBlock = from.inBlock;
}
protected RelIdArray( int type, IdBlock out, IdBlock in )
{
this( type );
this.outBlock = out;
this.inBlock = in;
}
/*
* Adding an id with direction BOTH means that it's a loop
*/
public void add( long id, DirectionWrapper direction )
{
IdBlock block = direction.getBlock( this );
if ( block == null || !block.accepts( id ) )
{
IdBlock newBlock = null;
if ( block == null && LowIdBlock.idIsLow( id ) )
{
newBlock = new LowIdBlock();
}
else
{
newBlock = block != null ? block.upgradeToHighIdBlock() : new HighIdBlock();
}
direction.setBlock( this, newBlock );
block = newBlock;
}
block.add( id );
}
protected boolean accepts( RelIdArray source )
{
return source.getLastLoopBlock() == null;
}
public RelIdArray addAll( RelIdArray source )
{
// if ( source == null )
// {
// return this;
// }
if ( !accepts( source ) )
{
return upgradeIfNeeded( source ).addAll( source );
}
else
{
appendFrom( source, DirectionWrapper.OUTGOING );
appendFrom( source, DirectionWrapper.INCOMING );
appendFrom( source, DirectionWrapper.BOTH );
return this;
}
}
protected IdBlock getLastLoopBlock()
{
return null;
}
public RelIdArray shrink()
{
IdBlock shrunkOut = outBlock != null ? outBlock.shrink() : null;
IdBlock shrunkIn = inBlock != null ? inBlock.shrink() : null;
return shrunkOut == outBlock && shrunkIn == inBlock ? this : new RelIdArray( type, shrunkOut, shrunkIn );
}
protected void setLastLoopBlock( IdBlock block )
{
throw new UnsupportedOperationException( "Should've upgraded to RelIdArrayWithLoops before this" );
}
public RelIdArray upgradeIfNeeded( RelIdArray capabilitiesToMatch )
{
return capabilitiesToMatch.getLastLoopBlock() != null ? new RelIdArrayWithLoops( this ) : this;
}
public RelIdArray downgradeIfPossible()
{
return this;
}
protected void appendFrom( RelIdArray source, DirectionWrapper direction )
{
IdBlock toBlock = direction.getBlock( this );
IdBlock fromBlock = direction.getBlock( source );
if ( fromBlock == null )
{
return;
}
if ( toBlock == null )
{ // We've got no ids for that direction, just pop it right in (a copy of it)
direction.setBlock( this, fromBlock.copyAndShrink() );
}
else if ( toBlock.accepts( fromBlock ) )
{ // We've got some existing ids and the new ids are compatible, so add them
toBlock.addAll( fromBlock );
}
else
{ // We've got some existing ids, but ids aren't compatible. Upgrade and add them to the upgraded block
toBlock = toBlock.upgradeToHighIdBlock();
toBlock.addAll( fromBlock );
direction.setBlock( this, toBlock );
}
}
public boolean isEmpty()
{
return outBlock == null && inBlock == null && getLastLoopBlock() == null ;
}
public RelIdIterator iterator( DirectionWrapper direction )
{
return direction.iterator( this );
}
protected RelIdArray newSimilarInstance()
{
return new RelIdArray( type );
}
public static final IdBlock EMPTY_BLOCK = new LowIdBlock();
public static enum DirectionWrapper
{
OUTGOING( Direction.OUTGOING )
{
@Override
RelIdIterator iterator( RelIdArray ids )
{
return new RelIdIteratorImpl( ids, DIRECTIONS_FOR_OUTGOING );
}
@Override
IdBlock getBlock( RelIdArray ids )
{
return ids.outBlock;
}
@Override
void setBlock( RelIdArray ids, IdBlock block )
{
ids.outBlock = block;
}
},
INCOMING( Direction.INCOMING )
{
@Override
RelIdIterator iterator( RelIdArray ids )
{
return new RelIdIteratorImpl( ids, DIRECTIONS_FOR_INCOMING );
}
@Override
IdBlock getBlock( RelIdArray ids )
{
return ids.inBlock;
}
@Override
void setBlock( RelIdArray ids, IdBlock block )
{
ids.inBlock = block;
}
},
BOTH( Direction.BOTH )
{
@Override
RelIdIterator iterator( RelIdArray ids )
{
return new RelIdIteratorImpl( ids, DIRECTIONS_FOR_BOTH );
}
@Override
IdBlock getBlock( RelIdArray ids )
{
return ids.getLastLoopBlock();
}
@Override
void setBlock( RelIdArray ids, IdBlock block )
{
ids.setLastLoopBlock( block );
}
};
private final Direction direction;
private DirectionWrapper( Direction direction )
{
this.direction = direction;
}
abstract RelIdIterator iterator( RelIdArray ids );
/*
* Only used during add
*/
abstract IdBlock getBlock( RelIdArray ids );
/*
* Only used during add
*/
abstract void setBlock( RelIdArray ids, IdBlock block );
public Direction direction()
{
return this.direction;
}
}
public static DirectionWrapper wrap( Direction direction )
{
switch ( direction )
{
case OUTGOING: return DirectionWrapper.OUTGOING;
case INCOMING: return DirectionWrapper.INCOMING;
case BOTH: return DirectionWrapper.BOTH;
default: throw new IllegalArgumentException( "" + direction );
}
}
public static abstract class IdBlock implements SizeOfObject
{
/**
* @return a shrunk version of itself. It returns itself if there is
* no need to shrink it or a {@link #copyAndShrink()} if there is slack in the array.
*/
IdBlock shrink()
{
return length() == capacity() ? this : copyAndShrink();
}
void add( long id )
{
int length = ensureSpace( 1 );
set( id, length );
setLength( length+1 );
}
void addAll( IdBlock block )
{
int otherBlockLength = block.length();
int length = ensureSpace( otherBlockLength+1 );
append( block, length+1, otherBlockLength );
setLength( otherBlockLength+length );
}
/**
* Returns the number of ids in the array, not the array size.
*/
int ensureSpace( int delta )
{
int length = length();
int newLength = length+delta;
int capacity = capacity();
if ( newLength >= capacity )
{ // We're out of space, try doubling the size
int calculatedLength = capacity*2;
if ( newLength > calculatedLength )
{ // Doubling the size wasn't enough, go with double what was required
calculatedLength = newLength*2;
}
extendArrayTo( length, calculatedLength );
}
return length;
}
protected abstract boolean accepts( long id );
protected abstract boolean accepts( IdBlock block );
protected abstract IdBlock copyAndShrink();
abstract IdBlock upgradeToHighIdBlock();
protected abstract void extendArrayTo( int numberOfItemsToCopy, int newLength );
protected abstract void setLength( int length );
protected abstract int length();
protected abstract int capacity();
protected abstract void append( IdBlock source, int targetStartIndex, int itemsToCopy );
protected abstract long get( int index );
protected abstract void set( long id, int index );
}
private static class LowIdBlock extends IdBlock
{
// First element is the actual length w/o the slack
private int[] ids = new int[3];
@Override
public int sizeOfObjectInBytesIncludingOverhead()
{
return withObjectOverhead( withReference( withArrayOverhead( 4*ids.length ) ) );
}
public static boolean idIsLow( long id )
{
return (id & 0xFF00000000L) == 0;
}
@Override
protected boolean accepts( long id )
{
return idIsLow( id );
}
@Override
protected boolean accepts( IdBlock block )
{
return block instanceof LowIdBlock;
}
@Override
protected void append( IdBlock source, int targetStartIndex, int itemsToCopy )
{
if ( source instanceof LowIdBlock )
{
arraycopy( ((LowIdBlock)source).ids, 1, ids, targetStartIndex, itemsToCopy );
}
else
{
throw new IllegalArgumentException( source.toString() );
}
}
@Override
IdBlock upgradeToHighIdBlock()
{
return new HighIdBlock( this );
}
@Override
protected IdBlock copyAndShrink()
{
LowIdBlock copy = new LowIdBlock();
copy.ids = Arrays.copyOf( ids, length()+1 );
return copy;
}
@Override
protected void extendArrayTo( int numberOfItemsToCopy, int newLength )
{
int[] newIds = new int[newLength+1];
arraycopy( ids, 0, newIds, 0, numberOfItemsToCopy+1 );
ids = newIds;
}
@Override
protected int length()
{
return ids[0];
}
@Override
protected int capacity()
{
return ids.length-1;
}
@Override
protected void setLength( int length )
{
ids[0] = length;
}
@Override
protected long get( int index )
{
assert index >= 0 && index < length();
return ids[index+1]&0xFFFFFFFFL;
}
@Override
protected void set( long id, int index )
{
ids[index+1] = (int) id; // guarded from outside that this is indeed an int
}
}
private static class HighIdBlock extends IdBlock
{
// First element is the actual length w/o the slack
private int[] ids;
private byte[] highBits;
public HighIdBlock()
{
ids = new int[3];
highBits = new byte[3];
}
private HighIdBlock( LowIdBlock lowIdBlock )
{
ids = Arrays.copyOf( lowIdBlock.ids, lowIdBlock.ids.length );
highBits = new byte[ids.length];
}
@Override
public int sizeOfObjectInBytesIncludingOverhead()
{
return withObjectOverhead(
withReference( withArrayOverhead( 4*ids.length ) ) +
withReference( withArrayOverhead( ids.length ) ) );
}
@Override
protected boolean accepts( long id )
{
return true;
}
@Override
protected boolean accepts( IdBlock block )
{
return true;
}
@Override
protected void append( IdBlock source, int targetStartIndex, int itemsToCopy )
{
if ( source instanceof LowIdBlock )
{
arraycopy( ((LowIdBlock)source).ids, 1, ids, targetStartIndex, itemsToCopy );
}
else
{
arraycopy( ((HighIdBlock)source).ids, 1, ids, targetStartIndex, itemsToCopy );
arraycopy( ((HighIdBlock)source).highBits, 1, highBits, targetStartIndex, itemsToCopy );
}
}
@Override
IdBlock upgradeToHighIdBlock()
{
return this;
}
@Override
protected IdBlock copyAndShrink()
{
HighIdBlock copy = new HighIdBlock();
int itemsToCopy = length()+1;
copy.ids = Arrays.copyOf( ids, itemsToCopy );
copy.highBits = Arrays.copyOf( highBits, itemsToCopy );
return copy;
}
@Override
protected void extendArrayTo( int numberOfItemsToCopy, int newLength )
{
int[] newIds = new int[newLength+1];
byte[] newHighBits = new byte[newLength+1];
arraycopy( ids, 0, newIds, 0, numberOfItemsToCopy+1 );
arraycopy( highBits, 0, newHighBits, 0, numberOfItemsToCopy+1 );
ids = newIds;
highBits = newHighBits;
}
@Override
protected int length()
{
return ids[0];
}
@Override
protected int capacity()
{
return ids.length-1;
}
@Override
protected void setLength( int length )
{
ids[0] = length;
}
@Override
protected long get( int index )
{
return ((long)highBits[index+1] << 32) | ids[index+1]&0xFFFFFFFFL;
}
@Override
protected void set( long id, int index )
{
ids[index+1] = (int)id;
highBits[index+1] = (byte) ((id&0xFF00000000L) >>> 32);
}
}
private static class IteratorState
{
private IdBlock block;
private int relativePosition;
public IteratorState( IdBlock block, int relativePosition )
{
this.block = block;
this.relativePosition = relativePosition;
}
boolean hasNext()
{
return relativePosition < block.length();
}
/*
* Only called if hasNext returns true
*/
long next()
{
long id = block.get( relativePosition++ );
return id;
}
public void update( IdBlock block )
{
this.block = block;
}
}
public static class RelIdIteratorImpl implements RelIdIterator
{
private final DirectionWrapper[] directions;
private int directionPosition = -1;
private DirectionWrapper currentDirection;
private IteratorState currentState;
private final IteratorState[] states;
private long nextElement;
private boolean nextElementDetermined;
private RelIdArray ids;
RelIdIteratorImpl( RelIdArray ids, DirectionWrapper[] directions )
{
this.ids = ids;
this.directions = directions;
this.states = new IteratorState[directions.length];
// Find the initial block which isn't null. There can be directions
// which have a null block currently, but could potentially be set
// after the next getMoreRelationships.
IdBlock block = null;
while ( block == null && directionPosition+1 < directions.length )
{
currentDirection = directions[++directionPosition];
block = currentDirection.getBlock( ids );
}
if ( block != null )
{
currentState = new IteratorState( block, 0 );
states[directionPosition] = currentState;
}
}
@Override
public int getType()
{
return ids.getType();
}
@Override
public RelIdIterator updateSource( RelIdArray newSource, DirectionWrapper direction )
{
if ( ids != newSource || newSource.couldBeNeedingUpdate() )
{
ids = newSource;
// Blocks may have gotten upgraded to support a linked list
// of blocks, so reestablish those references.
for ( int i = 0; i < states.length; i++ )
{
if ( states[i] != null )
{
states[i].update( directions[i].getBlock( ids ) );
}
}
}
return this;
}
@Override
public boolean hasNext()
{
if ( nextElementDetermined )
{
return nextElement != -1;
}
while ( true )
{
if ( currentState != null && currentState.hasNext() )
{
nextElement = currentState.next();
nextElementDetermined = true;
return true;
}
else
{
if ( !nextBlock() )
{
break;
}
}
}
// Keep this false since the next call could come after we've loaded
// some more relationships
nextElementDetermined = false;
nextElement = -1;
return false;
}
protected boolean nextBlock()
{
while ( directionPosition+1 < directions.length )
{
currentDirection = directions[++directionPosition];
IteratorState nextState = states[directionPosition];
if ( nextState != null )
{
currentState = nextState;
return true;
}
IdBlock block = currentDirection.getBlock( ids );
if ( block != null )
{
currentState = new IteratorState( block, 0 );
states[directionPosition] = currentState;
return true;
}
}
return false;
}
@Override
public void doAnotherRound()
{
directionPosition = -1;
nextBlock();
}
@Override
public long next()
{
if ( !hasNext() )
{
throw new NoSuchElementException();
}
nextElementDetermined = false;
return nextElement;
}
}
public static RelIdArray from( RelIdArray src, RelIdArray add, Collection<Long> remove )
{
if ( remove == null )
{
if ( src == null )
{
return add.downgradeIfPossible();
}
if ( add != null )
{
src = src.addAll( add );
return src.downgradeIfPossible();
}
return src;
}
else
{
if ( src == null && add == null )
{
return null;
}
RelIdArray newArray = null;
if ( src != null )
{
newArray = src.newSimilarInstance();
newArray.addAll( src );
evictExcluded( newArray, remove );
}
else
{
newArray = add.newSimilarInstance();
}
if ( add != null )
{
newArray = newArray.upgradeIfNeeded( add );
for ( RelIdIteratorImpl fromIterator = (RelIdIteratorImpl) add.iterator( DirectionWrapper.BOTH );
fromIterator.hasNext();)
{
long value = fromIterator.next();
if ( !remove.contains( value ) )
{
newArray.add( value, fromIterator.currentDirection );
}
}
}
return newArray;
}
}
private static void evictExcluded( RelIdArray ids, Collection<Long> excluded )
{
for ( RelIdIteratorImpl iterator = (RelIdIteratorImpl) DirectionWrapper.BOTH.iterator( ids );
iterator.hasNext(); )
{
long value = iterator.next();
if ( excluded.contains( value ) )
{
boolean swapSuccessful = false;
IteratorState state = iterator.currentState;
IdBlock block = state.block;
for ( int j = block.length() - 1; j >= state.relativePosition; j--)
{
long backValue = block.get( j );
block.setLength( block.length()-1 );
if ( !excluded.contains( backValue) )
{
block.set( backValue, state.relativePosition-1 );
swapSuccessful = true;
break;
}
}
if ( !swapSuccessful ) // all elements from pos in remove
{
block.setLength( block.length()-1 );
}
}
}
}
/**
* Optimization in the lazy loading of relationships for a node.
* {@link RelIdIterator#updateSource(RelIdArray, org.neo4j.kernel.impl.util.RelIdArray.DirectionWrapper)}
* is only called if this returns true, i.e if a {@link RelIdArray} or {@link IdBlock} might have
* gotten upgraded to handle f.ex loops or high id ranges so that the
* {@link RelIdIterator} gets updated accordingly.
*/
public boolean couldBeNeedingUpdate()
{
return (outBlock != null && outBlock instanceof HighIdBlock) ||
(inBlock != null && inBlock instanceof HighIdBlock);
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_util_RelIdArray.java
|
473
|
{
@Override
public T instance()
{
return value;
}
};
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_util_Providers.java
|
474
|
public class Providers
{
public static <T> Provider<T> singletonProvider( final T value)
{
return new Provider<T>()
{
@Override
public T instance()
{
return value;
}
};
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_util_Providers.java
|
475
|
public class PrimitiveLongIteratorForArray implements PrimitiveLongIterator
{
public static final PrimitiveLongIteratorForArray EMPTY = new PrimitiveLongIteratorForArray();
private final long[] values;
int i = 0;
public PrimitiveLongIteratorForArray( long... values )
{
this.values = values;
}
@Override
public boolean hasNext()
{
return i < values.length;
}
@Override
public long next()
{
if ( hasNext() )
{
return values[i++];
}
else
{
throw new NoSuchElementException( );
}
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_util_PrimitiveLongIteratorForArray.java
|
476
|
public class PrimitiveIntIteratorForArray implements PrimitiveIntIterator
{
private final int[] values;
int i = 0;
public PrimitiveIntIteratorForArray( int... values )
{
this.values = values;
}
@Override
public boolean hasNext()
{
return i < values.length;
}
@Override
public int next()
{
if ( hasNext() )
{
return values[i++];
}
throw new NoSuchElementException( );
}
public static final int[] EMPTY_INT_ARRAY = new int[0];
public static int[] primitiveIntIteratorToIntArray( PrimitiveIntIterator iterator )
{
if ( !iterator.hasNext() )
{
return EMPTY_INT_ARRAY;
}
int[] result = new int[5]; // arbitrary initial size
int cursor = 0;
while ( iterator.hasNext() )
{
if ( cursor >= result.length )
{
result = copyOf( result, result.length*2 );
}
result[cursor++] = iterator.next();
}
// shrink if needed
return cursor == result.length ? result : copyOf( result, cursor );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_util_PrimitiveIntIteratorForArray.java
|
477
|
{
public void run()
{
invocations.incrementAndGet();
}
}, 500, MILLISECONDS );
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_util_Neo4jJobSchedulerTest.java
|
478
|
public class SingleNodePath implements Path
{
private final Node node;
public SingleNodePath( Node node )
{
this.node = node;
}
@Override
public Node startNode()
{
return node;
}
@Override
public Node endNode()
{
return node;
}
@Override
public Relationship lastRelationship()
{
return null;
}
@Override
public Iterable<Relationship> relationships()
{
return Collections.emptyList();
}
@Override
public Iterable<Relationship> reverseRelationships()
{
return relationships();
}
@Override
public Iterable<Node> nodes()
{
return Arrays.asList( node );
}
@Override
public Iterable<Node> reverseNodes()
{
return nodes();
}
@Override
public int length()
{
return 0;
}
@Override
public Iterator<PropertyContainer> iterator()
{
return Arrays.<PropertyContainer>asList( node ).iterator();
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_util_SingleNodePath.java
|
479
|
public abstract class StringLogger
{
public static final String DEFAULT_NAME = "messages.log";
public static final String DEFAULT_ENCODING = "UTF-8";
public static final StringLogger SYSTEM, SYSTEM_ERR;
public static final StringLogger SYSTEM_DEBUG, SYSTEM_ERR_DEBUG;
static
{
SYSTEM = instantiateStringLoggerForPrintStream( System.out, false );
SYSTEM_ERR = instantiateStringLoggerForPrintStream( System.err, false );
SYSTEM_DEBUG = instantiateStringLoggerForPrintStream( System.out, true );
SYSTEM_ERR_DEBUG = instantiateStringLoggerForPrintStream( System.err, true );
}
private static ActualStringLogger instantiateStringLoggerForPrintStream( PrintStream stream,
boolean debugEnabled )
{
PrintWriter writer;
try
{
writer = new PrintWriter( new OutputStreamWriter( stream, DEFAULT_ENCODING ), true );
}
catch ( UnsupportedEncodingException e )
{
throw new RuntimeException( e );
}
return new ActualStringLogger( writer, debugEnabled )
{
@Override
public void close()
{
// don't close System.out
}
};
}
public static final int DEFAULT_THRESHOLD_FOR_ROTATION = 100 * 1024 * 1024;
private static final int NUMBER_OF_OLD_LOGS_TO_KEEP = 2;
public interface LineLogger
{
void logLine( String line );
}
public static StringLogger logger( File logfile )
{
try
{
return new ActualStringLogger( new PrintWriter(
new OutputStreamWriter( new FileOutputStream( logfile, true), DEFAULT_ENCODING ) ), false );
}
catch ( IOException cause )
{
throw new RuntimeException( "Could not create log file: " + logfile, cause );
}
}
public static StringLogger loggerDirectory( FileSystemAbstraction fileSystem, File logDirectory )
{
return loggerDirectory( fileSystem, logDirectory, DEFAULT_THRESHOLD_FOR_ROTATION, false );
}
public static StringLogger loggerDirectory( FileSystemAbstraction fileSystem, File logDirectory,
int rotationThreshold, boolean debugEnabled )
{
return new ActualStringLogger( fileSystem, new File( logDirectory, DEFAULT_NAME ).getPath(),
rotationThreshold, debugEnabled );
}
public static StringLogger wrap( Writer writer )
{
return new ActualStringLogger(
writer instanceof PrintWriter ? (PrintWriter) writer : new PrintWriter( writer ), false );
}
public static StringLogger wrap( final StringBuffer target )
{
return new ActualStringLogger( new PrintWriter( new Writer()
{
@Override
public void write( char[] cbuf, int off, int len ) throws IOException
{
target.append( cbuf, off, len );
}
@Override
public void write( int c ) throws IOException
{
target.appendCodePoint( c );
}
@Override
public void write( char[] cbuf ) throws IOException
{
target.append( cbuf );
}
@Override
public void write( String str ) throws IOException
{
target.append( str );
}
@Override
public void write( String str, int off, int len ) throws IOException
{
target.append( str, off, len );
}
@Override
public Writer append( char c ) throws IOException
{
target.append( c );
return this;
}
@Override
public Writer append( CharSequence csq ) throws IOException
{
target.append( csq );
return this;
}
@Override
public Writer append( CharSequence csq, int start, int end ) throws IOException
{
target.append( csq, start, end );
return this;
}
@Override
public void flush() throws IOException
{
// do nothing
}
@Override
public void close() throws IOException
{
// do nothing
}
} ), false );
}
public static StringLogger tee( final StringLogger logger1, final StringLogger logger2 )
{
return new StringLogger()
{
@Override
public void logLongMessage( String msg, Visitor<LineLogger, RuntimeException> source, boolean flush )
{
logger1.logLongMessage( msg, source, flush );
logger2.logLongMessage( msg, source, flush );
}
@Override
public void logMessage( String msg, boolean flush )
{
logger1.logMessage( msg, flush );
logger2.logMessage( msg, flush );
}
@Override
public void logMessage( String msg, LogMarker marker )
{
logger1.logMessage( msg, marker );
logger2.logMessage( msg, marker );
}
@Override
public void logMessage( String msg, Throwable cause, boolean flush )
{
logger1.logMessage( msg, cause, flush );
logger2.logMessage( msg, cause, flush );
}
@Override
public void addRotationListener( Runnable listener )
{
logger1.addRotationListener( listener );
logger2.addRotationListener( listener );
}
@Override
public void flush()
{
logger1.flush();
logger2.flush();
}
@Override
public void close()
{
logger1.close();
logger2.close();
}
@Override
protected void logLine( String line )
{
logger1.logLine( line );
logger2.logLine( line );
}
};
}
/**
* Create a StringLogger that only creates a file on the first attempt to write something to the log.
*/
public static StringLogger lazyLogger( final File logFile )
{
return new StringLogger()
{
StringLogger logger = null;
@Override
public void logLongMessage( String msg, Visitor<LineLogger, RuntimeException> source, boolean flush )
{
createLogger();
logger.logLongMessage( msg, source, flush );
}
@Override
public void logMessage( String msg, boolean flush )
{
createLogger();
logger.logMessage( msg, flush );
}
@Override
public void logMessage( String msg, LogMarker marker )
{
createLogger();
logger.logMessage( msg, marker );
}
@Override
public void logMessage( String msg, Throwable cause, boolean flush )
{
createLogger();
logger.logMessage( msg, cause, flush );
}
@Override
public void addRotationListener( Runnable listener )
{
createLogger();
logger.addRotationListener( listener );
}
@Override
public void flush()
{
createLogger();
logger.flush();
}
@Override
public void close()
{
if ( logger != null )
{
logger.close();
}
}
@Override
protected void logLine( String line )
{
createLogger();
logger.logLine( line );
}
private synchronized void createLogger()
{
if (logger == null){
logger = logger( logFile );
}
}
};
}
public void logMessage( String msg )
{
logMessage( msg, false );
}
public void logMessage( String msg, Throwable cause )
{
logMessage( msg, cause, false );
}
public void logMessage( String msg, Throwable cause, boolean flush, LogMarker marker )
{
// LogMarker is used by subclasses
logMessage( msg, cause, flush );
}
public void debug( String msg )
{
if ( isDebugEnabled() )
{
logMessage( msg );
}
}
public void debug( String msg, Throwable cause )
{
if ( isDebugEnabled() )
{
logMessage( msg, cause );
}
}
public boolean isDebugEnabled()
{
return false;
}
public void info( String msg )
{
logMessage( msg );
}
public void info( String msg, Throwable cause )
{
logMessage( msg, cause );
}
public void warn( String msg )
{
logMessage( msg );
}
public void warn( String msg, Throwable throwable )
{
logMessage( msg, throwable );
}
public void error( String msg )
{
logMessage( msg );
}
public void error( String msg, Throwable throwable )
{
logMessage( msg, throwable );
}
public void logLongMessage( String msg, Visitor<LineLogger, RuntimeException> source )
{
logLongMessage( msg, source, false );
}
public void logLongMessage( String msg, Iterable<String> source )
{
logLongMessage( msg, source, false );
}
public void logLongMessage( String msg, Iterable<String> source, boolean flush )
{
logLongMessage( msg, source.iterator(), flush );
}
public void logLongMessage( String msg, Iterator<String> source )
{
logLongMessage( msg, source, false );
}
public void logLongMessage( String msg, final Iterator<String> source, boolean flush )
{
logLongMessage( msg, new Visitor<LineLogger, RuntimeException>()
{
@Override
public boolean visit( LineLogger logger )
{
for ( String line : loop( source ) )
{
logger.logLine( line );
}
return true;
}
}, flush );
}
public abstract void logLongMessage( String msg, Visitor<LineLogger, RuntimeException> source, boolean flush );
public abstract void logMessage( String msg, boolean flush );
public abstract void logMessage( String msg, LogMarker marker );
public abstract void logMessage( String msg, Throwable cause, boolean flush );
public abstract void addRotationListener( Runnable listener );
public abstract void flush();
public abstract void close();
protected abstract void logLine( String line );
public static final StringLogger DEV_NULL = new StringLogger()
{
@Override
public void logMessage( String msg, boolean flush )
{
}
@Override
public void logMessage( String msg, LogMarker marker )
{
}
@Override
public void logMessage( String msg, Throwable cause, boolean flush )
{
}
@Override
public void logLongMessage( String msg, Visitor<LineLogger, RuntimeException> source, boolean flush )
{
}
@Override
protected void logLine( String line )
{
}
@Override
public void flush()
{
}
@Override
public void close()
{
}
@Override
public void addRotationListener( Runnable listener )
{
}
};
private static class ActualStringLogger extends StringLogger
{
private final static String encoding = "UTF-8";
private PrintWriter out;
private final Integer rotationThreshold;
private final File file;
private final List<Runnable> onRotation = new CopyOnWriteArrayList<Runnable>();
private final FileSystemAbstraction fileSystem;
private final boolean debugEnabled;
private ActualStringLogger( FileSystemAbstraction fileSystem, String filename, int rotationThreshold,
boolean debugEnabled )
{
this.fileSystem = fileSystem;
this.rotationThreshold = rotationThreshold;
this.debugEnabled = debugEnabled;
try
{
file = new File( filename );
if ( file.getParentFile() != null )
{
fileSystem.mkdirs( file.getParentFile() );
}
instantiateWriter();
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
}
private ActualStringLogger( PrintWriter writer, boolean debugEnabled )
{
this.out = writer;
this.rotationThreshold = null;
this.file = null;
this.fileSystem = null;
this.debugEnabled = debugEnabled;
}
@Override
public boolean isDebugEnabled()
{
return debugEnabled;
}
@Override
public void addRotationListener( Runnable trigger )
{
onRotation.add( trigger );
}
private void instantiateWriter() throws IOException
{
out = new PrintWriter( new OutputStreamWriter( fileSystem.openAsOutputStream( file, true ), encoding ) );
for ( Runnable trigger : onRotation )
{
trigger.run();
}
}
@Override
public synchronized void logMessage( String msg, boolean flush )
{
out.println( time() + " INFO [org.neo4j]: " + msg );
if ( flush )
{
out.flush();
}
checkRotation();
}
@Override
public void logMessage( String msg, LogMarker marker )
{
// LogMarker is used by subclasses
logMessage( msg );
}
private String time()
{
return Format.date();
}
@Override
public synchronized void logMessage( String msg, Throwable cause, boolean flush )
{
out.println( time() + " ERROR [org.neo4j]: " + msg + " " + cause.getMessage());
cause.printStackTrace( out );
if ( flush )
{
out.flush();
}
checkRotation();
}
@Override
public synchronized void logLongMessage( String msg, Visitor<LineLogger, RuntimeException> source, boolean flush )
{
out.println( time() + " INFO [org.neo4j]: " + msg );
source.visit( new LineLoggerImpl( this ) );
if ( flush )
{
out.flush();
}
checkRotation();
}
@Override
protected void logLine( String line )
{
out.println( " " + line );
}
private volatile boolean doingRotation = false;
private void checkRotation()
{
if ( rotationThreshold != null && fileSystem.getFileSize( file ) > rotationThreshold && !doingRotation )
{
doRotation();
}
}
private void doRotation()
{
doingRotation = true;
out.close();
moveAwayFile();
try
{
instantiateWriter();
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
finally
{
doingRotation = false;
}
}
/**
* Will move:
* messages.log.1 -> messages.log.2
* messages.log -> messages.log.1
* <p/>
* Will delete (if exists):
* messages.log.2
*/
private void moveAwayFile()
{
File oldLogFile = new File( file.getParentFile(), file.getName() + "." + NUMBER_OF_OLD_LOGS_TO_KEEP );
if ( fileSystem.fileExists( oldLogFile ) )
{
fileSystem.deleteFile( oldLogFile );
}
for ( int i = NUMBER_OF_OLD_LOGS_TO_KEEP - 1; i >= 0; i-- )
{
oldLogFile = new File( file.getParentFile(), file.getName() + (i == 0 ? "" : ("." + i)) );
if ( fileSystem.fileExists( oldLogFile ) )
{
try
{
fileSystem.renameFile( oldLogFile, new File( file.getParentFile(), file.getName() + "." + (i + 1) ) );
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
}
}
}
@Override
public void flush()
{
out.flush();
}
@Override
public void close()
{
out.close();
}
@Override
public String toString()
{
return "StringLogger[" + this.file + "]";
}
}
protected static final class LineLoggerImpl implements LineLogger
{
private final StringLogger target;
public LineLoggerImpl( StringLogger target )
{
this.target = target;
}
@Override
public void logLine( String line )
{
target.logLine( line );
}
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_util_StringLogger.java
|
480
|
{
@Override
public void close()
{
// don't close System.out
}
};
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_util_StringLogger.java
|
481
|
public class TestArrayIntSet
{
@Test
public void testArrayIntSet()
{
ArrayIntSet set = new ArrayIntSet();
set.add( 1 );
set.add( 2 );
set.add( 3 );
set.add( 4 );
set.add( 5 );
set.add( 6 );
set.add( 7 );
set.add( 8 );
set.add( 9 );
set.add( 10 );
int count = 0;
for ( int value : set.values() )
{
assertTrue( set.contains( value ) );
count++;
}
assertEquals( 10, count );
assertTrue( set.remove( 2 ) );
assertTrue( set.remove( 9 ) );
assertTrue( set.remove( 5 ) );
assertTrue( !set.remove( 2 ) );
assertTrue( !set.remove( 9 ) );
assertTrue( !set.remove( 5 ) );
count = 0;
for ( int value : set.values() )
{
assertTrue( set.contains( value ) );
count++;
}
assertEquals( 7, count );
assertTrue( set.remove( 3 ) );
assertTrue( set.remove( 8 ) );
assertTrue( set.remove( 4 ) );
assertTrue( !set.remove( 3 ) );
assertTrue( !set.remove( 8 ) );
assertTrue( !set.remove( 4 ) );
count = 0;
for ( int value : set.values() )
{
assertTrue( set.contains( value ) );
count++;
}
assertEquals( 4, count );
assertTrue( set.remove( 1 ) );
assertTrue( set.remove( 7 ) );
assertTrue( set.remove( 6 ) );
assertTrue( !set.remove( 1 ) );
assertTrue( !set.remove( 7 ) );
assertTrue( !set.remove( 6 ) );
count = 0;
for ( int value : set.values() )
{
assertTrue( set.contains( value ) );
count++;
}
assertEquals( 1, count );
assertTrue( set.remove( 10 ) );
assertTrue( !set.remove( 10 ) );
count = 0;
for ( int value : set.values() )
{
assertTrue( set.contains( value ) );
count++;
}
assertEquals( 0, count );
}
@Test
public void testContains()
{
ArrayIntSet set = new ArrayIntSet();
for ( int i = 0; i < 10; i++ )
{
set.add( i );
assertTrue( set.contains( i ) );
}
for ( int i = 0; i < 10; i++ )
{
assertTrue( set.contains( i ) );
}
for ( int i = 0; i < 10; i+=2 )
{
set.remove( i );
assertTrue( !set.contains( i ) );
}
for ( int i = 0; i < 10; i++ )
{
if ( i % 2 == 0 )
{
assertTrue( !set.contains( i ) );
}
else
{
assertTrue( set.contains( i ) );
}
}
for ( int i = 0; i < 1000; i++ )
{
set.add( i );
assertTrue( set.contains( i ) );
}
for ( int i = 0; i < 1000; i++ )
{
assertTrue( set.contains( i ) );
}
for ( int i = 0; i < 1000; i+=2 )
{
set.remove( i );
assertTrue( !set.contains( i ) );
}
for ( int i = 0; i < 1000; i++ )
{
if ( i % 2 == 0 )
{
assertTrue( !set.contains( i ) );
}
else
{
assertTrue( set.contains( i ) );
}
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_util_TestArrayIntSet.java
|
482
|
public class TestLogger extends StringLogger
{
private enum Level
{
DEBUG,
INFO,
WARN,
ERROR
}
public static final class LogCall
{
protected final Level level;
protected final String message;
protected final Throwable cause;
protected final boolean flush;
private LogCall( Level level, String message, Throwable cause, boolean flush )
{
this.level = level;
this.message = message;
this.cause = cause;
this.flush = flush;
}
// DSL sugar methods to use when writing assertions.
public static LogCall debug(String msg) { return new LogCall(Level.DEBUG, msg, null, false); }
public static LogCall info(String msg) { return new LogCall(Level.INFO, msg, null, false); }
public static LogCall warn(String msg) { return new LogCall(Level.WARN, msg, null, false); }
public static LogCall error(String msg) { return new LogCall(Level.ERROR, msg, null, false); }
public static LogCall debug(String msg, Throwable c) { return new LogCall(Level.DEBUG, msg, c, false); }
public static LogCall info(String msg, Throwable c) { return new LogCall(Level.INFO, msg, c, false); }
public static LogCall warn(String msg, Throwable c) { return new LogCall(Level.WARN, msg, c, false); }
public static LogCall error(String msg, Throwable c) { return new LogCall(Level.ERROR, msg, c, false); }
@Override
public String toString()
{
return "LogCall{ " + level +
", message='" + message + '\'' +
", cause=" + cause +
'}';
}
@Override
public boolean equals( Object o )
{
if ( this == o )
return true;
if ( o == null || getClass() != o.getClass() )
return false;
LogCall logCall = (LogCall) o;
return flush == logCall.flush && level == logCall.level &&
message.equals( logCall.message ) &&
!(cause != null ? !cause.equals( logCall.cause ) : logCall.cause != null);
}
@Override
public int hashCode()
{
int result = level.hashCode();
result = 31 * result + message.hashCode();
result = 31 * result + (cause != null ? cause.hashCode() : 0);
result = 31 * result + (flush ? 1 : 0);
return result;
}
}
private List<LogCall> logCalls = new ArrayList<LogCall>();
//
// TEST TOOLS
//
public void assertExactly(LogCall... expectedLogCalls )
{
Iterator<LogCall> expected = asList( expectedLogCalls ).iterator();
Iterator<LogCall> actual = logCalls.iterator();
while(expected.hasNext())
{
if(actual.hasNext())
{
assertEquals( expected.next(), actual.next() );
} else
{
fail(format( "Got fewer log calls than expected. The missing log calls were: \n%s", serialize(expected)));
}
}
if(actual.hasNext())
{
fail(format( "Got more log calls than expected. The remaining log calls were: \n%s", serialize(actual)));
}
}
/**
* Note: Does not care about ordering.
*/
public void assertAtLeastOnce( LogCall... expectedCalls )
{
Set<LogCall> expected = asSet(expectedCalls);
for ( LogCall logCall : logCalls )
expected.remove( logCall );
if(expected.size() > 0)
{
fail( "These log calls were expected, but never occurred: \n" + serialize( expected.iterator() ) );
}
}
public void assertNoDebugs()
{
assertNo( hasLevel( Level.DEBUG ), "Expected no messages with level DEBUG.");
}
public void assertNoInfos()
{
assertNo( hasLevel( Level.INFO ), "Expected no messages with level INFO.");
}
public void assertNoWarnings()
{
assertNo( hasLevel( Level.WARN ), "Expected no messages with level WARN.");
}
public void assertNoErrors()
{
assertNo( hasLevel( Level.ERROR ), "Expected no messages with level ERROR.");
}
public void assertNoLoggingOccurred()
{
if(logCalls.size() != 0)
{
fail( "Expected no log messages at all, but got:\n" + serialize( logCalls.iterator() ) );
}
}
public void assertNo(LogCall call)
{
long found = count( filter( equalTo(call), logCalls ) );
if( found != 0 )
{
fail( "Expected no occurrence of " + call + ", but it was in fact logged " + found + " times." );
}
}
public void assertNo(Predicate<LogCall> predicate, String failMessage)
{
Iterable<LogCall> found = filter( predicate, logCalls );
if(count( found ) != 0 )
{
fail( failMessage + " But found: \n" + serialize( found.iterator() ) );
}
}
/**
* Clear this logger for re-use.
*/
public void clear()
{
logCalls.clear();
}
//
// IMPLEMENTATION
//
private void log( Level level, String message, Throwable cause )
{
logCalls.add( new LogCall(level, message, cause, false) );
}
@Override
public void debug( String msg )
{
debug( msg, null );
}
@Override
public void debug( String msg, Throwable cause )
{
log( Level.DEBUG, msg, cause );
}
@Override
public void info( String msg )
{
info( msg, null );
}
@Override
public void info( String msg, Throwable cause )
{
log( Level.INFO, msg, cause );
}
@Override
public void warn( String msg )
{
warn( msg, null );
}
@Override
public void warn( String msg, Throwable cause )
{
log( Level.WARN, msg, cause );
}
@Override
public void error( String msg )
{
error( msg, null );
}
@Override
public void error( String msg, Throwable cause )
{
log( Level.ERROR, msg, cause );
}
@Override
public void logMessage( String msg, Throwable cause, boolean flush )
{
throw new RuntimeException("For future-compatibility reasons, please don't use the logMessage methods. " +
"Use the debug/info/warn/error methods instead. This exception is thrown to avoid adding new calls and " +
"to force refactoring old calls when we're writing tests.");
}
@Override
public void logMessage( String msg, boolean flush )
{
logMessage( msg, null, flush );
}
@Override
public void logMessage( String msg, LogMarker marker )
{
logMessage( msg, null, false );
}
@Override
protected void logLine( String line )
{
// Not sure about the state of the line logger. For now, we delegate to throw the "don't use this" runtime exception
// please modify appropriately if you know anything about this, because I'm not confident about this. /jake
logMessage( line );
}
@Override
public void logLongMessage( String msg, Visitor<LineLogger, RuntimeException> source, boolean flush )
{
source.visit( new LineLoggerImpl( this ) );
}
@Override
public void addRotationListener( Runnable listener )
{
}
@Override
public void flush()
{
}
@Override
public void close()
{
// no-op
}
private String serialize( Iterator<LogCall> events )
{
StringBuilder sb = new StringBuilder( );
while(events.hasNext())
{
sb.append( events.next().toString() );
sb.append("\n");
}
return sb.toString();
}
private Predicate<LogCall> hasLevel( final Level level )
{
return new Predicate<LogCall>(){
@Override
public boolean accept( LogCall item )
{
return item.level == level;
}
};
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_util_TestLogger.java
|
483
|
public class TestFileUtils
{
private File path;
@Before
public void doBefore() throws Exception
{
path = TargetDirectory.forTest( getClass() ).cleanDirectory( "path" );
}
@Test
public void moveFileToDirectory() throws Exception
{
File file = touchFile( "source" );
File targetDir = directory( "dir" );
File newLocationOfFile = FileUtils.moveFileToDirectory( file, targetDir );
assertTrue( newLocationOfFile.exists() );
assertFalse( file.exists() );
assertEquals( newLocationOfFile, targetDir.listFiles()[0] );
}
@Test
public void moveFile() throws Exception
{
File file = touchFile( "source" );
File targetDir = directory( "dir" );
File newLocationOfFile = new File( targetDir, "new-name" );
FileUtils.moveFile( file, newLocationOfFile );
assertTrue( newLocationOfFile.exists() );
assertFalse( file.exists() );
assertEquals( newLocationOfFile, targetDir.listFiles()[0] );
}
private File directory( String name ) throws IOException
{
File dir = new File( path, name );
dir.mkdirs();
return dir;
}
private File touchFile( String name ) throws IOException
{
File file = new File( path, name );
file.createNewFile();
return file;
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_util_TestFileUtils.java
|
484
|
public class TestExceptionCauseSetter {
@Test
public void shouldBeAbleToSetCauseOfException()
{
Throwable original = new Throwable();
Throwable cause = new Throwable();
ExceptionCauseSetter.setCause(original, cause);
assertThat(original.getCause(), is(cause));
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_util_TestExceptionCauseSetter.java
|
485
|
public class TestCopyOnWriteHashMap
{
@Test
public void keySetUnaffectedByChanges() throws Exception
{
Map<Integer, String> map = new CopyOnWriteHashMap<Integer, String>();
map.put( 0, "0" );
map.put( 1, "1" );
map.put( 2, "2" );
assertContains( map.keySet(), 0, 1, 2 );
Iterator<Integer> keys = map.keySet().iterator();
map.remove( 1 );
assertContains( keys, 0, 1, 2 );
}
@Test
public void entrySetUnaffectedByChanges() throws Exception
{
Map<Integer, String> map = new CopyOnWriteHashMap<Integer, String>();
map.put( 0, "0" );
map.put( 1, "1" );
map.put( 2, "2" );
@SuppressWarnings( "unchecked" )
Map.Entry<Integer, String>[] allEntries = map.entrySet().toArray( new Map.Entry[0] );
assertContains( map.entrySet(), allEntries );
Iterator<Entry<Integer, String>> entries = map.entrySet().iterator();
map.remove( 1 );
assertContains( entries, allEntries );
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_util_TestCopyOnWriteHashMap.java
|
486
|
public class TestBufferedFileChannel
{
@Test
public void testCorrectness() throws Exception
{
File file = createBigTempFile( 1 );
StoreChannel channel = new BufferedFileChannel(
getFileChannel( file ),
new Monitors().newMonitor( ByteCounterMonitor.class ) );
ByteBuffer buffer = ByteBuffer.allocateDirect( 15 );
int counter = 0;
int loopCounter = 0;
while ( channel.read( buffer ) != -1 )
{
buffer.flip();
while ( buffer.hasRemaining() )
{
byte value = buffer.get();
assertEquals( value, (byte)(counter%10) );
counter++;
}
assertEquals( counter, channel.position() );
int newLimit = loopCounter%buffer.capacity();
buffer.clear().limit( newLimit == 0 ? 1 : newLimit );
loopCounter++;
}
channel.close();
file.delete();
}
private StoreChannel getFileChannel( File file ) throws FileNotFoundException
{
return new StoreFileChannel( new RandomAccessFile( file, "r" ).getChannel() );
}
@Test
public void testPositioning() throws Exception
{
File file = createBigTempFile( 1 );
StoreChannel channel = new BufferedFileChannel(
getFileChannel( file ),
new Monitors().newMonitor( ByteCounterMonitor.class ));
ByteBuffer buffer = ByteBuffer.allocateDirect( 15 );
channel.read( buffer );
buffer.flip();
for ( int value = 0; buffer.hasRemaining(); value++ )
{
assertEquals( value%10, buffer.get() );
}
buffer.clear();
channel.position( channel.position()+5 );
channel.read( buffer );
buffer.flip();
for ( int value = 0; buffer.hasRemaining(); value++ )
{
assertEquals( value%10, buffer.get() );
}
buffer.clear();
channel.position( channel.size()-13 );
channel.read( buffer );
buffer.flip();
for ( int value = 7; buffer.hasRemaining(); value++ )
{
assertEquals( value%10, buffer.get() );
}
channel.close();
file.delete();
}
private File createBigTempFile( int mb ) throws IOException
{
File file = File.createTempFile( "neo4j", "temp" );
file.deleteOnExit();
FileChannel channel = new RandomAccessFile( file, "rw" ).getChannel();
byte[] bytes = newStripedBytes( 1000 );
ByteBuffer buffer = ByteBuffer.wrap( bytes );
for ( int i = 0; i < 1000*mb; i++ )
{
buffer.clear();
buffer.position( buffer.capacity() );
buffer.flip();
channel.write( buffer );
}
channel.close();
return file;
}
private byte[] newStripedBytes( int size )
{
byte[] result = new byte[size];
for ( int i = 0; i < size; i++ )
{
result[i] = (byte)(i%10);
}
return result;
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_util_TestBufferedFileChannel.java
|
487
|
public class TestBits
{
@Test
public void asBytes() throws Exception
{
int numberOfBytes = 14;
Bits bits = bits( numberOfBytes );
for ( byte i = 0; i < numberOfBytes; i++ )
{
bits.put( i );
}
byte[] bytes = bits.asBytes();
for ( byte i = 0; i < numberOfBytes; i++ )
{
assertEquals( i, bytes[i] );
}
}
@Test
public void doubleAsBytes() throws Exception
{
double[] array1 = new double[] { 1.0, 2.0, 3.0, 4.0, 5.0 };
Bits bits = Bits.bits( array1.length*8 );
for ( double value : array1 )
{
bits.put( Double.doubleToRawLongBits( value ) );
}
String first = bits.toString();
byte[] asBytes = bits.asBytes();
String other = Bits.bitsFromBytes( asBytes ).toString();
assertEquals( first, other );
}
@Test
public void writeAndRead() throws Exception
{
for ( int b = 5; b <= 8; b++ )
{
Bits bits = Bits.bits( 16 );
for ( byte value = 0; value < 16; value++ )
{
bits.put( value, b );
}
for ( byte expected = 0; bits.available(); expected++ )
{
assertEquals( expected, bits.getByte( b ) );
}
}
for ( byte value = Byte.MIN_VALUE; value < Byte.MAX_VALUE; value++ )
{
Bits bits = Bits.bits( 8 );
bits.put( value );
assertEquals( value, bits.getByte() );
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_util_TestBits.java
|
488
|
private static class WorkerThread extends Thread
{
private final ArrayMap<Integer,Object> map;
private volatile boolean success = false;
private volatile Throwable t = null;
private final CountDownLatch done;
WorkerThread( ArrayMap<Integer,Object> map, CountDownLatch done )
{
this.map = map;
this.done = done;
}
@Override
public void run()
{
try
{
for ( int i = 0; i < 10000; i++ )
{
if ( map.size() > 5 )
{
for ( int j = i; j < (i+10); j++ )
{
if ( map.remove( j % 10 ) != null )
{
break;
}
}
}
// calling size again to increase chance to hit CCE
else if ( map.size() <= 5 )
{
map.put( i % 10, new Object() );
}
yield();
}
success = true;
}
catch ( Throwable t )
{
this.t = t;
}
finally
{
done.countDown();
}
}
boolean wasSuccessful()
{
return success;
}
Throwable getCause()
{
return t;
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_util_TestArrayMap.java
|
489
|
public class TestArrayMap
{
@Test
public void testArrayMap()
{
ArrayMap<String,Integer> map = new ArrayMap<String,Integer>();
assertTrue( map.get( "key1" ) == null );
map.put( "key1", 0 );
assertEquals( new Integer(0), map.get( "key1" ) );
assertEquals( new Integer(0), map.get( "key1" ) );
map.put( "key1", 1 );
assertEquals( new Integer(1), map.get( "key1" ) );
map.put( "key2", 0 );
assertEquals( new Integer(0), map.get( "key2" ) );
map.put( "key2", 2 );
assertEquals( new Integer(2), map.get( "key2" ) );
assertEquals( new Integer(2), map.remove( "key2" ) );
assertTrue( map.get( "key2" ) == null );
assertEquals( new Integer(1), map.get( "key1" ) );
assertEquals( new Integer(1), map.remove( "key1" ) );
assertTrue( map.get( "key1" ) == null );
map.put( "key1", 1 );
map.put( "key2", 2 );
map.put( "key3", 3 );
map.put( "key4", 4 );
map.put( "key5", 5 );
assertEquals( new Integer(5), map.get( "key5" ) );
assertEquals( new Integer(4), map.get( "key4" ) );
assertEquals( new Integer(3), map.get( "key3" ) );
assertEquals( new Integer(2), map.get( "key2" ) );
assertEquals( new Integer(1), map.get( "key1" ) );
assertEquals( new Integer(5), map.remove( "key5" ) );
assertEquals( new Integer(1), map.get( "key1" ) );
assertEquals( new Integer(4), map.get( "key4" ) );
assertEquals( new Integer(3), map.get( "key3" ) );
assertEquals( new Integer(2), map.get( "key2" ) );
assertEquals( new Integer(3), map.remove( "key3" ) );
assertEquals( new Integer(1), map.remove( "key1" ) );
assertEquals( new Integer(2), map.remove( "key2" ) );
for ( int i = 0; i < 100; i++ )
{
map.put( "key" + i, i );
}
for ( int i = 0; i < 100; i++ )
{
assertEquals( new Integer(i), map.get( "key" + i) );
}
for ( int i = 0; i < 100; i++ )
{
assertEquals( new Integer(i), map.remove( "key" + i) );
}
for ( int i = 0; i < 100; i++ )
{
assertTrue( map.get( "key" + i ) == null );
}
}
@Test
public void arraymapIsClearedWhenExpandingToHashMapIfNonShrinkable() throws Exception
{
assertDataRepresentationSwitchesWhenAboveThreshold( new ArrayMap<String, Integer>( (byte)3, false,
false ), false );
}
@Test
public void arraymapIsClearedWhenExpandingToHashMapIfShrinkable() throws Exception
{
assertDataRepresentationSwitchesWhenAboveThreshold( new ArrayMap<String, Integer>( (byte)3, false,
true ), true );
}
@Test
public void arraymapIsClearedWhenExpandingToHashMapIfNonShrinkableAndSynchronized()
throws Exception
{
assertDataRepresentationSwitchesWhenAboveThreshold( new ArrayMap<String, Integer>( (byte)3, true,
false ), false );
}
@Test
public void arraymapIsClearedWhenExpandingToHashMapIfShrinkableAndSynchronized()
throws Exception
{
assertDataRepresentationSwitchesWhenAboveThreshold(
new ArrayMap<String, Integer>( (byte)3, true, true ), true );
}
@SuppressWarnings( "rawtypes" )
private void assertDataRepresentationSwitchesWhenAboveThreshold( ArrayMap<String, Integer> map,
boolean shrinkable ) throws Exception
{
// Perhaps not the pretties solution... quite brittle...
Field mapThresholdField = ArrayMap.class.getDeclaredField( "toMapThreshold" );
mapThresholdField.setAccessible( true );
int arraySize = mapThresholdField.getInt( map );
Field dataField = ArrayMap.class.getDeclaredField( "data" );
dataField.setAccessible( true );
assertTrue( dataField.get( map ) instanceof Object[] );
for ( int i = 0; i < arraySize; i++ )
{
map.put( "key" + i, i );
assertTrue( dataField.get( map ) instanceof Object[] );
}
map.put( "next key", 999 );
Map dataAsMap = (Map) dataField.get( map );
assertEquals( arraySize+1, dataAsMap.size() );
map.remove( "key1" );
map.remove( "key2" );
map.remove( "key3" );
if ( shrinkable )
{
// It should've shrinked back into an array
assertTrue( dataField.get( map ) instanceof Object[] );
}
else
{
// It should stay as Map representation
assertTrue( dataField.get( map ) instanceof Map );
}
}
@Test
public void canOverwriteThenRemoveElementAcrossDeflation() throws Exception
{
ArrayMap<String, Integer> map = new ArrayMap<String, Integer>( (byte)3, false, true );
map.put( "key1", 1 );
map.put( "key2", 2 );
map.put( "key3", 3 );
map.put( "key4", 4 );
map.put( "key5", 5 );
map.put( "key1", 6 );
map.remove( "key1" );
assertNull( "removed element still found", map.get( "key1" ) );
map.remove( "key2" );
assertNull( "removed element still found", map.get( "key1" ) );
map.remove( "key3" );
assertNull( "removed element still found", map.get( "key1" ) );
map.remove( "key4" );
assertNull( "removed element still found", map.get( "key1" ) );
}
@Ignore("Takes 30mins to run on Windows. Ignoring")
@Test
public void testThreadSafeSize() throws InterruptedException
{
ArrayMap<Integer,Object> map = new ArrayMap<Integer,Object>((byte)5, true, true );
map.put( 1, new Object() );
map.put( 2, new Object() );
map.put( 3, new Object() );
map.put( 4, new Object() );
map.put( 5, new Object() );
final int NUM_THREADS = 100;
CountDownLatch done = new CountDownLatch( NUM_THREADS );
List<WorkerThread> threads = new ArrayList<WorkerThread>( NUM_THREADS );
for ( int i = 0; i < NUM_THREADS; i++ )
{
WorkerThread thread = new WorkerThread( map, done );
threads.add( thread );
thread.start();
}
done.await();
for ( WorkerThread thread : threads )
{
assertTrue( "Synchronized ArrayMap concurrent size invoke failed: " + thread.getCause(), thread.wasSuccessful() );
}
}
private static class WorkerThread extends Thread
{
private final ArrayMap<Integer,Object> map;
private volatile boolean success = false;
private volatile Throwable t = null;
private final CountDownLatch done;
WorkerThread( ArrayMap<Integer,Object> map, CountDownLatch done )
{
this.map = map;
this.done = done;
}
@Override
public void run()
{
try
{
for ( int i = 0; i < 10000; i++ )
{
if ( map.size() > 5 )
{
for ( int j = i; j < (i+10); j++ )
{
if ( map.remove( j % 10 ) != null )
{
break;
}
}
}
// calling size again to increase chance to hit CCE
else if ( map.size() <= 5 )
{
map.put( i % 10, new Object() );
}
yield();
}
success = true;
}
catch ( Throwable t )
{
this.t = t;
}
finally
{
done.countDown();
}
}
boolean wasSuccessful()
{
return success;
}
Throwable getCause()
{
return t;
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_util_TestArrayMap.java
|
490
|
{
@Override
public boolean accept( String item )
{
return item.contains( string );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_util_StringLoggerTest.java
|
491
|
{
@Override
public void write( char[] cbuf, int off, int len ) throws IOException
{
target.append( cbuf, off, len );
}
@Override
public void write( int c ) throws IOException
{
target.appendCodePoint( c );
}
@Override
public void write( char[] cbuf ) throws IOException
{
target.append( cbuf );
}
@Override
public void write( String str ) throws IOException
{
target.append( str );
}
@Override
public void write( String str, int off, int len ) throws IOException
{
target.append( str, off, len );
}
@Override
public Writer append( char c ) throws IOException
{
target.append( c );
return this;
}
@Override
public Writer append( CharSequence csq ) throws IOException
{
target.append( csq );
return this;
}
@Override
public Writer append( CharSequence csq, int start, int end ) throws IOException
{
target.append( csq, start, end );
return this;
}
@Override
public void flush() throws IOException
{
// do nothing
}
@Override
public void close() throws IOException
{
// do nothing
}
} ), false );
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_util_StringLogger.java
|
492
|
{
@Override
public void run()
{
logger.logMessage( baseMessage + " from trigger", true );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_util_StringLoggerTest.java
|
493
|
public class StringLoggerTest
{
private final FileSystemAbstraction fileSystem = new EphemeralFileSystemAbstraction();
@Test
public void makeSureLogsAreRotated() throws Exception
{
String path = "target/test-data/stringlogger";
deleteRecursively( new File( path ) );
File logFile = new File( path, StringLogger.DEFAULT_NAME );
File oldFile = new File( path, StringLogger.DEFAULT_NAME + ".1" );
File oldestFile = new File( path, StringLogger.DEFAULT_NAME + ".2" );
StringLogger logger = StringLogger.loggerDirectory( fileSystem,
new File( path ), 200 * 1024, false );
assertFalse( fileSystem.fileExists( oldFile ) );
int counter = 0;
String prefix = "Bogus message ";
// First rotation
while ( !fileSystem.fileExists( oldFile ) )
{
logger.logMessage( prefix + counter++, true );
}
int mark1 = counter-1;
logger.logMessage( prefix + counter++, true );
assertTrue( firstLineOfFile( oldFile ).contains( prefix + "0" ) );
assertTrue( lastLineOfFile( oldFile ).first().contains( prefix + mark1 ) );
assertTrue( firstLineOfFile( logFile ).contains( prefix + (counter-1) ) );
// Second rotation
while ( !fileSystem.fileExists( oldestFile ) )
{
logger.logMessage( prefix + counter++, true );
}
int mark2 = counter-1;
logger.logMessage( prefix + counter++, true );
assertTrue( firstLineOfFile( oldestFile ).contains( prefix + "0" ) );
assertTrue( lastLineOfFile( oldestFile ).first().contains( prefix + mark1 ) );
assertTrue( firstLineOfFile( oldFile ).contains( prefix + (mark1+1) ) );
assertTrue( lastLineOfFile( oldFile ).first().contains( prefix + mark2 ) );
assertTrue( firstLineOfFile( logFile ).contains( prefix + (counter-1) ) );
// Third rotation, assert .2 file is now what used to be .1 used to be and
// .3 doesn't exist
long previousSize = 0;
while ( true )
{
logger.logMessage( prefix + counter++, true );
if ( fileSystem.getFileSize( logFile ) < previousSize )
{
break;
}
previousSize = fileSystem.getFileSize( logFile );
}
assertFalse( fileSystem.fileExists( new File( path, StringLogger.DEFAULT_NAME + ".3" ) ) );
assertTrue( firstLineOfFile( oldestFile ).contains( prefix + (mark1+1) ) );
assertTrue( lastLineOfFile( oldestFile ).first().contains( prefix + mark2 ) );
}
@Test
public void makeSureRotationDoesNotRecurse() throws Exception
{
final String baseMessage = "base message";
File target = TargetDirectory.forTest( StringLoggerTest.class ).cleanDirectory( "recursionTest" );
final StringLogger logger = StringLogger.loggerDirectory( fileSystem, target,
baseMessage.length() /*rotation threshold*/, false );
/*
* The trigger that will log more than the threshold during rotation, possibly causing another rotation
*/
Runnable trigger = new Runnable()
{
@Override
public void run()
{
logger.logMessage( baseMessage + " from trigger", true );
}
};
logger.addRotationListener( trigger );
logger.logMessage( baseMessage + " from main", true );
File rotated = new File( target, "messages.log.1" );
assertTrue( "rotated file not present, should have been created", fileSystem.fileExists( rotated ) );
Pair<String, Integer> rotatedInfo = lastLineOfFile( rotated );
assertTrue( "rotated file should have only stuff from main", rotatedInfo.first().endsWith( " from main" )
&& rotatedInfo.other() == 1 );
File current = new File( target, "messages.log" );
assertTrue( "should have created a new messages.log file", fileSystem.fileExists( current ) );
Pair<String, Integer> currentInfo = lastLineOfFile( current );
assertTrue( "current file should have only stuff from trigger", currentInfo.first().endsWith( " from trigger" )
&& currentInfo.other() == 1 );
}
@SuppressWarnings( "unchecked" )
@Test
public void shouldLogDebugMessagesIfToldTo() throws Exception
{
// GIVEN
File target = TargetDirectory.forTest( StringLoggerTest.class ).cleanDirectory( "debug" );
StringLogger logger = StringLogger.loggerDirectory( fileSystem, target, DEFAULT_THRESHOLD_FOR_ROTATION, true );
// WHEN
String firstMessage = "First message";
String secondMessage = "Second message";
String thirdMessage = "Third message";
logger.debug( firstMessage );
logger.debug( secondMessage, new RuntimeException( thirdMessage ) );
logger.close();
// THEN
File logFile = new File( target, DEFAULT_NAME );
assertTrue( "Should have contained " + firstMessage, fileContains( logFile, stringContaining( firstMessage ) ) );
assertTrue( "Should have contained " + secondMessage, fileContains( logFile, stringContaining( secondMessage ) ) );
assertTrue( "Should have contained " + thirdMessage, fileContains( logFile, stringContaining( thirdMessage ) ) );
assertTrue( "Should have contained stack trace from " + thirdMessage, fileContains( logFile, and(
stringContaining( "at " ), stringContaining( testName.getMethodName() ) ) ) );
}
private Predicate<String> stringContaining( final String string )
{
return new Predicate<String>()
{
@Override
public boolean accept( String item )
{
return item.contains( string );
}
};
}
private String firstLineOfFile( File file ) throws Exception
{
BufferedReader reader = new BufferedReader( fileSystem.openAsReader( file, Charset.defaultCharset().name() ) );
String result = reader.readLine();
reader.close();
return result;
}
private boolean fileContains( File file, Predicate<String> predicate ) throws IOException
{
BufferedReader reader = new BufferedReader( fileSystem.openAsReader( file, Charset.defaultCharset().name() ) );
try
{
String line = null;
while ( (line = reader.readLine()) != null )
{
if ( predicate.accept( line ) )
{
return true;
}
}
return false;
}
finally
{
reader.close();
}
}
/*
* Returns a Pair of the last line in the file and the number of lines in the file, so the
* other part from a one line file will be 1 and the other part from an empty file 0.
*/
private Pair<String, Integer> lastLineOfFile( File file ) throws Exception
{
int count = 0;
BufferedReader reader = new BufferedReader( fileSystem.openAsReader( file, Charset.defaultCharset().name() ) );
String line = null;
String result = null;
while ( (line = reader.readLine()) != null )
{
result = line;
count++;
}
reader.close();
return Pair.of( result, count );
}
public final @Rule TestName testName = new TestName();
}
| false
|
community_kernel_src_test_java_org_neo4j_kernel_impl_util_StringLoggerTest.java
|
494
|
protected static final class LineLoggerImpl implements LineLogger
{
private final StringLogger target;
public LineLoggerImpl( StringLogger target )
{
this.target = target;
}
@Override
public void logLine( String line )
{
target.logLine( line );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_util_StringLogger.java
|
495
|
private static class ActualStringLogger extends StringLogger
{
private final static String encoding = "UTF-8";
private PrintWriter out;
private final Integer rotationThreshold;
private final File file;
private final List<Runnable> onRotation = new CopyOnWriteArrayList<Runnable>();
private final FileSystemAbstraction fileSystem;
private final boolean debugEnabled;
private ActualStringLogger( FileSystemAbstraction fileSystem, String filename, int rotationThreshold,
boolean debugEnabled )
{
this.fileSystem = fileSystem;
this.rotationThreshold = rotationThreshold;
this.debugEnabled = debugEnabled;
try
{
file = new File( filename );
if ( file.getParentFile() != null )
{
fileSystem.mkdirs( file.getParentFile() );
}
instantiateWriter();
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
}
private ActualStringLogger( PrintWriter writer, boolean debugEnabled )
{
this.out = writer;
this.rotationThreshold = null;
this.file = null;
this.fileSystem = null;
this.debugEnabled = debugEnabled;
}
@Override
public boolean isDebugEnabled()
{
return debugEnabled;
}
@Override
public void addRotationListener( Runnable trigger )
{
onRotation.add( trigger );
}
private void instantiateWriter() throws IOException
{
out = new PrintWriter( new OutputStreamWriter( fileSystem.openAsOutputStream( file, true ), encoding ) );
for ( Runnable trigger : onRotation )
{
trigger.run();
}
}
@Override
public synchronized void logMessage( String msg, boolean flush )
{
out.println( time() + " INFO [org.neo4j]: " + msg );
if ( flush )
{
out.flush();
}
checkRotation();
}
@Override
public void logMessage( String msg, LogMarker marker )
{
// LogMarker is used by subclasses
logMessage( msg );
}
private String time()
{
return Format.date();
}
@Override
public synchronized void logMessage( String msg, Throwable cause, boolean flush )
{
out.println( time() + " ERROR [org.neo4j]: " + msg + " " + cause.getMessage());
cause.printStackTrace( out );
if ( flush )
{
out.flush();
}
checkRotation();
}
@Override
public synchronized void logLongMessage( String msg, Visitor<LineLogger, RuntimeException> source, boolean flush )
{
out.println( time() + " INFO [org.neo4j]: " + msg );
source.visit( new LineLoggerImpl( this ) );
if ( flush )
{
out.flush();
}
checkRotation();
}
@Override
protected void logLine( String line )
{
out.println( " " + line );
}
private volatile boolean doingRotation = false;
private void checkRotation()
{
if ( rotationThreshold != null && fileSystem.getFileSize( file ) > rotationThreshold && !doingRotation )
{
doRotation();
}
}
private void doRotation()
{
doingRotation = true;
out.close();
moveAwayFile();
try
{
instantiateWriter();
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
finally
{
doingRotation = false;
}
}
/**
* Will move:
* messages.log.1 -> messages.log.2
* messages.log -> messages.log.1
* <p/>
* Will delete (if exists):
* messages.log.2
*/
private void moveAwayFile()
{
File oldLogFile = new File( file.getParentFile(), file.getName() + "." + NUMBER_OF_OLD_LOGS_TO_KEEP );
if ( fileSystem.fileExists( oldLogFile ) )
{
fileSystem.deleteFile( oldLogFile );
}
for ( int i = NUMBER_OF_OLD_LOGS_TO_KEEP - 1; i >= 0; i-- )
{
oldLogFile = new File( file.getParentFile(), file.getName() + (i == 0 ? "" : ("." + i)) );
if ( fileSystem.fileExists( oldLogFile ) )
{
try
{
fileSystem.renameFile( oldLogFile, new File( file.getParentFile(), file.getName() + "." + (i + 1) ) );
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
}
}
}
@Override
public void flush()
{
out.flush();
}
@Override
public void close()
{
out.close();
}
@Override
public String toString()
{
return "StringLogger[" + this.file + "]";
}
}
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_util_StringLogger.java
|
496
|
{
@Override
public void logMessage( String msg, boolean flush )
{
}
@Override
public void logMessage( String msg, LogMarker marker )
{
}
@Override
public void logMessage( String msg, Throwable cause, boolean flush )
{
}
@Override
public void logLongMessage( String msg, Visitor<LineLogger, RuntimeException> source, boolean flush )
{
}
@Override
protected void logLine( String line )
{
}
@Override
public void flush()
{
}
@Override
public void close()
{
}
@Override
public void addRotationListener( Runnable listener )
{
}
};
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_util_StringLogger.java
|
497
|
{
@Override
public boolean visit( LineLogger logger )
{
for ( String line : loop( source ) )
{
logger.logLine( line );
}
return true;
}
}, flush );
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_util_StringLogger.java
|
498
|
{
StringLogger logger = null;
@Override
public void logLongMessage( String msg, Visitor<LineLogger, RuntimeException> source, boolean flush )
{
createLogger();
logger.logLongMessage( msg, source, flush );
}
@Override
public void logMessage( String msg, boolean flush )
{
createLogger();
logger.logMessage( msg, flush );
}
@Override
public void logMessage( String msg, LogMarker marker )
{
createLogger();
logger.logMessage( msg, marker );
}
@Override
public void logMessage( String msg, Throwable cause, boolean flush )
{
createLogger();
logger.logMessage( msg, cause, flush );
}
@Override
public void addRotationListener( Runnable listener )
{
createLogger();
logger.addRotationListener( listener );
}
@Override
public void flush()
{
createLogger();
logger.flush();
}
@Override
public void close()
{
if ( logger != null )
{
logger.close();
}
}
@Override
protected void logLine( String line )
{
createLogger();
logger.logLine( line );
}
private synchronized void createLogger()
{
if (logger == null){
logger = logger( logFile );
}
}
};
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_util_StringLogger.java
|
499
|
{
@Override
public void logLongMessage( String msg, Visitor<LineLogger, RuntimeException> source, boolean flush )
{
logger1.logLongMessage( msg, source, flush );
logger2.logLongMessage( msg, source, flush );
}
@Override
public void logMessage( String msg, boolean flush )
{
logger1.logMessage( msg, flush );
logger2.logMessage( msg, flush );
}
@Override
public void logMessage( String msg, LogMarker marker )
{
logger1.logMessage( msg, marker );
logger2.logMessage( msg, marker );
}
@Override
public void logMessage( String msg, Throwable cause, boolean flush )
{
logger1.logMessage( msg, cause, flush );
logger2.logMessage( msg, cause, flush );
}
@Override
public void addRotationListener( Runnable listener )
{
logger1.addRotationListener( listener );
logger2.addRotationListener( listener );
}
@Override
public void flush()
{
logger1.flush();
logger2.flush();
}
@Override
public void close()
{
logger1.close();
logger2.close();
}
@Override
protected void logLine( String line )
{
logger1.logLine( line );
logger2.logLine( line );
}
};
| false
|
community_kernel_src_main_java_org_neo4j_kernel_impl_util_StringLogger.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.