io.datakernel.datastream.processor.StreamUnion Maven / Gradle / Ivy
/*
* Copyright (C) 2015 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.processor;
import io.datakernel.datastream.*;
import io.datakernel.promise.Promise;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
/**
* It is Stream Transformer which unions all input streams and streams it
* combination to the destination.
*
* @param type of output data
*/
public final class StreamUnion implements StreamOutput, StreamInputs {
private final List inputs = new ArrayList<>();
private final Output output;
// region creators
private StreamUnion() {
this.output = new Output();
}
public static StreamUnion create() {
return new StreamUnion<>();
}
@Override
public List extends StreamConsumer>> getInputs() {
return inputs;
}
@Override
public StreamSupplier getOutput() {
return output;
}
public StreamConsumer newInput() {
Input input = new Input();
inputs.add(input);
return input;
}
// endregion
private final class Input extends AbstractStreamConsumer {
@Override
protected Promise onEndOfStream() {
if (inputs.stream().allMatch(input -> input.getEndOfStream().isResult())) {
output.sendEndOfStream();
}
return output.getConsumer().getAcknowledgement();
}
@Override
protected void onError(Throwable e) {
output.close(e);
}
}
private final class Output extends AbstractStreamSupplier {
@Override
protected void onSuspended() {
for (Input input : inputs) {
input.getSupplier().suspend();
}
}
@Override
protected void onProduce(@NotNull StreamDataAcceptor dataAcceptor) {
if (!inputs.isEmpty()) {
for (Input input : inputs) {
input.getSupplier().resume(dataAcceptor);
}
} else {
eventloop.post(this::sendEndOfStream);
}
}
@Override
protected void onError(Throwable e) {
inputs.forEach(input -> input.close(e));
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy