tdlight-java/src/main/java/it/tdlight/common/InternalClientManager.java

68 lines
2.2 KiB
Java
Raw Normal View History

2020-10-13 01:31:32 +02:00
package it.tdlight.common;
2020-10-13 15:12:13 +02:00
import java.util.concurrent.ConcurrentHashMap;
2020-10-13 01:31:32 +02:00
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
public class InternalClientManager implements AutoCloseable {
private static final AtomicReference<InternalClientManager> INSTANCE = new AtomicReference<>(null);
private final String implementationName;
private final ResponseReceiver responseReceiver = new ResponseReceiver(this::handleClientEvents);
2020-10-13 15:12:13 +02:00
private final ConcurrentHashMap<Integer, ClientEventsHandler> registeredClientEventHandlers = new ConcurrentHashMap<>();
2020-10-13 01:31:32 +02:00
private final AtomicLong currentQueryId = new AtomicLong();
private InternalClientManager(String implementationName) {
try {
Init.start();
} catch (Throwable ex) {
ex.printStackTrace();
System.exit(1);
}
2020-10-13 01:31:32 +02:00
this.implementationName = implementationName;
}
public static InternalClientManager get(String implementationName) {
return INSTANCE.updateAndGet(val -> val == null ? new InternalClientManager(implementationName) : val);
}
private void handleClientEvents(int clientId, boolean isClosed, long[] clientEventIds, Object[] clientEvents) {
2020-10-13 15:12:13 +02:00
ClientEventsHandler handler = registeredClientEventHandlers.get(clientId);
2020-10-13 01:31:32 +02:00
if (handler != null) {
handler.handleEvents(isClosed, clientEventIds, clientEvents);
} else {
System.err.println("Unknown client id " + clientId + ", " + clientEvents.length + " events have been dropped!");
2021-01-24 18:02:00 +01:00
for (Object clientEvent : clientEvents) {
System.err.println(clientEvent);
}
2020-10-13 01:31:32 +02:00
}
if (isClosed) {
2020-10-13 15:12:13 +02:00
registeredClientEventHandlers.remove(clientId);
2020-10-13 01:31:32 +02:00
}
}
2020-10-13 15:12:13 +02:00
public void registerClient(int clientId, InternalClient internalClient) {
2020-11-14 11:12:52 +01:00
responseReceiver.registerClient(clientId);
2020-10-13 18:33:06 +02:00
boolean replaced = registeredClientEventHandlers.put(clientId, internalClient) != null;
if (replaced) {
throw new IllegalStateException("Client " + clientId + " already registered");
}
2020-10-13 01:31:32 +02:00
}
public String getImplementationName() {
return implementationName;
}
public long getNextQueryId() {
2020-10-13 04:10:20 +02:00
return currentQueryId.updateAndGet(value -> (value >= Long.MAX_VALUE ? 0 : value) + 1);
2020-10-13 01:31:32 +02:00
}
@Override
public void close() throws InterruptedException {
responseReceiver.close();
}
}