com.kolibrifx.plovercrest.server.internal.streams.RangeStreamObserver Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of plovercrest-server Show documentation
Show all versions of plovercrest-server Show documentation
Plovercrest server library.
The newest version!
/*
* Copyright (c) 2010-2017, KolibriFX AS. Licensed under the Apache License, version 2.0.
*/
package com.kolibrifx.plovercrest.server.internal.streams;
import com.kolibrifx.plovercrest.server.streams.StreamObserver;
/**
* Base class for observing a range of elements.
*/
public abstract class RangeStreamObserver implements StreamObserver {
@SuppressWarnings("serial")
static class EndOfRangeException extends RuntimeException {
}
/** Exception constant used for simple control flow. */
private static final EndOfRangeException END_OF_RANGE = new EndOfRangeException();
private StreamObserver wrappedObserver;
private int observedCount = 0;
private long lastObserved = -1;
private boolean atEndOfStream = false;
private long lastValidTimestamp = -1;
public RangeStreamObserver(final StreamObserver wrappedObserver) {
this.wrappedObserver = wrappedObserver;
}
@Override
public void onObserveEnd(final long lastValidTimestamp, final long elementCount) {
atEndOfStream = true;
this.lastValidTimestamp = lastValidTimestamp;
}
@Override
public void onObserveFrozen() {
wrappedObserver.onObserveFrozen();
}
protected void throwEndOfRange() {
throw END_OF_RANGE;
}
protected void callWrappedObserver(final long timestamp, final long index, final T element) {
wrappedObserver.onObserve(timestamp, index, element);
observedCount++;
lastObserved = timestamp;
}
public int getObservedCount() {
return observedCount;
}
public boolean isAtEndOfStream() {
return atEndOfStream;
}
public long getLastValidTimestamp() {
return Math.max(lastValidTimestamp, lastObserved);
}
/**
* Call to replace the wrapped observer: useful when resuming a read.
*/
public void setWrappedObserver(final StreamObserver observer) {
this.wrappedObserver = observer;
}
@Override
public final void onObserve(final long timestamp, final long index, final T element) {
atEndOfStream = false;
onObserveImpl(timestamp, index, element);
}
protected abstract void onObserveImpl(long timestamp, long index, T element);
}