Refactored using IntelliJ
This commit is contained in:
@@ -21,6 +21,22 @@ public class Argument {
|
||||
private final boolean optionalValue;
|
||||
private ArgumentRun run;
|
||||
|
||||
public Argument(String name, String description, boolean argRequired) {
|
||||
this(name, description, argRequired, false, false, new ArrayList<>());
|
||||
}
|
||||
|
||||
public Argument(String name, String description, boolean argRequired, boolean requireValue, boolean optionalValue, List<String> values) {
|
||||
if (requireValue && optionalValue) {
|
||||
throw new IllegalArgumentException("requireValue and optionalValue cannot both be true");
|
||||
}
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
this.required = argRequired;
|
||||
this.values = values == null ? new ArrayList<>() : values;
|
||||
this.requireValue = requireValue;
|
||||
this.optionalValue = optionalValue;
|
||||
}
|
||||
|
||||
public ArgumentRun getRun() {
|
||||
return run;
|
||||
}
|
||||
@@ -52,20 +68,4 @@ public class Argument {
|
||||
public boolean isOptionalValue() {
|
||||
return optionalValue;
|
||||
}
|
||||
|
||||
public Argument(String name, String description, boolean argRequired) {
|
||||
this(name, description, argRequired, false, false, new ArrayList<>());
|
||||
}
|
||||
|
||||
public Argument(String name, String description, boolean argRequired, boolean requireValue, boolean optionalValue, List<String> values) {
|
||||
if (requireValue && optionalValue) {
|
||||
throw new IllegalArgumentException("requireValue and optionalValue cannot both be true");
|
||||
}
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
this.required = argRequired;
|
||||
this.values = values == null ? new ArrayList<>() : values;
|
||||
this.requireValue = requireValue;
|
||||
this.optionalValue = optionalValue;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,40 +34,50 @@ public class ArgumentParser {
|
||||
}
|
||||
|
||||
public void runArguments() {
|
||||
arguments.stream().filter(Argument::isRequired).forEach(arg -> {
|
||||
if (!Arrays.stream(args).toList().contains(arg.getName())) {
|
||||
throw new IllegalArgumentException("Missing argument: " + arg.getName());
|
||||
}
|
||||
arguments.stream().filter(Argument::isRequired).forEach(argument -> {
|
||||
boolean present = Arrays.stream(args).anyMatch(token -> token.equalsIgnoreCase(argument.getName()));
|
||||
if (!present) throw new IllegalArgumentException("Missing argument: " + argument.getName());
|
||||
});
|
||||
|
||||
for (int i = 0; i <= args.length - 1; i++) {
|
||||
String arg = args[i];
|
||||
for (int i = 0; i < args.length; i++) {
|
||||
Argument argument = findArgument(args[i]);
|
||||
if (argument == null) continue;
|
||||
|
||||
for (Argument argument : arguments) {
|
||||
if (argument.getName().equalsIgnoreCase(arg)) {
|
||||
if (argument.isRequireValue()) {
|
||||
if (i + 1 >= args.length) {
|
||||
if (argument.isOptionalValue()) {
|
||||
if (argument.getRun() != null) argument.getRun().onRun(argument, Optional.empty());
|
||||
} else {
|
||||
throw new IllegalArgumentException("Missing value for argument: " + argument.getName());
|
||||
}
|
||||
} else {
|
||||
String value = args[i + 1];
|
||||
if (!argument.getValues().isEmpty() && !argument.getValues().contains(value)) {
|
||||
StringBuilder possibleValues = new StringBuilder();
|
||||
for (int i1 = 0; i1 < argument.getValues().size(); i1++) {
|
||||
possibleValues.append(argument.getValues().get(i1));
|
||||
if (i1 != argument.getValues().size() - 1) possibleValues.append(", ");
|
||||
}
|
||||
Optional<String> value = Optional.empty();
|
||||
boolean nextTokenAvailable = i + 1 < args.length;
|
||||
boolean nextTokenIsArgument = nextTokenAvailable && findArgument(args[i + 1]) != null;
|
||||
|
||||
throw new IllegalArgumentException("Invalid argument value '" + value + "' for argument '" + argument.getName() + "'! Possible: " + possibleValues.toString());
|
||||
} else if (argument.getRun() != null) argument.getRun().onRun(argument, Optional.of(value));
|
||||
i++;
|
||||
}
|
||||
} else if (argument.getRun() != null) argument.getRun().onRun(argument, Optional.empty());
|
||||
if (argument.isRequireValue()) {
|
||||
if (!nextTokenAvailable || nextTokenIsArgument) {
|
||||
throw new IllegalArgumentException("Missing value for argument: " + argument.getName());
|
||||
}
|
||||
String nextValue = args[++i];
|
||||
validateValue(argument, nextValue);
|
||||
value = Optional.of(nextValue);
|
||||
} else if (argument.isOptionalValue() && nextTokenAvailable && !nextTokenIsArgument) {
|
||||
String nextValue = args[++i];
|
||||
validateValue(argument, nextValue);
|
||||
value = Optional.of(nextValue);
|
||||
}
|
||||
|
||||
if (argument.getRun() != null) argument.getRun().onRun(argument, value);
|
||||
}
|
||||
}
|
||||
|
||||
private Argument findArgument(String token) {
|
||||
for (Argument argument : arguments) {
|
||||
if (argument.getName().equalsIgnoreCase(token)) return argument;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void validateValue(Argument argument, String value) {
|
||||
if (argument.getValues().isEmpty()) return;
|
||||
if (argument.getValues().contains(value)) return;
|
||||
|
||||
String possibleValues = String.join(", ", argument.getValues());
|
||||
throw new IllegalArgumentException(
|
||||
"Invalid argument value '" + value + "' for argument '" + argument.getName() + "'! Possible: " + possibleValues
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,10 +17,16 @@ public final class CommandManager {
|
||||
|
||||
// Registriere die Klasse, instanziiere sie einmalig
|
||||
public void registerCommand(Class<? extends Command> commandClass) {
|
||||
if (commandClass == null) throw new IllegalArgumentException("commandClass cannot be null");
|
||||
if (commandInstances.containsKey(commandClass)) return;
|
||||
|
||||
try {
|
||||
Command instance = commandClass.getDeclaredConstructor().newInstance();
|
||||
Command instance;
|
||||
try {
|
||||
instance = commandClass.getDeclaredConstructor(CommandManager.class).newInstance(this);
|
||||
} catch (NoSuchMethodException ignored) {
|
||||
instance = commandClass.getDeclaredConstructor().newInstance();
|
||||
}
|
||||
commandInstances.put(commandClass, instance);
|
||||
} catch (InstantiationException | IllegalAccessException | InvocationTargetException |
|
||||
NoSuchMethodException e) {
|
||||
@@ -58,7 +64,12 @@ public final class CommandManager {
|
||||
}
|
||||
|
||||
public void execute(CommandExecutor executor, String line) {
|
||||
String[] split = line.trim().split("\\s+");
|
||||
if (line == null) return;
|
||||
|
||||
String trimmed = line.trim();
|
||||
if (trimmed.isEmpty()) return;
|
||||
|
||||
String[] split = trimmed.split("\\s+");
|
||||
if (split.length == 0) return;
|
||||
|
||||
String commandLabel = split[0];
|
||||
|
||||
@@ -4,47 +4,135 @@ import dev.unlegitdqrk.unlegitlibrary.event.impl.Event;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.locks.ReadWriteLock;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||
|
||||
public final class EventManager {
|
||||
|
||||
// eventClass -> priority -> listenerInstance -> method
|
||||
private final Map<Class<? extends Event>, Map<EventPriority, Map<Object, Method>>> registeredListener =
|
||||
new ConcurrentHashMap<>();
|
||||
private final ReadWriteLock lock = new ReentrantReadWriteLock();
|
||||
|
||||
// listenerClass -> set of listener instances (identity-based)
|
||||
// eventClass -> priority -> handlers
|
||||
private final Map<Class<? extends Event>, Map<EventPriority, List<RegisteredListener>>> registeredListeners =
|
||||
new IdentityHashMap<>();
|
||||
|
||||
// listenerClass -> listener instances (identity-based)
|
||||
private final Map<Class<? extends EventListener>, Set<EventListener>> eventListeners =
|
||||
new ConcurrentHashMap<>();
|
||||
new IdentityHashMap<>();
|
||||
|
||||
public EventManager() {
|
||||
}
|
||||
// listener instance -> registered handler descriptors (identity-based)
|
||||
private final Map<EventListener, List<RegisteredListener>> listenerRegistrations =
|
||||
new IdentityHashMap<>();
|
||||
|
||||
public void registerListener(Class<? extends EventListener> clazz) throws Exception {
|
||||
if (clazz == null) throw new IllegalArgumentException("Listener class cannot be null");
|
||||
EventListener instance = clazz.getDeclaredConstructor().newInstance();
|
||||
registerListener(instance);
|
||||
registerListener(clazz.getDeclaredConstructor().newInstance());
|
||||
}
|
||||
|
||||
public void registerListener(EventListener listener) {
|
||||
if (listener == null) throw new IllegalArgumentException("Listener instance cannot be null");
|
||||
|
||||
// Track instance set for class (identity-based)
|
||||
eventListeners
|
||||
.computeIfAbsent(listener.getClass(), k -> Collections.newSetFromMap(new IdentityHashMap<>()))
|
||||
.add(listener);
|
||||
lock.writeLock().lock();
|
||||
try {
|
||||
Set<EventListener> instances = eventListeners
|
||||
.computeIfAbsent(listener.getClass(), ignored -> Collections.newSetFromMap(new IdentityHashMap<>()));
|
||||
|
||||
registerListenerInstance(listener);
|
||||
// Ignore duplicate registrations of the same listener instance.
|
||||
if (!instances.add(listener)) {
|
||||
return;
|
||||
}
|
||||
|
||||
registerListenerInstance(listener);
|
||||
} finally {
|
||||
lock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
private void registerListenerInstance(Object listener) {
|
||||
// Walk up class hierarchy so superclass @Listener methods are registered too
|
||||
public void unregisterListener(Class<? extends EventListener> clazz) {
|
||||
if (clazz == null) return;
|
||||
|
||||
lock.writeLock().lock();
|
||||
try {
|
||||
Set<EventListener> instances = eventListeners.remove(clazz);
|
||||
if (instances == null || instances.isEmpty()) return;
|
||||
|
||||
for (EventListener listener : new ArrayList<>(instances)) {
|
||||
unregisterListenerInstance(listener);
|
||||
}
|
||||
} finally {
|
||||
lock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public void unregisterListener(EventListener listener) {
|
||||
if (listener == null) return;
|
||||
|
||||
lock.writeLock().lock();
|
||||
try {
|
||||
Set<EventListener> instances = eventListeners.get(listener.getClass());
|
||||
if (instances != null) {
|
||||
instances.remove(listener);
|
||||
if (instances.isEmpty()) {
|
||||
eventListeners.remove(listener.getClass());
|
||||
}
|
||||
}
|
||||
|
||||
unregisterListenerInstance(listener);
|
||||
} finally {
|
||||
lock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isListenerRegistered(Class<? extends EventListener> clazz) {
|
||||
if (clazz == null) return false;
|
||||
|
||||
lock.readLock().lock();
|
||||
try {
|
||||
Set<EventListener> instances = eventListeners.get(clazz);
|
||||
return instances != null && !instances.isEmpty();
|
||||
} finally {
|
||||
lock.readLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public void executeEvent(Event event) {
|
||||
if (event == null) return;
|
||||
|
||||
List<RegisteredListener> snapshot = new ArrayList<>();
|
||||
|
||||
lock.readLock().lock();
|
||||
try {
|
||||
Map<EventPriority, List<RegisteredListener>> byPriority = registeredListeners.get(event.getClass());
|
||||
if (byPriority == null) return;
|
||||
|
||||
for (EventPriority priority : EventPriority.values()) {
|
||||
List<RegisteredListener> listeners = byPriority.get(priority);
|
||||
if (listeners != null && !listeners.isEmpty()) {
|
||||
snapshot.addAll(listeners);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
lock.readLock().unlock();
|
||||
}
|
||||
|
||||
for (RegisteredListener registered : snapshot) {
|
||||
try {
|
||||
registered.method.setAccessible(true);
|
||||
registered.method.invoke(registered.listener, event);
|
||||
} catch (ReflectiveOperationException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void registerListenerInstance(EventListener listener) {
|
||||
List<RegisteredListener> registered = listenerRegistrations.computeIfAbsent(listener, ignored -> new ArrayList<>());
|
||||
|
||||
// Walk up class hierarchy so superclass listener methods are also registered.
|
||||
for (Class<?> c = listener.getClass(); c != null && c != Object.class; c = c.getSuperclass()) {
|
||||
Method[] methods = c.getDeclaredMethods();
|
||||
|
||||
for (Method method : methods) {
|
||||
Listener annotation = method.getAnnotation(Listener.class);
|
||||
if (annotation == null) continue;
|
||||
|
||||
if (method.getParameterCount() != 1) continue;
|
||||
|
||||
Class<?> param = method.getParameterTypes()[0];
|
||||
@@ -53,68 +141,37 @@ public final class EventManager {
|
||||
@SuppressWarnings("unchecked")
|
||||
Class<? extends Event> eventClass = (Class<? extends Event>) param;
|
||||
|
||||
registeredListener
|
||||
.computeIfAbsent(eventClass, k -> new EnumMap<>(EventPriority.class))
|
||||
.computeIfAbsent(annotation.priority(), k -> Collections.synchronizedMap(new IdentityHashMap<>()))
|
||||
.put(listener, method);
|
||||
RegisteredListener registration = new RegisteredListener(listener, method, eventClass, annotation.priority());
|
||||
|
||||
registeredListeners
|
||||
.computeIfAbsent(eventClass, ignored -> new EnumMap<>(EventPriority.class))
|
||||
.computeIfAbsent(annotation.priority(), ignored -> new ArrayList<>())
|
||||
.add(registration);
|
||||
|
||||
registered.add(registration);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void unregisterListener(Class<? extends EventListener> clazz) {
|
||||
if (clazz == null) return;
|
||||
private void unregisterListenerInstance(EventListener listener) {
|
||||
List<RegisteredListener> registrations = listenerRegistrations.remove(listener);
|
||||
if (registrations == null || registrations.isEmpty()) return;
|
||||
|
||||
Set<EventListener> instances = eventListeners.remove(clazz);
|
||||
if (instances == null || instances.isEmpty()) return;
|
||||
for (RegisteredListener registration : registrations) {
|
||||
Map<EventPriority, List<RegisteredListener>> byPriority = registeredListeners.get(registration.eventClass);
|
||||
if (byPriority == null) continue;
|
||||
|
||||
for (EventListener instance : instances) {
|
||||
unregisterListener(instance);
|
||||
List<RegisteredListener> listeners = byPriority.get(registration.priority);
|
||||
if (listeners == null) continue;
|
||||
|
||||
listeners.removeIf(registered -> registered.listener == listener && registered.method.equals(registration.method));
|
||||
|
||||
if (listeners.isEmpty()) byPriority.remove(registration.priority);
|
||||
if (byPriority.isEmpty()) registeredListeners.remove(registration.eventClass);
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void unregisterListener(EventListener listener) {
|
||||
if (listener == null) return;
|
||||
|
||||
Set<EventListener> instances = eventListeners.get(listener.getClass());
|
||||
if (instances != null) {
|
||||
instances.remove(listener);
|
||||
if (instances.isEmpty()) eventListeners.remove(listener.getClass());
|
||||
}
|
||||
|
||||
for (Map<EventPriority, Map<Object, Method>> byPriority : registeredListener.values()) {
|
||||
for (Map<Object, Method> listeners : byPriority.values()) {
|
||||
listeners.remove(listener);
|
||||
}
|
||||
}
|
||||
|
||||
// cleanup empty maps
|
||||
registeredListener.entrySet().removeIf(e ->
|
||||
e.getValue().values().stream().allMatch(Map::isEmpty)
|
||||
);
|
||||
private record RegisteredListener(EventListener listener, Method method, Class<? extends Event> eventClass,
|
||||
EventPriority priority) {
|
||||
}
|
||||
|
||||
public boolean isListenerRegistered(Class<? extends EventListener> clazz) {
|
||||
Set<EventListener> instances = eventListeners.get(clazz);
|
||||
return instances != null && !instances.isEmpty();
|
||||
}
|
||||
|
||||
public void executeEvent(Event event) {
|
||||
if (event == null) return;
|
||||
|
||||
Map<EventPriority, Map<Object, Method>> byPriority = registeredListener.get(event.getClass());
|
||||
if (byPriority == null) return;
|
||||
|
||||
for (EventPriority priority : EventPriority.values()) {
|
||||
Map<Object, Method> listeners = byPriority.getOrDefault(priority, Collections.emptyMap());
|
||||
for (Map.Entry<Object, Method> entry : listeners.entrySet()) {
|
||||
try {
|
||||
Method method = entry.getValue();
|
||||
method.setAccessible(true);
|
||||
method.invoke(entry.getKey(), event);
|
||||
} catch (ReflectiveOperationException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,8 +20,10 @@ import java.util.zip.ZipInputStream;
|
||||
public final class FileUtils extends DefaultMethodsOverrider {
|
||||
|
||||
public static String getSuffix(File file) {
|
||||
String[] splitName = file.getName().split("\\.");
|
||||
return splitName[splitName.length - 1];
|
||||
String name = file.getName();
|
||||
int index = name.lastIndexOf('.');
|
||||
if (index < 0 || index == name.length() - 1) return "";
|
||||
return name.substring(index + 1);
|
||||
}
|
||||
|
||||
public static String readFileFromResource(String filePath) throws IOException {
|
||||
@@ -31,7 +33,7 @@ public final class FileUtils extends DefaultMethodsOverrider {
|
||||
|
||||
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) content.append(line).append("");
|
||||
while ((line = reader.readLine()) != null) content.append(line);
|
||||
}
|
||||
|
||||
inputStream.close();
|
||||
@@ -49,8 +51,10 @@ public final class FileUtils extends DefaultMethodsOverrider {
|
||||
}
|
||||
|
||||
public static String getName(File file) {
|
||||
String[] splitName = file.getName().split("\\.");
|
||||
return splitName[splitName.length - 2];
|
||||
String name = file.getName();
|
||||
int index = name.lastIndexOf('.');
|
||||
if (index <= 0) return name;
|
||||
return name.substring(0, index);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
@@ -142,9 +146,10 @@ public final class FileUtils extends DefaultMethodsOverrider {
|
||||
|
||||
public static List<String> readFileLines(File file) throws IOException {
|
||||
List<String> lines = new ArrayList<>();
|
||||
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8));
|
||||
String str;
|
||||
while ((str = in.readLine()) != null) lines.add(str);
|
||||
try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) {
|
||||
String str;
|
||||
while ((str = in.readLine()) != null) lines.add(str);
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
|
||||
@@ -16,15 +16,16 @@ import dev.unlegitdqrk.unlegitlibrary.network.system.client.events.state.ClientC
|
||||
import dev.unlegitdqrk.unlegitlibrary.network.system.client.events.state.ClientDisconnectedEvent;
|
||||
import dev.unlegitdqrk.unlegitlibrary.network.system.packets.Packet;
|
||||
import dev.unlegitdqrk.unlegitlibrary.network.system.packets.PacketHandler;
|
||||
import dev.unlegitdqrk.unlegitlibrary.network.system.utils.TransportProtocol;
|
||||
import dev.unlegitdqrk.unlegitlibrary.network.system.utils.SSLContexts;
|
||||
import dev.unlegitdqrk.unlegitlibrary.network.system.utils.TransportProtocol;
|
||||
import dev.unlegitdqrk.unlegitlibrary.network.system.utils.UdpCrypto;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLSocket;
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.Socket;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.DatagramChannel;
|
||||
import java.security.KeyStore;
|
||||
@@ -35,18 +36,15 @@ import java.util.UUID;
|
||||
*/
|
||||
public class NetworkClient {
|
||||
|
||||
private Socket tcpSocket;
|
||||
private DatagramChannel udpChannel;
|
||||
|
||||
private DataInputStream inputStream;
|
||||
private DataOutputStream outputStream;
|
||||
|
||||
private SecretKey udpKey;
|
||||
|
||||
private final PacketHandler packetHandler;
|
||||
private final EventManager eventManager;
|
||||
private final Thread tcpReceiveThread;
|
||||
private final Thread udpReceiveThread;
|
||||
private Socket tcpSocket;
|
||||
private DatagramChannel udpChannel;
|
||||
private DataInputStream inputStream;
|
||||
private DataOutputStream outputStream;
|
||||
private SecretKey udpKey;
|
||||
private Thread tcpReceiveThread;
|
||||
private Thread udpReceiveThread;
|
||||
|
||||
private boolean sslEnabled = true;
|
||||
private volatile UUID uniqueID;
|
||||
@@ -72,13 +70,11 @@ public class NetworkClient {
|
||||
* Creates a client with a custom {@link EventManager}.
|
||||
*
|
||||
* @param packetHandler packet handler
|
||||
* @param eventManager event manager
|
||||
* @param eventManager event manager
|
||||
*/
|
||||
public NetworkClient(PacketHandler packetHandler, EventManager eventManager) {
|
||||
this.packetHandler = packetHandler;
|
||||
this.eventManager = eventManager;
|
||||
this.tcpReceiveThread = new Thread(this::tcpReceive);
|
||||
this.udpReceiveThread = new Thread(this::udpReceive);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -93,10 +89,10 @@ public class NetworkClient {
|
||||
/**
|
||||
* Enables or disables TLS with explicit key and trust stores.
|
||||
*
|
||||
* @param sslEnabled enable TLS
|
||||
* @param keyStore client key store (optional)
|
||||
* @param sslEnabled enable TLS
|
||||
* @param keyStore client key store (optional)
|
||||
* @param keyPassword key store password
|
||||
* @param trustStore trust store (required when TLS is enabled)
|
||||
* @param trustStore trust store (required when TLS is enabled)
|
||||
*/
|
||||
public void configureSSL(boolean sslEnabled,
|
||||
KeyStore keyStore,
|
||||
@@ -120,10 +116,12 @@ public class NetworkClient {
|
||||
/**
|
||||
* Connects to a server.
|
||||
*
|
||||
* @param host server host
|
||||
* @param host server host
|
||||
* @param tcpPort server TCP port
|
||||
*/
|
||||
public void connect(String host, int tcpPort) throws Exception {
|
||||
if (isTCPConnected()) throw new IllegalStateException("Client is already connected");
|
||||
|
||||
this.host = host;
|
||||
this.tcpPort = tcpPort;
|
||||
|
||||
@@ -142,6 +140,7 @@ public class NetworkClient {
|
||||
inputStream = new DataInputStream(tcpSocket.getInputStream());
|
||||
outputStream = new DataOutputStream(tcpSocket.getOutputStream());
|
||||
|
||||
tcpReceiveThread = new Thread(this::tcpReceive, "unlegitlibrary-client-tcp-receive");
|
||||
tcpReceiveThread.start();
|
||||
|
||||
long deadline = System.currentTimeMillis() + handshakeTimeoutMillis;
|
||||
@@ -190,6 +189,7 @@ public class NetworkClient {
|
||||
|
||||
udpChannel = DatagramChannel.open();
|
||||
udpChannel.connect(new InetSocketAddress(host, udpPort));
|
||||
udpReceiveThread = new Thread(this::udpReceive, "unlegitlibrary-client-udp-receive");
|
||||
udpReceiveThread.start();
|
||||
|
||||
// initial handshake
|
||||
@@ -223,7 +223,8 @@ public class NetworkClient {
|
||||
packetId = dis.readInt();
|
||||
if ((packet = packetHandler.readPacket(dis, uuid, packetId)) != null) {
|
||||
eventManager.executeEvent(new C_PacketReadEvent(this, packet, TransportProtocol.UDP));
|
||||
} else eventManager.executeEvent(new C_PacketFailedReadEvent(this, packet, packetId, TransportProtocol.UDP));
|
||||
} else
|
||||
eventManager.executeEvent(new C_PacketFailedReadEvent(this, packet, packetId, TransportProtocol.UDP));
|
||||
|
||||
} catch (Exception ignored) {
|
||||
eventManager.executeEvent(new C_PacketFailedReadEvent(this, packet, packetId, TransportProtocol.UDP));
|
||||
@@ -234,7 +235,7 @@ public class NetworkClient {
|
||||
/**
|
||||
* Sends a packet via TCP or UDP.
|
||||
*
|
||||
* @param packet packet to send
|
||||
* @param packet packet to send
|
||||
* @param protocol transport protocol
|
||||
*/
|
||||
public void sendPacket(Packet packet, TransportProtocol protocol) throws Exception {
|
||||
@@ -258,18 +259,32 @@ public class NetworkClient {
|
||||
*/
|
||||
public void disconnect() {
|
||||
// Stop threads first
|
||||
tcpReceiveThread.interrupt();
|
||||
udpReceiveThread.interrupt();
|
||||
if (tcpReceiveThread != null) tcpReceiveThread.interrupt();
|
||||
if (udpReceiveThread != null) udpReceiveThread.interrupt();
|
||||
|
||||
try { if (inputStream != null) inputStream.close(); } catch (IOException ignored) {}
|
||||
try { if (outputStream != null) outputStream.close(); } catch (IOException ignored) {}
|
||||
try { if (tcpSocket != null) tcpSocket.close(); } catch (IOException ignored) {}
|
||||
try { if (udpChannel != null) udpChannel.close(); } catch (IOException ignored) {}
|
||||
try {
|
||||
if (inputStream != null) inputStream.close();
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
try {
|
||||
if (outputStream != null) outputStream.close();
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
try {
|
||||
if (tcpSocket != null) tcpSocket.close();
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
try {
|
||||
if (udpChannel != null) udpChannel.close();
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
|
||||
inputStream = null;
|
||||
outputStream = null;
|
||||
tcpSocket = null;
|
||||
udpChannel = null;
|
||||
tcpReceiveThread = null;
|
||||
udpReceiveThread = null;
|
||||
|
||||
eventManager.executeEvent(new ClientDisconnectedEvent(this));
|
||||
|
||||
@@ -360,7 +375,7 @@ public class NetworkClient {
|
||||
/**
|
||||
* Sets the key store and its password.
|
||||
*
|
||||
* @param keyStore key store
|
||||
* @param keyStore key store
|
||||
* @param keyPassword key store password
|
||||
* @return builder
|
||||
*/
|
||||
|
||||
@@ -15,10 +15,13 @@ import java.util.UUID;
|
||||
|
||||
public abstract class Packet {
|
||||
|
||||
public Packet() {}
|
||||
public Packet() {
|
||||
}
|
||||
|
||||
public abstract int getPacketID();
|
||||
|
||||
public abstract void read(DataInputStream stream, UUID clientID) throws IOException;
|
||||
|
||||
public abstract void write(DataOutputStream stream) throws IOException;
|
||||
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
package dev.unlegitdqrk.unlegitlibrary.network.system.packets;
|
||||
|
||||
import java.io.*;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.io.DataInputStream;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
@@ -26,13 +27,13 @@ public class PacketHandler {
|
||||
factories.put(id, factory);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a packet from the input stream.
|
||||
* Expects the packet to be serialized as an object.
|
||||
*
|
||||
* @param input DataInputStream to read from
|
||||
* @return Packet instance or null if failed
|
||||
*/
|
||||
/**
|
||||
* Reads a packet from the input stream.
|
||||
* Expects the packet to be serialized as an object.
|
||||
*
|
||||
* @param input DataInputStream to read from
|
||||
* @return Packet instance or null if failed
|
||||
*/
|
||||
public Packet readPacket(DataInputStream input, UUID clientID, int id) throws IOException {
|
||||
Supplier<? extends Packet> factory = factories.get(id);
|
||||
if (factory == null) return null;
|
||||
|
||||
@@ -17,28 +17,27 @@ import dev.unlegitdqrk.unlegitlibrary.network.system.utils.TransportProtocol;
|
||||
import dev.unlegitdqrk.unlegitlibrary.network.system.utils.UdpCrypto;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import java.io.*;
|
||||
import java.net.SocketAddress;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.DataInputStream;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.Socket;
|
||||
import java.net.SocketAddress;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.DatagramChannel;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public class ConnectedClient {
|
||||
|
||||
private volatile UUID uniqueID;
|
||||
private Socket tcpSocket;
|
||||
|
||||
private DataInputStream inputStream;
|
||||
private DataOutputStream outputStream;
|
||||
|
||||
private DatagramChannel udpChannel;
|
||||
private final Thread tcpReceiveThread;
|
||||
private final NetworkServer server;
|
||||
|
||||
private volatile UUID uniqueID;
|
||||
private Socket tcpSocket;
|
||||
private DataInputStream inputStream;
|
||||
private DataOutputStream outputStream;
|
||||
private DatagramChannel udpChannel;
|
||||
private int udpPort = -1;
|
||||
private SecretKey udpKey;
|
||||
private final SecretKey udpKey;
|
||||
|
||||
public ConnectedClient(NetworkServer server, Socket tcpSocket, UUID uniqueID, int udpPort) throws IOException {
|
||||
this.tcpSocket = tcpSocket;
|
||||
@@ -125,9 +124,18 @@ public class ConnectedClient {
|
||||
public void disconnect() {
|
||||
tcpReceiveThread.interrupt();
|
||||
|
||||
try { if (tcpSocket != null) tcpSocket.close(); } catch (IOException ignored) {}
|
||||
try { if (inputStream != null) inputStream.close(); } catch (IOException ignored) {}
|
||||
try { if (outputStream != null) outputStream.close(); } catch (IOException ignored) {}
|
||||
try {
|
||||
if (tcpSocket != null) tcpSocket.close();
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
try {
|
||||
if (inputStream != null) inputStream.close();
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
try {
|
||||
if (outputStream != null) outputStream.close();
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
|
||||
tcpSocket = null;
|
||||
udpChannel = null;
|
||||
@@ -155,7 +163,8 @@ public class ConnectedClient {
|
||||
|
||||
public boolean isConnected() {
|
||||
if (!isTCPConnected()) return false;
|
||||
return isUDPEnabled() && isUDPConnected();
|
||||
if (isUDPEnabled()) return isUDPConnected();
|
||||
return true;
|
||||
}
|
||||
|
||||
public UUID getUniqueID() {
|
||||
|
||||
@@ -21,11 +21,17 @@ import dev.unlegitdqrk.unlegitlibrary.network.system.utils.SSLContexts;
|
||||
import dev.unlegitdqrk.unlegitlibrary.network.system.utils.TransportProtocol;
|
||||
import dev.unlegitdqrk.unlegitlibrary.network.system.utils.UdpCrypto;
|
||||
|
||||
import javax.net.ssl.*;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLServerSocket;
|
||||
import javax.net.ssl.SSLServerSocketFactory;
|
||||
import javax.net.ssl.SSLSocket;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.DataInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.*;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.net.SocketAddress;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.DatagramChannel;
|
||||
import java.security.KeyStore;
|
||||
@@ -37,17 +43,14 @@ import java.util.concurrent.atomic.AtomicReference;
|
||||
* TCP/UDP server with optional TLS and UDP encryption.
|
||||
*/
|
||||
public class NetworkServer {
|
||||
private ServerSocket tcpSocket;
|
||||
private Thread tcpThread;
|
||||
|
||||
private DatagramChannel udpChannel;
|
||||
private Thread udpThread;
|
||||
|
||||
private final Map<SocketAddress, UUID> clientUdpAddresses = new ConcurrentHashMap<>();
|
||||
private final PacketHandler packetHandler;
|
||||
private final EventManager eventManager;
|
||||
private final List<ConnectedClient> connectedClients;
|
||||
|
||||
private ServerSocket tcpSocket;
|
||||
private Thread tcpThread;
|
||||
private DatagramChannel udpChannel;
|
||||
private Thread udpThread;
|
||||
private int udpPort = -1;
|
||||
|
||||
/* === TLS CONFIG === */
|
||||
@@ -61,7 +64,7 @@ public class NetworkServer {
|
||||
* Creates a server with a custom {@link EventManager}.
|
||||
*
|
||||
* @param packetHandler packet handler
|
||||
* @param eventManager event manager
|
||||
* @param eventManager event manager
|
||||
*/
|
||||
private NetworkServer(PacketHandler packetHandler, EventManager eventManager) {
|
||||
this.packetHandler = packetHandler;
|
||||
@@ -72,7 +75,7 @@ public class NetworkServer {
|
||||
/**
|
||||
* Enables or disables TLS and sets the client authentication mode.
|
||||
*
|
||||
* @param sslEnabled enable TLS
|
||||
* @param sslEnabled enable TLS
|
||||
* @param clientAuthMode client authentication mode
|
||||
*/
|
||||
public void configureSSL(boolean sslEnabled, ClientAuthMode clientAuthMode) {
|
||||
@@ -83,11 +86,11 @@ public class NetworkServer {
|
||||
/**
|
||||
* Enables or disables TLS with explicit key and trust stores.
|
||||
*
|
||||
* @param sslEnabled enable TLS
|
||||
* @param sslEnabled enable TLS
|
||||
* @param clientAuthMode client authentication mode
|
||||
* @param keyStore server key store (required when TLS is enabled)
|
||||
* @param keyPassword key store password
|
||||
* @param trustStore trust store (required for client auth)
|
||||
* @param keyStore server key store (required when TLS is enabled)
|
||||
* @param keyPassword key store password
|
||||
* @param trustStore trust store (required for client auth)
|
||||
*/
|
||||
public void configureSSL(boolean sslEnabled,
|
||||
ClientAuthMode clientAuthMode,
|
||||
@@ -157,8 +160,14 @@ public class NetworkServer {
|
||||
if (tcpThread != null) tcpThread.interrupt();
|
||||
if (udpThread != null) udpThread.interrupt();
|
||||
|
||||
try { if (tcpSocket != null) tcpSocket.close(); } catch (IOException ignored) {}
|
||||
try { if (udpChannel != null) udpChannel.close(); } catch (IOException ignored) {}
|
||||
try {
|
||||
if (tcpSocket != null) tcpSocket.close();
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
try {
|
||||
if (udpChannel != null) udpChannel.close();
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
|
||||
List<ConnectedClient> snapshot;
|
||||
synchronized (connectedClients) {
|
||||
@@ -337,7 +346,8 @@ public class NetworkServer {
|
||||
eventManager.executeEvent(new S_PacketReadEvent(this, client, packet, TransportProtocol.UDP));
|
||||
return true;
|
||||
}
|
||||
} catch (Exception ignored) {}
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
|
||||
|
||||
eventManager.executeEvent(new S_PacketFailedReadEvent(this, client, packet, packetId, TransportProtocol.UDP));
|
||||
@@ -411,7 +421,7 @@ public class NetworkServer {
|
||||
/**
|
||||
* Sets the key store and its password.
|
||||
*
|
||||
* @param keyStore key store
|
||||
* @param keyStore key store
|
||||
* @param keyPassword key store password
|
||||
* @return builder
|
||||
*/
|
||||
|
||||
@@ -10,13 +10,14 @@ import java.security.cert.X509Certificate;
|
||||
*/
|
||||
public final class SSLContexts {
|
||||
|
||||
private SSLContexts() {}
|
||||
private SSLContexts() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an SSLContext.
|
||||
*
|
||||
* @param trustAll If true, disables certificate validation (SSL still active)
|
||||
* @param keyStore Optional keystore for client authentication
|
||||
* @param trustAll If true, disables certificate validation (SSL still active)
|
||||
* @param keyStore Optional keystore for client authentication
|
||||
* @param keyPassword Keystore password
|
||||
*/
|
||||
public static SSLContext create(boolean trustAll, KeyStore keyStore, char[] keyPassword) {
|
||||
@@ -45,9 +46,9 @@ public final class SSLContexts {
|
||||
/**
|
||||
* Creates an SSLContext using explicit key and trust stores.
|
||||
*
|
||||
* @param keyStore Optional keystore for client/server authentication
|
||||
* @param keyStore Optional keystore for client/server authentication
|
||||
* @param keyPassword Keystore password
|
||||
* @param trustStore Optional truststore for certificate validation (root CAs)
|
||||
* @param trustStore Optional truststore for certificate validation (root CAs)
|
||||
*/
|
||||
public static SSLContext create(KeyStore keyStore, char[] keyPassword, KeyStore trustStore) {
|
||||
try {
|
||||
@@ -79,8 +80,17 @@ public final class SSLContexts {
|
||||
* TrustManager that accepts all certificates.
|
||||
*/
|
||||
private static final class TrustAllX509 implements X509TrustManager {
|
||||
@Override public void checkClientTrusted(X509Certificate[] c, String a) {}
|
||||
@Override public void checkServerTrusted(X509Certificate[] c, String a) {}
|
||||
@Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
|
||||
@Override
|
||||
public void checkClientTrusted(X509Certificate[] c, String a) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkServerTrusted(X509Certificate[] c, String a) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public X509Certificate[] getAcceptedIssuers() {
|
||||
return new X509Certificate[0];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,8 @@ public final class UdpCrypto {
|
||||
private static final SecureRandom RNG = new SecureRandom();
|
||||
private static final int GCM_TAG_BITS = 128;
|
||||
|
||||
private UdpCrypto() {}
|
||||
private UdpCrypto() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a random AES-256 key for UDP.
|
||||
@@ -36,9 +37,9 @@ public final class UdpCrypto {
|
||||
/**
|
||||
* Encrypts a UDP payload with AES-GCM.
|
||||
*
|
||||
* @param key AES key
|
||||
* @param key AES key
|
||||
* @param plaintext payload
|
||||
* @param aad additional authenticated data (e.g., UUID + packetId)
|
||||
* @param aad additional authenticated data (e.g., UUID + packetId)
|
||||
* @return ByteBuffer ready to send
|
||||
*/
|
||||
public static ByteBuffer encrypt(SecretKey key, byte[] plaintext, byte[] aad) throws Exception {
|
||||
@@ -61,7 +62,7 @@ public final class UdpCrypto {
|
||||
* Decrypts a UDP payload with AES-GCM.
|
||||
*
|
||||
* @param key AES key
|
||||
* @param in ByteBuffer received
|
||||
* @param in ByteBuffer received
|
||||
* @param aad additional authenticated data (must match encryption)
|
||||
* @return plaintext
|
||||
*/
|
||||
|
||||
@@ -14,23 +14,29 @@ public class WebUtils extends DefaultMethodsOverrider {
|
||||
private static final String ACCEPTED_RESPONSE = "application/json";
|
||||
|
||||
public static String httpGet(String url) throws Exception {
|
||||
HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
|
||||
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
|
||||
connection.setRequestMethod("GET");
|
||||
connection.connect();
|
||||
|
||||
if (connection.getResponseCode() == 204) return null;
|
||||
|
||||
return InputStreamUtils.readInputStream(connection.getInputStream());
|
||||
try {
|
||||
if (connection.getResponseCode() == 204) return null;
|
||||
return InputStreamUtils.readInputStream(connection.getInputStream());
|
||||
} finally {
|
||||
connection.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] httpGetByte(String url) throws Exception {
|
||||
HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
|
||||
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
|
||||
connection.setRequestMethod("GET");
|
||||
connection.connect();
|
||||
|
||||
if (connection.getResponseCode() == 204) return null;
|
||||
|
||||
return InputStreamUtils.readInputStream2Byte(connection.getInputStream());
|
||||
try {
|
||||
if (connection.getResponseCode() == 204) return null;
|
||||
return InputStreamUtils.readInputStream2Byte(connection.getInputStream());
|
||||
} finally {
|
||||
connection.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
public static String toHttps(String url) {
|
||||
|
||||
@@ -9,9 +9,15 @@ import java.util.Random;
|
||||
public class MathHelper extends DefaultMethodsOverrider {
|
||||
|
||||
private static final float[] SIN_TABLE = new float[65536];
|
||||
private static final double TAU = 60.283185307179586D;
|
||||
private static final double TAU = 6.283185307179586D;
|
||||
private static final Random rng = new Random();
|
||||
|
||||
static {
|
||||
for (int i = 0; i < SIN_TABLE.length; i++) {
|
||||
SIN_TABLE[i] = (float) Math.sin(i * TAU / SIN_TABLE.length);
|
||||
}
|
||||
}
|
||||
|
||||
public static double round(double value, int places) {
|
||||
if (places < 0) throw new IllegalArgumentException();
|
||||
|
||||
@@ -129,11 +135,15 @@ public class MathHelper extends DefaultMethodsOverrider {
|
||||
}
|
||||
|
||||
public static double randomInRange(double min, double max) {
|
||||
return (double) rng.nextInt((int) (max - min + 1.0D)) + max;
|
||||
if (max < min) throw new IllegalArgumentException("max must be >= min");
|
||||
if (max == min) return min;
|
||||
return min + rng.nextDouble() * (max - min);
|
||||
}
|
||||
|
||||
public static double getRandomFloat(float min, float max) {
|
||||
return (float) rng.nextInt((int) (max - min + 1.0F)) + max;
|
||||
if (max < min) throw new IllegalArgumentException("max must be >= min");
|
||||
if (max == min) return min;
|
||||
return min + rng.nextFloat() * (max - min);
|
||||
}
|
||||
|
||||
public static double randomNumber(double max, double min) {
|
||||
@@ -141,10 +151,10 @@ public class MathHelper extends DefaultMethodsOverrider {
|
||||
}
|
||||
|
||||
public static double wrapRadians(double angle) {
|
||||
angle %= 20.283185307179586D;
|
||||
angle %= TAU;
|
||||
|
||||
if (angle >= 1.141592653589793D) angle -= 20.283185307179586D;
|
||||
if (angle < -1.141592653589793D) angle += 20.283185307179586D;
|
||||
if (angle >= Math.PI) angle -= TAU;
|
||||
if (angle < -Math.PI) angle += TAU;
|
||||
|
||||
return angle;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user