commit 96d3490d4a391789239414316822937baa428056 Author: Weapie Date: Tue Jul 2 15:12:06 2024 +0200 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bc375f4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,43 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr +.idea +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..04365aa --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,33 @@ +plugins { + id("java-library") +} + +allprojects { + apply(plugin = "java-library") + + group = "de.weapie" + version = "2024.07.02-01" + + repositories { + mavenCentral() + } + + dependencies { + implementation(rootProject.libs.lombok) + annotationProcessor(rootProject.libs.lombok) + + implementation(rootProject.libs.annotations) + annotationProcessor(rootProject.libs.annotations) + + testAnnotationProcessor(rootProject.libs.lombok) + testImplementation(rootProject.libs.lombok) + } + + tasks.withType { + sourceCompatibility = JavaVersion.VERSION_17.toString() + targetCompatibility = JavaVersion.VERSION_17.toString() + // options + options.encoding = "UTF-8" + options.isIncremental = true + } +} \ No newline at end of file diff --git a/devlok-files/build.gradle.kts b/devlok-files/build.gradle.kts new file mode 100644 index 0000000..ffcf38b --- /dev/null +++ b/devlok-files/build.gradle.kts @@ -0,0 +1,16 @@ +dependencies { + compileOnly(libs.gson) + api(project(":devlok-utils")) + + testImplementation(libs.gson) + testImplementation(platform("org.junit:junit-bom:5.10.2")) + testImplementation("org.junit.jupiter:junit-jupiter") + testRuntimeOnly("org.junit.platform:junit-platform-launcher") +} + +tasks.test { + useJUnitPlatform() + testLogging { + events("passed", "skipped", "failed") + } +} diff --git a/devlok-files/config/config.json b/devlok-files/config/config.json new file mode 100644 index 0000000..d355928 --- /dev/null +++ b/devlok-files/config/config.json @@ -0,0 +1,4 @@ +{ + "name": "test", + "stable": false +} \ No newline at end of file diff --git a/devlok-files/src/main/java/de/weapie/devlok/files/Files.java b/devlok-files/src/main/java/de/weapie/devlok/files/Files.java new file mode 100644 index 0000000..933606d --- /dev/null +++ b/devlok-files/src/main/java/de/weapie/devlok/files/Files.java @@ -0,0 +1,48 @@ +package de.weapie.devlok.files; + +import lombok.SneakyThrows; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Path; + +public class Files { + + public static void copyInputStreamToFile(InputStream inputStream, File file) throws IOException { + try (var outputStream = new FileOutputStream(file, false)) { + int read; + var bytes = new byte[8192]; + while ((read = inputStream.read(bytes)) != -1) { + outputStream.write(bytes, 0, read); + } + } + } + + @SneakyThrows + public static void createDirectoryIfNotExists(Path path) { + if(!java.nio.file.Files.exists(path)) { + java.nio.file.Files.createDirectory(path); + } + } + + @SneakyThrows + public static void writeString(Path path, String content) { + java.nio.file.Files.writeString(path, content); + } + + public static void writeString(String path, String content) { + writeString(Path.of(path), content); + } + + @SneakyThrows + public static String readString(Path path) { + return java.nio.file.Files.readString(path); + } + + public static String readString(String path) { + return readString(Path.of(path)); + } + +} diff --git a/devlok-files/src/main/java/de/weapie/devlok/files/config/DevlokConfig.java b/devlok-files/src/main/java/de/weapie/devlok/files/config/DevlokConfig.java new file mode 100644 index 0000000..d988df9 --- /dev/null +++ b/devlok-files/src/main/java/de/weapie/devlok/files/config/DevlokConfig.java @@ -0,0 +1,113 @@ +package de.weapie.devlok.files.config; + +import de.weapie.devlok.files.config.annotations.Config; +import de.weapie.devlok.utils.validate.Check; +import lombok.*; +import lombok.experimental.Accessors; +import org.jetbrains.annotations.ApiStatus; + +import java.io.File; +import java.io.FileReader; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.function.Supplier; + +@Getter +@Accessors(fluent = true) +@RequiredArgsConstructor(access = AccessLevel.PACKAGE) +public final class DevlokConfig { + + private final Class type; + private final String name; + private final Supplier defaultValue; + private T value; + private final Path path; + + public static Builder builder(@NonNull Class type) { + return new Builder<>(type); + } + + public T value(T value) { + this.value = value; + return this.value; + } + + public T value() { + T t = this.value; + + if (t == null) { + return defaultValue.get(); + } + + return t; + } + + public File file() { + return new File(this.path.toFile(), this.name + ".json"); + } + + public boolean exists() { + return Files.exists(this.file().toPath()); + } + + @SneakyThrows + public void write(boolean pretty, boolean override) { + if(!this.path.toFile().exists()) { + Files.createDirectories(this.path); + } + + if(!override && Files.exists(this.file().toPath())) { + return; + } + + if(pretty) { + JsonUtils.writePrettyJson(this.value(), this.file()); + return; + } + + JsonUtils.writeJson(this.value(), this.file()); + } + + public void write(boolean pretty) { + this.write(pretty, false); + } + + public void write() { + this.write(true, false); + } + + @SneakyThrows + public T read() { + this.value(JsonUtils.fromJson(this.file(), type)); + return this.value(); + } + + @ApiStatus.Internal + @RequiredArgsConstructor(access = AccessLevel.PACKAGE) + public static class Builder { + + private final Class type; + private Supplier defaultValue; + private Path path; + + public Builder withPath(String path) { + this.path = Path.of(path); + return this; + } + + public Builder withDefault(Supplier value) { + this.defaultValue = value; + return this; + } + + public DevlokConfig build() { + Check.notNull(this.type, "type cannot be null"); + Check.notNull(this.type.isAnnotationPresent(Config.class), "not config annotation assigned"); + Check.notNull(this.type.getDeclaredAnnotation(Config.class).id(), "id cannot be null"); + Check.notNull(this.path, "path cannot be null"); + + return new DevlokConfig<>(this.type, this.type.getDeclaredAnnotation(Config.class).id(), this.defaultValue, this.path); + } + } + +} diff --git a/devlok-files/src/main/java/de/weapie/devlok/files/config/JsonExclusionStrategy.java b/devlok-files/src/main/java/de/weapie/devlok/files/config/JsonExclusionStrategy.java new file mode 100644 index 0000000..1b189db --- /dev/null +++ b/devlok-files/src/main/java/de/weapie/devlok/files/config/JsonExclusionStrategy.java @@ -0,0 +1,19 @@ +package de.weapie.devlok.files.config; + +import com.google.gson.ExclusionStrategy; +import com.google.gson.FieldAttributes; +import de.weapie.devlok.files.config.annotations.ConfigExclude; + +public final class JsonExclusionStrategy implements ExclusionStrategy { + + @Override + public boolean shouldSkipField(FieldAttributes f) { + return f.getAnnotation(ConfigExclude.class) != null; + } + + @Override + public boolean shouldSkipClass(Class clazz) { + return clazz.isAnnotationPresent(ConfigExclude.class); + } + +} \ No newline at end of file diff --git a/devlok-files/src/main/java/de/weapie/devlok/files/config/JsonUtils.java b/devlok-files/src/main/java/de/weapie/devlok/files/config/JsonUtils.java new file mode 100644 index 0000000..27b854d --- /dev/null +++ b/devlok-files/src/main/java/de/weapie/devlok/files/config/JsonUtils.java @@ -0,0 +1,76 @@ +package de.weapie.devlok.files.config; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; + +public class JsonUtils { + + private static final Gson JSON = new GsonBuilder() + .setExclusionStrategies(new JsonExclusionStrategy()) + .create(); + private static final Gson PRETTY_JSON = new GsonBuilder() + .setPrettyPrinting() + .setExclusionStrategies(new JsonExclusionStrategy()) + .create(); + + public static Gson getGson() { + return JSON; + } + + public static Gson getPrettyGson() { + return PRETTY_JSON; + } + + public static String toJson(Object object) { + return JSON.toJson(object); + } + + public static String toPrettyJson(Object object) { + return PRETTY_JSON.toJson(object); + } + + public static void writeJson(Object object, File file) { + try(FileWriter fileWriter = new FileWriter(file)) { + String prettyJsonString = JSON.toJson(object); + fileWriter.write(prettyJsonString); + fileWriter.close(); + } catch (IOException ex) { + System.out.println("Exception thrown while writing the file " + file.getPath()); + ex.printStackTrace(); + } + } + + public static void writePrettyJson(Object object, File file) { + try(FileWriter fileWriter = new FileWriter(file)) { + String prettyJsonString = PRETTY_JSON.toJson(object); + fileWriter.write(prettyJsonString); + fileWriter.close(); + } catch (IOException ex) { + System.out.println("Exception thrown while writing the file " + file.getPath()); + ex.printStackTrace(); + } + } + + public static T fromJson(String string, Class tClass) { + return JSON.fromJson(string, tClass); + } + + public static T fromJson(File file, Class tClass) { + try { + FileReader fileReader = new FileReader(file); + T config = JSON.fromJson(fileReader, tClass); + fileReader.close(); + return config; + } catch (IOException ex) { + System.out.println("Exception thrown while reading the file " + file.getPath()); + ex.printStackTrace(); + return null; + } + } + +} diff --git a/devlok-files/src/main/java/de/weapie/devlok/files/config/annotations/Config.java b/devlok-files/src/main/java/de/weapie/devlok/files/config/annotations/Config.java new file mode 100644 index 0000000..b369642 --- /dev/null +++ b/devlok-files/src/main/java/de/weapie/devlok/files/config/annotations/Config.java @@ -0,0 +1,14 @@ +package de.weapie.devlok.files.config.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE}) +public @interface Config { + + String id(); + +} \ No newline at end of file diff --git a/devlok-files/src/main/java/de/weapie/devlok/files/config/annotations/ConfigExclude.java b/devlok-files/src/main/java/de/weapie/devlok/files/config/annotations/ConfigExclude.java new file mode 100644 index 0000000..8fda28a --- /dev/null +++ b/devlok-files/src/main/java/de/weapie/devlok/files/config/annotations/ConfigExclude.java @@ -0,0 +1,8 @@ +package de.weapie.devlok.files.config.annotations; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +@Retention(RetentionPolicy.RUNTIME) +public @interface ConfigExclude { +} diff --git a/devlok-files/src/main/java/de/weapie/devlok/files/haste/HasteAPI.java b/devlok-files/src/main/java/de/weapie/devlok/files/haste/HasteAPI.java new file mode 100644 index 0000000..2a279c9 --- /dev/null +++ b/devlok-files/src/main/java/de/weapie/devlok/files/haste/HasteAPI.java @@ -0,0 +1,63 @@ +package de.weapie.devlok.files.haste; + +import com.google.gson.JsonObject; +import de.weapie.devlok.files.config.JsonUtils; +import lombok.SneakyThrows; + +import javax.net.ssl.HttpsURLConnection; +import java.io.*; +import java.net.URI; +import java.nio.charset.StandardCharsets; + +public class HasteAPI { + + private static String HASTE_URL = "https://haste.weapie.de"; + private static String POST_HASTE_URL = HASTE_URL + "/documents"; + + public static void setHasteUrl(String hasteUrl) { + HASTE_URL = hasteUrl; + POST_HASTE_URL = HASTE_URL + "/documents"; + } + + public static String createHaste(String content) { + return postHaste(content.getBytes(StandardCharsets.UTF_8)); + } + + @SneakyThrows + public static String createHaste(InputStream in) { + return postHaste(in.readAllBytes()); + } + + public static String getHasteKeyFromUrl(String url) { + return url.substring(url.lastIndexOf("/") + 1); + } + + @SneakyThrows + private static String postHaste(byte[] postData) { + try { + var connection = (HttpsURLConnection) URI.create(POST_HASTE_URL).toURL().openConnection(); + connection.setDoOutput(true); + connection.setInstanceFollowRedirects(false); + connection.setRequestMethod("POST"); + connection.setUseCaches(false); + + try (var out = new DataOutputStream(connection.getOutputStream())) { + out.write(postData); + } + + try (var in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { + var response = in.readLine(); + if (response == null) { + return HASTE_URL; + } + var jsonObject = JsonUtils.fromJson(response, JsonObject.class); + if (!jsonObject.has("key")) { + return HASTE_URL; + } + return HASTE_URL + "/" + jsonObject.get("key").getAsString(); + } + } catch (IOException e) { + return HASTE_URL; + } + } +} diff --git a/devlok-files/src/test/java/de/weapie/devlok/files/test/Config.java b/devlok-files/src/test/java/de/weapie/devlok/files/test/Config.java new file mode 100644 index 0000000..d199bd6 --- /dev/null +++ b/devlok-files/src/test/java/de/weapie/devlok/files/test/Config.java @@ -0,0 +1,20 @@ +package de.weapie.devlok.files.test; + +import de.weapie.devlok.files.config.annotations.ConfigExclude; +import lombok.*; + +@de.weapie.devlok.files.config.annotations.Config(id = "config") +@AllArgsConstructor +@ToString +@Getter +@Setter +public class Config { + + private String name; + private boolean stable; + private int number; + + @ConfigExclude + private String notRelevant = "Test 123"; + +} diff --git a/devlok-files/src/test/java/de/weapie/devlok/files/test/TestFiles.java b/devlok-files/src/test/java/de/weapie/devlok/files/test/TestFiles.java new file mode 100644 index 0000000..a42692b --- /dev/null +++ b/devlok-files/src/test/java/de/weapie/devlok/files/test/TestFiles.java @@ -0,0 +1,21 @@ +package de.weapie.devlok.files.test; + +import de.weapie.devlok.files.config.DevlokConfig; +import lombok.SneakyThrows; +import org.junit.jupiter.api.Test; + +public class TestFiles { + + private DevlokConfig config = DevlokConfig.builder(Config.class) + .withDefault(() -> new Config("test", false, 1, "test 123")) + .withPath("./config/") + .build(); + + @Test + @SneakyThrows + public void handle() { + config.write(); + config.read(); + } + +} diff --git a/devlok-netty/build.gradle.kts b/devlok-netty/build.gradle.kts new file mode 100644 index 0000000..8c7e4d6 --- /dev/null +++ b/devlok-netty/build.gradle.kts @@ -0,0 +1,19 @@ +dependencies { + implementation(libs.netty5) + compileOnly(libs.gson) + api(project(":devlok-utils")) + api(project(":devlok-files")) + api(project(":devlok-reflections")) + + testImplementation(libs.gson) + testImplementation(platform("org.junit:junit-bom:5.10.2")) + testImplementation("org.junit.jupiter:junit-jupiter") + testRuntimeOnly("org.junit.platform:junit-platform-launcher") +} + +tasks.test { + useJUnitPlatform() + testLogging { + events("passed", "skipped", "failed") + } +} diff --git a/devlok-netty/src/main/java/de/weapie/devlok/networking/CommunicationComponent.java b/devlok-netty/src/main/java/de/weapie/devlok/networking/CommunicationComponent.java new file mode 100644 index 0000000..eeded42 --- /dev/null +++ b/devlok-netty/src/main/java/de/weapie/devlok/networking/CommunicationComponent.java @@ -0,0 +1,56 @@ +package de.weapie.devlok.networking; + +import de.weapie.devlok.utils.executers.FutureResult; +import io.netty5.channel.Channel; +import io.netty5.channel.EventLoopGroup; +import io.netty5.util.concurrent.FutureListener; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.Setter; +import lombok.experimental.Accessors; + +@Accessors(fluent = true) +public abstract class CommunicationComponent extends CommunicationListener { + + @Getter(AccessLevel.PROTECTED) + @Setter(AccessLevel.PROTECTED) + private FutureResult connectionFuture = new FutureResult<>(); + @Getter(AccessLevel.PROTECTED) + private final EventLoopGroup bossGroup; + @Getter(AccessLevel.PROTECTED) + private final String hostname; + @Getter(AccessLevel.PROTECTED) + private final int port; + + public CommunicationComponent(int bossGroupThreads, String hostname, int port) { + this.bossGroup = CommunicationNetworkUtils.createEventLoopGroup(bossGroupThreads); + this.hostname = hostname; + this.port = port; + } + + public abstract void initialize(); + + public FutureListener handleConnectionRelease() { + return it -> { + if (it.isSuccess()) { + connectionFuture.complete(null); + it.getNow().closeFuture(); + } else { + connectionFuture.completeExceptionally(it.cause()); + } + }; + } + + public boolean isConnected() { + return connectionFuture.isDone(); + } + + public boolean isAlive() { + return !bossGroup.isShutdown() && !bossGroup.isTerminated() && !bossGroup.isShuttingDown(); + } + + public void close() { + bossGroup.shutdownGracefully(); + } + +} \ No newline at end of file diff --git a/devlok-netty/src/main/java/de/weapie/devlok/networking/CommunicationListener.java b/devlok-netty/src/main/java/de/weapie/devlok/networking/CommunicationListener.java new file mode 100644 index 0000000..4f318c7 --- /dev/null +++ b/devlok-netty/src/main/java/de/weapie/devlok/networking/CommunicationListener.java @@ -0,0 +1,95 @@ +package de.weapie.devlok.networking; + +import de.weapie.devlok.networking.channel.ChannelTransmit; +import de.weapie.devlok.networking.packet.BadRequestPacket; +import de.weapie.devlok.networking.packet.Packet; +import de.weapie.devlok.networking.packet.RequestPacket; +import de.weapie.devlok.networking.packet.RequestResponsePacket; +import lombok.Getter; +import lombok.experimental.Accessors; +import org.jetbrains.annotations.NotNull; + +import java.util.*; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Function; + +@Getter +@Accessors(fluent = true) +public abstract class CommunicationListener { + + private final Map, List>> listeners = new HashMap<>(); + private final Map> responders = new HashMap<>(); + private final Map> requests = new HashMap<>(); + + @SuppressWarnings("unchecked") + public

void listen(Class

listeningClass, BiConsumer packetCallback) { + var packetListeners = listeners.getOrDefault(listeningClass, new ArrayList<>()); + packetListeners.add((BiConsumer) packetCallback); + listeners.put(listeningClass, packetListeners); + } + + public

void listen(Class

listeningClass, Consumer

packetCallback) { + this.listen(listeningClass, (channelTransmit, packet) -> packetCallback.accept(packet)); + } + + @SuppressWarnings("unchecked") + public

void request(String id, CommunicationProperty property, Class

packet, Consumer

packetCallback) { + var uuid = UUID.randomUUID(); + this.requests.put(uuid, (Consumer) packetCallback); + sendPacket(new RequestPacket(id, uuid, property)); + } + + public

void request(String id, Class

packet, Consumer

packetCallback) { + request(id, new CommunicationProperty(), packet, packetCallback); + } + + + public void callResponder(ChannelTransmit channelTransmit, @NotNull RequestPacket requestPacket) { + if (!responders.containsKey(requestPacket.id())) { + channelTransmit.sendPacket(new BadRequestPacket(requestPacket.uuid())); + System.out.println("Found no responder for: " + requestPacket.id()); + return; + } + + var response = responders.get(requestPacket.id()).apply(requestPacket.property()); + channelTransmit.sendPacket(new RequestResponsePacket(requestPacket.uuid(), response)); + } + + public void responder(String id, Function packetFunction) { + this.responders.put(id, packetFunction); + } + + public

boolean call(@NotNull P packet, ChannelTransmit channelTransmit) { + if (packet instanceof RequestPacket requestPacket) { + this.callResponder(channelTransmit, requestPacket); + return true; + } + + if (packet instanceof RequestResponsePacket requestResponsePacket) { + if (!this.requests.containsKey(requestResponsePacket.uuid())) { + return true; + } + this.requests.get(requestResponsePacket.uuid()).accept(requestResponsePacket.response()); + this.requests.remove(requestResponsePacket.uuid()); + return true; + } + + if (packet instanceof BadRequestPacket badRequestPacket) { + this.requests.remove(badRequestPacket.uuid()); + System.out.println("Invalid request from: " + badRequestPacket.uuid()); + return true; + } + + if (!this.listeners.containsKey(packet.getClass())) { + return false; + } + + for (var consumer : this.listeners.get(packet.getClass())) { + consumer.accept(channelTransmit, packet); + } + return true; + } + + public abstract void sendPacket(Packet packet); +} diff --git a/devlok-netty/src/main/java/de/weapie/devlok/networking/CommunicationNetworkUtils.java b/devlok-netty/src/main/java/de/weapie/devlok/networking/CommunicationNetworkUtils.java new file mode 100644 index 0000000..d42d54b --- /dev/null +++ b/devlok-netty/src/main/java/de/weapie/devlok/networking/CommunicationNetworkUtils.java @@ -0,0 +1,35 @@ +package de.weapie.devlok.networking; + +import io.netty5.channel.EventLoop; +import io.netty5.channel.MultithreadEventLoopGroup; +import io.netty5.channel.ServerChannel; +import io.netty5.channel.ServerChannelFactory; +import io.netty5.channel.epoll.Epoll; +import io.netty5.channel.epoll.EpollHandler; +import io.netty5.channel.epoll.EpollServerSocketChannel; +import io.netty5.channel.epoll.EpollSocketChannel; +import io.netty5.channel.nio.NioHandler; +import io.netty5.channel.socket.SocketChannel; +import io.netty5.channel.socket.nio.NioServerSocketChannel; +import io.netty5.channel.socket.nio.NioSocketChannel; +import lombok.experimental.UtilityClass; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; + +@UtilityClass +public class CommunicationNetworkUtils { + + @Contract("_ -> new") + public static @NotNull MultithreadEventLoopGroup createEventLoopGroup(int threads) { + return new MultithreadEventLoopGroup(threads, Epoll.isAvailable() ? EpollHandler.newFactory() : NioHandler.newFactory()); + } + + public static @NotNull SocketChannel createChannelFactory(EventLoop loop) { + return Epoll.isAvailable() ? new EpollSocketChannel(loop) : new NioSocketChannel(loop); + } + + public static ServerChannelFactory generateChannelFactory() { + return Epoll.isAvailable() ? EpollServerSocketChannel::new : NioServerSocketChannel::new; + } + +} diff --git a/devlok-netty/src/main/java/de/weapie/devlok/networking/CommunicationProperty.java b/devlok-netty/src/main/java/de/weapie/devlok/networking/CommunicationProperty.java new file mode 100644 index 0000000..7a888fc --- /dev/null +++ b/devlok-netty/src/main/java/de/weapie/devlok/networking/CommunicationProperty.java @@ -0,0 +1,160 @@ +package de.weapie.devlok.networking; + +import de.weapie.devlok.networking.packet.PacketBuffer; +import lombok.SneakyThrows; +import org.jetbrains.annotations.NotNull; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public class CommunicationProperty { + + private final Map properties = new HashMap<>(); + + + public boolean has(String key) { + return this.properties.containsKey(key); + } + + public CommunicationProperty set(String key, int value) { + this.properties.put(key, value); + return this; + } + + public CommunicationProperty set(String key, String value) { + this.properties.put(key, value); + return this; + } + + public CommunicationProperty set(String key, boolean value) { + this.properties.put(key, value); + return this; + } + + public CommunicationProperty set(String key, long value) { + this.properties.put(key, value); + return this; + } + + public CommunicationProperty set(String key, float value) { + this.properties.put(key, value); + return this; + } + + public CommunicationProperty set(String key, short value) { + this.properties.put(key, value); + return this; + } + + public CommunicationProperty set(String key, UUID value) { + this.properties.put(key, value); + return this; + } + + public CommunicationProperty set(String key, Enum value) { + this.properties.put(key, value); + return this; + } + + public String getString(String key) { + return (String) this.properties.get(key); + } + + public Boolean getBoolean(String key) { + return (Boolean) this.properties.get(key); + } + + public Integer getInteger(String key) { + return (Integer) this.properties.get(key); + } + + public Float getFloat(String key) { + return (Float) this.properties.get(key); + } + + public Float getLong(String key) { + return (Float) this.properties.get(key); + } + + public Short getShort(String key) { + return (Short) this.properties.get(key); + } + + public UUID getUUID(String key) { + return (UUID) this.properties.get(key); + } + + public > T getEnum(String key, Class enumClass) { + return (T) this.properties.get(key); + } + + + public void write(@NotNull PacketBuffer buffer) { + buffer.writeInt(properties.size()); + properties.forEach((s, o) -> { + buffer.writeString(s); + if (o instanceof Integer intValue) { + buffer.writeEnum(PropertyTypes.INTEGER); + buffer.writeInt(intValue); + } else if (o instanceof String stringValue) { + buffer.writeEnum(PropertyTypes.STRING); + buffer.writeString(stringValue); + } else if (o instanceof Float floatValue) { + buffer.writeEnum(PropertyTypes.FLOAT); + buffer.writeFloat(floatValue); + } else if (o instanceof Short shortValue) { + buffer.writeEnum(PropertyTypes.SHORT); + buffer.writeShort(shortValue); + } else if (o instanceof Enum enumValue) { + buffer.writeEnum(PropertyTypes.ENUM); + buffer.writeString(enumValue.getClass().getName()); + buffer.writeEnum(enumValue); + } else if (o instanceof UUID uuidValue) { + buffer.writeEnum(PropertyTypes.UUID); + buffer.writeUniqueId(uuidValue); + } else if (o instanceof Boolean booleanValue) { + buffer.writeEnum(PropertyTypes.BOOLEAN); + buffer.writeBoolean(booleanValue); + } else if (o instanceof Long longValue) { + buffer.writeEnum(PropertyTypes.LONG); + buffer.writeLong(longValue); + } else { + System.err.println("Unknown property: " + o.getClass().getSimpleName() + ":" + s); + } + }); + } + + @SneakyThrows + @SuppressWarnings("unchecked") + public void read(@NotNull PacketBuffer buffer) { + int size = buffer.readInt(); + + for (int i = 0; i < size; i++) { + var id = buffer.readString(); + var type = buffer.readEnum(PropertyTypes.class); + + properties.put(id, switch (type) { + case ENUM -> buffer.readEnum(((Class>) Class.forName(buffer.readString()))); + case LONG -> buffer.readLong(); + case STRING -> buffer.readString(); + case SHORT -> buffer.readShort(); + case BOOLEAN -> buffer.readBoolean(); + case FLOAT -> buffer.readFloat(); + case UUID -> buffer.readUniqueId(); + case INTEGER -> buffer.readInt(); + }); + } + } + + private enum PropertyTypes { + INTEGER, + STRING, + LONG, + FLOAT, + SHORT, + ENUM, + UUID, + BOOLEAN + } +} diff --git a/devlok-netty/src/main/java/de/weapie/devlok/networking/CommunicationTransmitHandler.java b/devlok-netty/src/main/java/de/weapie/devlok/networking/CommunicationTransmitHandler.java new file mode 100644 index 0000000..56f2d50 --- /dev/null +++ b/devlok-netty/src/main/java/de/weapie/devlok/networking/CommunicationTransmitHandler.java @@ -0,0 +1,42 @@ +package de.weapie.devlok.networking; + +import de.weapie.devlok.networking.channel.ChannelTransmit; +import de.weapie.devlok.networking.packet.Packet; +import io.netty5.channel.Channel; +import io.netty5.channel.ChannelHandlerContext; +import io.netty5.channel.SimpleChannelInboundHandler; +import lombok.AllArgsConstructor; +import org.jetbrains.annotations.NotNull; + +import java.util.List; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Function; + +@AllArgsConstructor +public final class CommunicationTransmitHandler extends SimpleChannelInboundHandler { + + private final Function> findTransmitFunction; + private final BiConsumer channelTransmitPacketConsumer; + private final Consumer channelTransmitConsumer; + + @Override + protected void messageReceived(ChannelHandlerContext channelHandlerContext, Packet packet) { + channelTransmitPacketConsumer.accept(packet, findTransmitFunction.apply(channelHandlerContext.channel()).stream().filter(it -> it.channel().equals(channelHandlerContext.channel())).findFirst().orElseThrow()); + } + + @Override + public void channelActive(@NotNull ChannelHandlerContext ctx) { + this.channelTransmitConsumer.accept(new ChannelTransmit(ctx.channel().id().asLongText(), ctx.channel())); + } + + @Override + public void channelInactive(ChannelHandlerContext ctx) { + + } + + @Override + public void channelExceptionCaught(ChannelHandlerContext ctx, @NotNull Throwable cause) { + if (!cause.getMessage().equals("Connection reset")) cause.printStackTrace(); + } +} diff --git a/devlok-netty/src/main/java/de/weapie/devlok/networking/channel/ChannelInitializer.java b/devlok-netty/src/main/java/de/weapie/devlok/networking/channel/ChannelInitializer.java new file mode 100644 index 0000000..9e5d310 --- /dev/null +++ b/devlok-netty/src/main/java/de/weapie/devlok/networking/channel/ChannelInitializer.java @@ -0,0 +1,29 @@ +package de.weapie.devlok.networking.channel; + +import de.weapie.devlok.networking.codec.PacketDecoder; +import de.weapie.devlok.networking.codec.PacketEncoder; +import de.weapie.devlok.networking.CommunicationTransmitHandler; +import io.netty5.channel.Channel; +import io.netty5.handler.codec.LengthFieldBasedFrameDecoder; +import io.netty5.handler.codec.LengthFieldPrepender; +import lombok.AllArgsConstructor; +import lombok.Setter; +import lombok.experimental.Accessors; +import org.jetbrains.annotations.NotNull; + +@Setter +@Accessors(fluent = true) +@AllArgsConstructor +public final class ChannelInitializer extends io.netty5.channel.ChannelInitializer { + + private final CommunicationTransmitHandler transmitHandler; + + @Override + protected void initChannel(@NotNull Channel channel) { + channel.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, Integer.BYTES, 0, Integer.BYTES)) + .addLast(new PacketDecoder()) + .addLast(new LengthFieldPrepender(Integer.BYTES)) + .addLast(new PacketEncoder()) + .addLast(transmitHandler); + } +} diff --git a/devlok-netty/src/main/java/de/weapie/devlok/networking/channel/ChannelTransmit.java b/devlok-netty/src/main/java/de/weapie/devlok/networking/channel/ChannelTransmit.java new file mode 100644 index 0000000..6c9da44 --- /dev/null +++ b/devlok-netty/src/main/java/de/weapie/devlok/networking/channel/ChannelTransmit.java @@ -0,0 +1,22 @@ +package de.weapie.devlok.networking.channel; + +import de.weapie.devlok.networking.CommunicationListener; +import de.weapie.devlok.networking.packet.Packet; +import io.netty5.channel.Channel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.experimental.Accessors; + +@Getter +@AllArgsConstructor +@Accessors(fluent = true) +public class ChannelTransmit extends CommunicationListener { + + private final String id; + private final Channel channel; + + @Override + public void sendPacket(Packet packet) { + this.channel.writeAndFlush(packet); + } +} diff --git a/devlok-netty/src/main/java/de/weapie/devlok/networking/client/CommunicationClient.java b/devlok-netty/src/main/java/de/weapie/devlok/networking/client/CommunicationClient.java new file mode 100644 index 0000000..673fbc5 --- /dev/null +++ b/devlok-netty/src/main/java/de/weapie/devlok/networking/client/CommunicationClient.java @@ -0,0 +1,60 @@ +package de.weapie.devlok.networking.client; + +import de.weapie.devlok.networking.channel.ChannelInitializer; +import de.weapie.devlok.networking.channel.ChannelTransmit; +import de.weapie.devlok.networking.packet.Packet; +import de.weapie.devlok.networking.CommunicationComponent; +import de.weapie.devlok.networking.CommunicationNetworkUtils; +import de.weapie.devlok.networking.CommunicationTransmitHandler; +import io.netty5.bootstrap.Bootstrap; +import io.netty5.channel.ChannelOption; +import io.netty5.channel.epoll.Epoll; + +import java.util.List; +import java.util.function.Consumer; + +public final class CommunicationClient extends CommunicationComponent { + + private final Bootstrap bootstrap; + private CommunicationClientTransmit channelTransmit; + + public CommunicationClient(String hostname, int port, Consumer clientConnected) { + super(0, hostname, port); + + // default listener transmit + this.channelTransmit = CommunicationClientTransmit.empty(this); + + this.bootstrap = new Bootstrap() + .group(bossGroup()) + .channelFactory(CommunicationNetworkUtils::createChannelFactory) + .handler(new ChannelInitializer(new CommunicationTransmitHandler(it -> List.of(channelTransmit), (it, channel) -> this.channelTransmit.call(it, channel), it -> { + this.channelTransmit = CommunicationClientTransmit.of(this, it); + clientConnected.accept(this.channelTransmit); + }))) + .option(ChannelOption.AUTO_READ, true) + .option(ChannelOption.TCP_NODELAY, true) + .option(ChannelOption.IP_TOS, 24) + .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000); + + if (Epoll.isTcpFastOpenClientSideAvailable()) { + bootstrap.option(ChannelOption.TCP_FASTOPEN_CONNECT, true); + } + } + + @Override + public void initialize() { + this.bootstrap.connect(hostname(), port()).addListener(future -> { + if (future.isSuccess()) { + this.connectionFuture().complete(null); + return; + } + this.connectionFuture().completeExceptionally(future.cause()); + this.connectionFuture(null); + }); + } + + @Override + public void sendPacket(Packet packet) { + this.channelTransmit.sendPacket(packet); + } +} \ No newline at end of file diff --git a/devlok-netty/src/main/java/de/weapie/devlok/networking/client/CommunicationClientTransmit.java b/devlok-netty/src/main/java/de/weapie/devlok/networking/client/CommunicationClientTransmit.java new file mode 100644 index 0000000..7b0d4eb --- /dev/null +++ b/devlok-netty/src/main/java/de/weapie/devlok/networking/client/CommunicationClientTransmit.java @@ -0,0 +1,41 @@ +package de.weapie.devlok.networking.client; + +import de.weapie.devlok.networking.channel.ChannelTransmit; +import de.weapie.devlok.networking.packet.Packet; +import de.weapie.devlok.networking.CommunicationComponent; +import io.netty5.channel.Channel; +import org.jetbrains.annotations.NotNull; + +import java.util.function.Consumer; + +public final class CommunicationClientTransmit extends ChannelTransmit { + + private final CommunicationComponent communicationComponent; + + public CommunicationClientTransmit(CommunicationComponent communicationComponent, String id, Channel channel) { + super(id, channel); + this.communicationComponent = communicationComponent; + } + + @Override + public

boolean call(@NotNull P packet, ChannelTransmit transmit) { + return this.communicationComponent.call(packet, transmit); + } + + @Override + public

void listen(Class

listeningClass, Consumer

packetCallback) { + communicationComponent.listen(listeningClass, packetCallback); + } + + public static CommunicationClientTransmit empty(CommunicationComponent communicationComponent) { + return new CommunicationClientTransmit(communicationComponent, null, null); + } + + public static CommunicationClientTransmit of(CommunicationComponent communicationComponent, ChannelTransmit transmit) { + var clientTransmit = new CommunicationClientTransmit(communicationComponent, transmit.id(), transmit.channel()); + clientTransmit.listeners().putAll(transmit.listeners()); + clientTransmit.requests().putAll(transmit.requests()); + clientTransmit.responders().putAll(transmit.responders()); + return clientTransmit; + } +} diff --git a/devlok-netty/src/main/java/de/weapie/devlok/networking/codec/PacketDecoder.java b/devlok-netty/src/main/java/de/weapie/devlok/networking/codec/PacketDecoder.java new file mode 100644 index 0000000..e80e078 --- /dev/null +++ b/devlok-netty/src/main/java/de/weapie/devlok/networking/codec/PacketDecoder.java @@ -0,0 +1,33 @@ +package de.weapie.devlok.networking.codec; + +import de.weapie.devlok.networking.packet.Packet; +import de.weapie.devlok.networking.packet.PacketBuffer; +import de.weapie.devlok.reflections.common.Allocator; +import io.netty5.buffer.Buffer; +import io.netty5.channel.ChannelHandlerContext; +import io.netty5.handler.codec.ByteToMessageDecoder; + +public class PacketDecoder extends ByteToMessageDecoder { + @Override + protected void decode(ChannelHandlerContext ctx, Buffer in) { + var buffer = new PacketBuffer(in); + + var className = buffer.readString(); + + try { + var readableBytes = buffer.readInt(); + var content = new PacketBuffer(in.copy(in.readerOffset(), readableBytes, true)); + in.skipReadableBytes(readableBytes); + + var packet = (Packet) Allocator.allocate(Class.forName(className)); + + packet.read(content); + + buffer.resetBuffer(); + ctx.fireChannelRead(packet); + } catch (Exception e) { + System.err.println("Error while decoding packet " + className); + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/devlok-netty/src/main/java/de/weapie/devlok/networking/codec/PacketEncoder.java b/devlok-netty/src/main/java/de/weapie/devlok/networking/codec/PacketEncoder.java new file mode 100644 index 0000000..83b4331 --- /dev/null +++ b/devlok-netty/src/main/java/de/weapie/devlok/networking/codec/PacketEncoder.java @@ -0,0 +1,61 @@ +package de.weapie.devlok.networking.codec; + +import de.weapie.devlok.networking.packet.Packet; +import de.weapie.devlok.networking.packet.PacketBuffer; +import io.netty5.buffer.Buffer; +import io.netty5.channel.ChannelHandlerContext; +import io.netty5.handler.codec.MessageToByteEncoder; +import lombok.SneakyThrows; + +import java.nio.charset.StandardCharsets; +import java.util.HashMap; + +public class PacketEncoder extends MessageToByteEncoder { + + private static final HashMap tempPacketEncoderList = new HashMap<>(); + + @Override + @SneakyThrows + protected Buffer allocateBuffer(ChannelHandlerContext ctx, Packet packet) { + try { + var buffer = PacketBuffer.allocate(); + + packet.write(buffer); + + tempPacketEncoderList.put(packet, buffer); + + // amount of chars in class name + var bytes = Integer.BYTES + + // class name + packet.getClass().getName().getBytes(StandardCharsets.UTF_8).length + + // amount of bytes in buffer + Integer.BYTES + + // buffer content + buffer.getOrigin().readableBytes(); + + return ctx.bufferAllocator().allocate(bytes); + } catch (Exception exception) { + exception.printStackTrace(); + } + return null; + } + + @Override + protected void encode(ChannelHandlerContext ctx, Packet msg, Buffer out) { + try { + var origin = tempPacketEncoderList.get(msg).getOrigin(); + var buffer = new PacketBuffer(out); + var readableBytes = origin.readableBytes(); + + buffer.writeString(msg.getClass().getName()); + buffer.writeInt(readableBytes); + + origin.copyInto(0, out, out.writerOffset(), readableBytes); + out.skipWritableBytes(readableBytes); + } catch (Exception e) { + System.err.println("Error while encoding packet " + msg.getClass().getName()); + e.printStackTrace(); + } + tempPacketEncoderList.remove(msg); + } +} \ No newline at end of file diff --git a/devlok-netty/src/main/java/de/weapie/devlok/networking/packet/BadRequestPacket.java b/devlok-netty/src/main/java/de/weapie/devlok/networking/packet/BadRequestPacket.java new file mode 100644 index 0000000..a4c1a3a --- /dev/null +++ b/devlok-netty/src/main/java/de/weapie/devlok/networking/packet/BadRequestPacket.java @@ -0,0 +1,25 @@ +package de.weapie.devlok.networking.packet; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.experimental.Accessors; + +import java.util.UUID; + +@Getter +@AllArgsConstructor +@Accessors(fluent = true) +public class BadRequestPacket extends Packet { + + private UUID uuid; + + @Override + public void read(PacketBuffer buffer) { + this.uuid = buffer.readUniqueId(); + } + + @Override + public void write(PacketBuffer buffer) { + buffer.writeUniqueId(uuid); + } +} diff --git a/devlok-netty/src/main/java/de/weapie/devlok/networking/packet/Packet.java b/devlok-netty/src/main/java/de/weapie/devlok/networking/packet/Packet.java new file mode 100644 index 0000000..e006e00 --- /dev/null +++ b/devlok-netty/src/main/java/de/weapie/devlok/networking/packet/Packet.java @@ -0,0 +1,9 @@ +package de.weapie.devlok.networking.packet; + +public abstract class Packet { + + public abstract void read(PacketBuffer buffer); + + public abstract void write(PacketBuffer buffer); + +} diff --git a/devlok-netty/src/main/java/de/weapie/devlok/networking/packet/PacketBuffer.java b/devlok-netty/src/main/java/de/weapie/devlok/networking/packet/PacketBuffer.java new file mode 100644 index 0000000..e983924 --- /dev/null +++ b/devlok-netty/src/main/java/de/weapie/devlok/networking/packet/PacketBuffer.java @@ -0,0 +1,171 @@ +package de.weapie.devlok.networking.packet; + +import io.netty5.buffer.Buffer; +import io.netty5.buffer.BufferAllocator; +import io.netty5.buffer.DefaultBufferAllocators; +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.jetbrains.annotations.NotNull; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; +import java.util.function.BiConsumer; +import java.util.function.Supplier; + +@AllArgsConstructor +public final class PacketBuffer { + private static final BufferAllocator BUFFER_ALLOCATOR = DefaultBufferAllocators.offHeapAllocator(); + + @Getter + private final Buffer origin; + + public static PacketBuffer allocate() { + return new PacketBuffer(BUFFER_ALLOCATOR.allocate(0)); + } + + public void resetBuffer() { + if (origin.readableBytes() > 0) { + System.err.println("Buffer not empty! Skipping remaining bytes: " + origin.readableBytes()); + origin.skipReadableBytes(origin.readableBytes()); + } + } + + public PacketBuffer writeString(String value) { + var bytes = value.getBytes(StandardCharsets.UTF_8); + this.origin.writeInt(bytes.length); + this.origin.writeBytes(bytes); + return this; + } + + public String readString() { + return this.origin.readCharSequence(this.origin.readInt(), StandardCharsets.UTF_8).toString(); + } + + public PacketBuffer writeBoolean(Boolean booleanValue) { + this.origin.writeBoolean(booleanValue); + return this; + } + + public boolean readBoolean() { + return this.origin.readBoolean(); + } + + public PacketBuffer writeUniqueId(UUID uniqueId) { + this.origin.writeLong(uniqueId.getMostSignificantBits()); + this.origin.writeLong(uniqueId.getLeastSignificantBits()); + return this; + } + + public UUID readUniqueId() { + return new UUID(this.origin.readLong(), this.origin.readLong()); + } + + public PacketBuffer writeInt(int value) { + this.origin.writeInt(value); + return this; + } + + public int readInt() { + return this.origin.readInt(); + } + + public PacketBuffer writeEnum(Enum value) { + this.origin.writeInt(value.ordinal()); + return this; + } + + public > T readEnum(Class clazz) { + return clazz.getEnumConstants()[this.origin.readInt()]; + } + + + public void writeList(@NotNull List list, BiConsumer consumer) { + this.writeInt(list.size()); + + list.forEach(o -> consumer.accept(this, o)); + } + + public List readList(List list, Supplier supplier) { + var size = this.readInt(); + + for (int i = 0; i < size; i++) { + list.add(supplier.get()); + } + + return list; + } + + public void writeBuffer(PacketBuffer buffer) { + this.writeInt(buffer.getOrigin().readableBytes()); + this.writeBytes(buffer.getOrigin()); + } + + public PacketBuffer writeLong(long value) { + this.origin.writeLong(value); + return this; + } + + public long readLong() { + return this.origin.readLong(); + } + + public PacketBuffer writeFloat(float value) { + this.origin.writeFloat(value); + return this; + } + + public float readFloat() { + return this.origin.readFloat(); + } + + public PacketBuffer writeDouble(double value) { + this.origin.writeDouble(value); + return this; + } + + public double readDouble() { + return this.origin.readDouble(); + } + + public short readShort() { + return this.origin.readShort(); + } + + public PacketBuffer writeShort(short value) { + this.origin.writeShort(value); + return this; + } + + public PacketBuffer writeByte(byte value) { + this.origin.writeByte(value); + return this; + } + + public byte readByte() { + return this.origin.readByte(); + } + + public PacketBuffer writeBytes(Buffer bytes) { + this.origin.writeBytes(bytes); + return this; + } + + public PacketBuffer writeBytes(byte[] bytes) { + + this.origin.writeInt(bytes.length); + + for (byte b : bytes) { + this.origin.writeByte(b); + } + return this; + } + + public byte[] readBytes() { + var elements = new byte[this.origin.readInt()]; + + for (int i = 0; i < elements.length; i++) { + elements[i] = this.origin.readByte(); + } + return elements; + } +} \ No newline at end of file diff --git a/devlok-netty/src/main/java/de/weapie/devlok/networking/packet/RequestPacket.java b/devlok-netty/src/main/java/de/weapie/devlok/networking/packet/RequestPacket.java new file mode 100644 index 0000000..5d1a9ae --- /dev/null +++ b/devlok-netty/src/main/java/de/weapie/devlok/networking/packet/RequestPacket.java @@ -0,0 +1,40 @@ +package de.weapie.devlok.networking.packet; + +import de.weapie.devlok.networking.CommunicationProperty; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.SneakyThrows; +import lombok.experimental.Accessors; +import org.jetbrains.annotations.NotNull; + +import java.util.UUID; + +@Getter +@Accessors(fluent = true) +@AllArgsConstructor +public final class RequestPacket extends Packet { + + private String id; + private UUID uuid; + + //todo + private CommunicationProperty property; + + @Override + @SneakyThrows + public void read(@NotNull PacketBuffer buffer) { + this.id = buffer.readString(); + this.uuid = buffer.readUniqueId(); + + this.property = CommunicationProperty.class.getConstructor().newInstance(); + this.property.read(buffer); + } + + @Override + public void write(@NotNull PacketBuffer buffer) { + buffer.writeString(id); + buffer.writeUniqueId(uuid); + + property.write(buffer); + } +} diff --git a/devlok-netty/src/main/java/de/weapie/devlok/networking/packet/RequestResponsePacket.java b/devlok-netty/src/main/java/de/weapie/devlok/networking/packet/RequestResponsePacket.java new file mode 100644 index 0000000..3d690fd --- /dev/null +++ b/devlok-netty/src/main/java/de/weapie/devlok/networking/packet/RequestResponsePacket.java @@ -0,0 +1,35 @@ +package de.weapie.devlok.networking.packet; + +import de.weapie.devlok.reflections.common.Allocator; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.SneakyThrows; +import lombok.experimental.Accessors; + +import java.util.UUID; + +@Getter +@Accessors(fluent = true) +@AllArgsConstructor +public class RequestResponsePacket extends Packet { + + private UUID uuid; + private Packet response; + + @Override + @SneakyThrows + public void read(PacketBuffer buffer) { + this.uuid = buffer.readUniqueId(); + + this.response = (Packet) Allocator.allocate(Class.forName(buffer.readString())); + this.response.read(buffer); + } + + @Override + public void write(PacketBuffer buffer) { + buffer.writeUniqueId(uuid); + buffer.writeString(response.getClass().getName()); + + response.write(buffer); + } +} diff --git a/devlok-netty/src/main/java/de/weapie/devlok/networking/server/CommunicationServer.java b/devlok-netty/src/main/java/de/weapie/devlok/networking/server/CommunicationServer.java new file mode 100644 index 0000000..b7b451a --- /dev/null +++ b/devlok-netty/src/main/java/de/weapie/devlok/networking/server/CommunicationServer.java @@ -0,0 +1,53 @@ +package de.weapie.devlok.networking.server; + +import de.weapie.devlok.networking.CommunicationComponent; +import de.weapie.devlok.networking.CommunicationNetworkUtils; +import de.weapie.devlok.networking.CommunicationTransmitHandler; +import de.weapie.devlok.networking.channel.ChannelInitializer; +import de.weapie.devlok.networking.channel.ChannelTransmit; +import de.weapie.devlok.networking.packet.Packet; +import io.netty5.bootstrap.ServerBootstrap; +import io.netty5.channel.ChannelOption; +import io.netty5.channel.EventLoopGroup; +import lombok.Getter; +import lombok.experimental.Accessors; + +import java.util.ArrayList; +import java.util.List; + +@Accessors(fluent = true) +public final class CommunicationServer extends CommunicationComponent { + + @Getter + private final List channels = new ArrayList<>(); + private final EventLoopGroup workerGroup = CommunicationNetworkUtils.createEventLoopGroup(0); + + public CommunicationServer(String hostname, int port) { + super(1, hostname, port); + } + + @Override + public void initialize() { + var bootstrap = new ServerBootstrap() + .group(bossGroup(), workerGroup) + .channelFactory(CommunicationNetworkUtils.generateChannelFactory()) + .childHandler(new ChannelInitializer(new CommunicationTransmitHandler(it -> this.channels, (it, channel) -> channel.call(it, channel), channelTransmit -> channels.add(CommunicationServerTransmit.of(channelTransmit, this))))) + + // all channel options + .childOption(ChannelOption.TCP_NODELAY, true) + .childOption(ChannelOption.IP_TOS, 24) + .childOption(ChannelOption.SO_KEEPALIVE, true); + + bootstrap.bind(hostname(), port()).addListener(handleConnectionRelease()) + .addListener(future -> { + if (!future.isSuccess()) { + throw new RuntimeException(future.cause()); + } + }); + } + + @Override + public void sendPacket(Packet packet) { + this.channels.forEach(channelTransmit -> channelTransmit.sendPacket(packet)); + } +} diff --git a/devlok-netty/src/main/java/de/weapie/devlok/networking/server/CommunicationServerTransmit.java b/devlok-netty/src/main/java/de/weapie/devlok/networking/server/CommunicationServerTransmit.java new file mode 100644 index 0000000..1b6e0fe --- /dev/null +++ b/devlok-netty/src/main/java/de/weapie/devlok/networking/server/CommunicationServerTransmit.java @@ -0,0 +1,43 @@ +package de.weapie.devlok.networking.server; + +import de.weapie.devlok.networking.CommunicationComponent; +import de.weapie.devlok.networking.channel.ChannelTransmit; +import de.weapie.devlok.networking.packet.Packet; +import de.weapie.devlok.networking.packet.RequestPacket; +import io.netty5.channel.Channel; +import org.jetbrains.annotations.NotNull; + +public class CommunicationServerTransmit extends ChannelTransmit { + + private final CommunicationComponent communicationComponent; + + public CommunicationServerTransmit(String id, Channel channel, CommunicationComponent communicationComponent) { + super(id, channel); + this.communicationComponent = communicationComponent; + } + + @Override + public void callResponder(ChannelTransmit channelTransmit, @NotNull RequestPacket requestPacket) { + communicationComponent.callResponder(channelTransmit, requestPacket); + } + + @Override + public

boolean call(@NotNull P packet, ChannelTransmit channelTransmit) { + if (!super.call(packet, channelTransmit)) { + communicationComponent.call(packet, channelTransmit); + } + return true; + } + + public static CommunicationServerTransmit of(ChannelTransmit channelTransmit, CommunicationComponent communicationComponent) { + var transmit = new CommunicationServerTransmit(channelTransmit.id(), channelTransmit.channel(), communicationComponent); + + transmit.listeners().putAll(transmit.listeners()); + transmit.requests().putAll(transmit.requests()); + transmit.responders().putAll(transmit.responders()); + + return transmit; + } + + +} diff --git a/devlok-netty/src/test/java/de/weapie/devlok/test/networking/ServerTest.java b/devlok-netty/src/test/java/de/weapie/devlok/test/networking/ServerTest.java new file mode 100644 index 0000000..b8aa5f3 --- /dev/null +++ b/devlok-netty/src/test/java/de/weapie/devlok/test/networking/ServerTest.java @@ -0,0 +1,51 @@ +package de.weapie.devlok.test.networking; + +import de.weapie.devlok.networking.CommunicationProperty; +import de.weapie.devlok.networking.client.CommunicationClient; +import de.weapie.devlok.networking.server.CommunicationServer; +import lombok.SneakyThrows; +import org.junit.jupiter.api.Test; + +import java.util.UUID; + +public class ServerTest { + + @Test + @SneakyThrows + public void handle() { + + var server = new CommunicationServer("127.0.0.1", 8080); + var client = new CommunicationClient("127.0.0.1", 8080, channelTransmit -> { + System.out.println("Connection successfully established to " + channelTransmit.id()); + }); + + server.initialize(); + client.initialize(); + + Thread.sleep(200); + + server.listen(TestPacket.class, (channel, packet) -> { + System.out.println("[Server] " + channel.id() + " received a TestPacket " + packet.toString()); + }); + + client.listen(TestPacket.class, (channel, packet) -> { + System.out.println("[Client] " + channel.id() + " received a TestPacket " + packet.toString()); + }); + + client.sendPacket(new TestPacket("test", UUID.randomUUID(), System.currentTimeMillis())); + + server.responder("players", property -> { + System.out.println(property.getInteger("test")); + return new TestPacket("polo", UUID.randomUUID(), System.currentTimeMillis()); + }); + + client.request("players", new CommunicationProperty().set("test", 200), TestPacket.class, testPacket -> { + System.out.println("request work " + testPacket.name()); + }); + + server.channels().get(0).sendPacket(new TestPacket("test2", UUID.randomUUID(), System.currentTimeMillis())); + server.sendPacket(new TestPacket("test3", UUID.randomUUID(), System.currentTimeMillis())); + + Thread.currentThread().join(10000); + } +} \ No newline at end of file diff --git a/devlok-netty/src/test/java/de/weapie/devlok/test/networking/TestPacket.java b/devlok-netty/src/test/java/de/weapie/devlok/test/networking/TestPacket.java new file mode 100644 index 0000000..cd2c36c --- /dev/null +++ b/devlok-netty/src/test/java/de/weapie/devlok/test/networking/TestPacket.java @@ -0,0 +1,35 @@ +package de.weapie.devlok.test.networking; + +import de.weapie.devlok.networking.packet.Packet; +import de.weapie.devlok.networking.packet.PacketBuffer; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.ToString; +import lombok.experimental.Accessors; + +import java.util.UUID; + +@Getter +@ToString +@Accessors(fluent = true) +@AllArgsConstructor +public class TestPacket extends Packet { + + private String name; + private UUID uniqueId; + private long time; + + @Override + public void read(PacketBuffer buffer) { + this.name = buffer.readString(); + this.uniqueId = buffer.readUniqueId(); + this.time = buffer.readLong(); + } + + @Override + public void write(PacketBuffer buffer) { + buffer.writeString(name); + buffer.writeUniqueId(uniqueId); + buffer.writeLong(time); + } +} diff --git a/devlok-reflections/build.gradle.kts b/devlok-reflections/build.gradle.kts new file mode 100644 index 0000000..0ce6a16 --- /dev/null +++ b/devlok-reflections/build.gradle.kts @@ -0,0 +1,3 @@ +dependencies { + +} \ No newline at end of file diff --git a/devlok-reflections/src/main/java/de/weapie/devlok/reflections/FieldBindingReflections.java b/devlok-reflections/src/main/java/de/weapie/devlok/reflections/FieldBindingReflections.java new file mode 100644 index 0000000..38c768a --- /dev/null +++ b/devlok-reflections/src/main/java/de/weapie/devlok/reflections/FieldBindingReflections.java @@ -0,0 +1,47 @@ +package de.weapie.devlok.reflections; + +import lombok.SneakyThrows; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.lang.reflect.Field; +import java.lang.reflect.ParameterizedType; +import java.util.Arrays; + +public final class FieldBindingReflections extends Reflections { + + private final Field fieldBinding; + + FieldBindingReflections(Class clazz, Field fieldBinding) { + super(clazz); + this.fieldBinding = fieldBinding; + } + + public @Nullable Class generic(int index) { + return this.generics()[index]; + } + + public @NotNull Class[] generics() { + var genericType = fieldBinding.getGenericType(); + if (genericType instanceof ParameterizedType parameterizedType) { + return Arrays.stream(parameterizedType.getActualTypeArguments()).map(type -> (Class) type).toArray(value -> new Class[value]); + } else { + throw new UnsupportedOperationException("Cannot read generic from field: " + fieldBinding.getName()); + } + } + + @SneakyThrows + public Object value(Object parent) { + this.access(); + return this.fieldBinding.get(parent); + } + + @SuppressWarnings("unchecked") + public O value(Object parent, Class valueType) { + return (O) this.value(parent); + } + + public void access() { + this.fieldBinding.setAccessible(true); + } +} \ No newline at end of file diff --git a/devlok-reflections/src/main/java/de/weapie/devlok/reflections/ObjectBindingReflection.java b/devlok-reflections/src/main/java/de/weapie/devlok/reflections/ObjectBindingReflection.java new file mode 100644 index 0000000..88e1a99 --- /dev/null +++ b/devlok-reflections/src/main/java/de/weapie/devlok/reflections/ObjectBindingReflection.java @@ -0,0 +1,59 @@ +package de.weapie.devlok.reflections; + +import lombok.SneakyThrows; +import org.jetbrains.annotations.NotNull; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; + +public final class ObjectBindingReflection extends Reflections { + + private final T objectBinding; + + ObjectBindingReflection(Class clazz, T objectBinding) { + super(clazz); + this.objectBinding = objectBinding; + } + + @SneakyThrows + public Object value(@NotNull Field field) { + field.setAccessible(true); + return field.get(this.objectBinding); + } + + public Object value(String fieldId) { + return this.value(this.field(fieldId)); + } + + @SuppressWarnings("unchecked") + public R value(String fieldId, Class objectType) { + return (R) this.value(fieldId); + } + + @SuppressWarnings("unchecked") + @SneakyThrows + public R value(@NotNull Field field, Class objectType) { + return (R) this.value(field); + } + + @SneakyThrows + public void modify(@NotNull Field field, Object value) { + field.setAccessible(true); + field.set(this.objectBinding, value); + } + + @SneakyThrows + public void modify(String fieldId, Object value) { + this.modify(this.clazz().getDeclaredField(fieldId), value); + } + + @SneakyThrows + public void applyMethod(@NotNull Method method, Object... args) { + method.invoke(objectBinding, args); + } + + @SneakyThrows + public void applyMethod(String methodId, Object... args) { + method(methodId).invoke(objectBinding, args); + } +} diff --git a/devlok-reflections/src/main/java/de/weapie/devlok/reflections/Reflections.java b/devlok-reflections/src/main/java/de/weapie/devlok/reflections/Reflections.java new file mode 100644 index 0000000..a67195f --- /dev/null +++ b/devlok-reflections/src/main/java/de/weapie/devlok/reflections/Reflections.java @@ -0,0 +1,73 @@ +package de.weapie.devlok.reflections; + +import de.weapie.devlok.reflections.common.Allocator; +import lombok.*; +import lombok.experimental.Accessors; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.*; + +@Accessors(fluent = true) +@Getter(AccessLevel.PACKAGE) +@SuppressWarnings("unchecked") // it's fine +@AllArgsConstructor +public class Reflections { + + private final Class clazz; + + public Field[] fields() { + return clazz.getDeclaredFields(); + } + + public Set allFields() { + var fields = new HashSet<>(Arrays.asList(clazz.getDeclaredFields())); + var scannedPathClass = clazz; + + while (scannedPathClass.getSuperclass() != null) { + scannedPathClass = (Class) scannedPathClass.getSuperclass(); + fields.addAll(Arrays.asList(scannedPathClass.getDeclaredFields())); + } + return fields; + } + + @SneakyThrows + public Field field(String id) { + var field = this.clazz.getDeclaredField(id); + field.setAccessible(true); + return field; + } + + @Contract("_ -> new") + public static @NotNull Reflections on(Class clazz) { + return new Reflections<>(clazz); + } + + @Contract("_ -> new") + public static @NotNull ObjectBindingReflection on(R value) { + return new ObjectBindingReflection<>((Class) value.getClass(), value); + } + + @Contract("_ -> new") + public static @NotNull FieldBindingReflections on(Field field) { + return new FieldBindingReflections<>((Class) field.getType(), field); + } + + public T allocate() { + return Allocator.allocate(clazz); + } + + @SneakyThrows + public T instance(Object... args) { + return clazz.getDeclaredConstructor(Arrays.stream(args).map(Object::getClass).toArray(value -> new Class[value])).newInstance(args); + } + + @SneakyThrows + public Method method(String id) { + var method = this.clazz.getDeclaredMethod(id); + method.setAccessible(true); + return method; + } +} diff --git a/devlok-reflections/src/main/java/de/weapie/devlok/reflections/common/Allocator.java b/devlok-reflections/src/main/java/de/weapie/devlok/reflections/common/Allocator.java new file mode 100644 index 0000000..2881f28 --- /dev/null +++ b/devlok-reflections/src/main/java/de/weapie/devlok/reflections/common/Allocator.java @@ -0,0 +1,36 @@ +package de.weapie.devlok.reflections.common; + +import sun.misc.Unsafe; + +import java.lang.reflect.InvocationTargetException; + +public final class Allocator { + + private static final Unsafe unsafe; + + static { + try { + var field = Unsafe.class.getDeclaredField("theUnsafe"); + field.setAccessible(true); + unsafe = (Unsafe) field.get(null); + } catch (IllegalAccessException | NoSuchFieldException var1) { + throw new RuntimeException(var1); + } + } + + @SuppressWarnings("unchecked") + public static T allocate(Class tClass) { + try { + return (T) unsafe.allocateInstance(tClass); + } catch (InstantiationException e) { + try { + // default empty constructor + return tClass.getConstructor().newInstance(); + } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | + InvocationTargetException ex) { + System.err.println("Cannot create new object: " + tClass.getSimpleName()); + } + } + return null; + } +} \ No newline at end of file diff --git a/devlok-reflections/src/main/java/de/weapie/devlok/reflections/exceptions/ScannerException.java b/devlok-reflections/src/main/java/de/weapie/devlok/reflections/exceptions/ScannerException.java new file mode 100644 index 0000000..480fd78 --- /dev/null +++ b/devlok-reflections/src/main/java/de/weapie/devlok/reflections/exceptions/ScannerException.java @@ -0,0 +1,9 @@ +package de.weapie.devlok.reflections.exceptions; + +import javax.management.RuntimeErrorException; + +public class ScannerException extends RuntimeErrorException { + public ScannerException(Error e) { + super(e); + } +} diff --git a/devlok-reflections/src/main/java/de/weapie/devlok/reflections/scanner/ClassScanner.java b/devlok-reflections/src/main/java/de/weapie/devlok/reflections/scanner/ClassScanner.java new file mode 100644 index 0000000..a8c1d4c --- /dev/null +++ b/devlok-reflections/src/main/java/de/weapie/devlok/reflections/scanner/ClassScanner.java @@ -0,0 +1,69 @@ +package de.weapie.devlok.reflections.scanner; + +import de.weapie.devlok.reflections.exceptions.ScannerException; +import lombok.AccessLevel; +import lombok.RequiredArgsConstructor; +import lombok.SneakyThrows; + +import java.io.File; +import java.io.IOException; +import java.nio.file.*; +import java.util.*; +import java.util.function.Predicate; +import java.util.stream.Stream; + +@RequiredArgsConstructor(access = AccessLevel.PRIVATE) +public class ClassScanner { + + private final ClassLoader loader; + private final String packageName; // current separator + private final List>> criteria = new ArrayList<>(); + + public static ClassScanner of(ClassLoader loader, String packageName) { + return new ClassScanner(loader, packageName); + } + + public ClassScanner criteria(Predicate> criteria) { + this.criteria.add(criteria); + return this; + } + + @SneakyThrows + public Collection> scan() { + var replacedPath = packageName.replace('.', '/'); + var packageUri = Objects.requireNonNull(loader.getResource(replacedPath)).toURI(); + var classes = new ArrayList>(); + + Path path; + if (packageUri.toString().startsWith("jar:")) { + try { + path = FileSystems.getFileSystem(packageUri).getPath(replacedPath); + } catch (FileSystemNotFoundException e) { + try { + path = FileSystems.newFileSystem(packageUri, Collections.emptyMap()).getPath(replacedPath); + } catch (IOException ex) { + throw new ScannerException(new Error("Error during package scan: " + e.getMessage())); + } + } + } else { + path = Paths.get(packageUri); + } + try (Stream allPaths = Files.walk(path)) { + allPaths.filter(Files::isRegularFile).forEach(file -> { + String absolutePath = file.toString().replace(File.separator, ".").replace('/', '.'); + String className = absolutePath.substring(absolutePath.indexOf(packageName), absolutePath.length() - 6); + try { + Class clazz = loader.loadClass(className); + if (criteria.isEmpty() || criteria.stream().allMatch(classPredicate -> classPredicate.test(clazz))) { + classes.add(clazz); + } + } catch (ClassNotFoundException | StringIndexOutOfBoundsException | NoClassDefFoundError e) { + System.out.println("Error whilst loading class '" + className + "' (exception: " + e.getClass().getName() + ") Ignoring class!"); + } + }); + } catch (IOException e) { + throw new ScannerException(new Error("Error during package scan: " + e.getMessage())); + } + return classes; + } +} diff --git a/devlok-utils/build.gradle.kts b/devlok-utils/build.gradle.kts new file mode 100644 index 0000000..0ce6a16 --- /dev/null +++ b/devlok-utils/build.gradle.kts @@ -0,0 +1,3 @@ +dependencies { + +} \ No newline at end of file diff --git a/devlok-utils/src/main/java/de/weapie/devlok/utils/Patterns.java b/devlok-utils/src/main/java/de/weapie/devlok/utils/Patterns.java new file mode 100644 index 0000000..7fafd43 --- /dev/null +++ b/devlok-utils/src/main/java/de/weapie/devlok/utils/Patterns.java @@ -0,0 +1,21 @@ +package de.weapie.devlok.utils; + +import java.util.regex.Pattern; + +public class Patterns { + /** + * Pattern for a double. Source: ... + */ + + public static final Pattern DOUBLE_PATTERN = Pattern.compile( + "[\\x00-\\x20]*[+-]?(NaN|Infinity|((((\\p{Digit}+)(\\.)?((\\p{Digit}+)?)" + + "([eE][+-]?(\\p{Digit}+))?)|(\\.((\\p{Digit}+))([eE][+-]?(\\p{Digit}+))?)|" + + "(((0[xX](\\p{XDigit}+)(\\.)?)|(0[xX](\\p{XDigit}+)?(\\.)(\\p{XDigit}+)))" + + "[pP][+-]?(\\p{Digit}+)))[fFdD]?))[\\x00-\\x20]*"); + + /** + * Pattern for a {@link java.util.UUID}. Source: ... + */ + public static final Pattern UUID_PATTERN = Pattern.compile("^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$"); + +} \ No newline at end of file diff --git a/devlok-utils/src/main/java/de/weapie/devlok/utils/RandomUtils.java b/devlok-utils/src/main/java/de/weapie/devlok/utils/RandomUtils.java new file mode 100644 index 0000000..f21681b --- /dev/null +++ b/devlok-utils/src/main/java/de/weapie/devlok/utils/RandomUtils.java @@ -0,0 +1,20 @@ +package de.weapie.devlok.utils; + +import java.util.Random; + +public class RandomUtils { + + private static Random RANDOM = new Random(); + + public static int getRandomNumber() { + return RANDOM.nextInt(); + } + + public static int getRandomNumber(int max) { + return RANDOM.nextInt(max); + } + + public static int getRandomNumber(int min, int max) { + return RANDOM.nextInt(max - min + 1) + min; + } +} diff --git a/devlok-utils/src/main/java/de/weapie/devlok/utils/Utils.java b/devlok-utils/src/main/java/de/weapie/devlok/utils/Utils.java new file mode 100644 index 0000000..6cf9f35 --- /dev/null +++ b/devlok-utils/src/main/java/de/weapie/devlok/utils/Utils.java @@ -0,0 +1,26 @@ +package de.weapie.devlok.utils; + +import java.text.SimpleDateFormat; +import java.util.List; +import java.util.Random; + +public class Utils { + + public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd.MM.yyyy"); + + public static final SimpleDateFormat DATE_AND_TIME_FORMAT = new SimpleDateFormat("dd.MM.yyyy HH:mm"); + + public static final SimpleDateFormat DATE_AND_TIME_FORMAT_WITH_SECONDS = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); + + public static final Random RANDOM = new Random(); + + public static final List> JAVA_ELEMENTS = List.of(String.class, Integer.class, Boolean.class, Short.class, Float.class, Byte.class, Double.class, Long.class); + + public static final String LINE_BREAK_ELEMENT = System.lineSeparator(); + + public static final String SEMICOLON = ";"; + public static final String DOUBLETHINK = ":"; + public static final String SPACER = " "; + public static final String EMTPY_STRING = ""; + +} diff --git a/devlok-utils/src/main/java/de/weapie/devlok/utils/data/Pair.java b/devlok-utils/src/main/java/de/weapie/devlok/utils/data/Pair.java new file mode 100644 index 0000000..d29019f --- /dev/null +++ b/devlok-utils/src/main/java/de/weapie/devlok/utils/data/Pair.java @@ -0,0 +1,15 @@ +package de.weapie.devlok.utils.data; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@AllArgsConstructor +public class Pair { + + private K key; + private V value; + +} \ No newline at end of file diff --git a/devlok-utils/src/main/java/de/weapie/devlok/utils/decrypter/Base64Decrypter.java b/devlok-utils/src/main/java/de/weapie/devlok/utils/decrypter/Base64Decrypter.java new file mode 100644 index 0000000..10e609a --- /dev/null +++ b/devlok-utils/src/main/java/de/weapie/devlok/utils/decrypter/Base64Decrypter.java @@ -0,0 +1,14 @@ +package de.weapie.devlok.utils.decrypter; + +import java.util.Base64; + +public final class Base64Decrypter { + + public static String encode(String content) { + return new String(Base64.getEncoder().encode(content.getBytes())); + } + + public static String decode(String content) { + return new String(Base64.getDecoder().decode(content.getBytes())); + } +} diff --git a/devlok-utils/src/main/java/de/weapie/devlok/utils/exceptions/NotImplementedException.java b/devlok-utils/src/main/java/de/weapie/devlok/utils/exceptions/NotImplementedException.java new file mode 100644 index 0000000..23720c4 --- /dev/null +++ b/devlok-utils/src/main/java/de/weapie/devlok/utils/exceptions/NotImplementedException.java @@ -0,0 +1,11 @@ +package de.weapie.devlok.utils.exceptions; + +import lombok.NoArgsConstructor; + +@NoArgsConstructor +public class NotImplementedException extends RuntimeException { + + public NotImplementedException(String message) { + super(message); + } +} diff --git a/devlok-utils/src/main/java/de/weapie/devlok/utils/executers/FutureResult.java b/devlok-utils/src/main/java/de/weapie/devlok/utils/executers/FutureResult.java new file mode 100644 index 0000000..19853cc --- /dev/null +++ b/devlok-utils/src/main/java/de/weapie/devlok/utils/executers/FutureResult.java @@ -0,0 +1,33 @@ +package de.weapie.devlok.utils.executers; + +import lombok.Getter; +import lombok.Setter; +import lombok.experimental.Accessors; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; + +@Setter +@Getter +@Accessors(fluent = true) +public class FutureResult extends CompletableFuture { + + public FutureResult() { + this.exceptionally(throwable -> { + throwable.printStackTrace(); + return null; + }); + } + + public E sync(E defaultValue, long secondTimeout) { + try { + return get(secondTimeout, TimeUnit.SECONDS); + } catch (Exception e) { + return defaultValue; + } + } + + public E sync(E defaultValue) { + return sync(defaultValue, 5); + } +} \ No newline at end of file diff --git a/devlok-utils/src/main/java/de/weapie/devlok/utils/executers/ThreadExecutor.java b/devlok-utils/src/main/java/de/weapie/devlok/utils/executers/ThreadExecutor.java new file mode 100644 index 0000000..fb212f6 --- /dev/null +++ b/devlok-utils/src/main/java/de/weapie/devlok/utils/executers/ThreadExecutor.java @@ -0,0 +1,10 @@ +package de.weapie.devlok.utils.executers; + +import java.util.concurrent.Executor; +import java.util.concurrent.Executors; + +public final class ThreadExecutor { + + public static final Executor EXECUTOR = Executors.newCachedThreadPool(); + +} diff --git a/devlok-utils/src/main/java/de/weapie/devlok/utils/maths/EulerAngle.java b/devlok-utils/src/main/java/de/weapie/devlok/utils/maths/EulerAngle.java new file mode 100644 index 0000000..fafca8f --- /dev/null +++ b/devlok-utils/src/main/java/de/weapie/devlok/utils/maths/EulerAngle.java @@ -0,0 +1,41 @@ +package de.weapie.devlok.utils.maths; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class EulerAngle { + + public static final EulerAngle ZERO = new EulerAngle(0, 0, 0); + private double x, y, z; + + public EulerAngle add(double x, double y, double z) { + return new EulerAngle(this.x + x, this.y + y, this.z + z); + } + + public EulerAngle subtract(double x, double y, double z) { + return add(-x, -y, -z); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + var that = (EulerAngle) o; + return Double.compare(that.x, x) == 0 && Double.compare(that.y, y) == 0 && Double.compare(that.z, z) == 0; + } + + @Override + public int hashCode() { + var temp = Double.doubleToLongBits(x); + var result = Long.hashCode(temp); + temp = Double.doubleToLongBits(y); + result = 31 * result + Long.hashCode(temp); + temp = Double.doubleToLongBits(z); + result = 31 * result + Long.hashCode(temp); + return result; + } +} diff --git a/devlok-utils/src/main/java/de/weapie/devlok/utils/stream/StreamHelper.java b/devlok-utils/src/main/java/de/weapie/devlok/utils/stream/StreamHelper.java new file mode 100644 index 0000000..cd2b906 --- /dev/null +++ b/devlok-utils/src/main/java/de/weapie/devlok/utils/stream/StreamHelper.java @@ -0,0 +1,13 @@ +package de.weapie.devlok.utils.stream; + +import java.util.stream.IntStream; +import java.util.stream.Stream; + +public class StreamHelper { + + @SuppressWarnings("unchecked") + public static Stream reverse(Stream input) { + Object[] temp = input.toArray(); + return (Stream) IntStream.range(0, temp.length).mapToObj(i -> temp[temp.length - i - 1]); + } +} diff --git a/devlok-utils/src/main/java/de/weapie/devlok/utils/types/EnumUtils.java b/devlok-utils/src/main/java/de/weapie/devlok/utils/types/EnumUtils.java new file mode 100644 index 0000000..ea256fa --- /dev/null +++ b/devlok-utils/src/main/java/de/weapie/devlok/utils/types/EnumUtils.java @@ -0,0 +1,37 @@ +package de.weapie.devlok.utils.types; + +public final class EnumUtils { + + public static > boolean isValidEnum(Class enumClass, String value) { + return getEnum(enumClass, value) != null; + } + + public static > boolean isValidEnumIgnoreCase(Class enumClass, String value) { + return getEnumIgnoreCase(enumClass, value) != null; + } + + public static > E getEnum(Class enumClass, String value) { + if (value == null) { + return null; + } + + try { + return Enum.valueOf(enumClass, value); + } catch (final IllegalArgumentException ex) { + return null; + } + } + + public static > E getEnumIgnoreCase(Class enumClass, String value) { + if (value == null || !enumClass.isEnum()) { + return null; + } + + for (E each : enumClass.getEnumConstants()) { + if (each.name().equalsIgnoreCase(value)) { + return each; + } + } + return null; + } +} diff --git a/devlok-utils/src/main/java/de/weapie/devlok/utils/types/ListUtils.java b/devlok-utils/src/main/java/de/weapie/devlok/utils/types/ListUtils.java new file mode 100644 index 0000000..2674de6 --- /dev/null +++ b/devlok-utils/src/main/java/de/weapie/devlok/utils/types/ListUtils.java @@ -0,0 +1,11 @@ +package de.weapie.devlok.utils.types; + +import java.util.List; + +public final class ListUtils { + + public static List append(List list, T element) { + list.add(element); + return list; + } +} diff --git a/devlok-utils/src/main/java/de/weapie/devlok/utils/types/MessageUtils.java b/devlok-utils/src/main/java/de/weapie/devlok/utils/types/MessageUtils.java new file mode 100644 index 0000000..d2d0e0d --- /dev/null +++ b/devlok-utils/src/main/java/de/weapie/devlok/utils/types/MessageUtils.java @@ -0,0 +1,263 @@ +package de.weapie.devlok.utils.types; + +import de.weapie.devlok.utils.Patterns; +import de.weapie.devlok.utils.RandomUtils; +import de.weapie.devlok.utils.Utils; +import org.jetbrains.annotations.NotNull; + +import java.text.NumberFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.concurrent.TimeUnit; + + +public final class MessageUtils { + + private static final String ALPHABET = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + + public static String randomString(int length) { + StringBuilder builder = new StringBuilder(); + + for (int i = 0; i < length; i++) { + builder.append(ALPHABET.charAt(RandomUtils.getRandomNumber(ALPHABET.length()))); + } + + return builder.toString(); + } + + public static int countMatches(@NotNull final CharSequence str, final char ch) { + if (str.isEmpty()) { + return 0; + } + int count = 0; + for (int i = 0; i < str.length(); i++) { + if (ch == str.charAt(i)) { + count++; + } + } + return count; + } + + public static String replaceLast(String string, String substring, String replacement) { + int index = string.lastIndexOf(substring); + + if (index == -1) { + return string; + } + + return string.substring(0, index) + replacement + string.substring(index + substring.length()); + } + + public static boolean isValidDouble(String string) { + if (string == null || string.isEmpty()) { + return false; + } + + return Patterns.DOUBLE_PATTERN.matcher(string).matches(); + } + + public static boolean isValidInteger(String string) { + if (string == null || string.isEmpty()) { + return false; + } + + return NumberUtils.isParsable(string); + } + + public static boolean isAlphabeticWithNumbers(String string) { + return isAlphabeticWithNumbers(string); + } + + public static boolean isAlphabeticWithNumbers(String string, String... allowedChars) { + List list = Arrays.asList(allowedChars); + + for (int i = 0, n = string.length(); i < n; i++) { + char charAt = string.charAt(i); + + if (!list.contains(String.valueOf(charAt))) { + if (!Character.isDigit(charAt) && !Character.isAlphabetic(charAt)) { + return false; + } + } + } + + return true; + } + + public static boolean isAlphabetic(String string) { + return isAlphabetic(string); + } + + public static boolean isAlphabetic(String string, String... allowedChars) { + List list = Arrays.asList(allowedChars); + + for (int i = 0, n = string.length(); i < n; i++) { + char charAt = string.charAt(i); + + if (!list.contains(String.valueOf(charAt))) { + if (!Character.isAlphabetic(charAt)) { + return false; + } + } + } + + return true; + } + + public static boolean isValidDate(String dateToCheck) { + return isValidDate(dateToCheck, Utils.DATE_FORMAT); + } + + public static boolean isValidDateAndTime(String dateToCheck) { + return isValidDate(dateToCheck, Utils.DATE_AND_TIME_FORMAT); + } + + public static boolean isValidDateAndTimeWithSeconds(String dateToCheck) { + return isValidDate(dateToCheck, Utils.DATE_AND_TIME_FORMAT_WITH_SECONDS); + } + + public static boolean isValidDate(String dateToCheck, String dateFormat) { + return isValidDate(dateToCheck, new SimpleDateFormat(dateFormat)); + } + + public static boolean isValidDate(String dateToCheck, SimpleDateFormat dateFormat) { + dateFormat.setLenient(false); + + try { + dateFormat.parse(dateToCheck.trim()); + } catch (ParseException e) { + return false; + } + + return true; + } + + public static long convertDurationString(String durationStr) { + TimeUnit timeUnit; + + if (durationStr.endsWith("d")) { + durationStr = durationStr.replace("d", ""); + timeUnit = TimeUnit.DAYS; + } else if (durationStr.endsWith("h")) { + durationStr = durationStr.replace("h", ""); + timeUnit = TimeUnit.HOURS; + } else if (durationStr.endsWith("m")) { + durationStr = durationStr.replace("m", ""); + timeUnit = TimeUnit.MINUTES; + } else if (durationStr.endsWith("s")) { + durationStr = durationStr.replace("s", ""); + timeUnit = TimeUnit.SECONDS; + } else { + return -1; + } + + if (isValidInteger(durationStr)) { + int duration = Integer.parseInt(durationStr); + + return timeUnit.toMillis(duration); + } else { + return -1; + } + } + + public static String getDateFromMillis(long millis) { + return getDateFromMillis(millis, Utils.DATE_FORMAT); + } + + public static String getDateAndTimeFromMillis(long millis) { + return getDateFromMillis(millis, Utils.DATE_AND_TIME_FORMAT); + } + + public static String getDateAndTimeWithSecondsFromMillis(long millis) { + return getDateFromMillis(millis, Utils.DATE_AND_TIME_FORMAT_WITH_SECONDS); + } + + public static String getDateFromMillis(long millis, String dateFormat) { + return getDateFromMillis(millis, new SimpleDateFormat(dateFormat)); + } + + public static String getDateFromMillis(long millis, SimpleDateFormat dateFormat) { + if (millis == -1) { + return "§4PERMANENT"; + } + + Calendar calendar = Calendar.getInstance(); + calendar.setTimeInMillis(millis); + + Date date = calendar.getTime(); + + return dateFormat.format(date); + } + + public static long dateToMillis(String dateString) { + return dateToMillis(dateString, Utils.DATE_FORMAT); + } + + public static long dateAndTimeToMillis(String dateString) { + return dateToMillis(dateString, Utils.DATE_AND_TIME_FORMAT); + } + + public static long dateAndTimeWithSecondsToMillis(String dateString) { + return dateToMillis(dateString, Utils.DATE_AND_TIME_FORMAT_WITH_SECONDS); + } + + public static long dateToMillis(String dateString, String dateFormat) { + return dateToMillis(dateString, new SimpleDateFormat(dateFormat)); + } + + public static long dateToMillis(String dateString, SimpleDateFormat dateFormat) { + Date date; + + try { + date = dateFormat.parse(dateString); + } catch (ParseException e) { + return System.currentTimeMillis(); + } + + return date.getTime(); + } + + public static String argsToString(String[] args, int startingFrom) { + StringBuilder builder = new StringBuilder(); + + for (int i = startingFrom; i < args.length; i++) { + if (i > startingFrom) { + builder.append(" "); + } + + builder.append(args[startingFrom]); + } + + return builder.toString(); + } + + public static String getPercent(int amount, int percentOf) { + return getPercent(amount, percentOf, 1, true); + } + + public static String getPercent(int amount, int percentOf, int maxDigits, boolean hundredIsMax) { + if (amount == 0 || percentOf == 0) { + return "0%"; + } + + if (amount > percentOf && hundredIsMax) { + return "100%"; + } + + NumberFormat format = NumberFormat.getInstance(); + double percent = ((double) amount / (double) percentOf) * 100; + + format.setMaximumFractionDigits(maxDigits); + + return format.format(percent) + "%"; + } + + public static String formatNumber(long value) { + return NumberFormat.getInstance().format(value).replace(",", "."); + } + + public static String formatNumber(double value) { + return NumberFormat.getInstance().format(value); + } +} diff --git a/devlok-utils/src/main/java/de/weapie/devlok/utils/types/NumberUtils.java b/devlok-utils/src/main/java/de/weapie/devlok/utils/types/NumberUtils.java new file mode 100644 index 0000000..866beeb --- /dev/null +++ b/devlok-utils/src/main/java/de/weapie/devlok/utils/types/NumberUtils.java @@ -0,0 +1,33 @@ +package de.weapie.devlok.utils.types; + +public final class NumberUtils { + + public static boolean isNumber(Class clazz) { + return Number.class.isAssignableFrom(clazz); + } + + public static boolean isParsable(final String str) { + if (str.isEmpty() || str.charAt(str.length() - 1) == '.') { + return false; + } + if (str.charAt(0) == '-') { + return str.length() > 1 && withDecimalsParsing(str, 1); + } + return withDecimalsParsing(str, 0); + } + + public static boolean withDecimalsParsing(final String str, final int beginIdx) { + var decimal = 0; + for (var i = beginIdx; i < str.length(); i++) { + var currentChar = str.charAt(i); + if (currentChar == '.') { + if (++decimal > 1) { + return false; + } + } else if (!Character.isDigit(currentChar)) { + return false; + } + } + return true; + } +} \ No newline at end of file diff --git a/devlok-utils/src/main/java/de/weapie/devlok/utils/types/UniqueIDUtils.java b/devlok-utils/src/main/java/de/weapie/devlok/utils/types/UniqueIDUtils.java new file mode 100644 index 0000000..abc7331 --- /dev/null +++ b/devlok-utils/src/main/java/de/weapie/devlok/utils/types/UniqueIDUtils.java @@ -0,0 +1,10 @@ +package de.weapie.devlok.utils.types; + +import de.weapie.devlok.utils.Patterns; + +public final class UniqueIDUtils { + + public static boolean isUniqueId(String input) { + return input.matches(Patterns.UUID_PATTERN.pattern()); + } +} diff --git a/devlok-utils/src/main/java/de/weapie/devlok/utils/validate/Check.java b/devlok-utils/src/main/java/de/weapie/devlok/utils/validate/Check.java new file mode 100644 index 0000000..e304460 --- /dev/null +++ b/devlok-utils/src/main/java/de/weapie/devlok/utils/validate/Check.java @@ -0,0 +1,36 @@ +package de.weapie.devlok.utils.validate; + +import lombok.AccessLevel; +import lombok.NoArgsConstructor; + +import java.text.MessageFormat; +import java.util.Objects; + +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public final class Check { + + // simple not null check + public static void notNull(Object object, String reason) { + if (Objects.isNull(object)) { + throw new NullPointerException(reason); + } + } + + public static void notNull(Object object, String reason, Object... arguments) { + if (Objects.isNull(object)) { + throw new NullPointerException(MessageFormat.format(reason, arguments)); + } + } + + public static void argCondition(boolean condition, String message) { + if (condition) { + throw new IllegalArgumentException(message); + } + } + + public static void stateCondition(boolean condition, String message) { + if (condition) { + throw new IllegalStateException(message); + } + } +} diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..732b648 --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,19 @@ +[versions] + +annotations = "24.1.0" +lombok = "1.18.32" + +gson = "2.11.0" + +#networking +netty5 = "5.0.0.Alpha5" + +[libraries] +lombok = { group = "org.projectlombok", name="lombok", version.ref = "lombok" } +annotations = { group = "org.jetbrains", name="annotations", version.ref = "annotations" } +gson = { group = "com.google.code.gson", name="gson", version.ref = "gson" } + +#networking +netty5 = { group = "io.netty", name = "netty5-all", version.ref = "netty5" } + +[plugins] \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..893c810 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue Jan 23 09:21:27 CET 2024 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# 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 +# +# https://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. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..6de53a3 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,6 @@ +rootProject.name = "devlok" + +include("devlok-utils") +include("devlok-reflections") +include("devlok-files") +include("devlok-netty")