![JAR search and dependency download from the Maven repository](/logo.png)
com.kolibrifx.plovercrest.server.streams.folds.TakePreviousFoldCallbackAdapter 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.streams.folds;
import com.kolibrifx.lancebill.folds.FoldOutputStream;
import com.kolibrifx.lancebill.folds.GenericFold;
import com.kolibrifx.plovercrest.server.internal.folds.FoldCallback;
import com.kolibrifx.plovercrest.server.internal.folds.FoldWriter;
/**
* {@link FoldCallback} implementation that wraps a {@link FoldWriter} and {@link GenericFold} and
* implements take-previous behavior when writing to the underlying {@link FoldWriter}.
*/
public class TakePreviousFoldCallbackAdapter implements FoldCallback {
private final FoldWriter writer;
private final GenericFold fold;
private final FoldOutputStream outputStream;
private boolean hasStarted = false;
private long previousTimestamp = 0;
private T previousMessage = null;
public TakePreviousFoldCallbackAdapter(final long fromTimestamp,
final FoldWriter writer,
final GenericFold fold) {
this.writer = writer;
this.fold = fold;
this.outputStream = new FoldOutputStream() {
@Override
public void write(final long timestamp, final T message) {
// Messages before "fromTimestamp" are normally dropped. But we want "take previous" behavior,
// so keep track of the last message and trigger it when we receive the first message larger than
// "fromTimestamp". If we receive a message exactly at "fromTimestamp", the last message is dropped.
if (timestamp > fromTimestamp) {
maybeWritePrevious();
}
if (!hasStarted && timestamp < fromTimestamp) {
previousMessage = message;
} else {
previousMessage = null;
writer.write(timestamp, message);
hasStarted = true;
}
previousTimestamp = timestamp;
}
};
}
private void maybeWritePrevious() {
if (!hasStarted && previousMessage != null) {
writer.write(previousTimestamp, previousMessage);
hasStarted = true;
}
}
@Override
public void onNext(final String tableName, final long timestamp, final U data) {
fold.onInput(tableName, Math.max(timestamp, previousTimestamp), data, outputStream);
}
@Override
public void onEnd() {
// This ensures "take previous" behavior for subscribers
maybeWritePrevious();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy