com.kolibrifx.plovercrest.server.internal.ByteBufferStreamObserver Maven / Gradle / Ivy
Show all versions of plovercrest-server Show documentation
/*
* Copyright (c) 2010-2017, KolibriFX AS. Licensed under the Apache License, version 2.0.
*/
package com.kolibrifx.plovercrest.server.internal;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import com.kolibrifx.plovercrest.server.streams.StreamObserver;
/**
* Stream observer that appends data (starting with the timestamp) to a ByteBuffer, which must have
* enough space to contain the timestamp and bytes.
*
* On a buffer overflow, the overflow handler is invoked, and the put operations are retried (once).
*
* The observe() function always returns the ByteBuffer given to the constructor.
*/
public class ByteBufferStreamObserver implements StreamObserver {
private final ByteBuffer targetBuffer;
private final OverflowHandler overflowHandler;
private long lastValidTimestamp = -1;
public ByteBufferStreamObserver(final ByteBuffer targetBuffer, final OverflowHandler overflowHandler) {
this.targetBuffer = targetBuffer;
this.overflowHandler = overflowHandler;
}
@Override
public void onObserve(final long timestamp, final long index, final ByteBuffer element) {
final int mark = targetBuffer.position();
try {
targetBuffer.putLong(timestamp);
targetBuffer.put(element);
} catch (final BufferOverflowException e) {
targetBuffer.position(mark);
overflowHandler.writeChunk();
//targetBuffer.clear();
targetBuffer.putLong(timestamp);
targetBuffer.put(element);
}
}
@Override
public void onObserveEnd(final long lastValidTimestamp, final long elementCount) {
this.lastValidTimestamp = lastValidTimestamp;
}
@Override
public void onObserveFrozen() {
}
public long getLastValidTimestamp() {
return lastValidTimestamp;
}
}