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

io.datakernel.datastream.stats.StreamStatsForwarder Maven / Gradle / Ivy

/*
 * Copyright (C) 2015-2018 SoftIndex LLC.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.datakernel.datastream.stats;

import io.datakernel.datastream.*;
import io.datakernel.datastream.processor.StreamTransformer;
import io.datakernel.promise.Promise;
import org.jetbrains.annotations.NotNull;

import java.util.Set;

import static java.util.Collections.emptySet;

public class StreamStatsForwarder implements StreamTransformer {
	private final Input input;
	private final Output output;

	private final StreamStats stats;

	private StreamStatsForwarder(StreamStats stats) {
		this.stats = stats;
		this.input = new Input();
		this.output = new Output();
	}

	public static  StreamStatsForwarder create(StreamStats stats) {
		return new StreamStatsForwarder<>(stats);
	}

	@Override
	public StreamConsumer getInput() {
		return input;
	}

	@Override
	public StreamSupplier getOutput() {
		return output;
	}

	private class Input extends AbstractStreamConsumer {
		@Override
		protected void onStarted() {
			stats.onStarted();
		}

		@Override
		protected Promise onEndOfStream() {
			stats.onEndOfStream();
			return output.sendEndOfStream();
		}

		@Override
		protected void onError(Throwable e) {
			output.close(e);
		}

		@Override
		public Set getCapabilities() {
			StreamConsumer consumer = output.getConsumer();
			return consumer != null ? consumer.getCapabilities() : emptySet();
		}
	}

	private class Output extends AbstractStreamSupplier {
		@Override
		protected void onProduce(@NotNull StreamDataAcceptor dataAcceptor) {
			stats.onProduce();
			input.getSupplier().resume(stats.createDataAcceptor(dataAcceptor));
		}

		@Override
		protected void onSuspended() {
			stats.onSuspend();
			input.getSupplier().suspend();
		}

		@Override
		protected void onError(Throwable e) {
			stats.onError(e);
			input.close(e);
		}

		@Override
		public Set getCapabilities() {
			StreamSupplier supplier = input.getSupplier();
			return supplier != null ? supplier.getCapabilities() : emptySet();
		}
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy