All Downloads are FREE. Search and download functionalities are using the official Maven repository.

co.easimart.vertx.stream.ExpectedSizeReadStream Maven / Gradle / Ivy

The newest version!
package co.easimart.vertx.stream;

import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.streams.ReadStream;

/**
 * ReadStream<Buffer> which fires event if the stream receives data smaller or bigger than expected size.
 */
public class ExpectedSizeReadStream implements ReadStream {

    private Handler dataHandler;
    private Handler endHandler;
    private Handler unexpectedSizeHandler;
    private final ReadStream stream;
    private final Long expectedSize;
    private Long total;

    public ExpectedSizeReadStream(ReadStream stream, Long expectedSize) {
        this.stream = stream;
        this.expectedSize = expectedSize;
        this.total = 0L;

        this.stream.handler(buffer -> {
            if (this.total > this.expectedSize) return;
            this.total += buffer.length();
            if (this.total > this.expectedSize) {
                if (this.unexpectedSizeHandler != null)
                    this.unexpectedSizeHandler.handle(this.total);
            } else if (this.dataHandler != null) this.dataHandler.handle(buffer);
        });
        this.stream.endHandler(r -> {
            if (this.total < this.expectedSize) {
                if (this.unexpectedSizeHandler != null)
                    this.unexpectedSizeHandler.handle(this.total);
            }
            if (this.endHandler != null) this.endHandler.handle(r);
        });
    }

    @Override
    public ReadStream exceptionHandler(Handler handler) {
        this.stream.exceptionHandler(handler);
        return this;
    }

    @Override
    public ReadStream handler(Handler handler) {
        this.dataHandler = handler;
        return this;
    }

    @Override
    public ReadStream pause() {
        this.stream.pause();
        return this;
    }

    @Override
    public ReadStream resume() {
        this.stream.resume();
        return this;
    }

    @Override
    public ReadStream endHandler(Handler handler) {
        this.endHandler = handler;
        return this;
    }

    public ExpectedSizeReadStream unexpectedSizeHandler(Handler handler) {
        this.unexpectedSizeHandler = handler;
        return this;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy