public void testBufferOverflowWhileFetching() throws Exception
{
int bufferCapacity = 5;
Map environment = new HashMap();
environment.put(MX4JRemoteConstants.NOTIFICATION_BUFFER_CAPACITY, new Integer(bufferCapacity));
RemoteNotificationServerHandler handler = new DefaultRemoteNotificationServerHandler(environment);
// First Fetch
NotificationResult result = handler.fetchNotifications(-1, bufferCapacity + 1, 100);
// Add some notifications, but don't fill the buffer
long count = bufferCapacity - 2;
NotificationListener listener = handler.getServerNotificationListener();
Notification notification = new Notification("dummy", this, 0);
Integer listenerID = new Integer(1);
for (int i = 0; i < count; ++i) listener.handleNotification(notification, listenerID);
// Fetch again
result = handler.fetchNotifications(result.getNextSequenceNumber(), bufferCapacity + 1, 100);
assertEquals(result.getEarliestSequenceNumber(), 0);
assertEquals(result.getNextSequenceNumber(), count);
assertNotNull(result.getTargetedNotifications());
assertEquals(result.getTargetedNotifications().length, count);
// Add some notification overflowing the buffer by a number that will exceed the
// next sequence number sent by the client.
// The client will fetch with its own sequence number, but the server
// has discarded that number already (it overflew), be sure the system it does
// not screw up (IndexOutOfBoundsException)
int overflow = 7;
// Note that count == result.getNextSequenceNumber() always yield true at this point (see assertion above),
// so we actually overflew the buffer by a quantity q == count + overflow (see assertion below).
long overflowCount = (bufferCapacity - count) + result.getNextSequenceNumber() + overflow;
for (int i = 0; i < overflowCount; ++i) listener.handleNotification(notification, listenerID);
result = handler.fetchNotifications(result.getNextSequenceNumber(), bufferCapacity + 1, 100);
// After algebraic semplification, overflowCount == bufferCapacity + overflow, so
// the buffer is full, and we fetched all notifications
assertEquals(count + overflow, result.getEarliestSequenceNumber());
assertEquals(count + overflow + bufferCapacity, result.getNextSequenceNumber());