graphql.servlet.internal.WsSessionSubscriptions Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of graphql-java-servlet Show documentation
Show all versions of graphql-java-servlet Show documentation
relay.js-compatible GraphQL servlet
package graphql.servlet.internal;
import org.reactivestreams.Subscription;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author Andrew Potter
*/
public class WsSessionSubscriptions {
private final Object lock = new Object();
private boolean closed = false;
private Map subscriptions = new ConcurrentHashMap<>();
public void add(Subscription subscription) {
add(getImplicitId(subscription), subscription);
}
public void add(String id, Subscription subscription) {
synchronized (lock) {
if (closed) {
throw new IllegalStateException("Websocket was already closed!");
}
subscriptions.put(id, subscription);
}
}
public void cancel(Subscription subscription) {
cancel(getImplicitId(subscription));
}
public void cancel(String id) {
Subscription subscription = subscriptions.remove(id);
if(subscription != null) {
subscription.cancel();
}
}
public void close() {
synchronized (lock) {
closed = true;
subscriptions.forEach((k, v) -> v.cancel());
subscriptions.clear();
}
}
private String getImplicitId(Subscription subscription) {
return String.valueOf(subscription.hashCode());
}
public int getSubscriptionCount() { return subscriptions.size(); }
}