}
}
public void testRead() throws Exception
{
final AsynchronousFileImpl controller = new AsynchronousFileImpl(executor, pollerExecutor);
controller.setBufferCallback(new BufferCallback()
{
public void bufferDone(final ByteBuffer buffer)
{
AsynchronousFileImpl.destroyBuffer(buffer);
}
});
ByteBuffer readBuffer = null;
try
{
final int NUMBER_LINES = 1000;
final int SIZE = 1024;
controller.open(FILE_NAME, 1000);
controller.fill(0, 1, NUMBER_LINES * SIZE, (byte)'j');
{
CountDownLatch latch = new CountDownLatch(NUMBER_LINES);
ArrayList<Integer> result = new ArrayList<Integer>();
AtomicInteger errors = new AtomicInteger(0);
for (int i = 0; i < NUMBER_LINES; i++)
{
if (i % 100 == 0)
{
System.out.println("Wrote " + i + " lines");
}
ByteBuffer buffer = AsynchronousFileImpl.newBuffer(SIZE);
for (int j = 0; j < SIZE; j++)
{
buffer.put(UnitTestCase.getSamplebyte(j));
}
CountDownCallback aio = new CountDownCallback(latch, errors, result, i);
controller.write(i * SIZE, SIZE, buffer, aio);
}
latch.await();
Assert.assertEquals(0, errors.get());
CountDownCallback.checkResults(NUMBER_LINES, result);
}
// If you call close you're supposed to wait events to finish before
// closing it
controller.close();
controller.setBufferCallback(null);
controller.open(FILE_NAME, 10);
readBuffer = AsynchronousFileImpl.newBuffer(SIZE);
for (int i = 0; i < NUMBER_LINES; i++)
{
if (i % 100 == 0)
{
System.out.println("Read " + i + " lines");
}
AsynchronousFileImpl.clearBuffer(readBuffer);
CountDownLatch latch = new CountDownLatch(1);
AtomicInteger errors = new AtomicInteger(0);
CountDownCallback aio = new CountDownCallback(latch, errors, null, 0);
controller.read(i * SIZE, SIZE, readBuffer, aio);
latch.await();
Assert.assertEquals(0, errors.get());
Assert.assertTrue(aio.doneCalled);
byte bytesRead[] = new byte[SIZE];
readBuffer.get(bytesRead);
for (int count = 0; count < SIZE; count++)
{
Assert.assertEquals("byte position " + count + " differs on line " + i + " position = " + count,
UnitTestCase.getSamplebyte(count),
bytesRead[count]);
}
}
}
finally
{
if (readBuffer != null)
{
AsynchronousFileImpl.destroyBuffer(readBuffer);
}
try
{
controller.close();
}
catch (Throwable ignored)
{
}