
hu.akarnokd.reactive.pc.RsAPIManager Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of akarnokd-reactive-rpc Show documentation
Show all versions of akarnokd-reactive-rpc Show documentation
akarnokd-reactive-rpc developed by David Karnok
The newest version!
package hu.akarnokd.reactive.pc;
import java.io.IOException;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import org.reactivestreams.*;
import io.reactivex.plugins.RxJavaPlugins;
/**
* Allows registering Subscribers and Subscriptions for incoming messages
* and allows sending messages.
*/
public final class RsAPIManager implements RsPcReceive, RsPcSend {
static volatile boolean logMessages = false;
final ConcurrentMap> subscribers;
final ConcurrentMap subscriptions;
RsPcSend send;
final AtomicLong streamIds;
final boolean server;
final RsPcNewStream onNew;
final Runnable onTerminate;
final AtomicBoolean terminateOnce;
public RsAPIManager(boolean server, RsPcNewStream onNew, Runnable onTerminate) {
this.server = server;
this.onNew = onNew;
this.onTerminate = onTerminate;
this.terminateOnce = new AtomicBoolean();
this.subscribers = new ConcurrentHashMap<>();
this.subscriptions = new ConcurrentHashMap<>();
this.streamIds = new AtomicLong((server ? Long.MIN_VALUE : 0) + 1);
}
public long newStreamId() {
return streamIds.getAndIncrement();
}
public void registerSubscription(long streamId, Subscription s) {
if (subscriptions.putIfAbsent(streamId, s) != null) {
throw new IllegalStateException("StreamID " + streamId + " already registered");
}
}
public void registerSubscriber(long streamId, Subscriber> s) {
if (subscribers.putIfAbsent(streamId, s) != null) {
throw new IllegalStateException("StreamID " + streamId + " already registered");
}
}
public void deregister(long streamId) {
subscribers.remove(streamId);
subscriptions.remove(streamId);
}
@Override
public void onNew(long streamId, String function) {
if (logMessages) {
System.out.printf("%s/onNew/%d/%s%n", server ? "server" : "client", streamId, function);
}
if (!onNew.onNew(streamId, function, this)) {
if (logMessages) {
System.out.printf("%s/onNew/%d/%s%n", server ? "server" : "client", streamId, "New stream(" + function + ") rejected");
}
send.sendCancel(streamId, "New stream(" + function + ") rejected");
}
}
@Override
public void onNext(long streamId, Object o) {
if (logMessages) {
System.out.printf("%s/onNext/%d/value=%s%n", server ? "server" : "client", streamId, o);
}
@SuppressWarnings("unchecked")
Subscriber
© 2015 - 2025 Weber Informatics LLC | Privacy Policy