in mavibot/src/main/java/org/apache/directory/mavibot/btree/InMemoryBTree.java [499:577]
public void flush( File file ) throws IOException
{
File parentFile = file.getParentFile();
File baseDirectory = null;
if ( parentFile != null )
{
baseDirectory = new File( file.getParentFile().getAbsolutePath() );
}
else
{
baseDirectory = new File( "." );
}
// Create a temporary file in the same directory to flush the current btree
File tmpFileFD = File.createTempFile( "mavibot", null, baseDirectory );
FileOutputStream stream = new FileOutputStream( tmpFileFD );
FileChannel ch = stream.getChannel();
// Create a buffer containing 200 4Kb pages (around 1Mb)
ByteBuffer bb = ByteBuffer.allocateDirect( writeBufferSize );
try
{
TupleCursor<K, V> cursor = browse();
if ( keySerializer == null )
{
throw new MissingSerializerException( "Cannot flush the btree without a Key serializer" );
}
if ( valueSerializer == null )
{
throw new MissingSerializerException( "Cannot flush the btree without a Value serializer" );
}
// Write the number of elements first
bb.putLong( getBtreeHeader().getNbElems() );
while ( cursor.hasNext() )
{
Tuple<K, V> tuple = cursor.next();
byte[] keyBuffer = keySerializer.serialize( tuple.getKey() );
writeBuffer( ch, bb, keyBuffer );
byte[] valueBuffer = valueSerializer.serialize( tuple.getValue() );
writeBuffer( ch, bb, valueBuffer );
}
// Write the buffer if needed
if ( bb.position() > 0 )
{
bb.flip();
ch.write( bb );
}
// Flush to the disk for real
ch.force( true );
ch.close();
}
catch ( KeyNotFoundException knfe )
{
knfe.printStackTrace();
throw new IOException( knfe.getMessage() );
}
// Rename the current file to save a backup
File backupFile = File.createTempFile( "mavibot", null, baseDirectory );
file.renameTo( backupFile );
// Rename the temporary file to the initial file
tmpFileFD.renameTo( file );
// We can now delete the backup file
backupFile.delete();
}