commit 392658d54e3ba0f4098bdcc5f22ffabac7381e3c Author: CodingPhoenix Date: Fri May 8 11:04:40 2026 +0200 Initial Commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..aee08ff --- /dev/null +++ b/.gitignore @@ -0,0 +1,57 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ +.kotlin + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +### 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/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..bfc5d07 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,10 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Ignored default folder with query files +/queries/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml +/discord.xml +/git_toolbox_prj.xml diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..8a1aa7f --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,16 @@ + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..217a1af --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..a8b8805 --- /dev/null +++ b/build.gradle @@ -0,0 +1,18 @@ +plugins { + id 'java' +} + +group = 'dev.coph' +version = '1.0-SNAPSHOT' + +repositories { + mavenCentral() +} + +dependencies { + + + implementation 'io.netty:netty-all:4.2.6.Final' + implementation 'tools.jackson.core:jackson-databind:3.1.3' +} + 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..6a06ba8 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Fri May 08 10:10:06 CEST 2026 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.0-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 b/settings.gradle new file mode 100644 index 0000000..8c330d9 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'NexusWeb' \ No newline at end of file diff --git a/src/main/java/dev/coph/nextusweb/server/HttpRequestHandler.java b/src/main/java/dev/coph/nextusweb/server/HttpRequestHandler.java new file mode 100644 index 0000000..6861d01 --- /dev/null +++ b/src/main/java/dev/coph/nextusweb/server/HttpRequestHandler.java @@ -0,0 +1,88 @@ +package dev.coph.nextusweb.server; + +import dev.coph.nextusweb.server.router.Request; +import dev.coph.nextusweb.server.router.Response; +import dev.coph.nextusweb.server.router.Router; +import dev.coph.nextusweb.server.router.exception.BadRequestException; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelFutureListener; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.SimpleChannelInboundHandler; +import io.netty.handler.codec.http.*; + +import java.util.concurrent.Executor; +import java.util.concurrent.Executors; +import java.util.stream.Collectors; + +public final class HttpRequestHandler extends SimpleChannelInboundHandler { + + private static final Executor VT_EXECUTOR = + Executors.newVirtualThreadPerTaskExecutor(); + + private final Router router; + + public HttpRequestHandler(Router router) { + this.router = router; + } + + @Override + protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) { + req.retain(); + VT_EXECUTOR.execute(() -> { + try { + handle(ctx, req); + } finally { + req.release(); + } + }); + } + + private void handle(ChannelHandlerContext ctx, FullHttpRequest raw) { + String path = new QueryStringDecoder(raw.uri()).path(); + Router.Resolution resolution = router.resolve(raw.method(), path); + + Response res = new Response(); + + switch (resolution) { + case Router.Resolution.Match m -> { + Request request = new Request(raw, m.pathParams()); + try { + for (var mw : router.middlewares()) mw.accept(request, res); + m.handler().handle(request, res); + } catch (BadRequestException e) { + res.status(400).json("{\"error\":\"" + e.getMessage() + "\"}"); + } catch (Exception e) { + res.status(500).text("Internal Server Error: " + e.getMessage()); + } + } + case Router.Resolution.MethodNotAllowed mna -> { + String allow = mna.allowedMethods().stream() + .map(HttpMethod::name) + .sorted() + .collect(Collectors.joining(", ")); + res.status(405) + .header(HttpHeaderNames.ALLOW.toString(), allow) + .json("{\"error\":\"Method Not Allowed\",\"allowed\":\"" + allow + "\"}"); + } + case Router.Resolution.NotFound nf -> res.status(404).json("{\"error\":\"Not Found\"}"); + } + + send(ctx, res); + } + + private void send(ChannelHandlerContext ctx, Response res) { + var nettyRes = new DefaultFullHttpResponse( + HttpVersion.HTTP_1_1, + HttpResponseStatus.valueOf(res.status()), + Unpooled.wrappedBuffer(res.body()) + ); + nettyRes.headers().add(res.headers()); + nettyRes.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, res.body().length); + ctx.writeAndFlush(nettyRes).addListener(ChannelFutureListener.CLOSE); + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { + ctx.close(); + } +} \ No newline at end of file diff --git a/src/main/java/dev/coph/nextusweb/server/HttpServer.java b/src/main/java/dev/coph/nextusweb/server/HttpServer.java new file mode 100644 index 0000000..54d2fd3 --- /dev/null +++ b/src/main/java/dev/coph/nextusweb/server/HttpServer.java @@ -0,0 +1,60 @@ +package dev.coph.nextusweb.server; + +import dev.coph.nextusweb.server.router.Router; +import io.netty.bootstrap.ServerBootstrap; +import io.netty.channel.*; +import io.netty.channel.epoll.Epoll; +import io.netty.channel.epoll.EpollIoHandler; +import io.netty.channel.epoll.EpollServerSocketChannel; +import io.netty.channel.kqueue.KQueue; +import io.netty.channel.kqueue.KQueueIoHandler; +import io.netty.channel.kqueue.KQueueServerSocketChannel; +import io.netty.channel.nio.NioIoHandler; +import io.netty.channel.socket.SocketChannel; +import io.netty.channel.socket.nio.NioServerSocketChannel; +import io.netty.handler.codec.http.HttpObjectAggregator; +import io.netty.handler.codec.http.HttpServerCodec; + +public final class HttpServer { + + public static void start(int port, Router router) throws InterruptedException { + EventLoopGroup boss, worker; + Class channelClass; + + if (Epoll.isAvailable()) { + boss = new MultiThreadIoEventLoopGroup(1, EpollIoHandler.newFactory()); + worker = new MultiThreadIoEventLoopGroup(EpollIoHandler.newFactory()); + channelClass = EpollServerSocketChannel.class; + } else if (KQueue.isAvailable()) { + boss = new MultiThreadIoEventLoopGroup(1, KQueueIoHandler.newFactory()); + worker = new MultiThreadIoEventLoopGroup(KQueueIoHandler.newFactory()); + channelClass = KQueueServerSocketChannel.class; + } else { + boss = new MultiThreadIoEventLoopGroup(1, NioIoHandler.newFactory()); + worker = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory()); + channelClass = NioServerSocketChannel.class; + } + + try { + new ServerBootstrap() + .group(boss, worker) + .channel(channelClass) + .option(ChannelOption.SO_BACKLOG, 8192) + .childOption(ChannelOption.TCP_NODELAY, true) + .childOption(ChannelOption.SO_KEEPALIVE, true) + .childHandler(new ChannelInitializer() { + @Override + protected void initChannel(SocketChannel ch) { + ch.pipeline() + .addLast(new HttpServerCodec()) + .addLast(new HttpObjectAggregator(1024 * 1024)) + .addLast(new HttpRequestHandler(router)); + } + }) + .bind(port).sync().channel().closeFuture().sync(); + } finally { + boss.shutdownGracefully(); + worker.shutdownGracefully(); + } + } +} \ No newline at end of file diff --git a/src/main/java/dev/coph/nextusweb/server/annotation/AnnotationScanner.java b/src/main/java/dev/coph/nextusweb/server/annotation/AnnotationScanner.java new file mode 100644 index 0000000..ec464cc --- /dev/null +++ b/src/main/java/dev/coph/nextusweb/server/annotation/AnnotationScanner.java @@ -0,0 +1,103 @@ +package dev.coph.nextusweb.server.annotation; + +import dev.coph.nextusweb.server.router.Request; +import dev.coph.nextusweb.server.router.Response; +import dev.coph.nextusweb.server.router.Router; +import io.netty.handler.codec.http.HttpMethod; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.lang.reflect.Method; + +public final class AnnotationScanner { + + private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup(); + private static final MethodType HANDLER_TYPE = + MethodType.methodType(void.class, Request.class, Response.class); + + private AnnotationScanner() { + } + + public static void register(Router router, Object controller) { + Class clazz = controller.getClass(); + Controller ctrlAnno = clazz.getAnnotation(Controller.class); + if (ctrlAnno == null) { + throw new IllegalArgumentException( + clazz.getName() + " ist nicht mit @Controller annotiert"); + } + String prefix = normalizePrefix(ctrlAnno.value()); + + for (Method method : clazz.getDeclaredMethods()) { + RouteInfo info = extractRoute(method); + if (info == null) continue; + + validateSignature(method); + + try { + method.setAccessible(true); + MethodHandle mh = LOOKUP.unreflect(method).bindTo(controller); + + Router.Handler handler = (req, res) -> { + try { + mh.invokeExact(req, res); + } catch (Throwable t) { + if (t instanceof Exception e) throw e; + throw new RuntimeException(t); + } + }; + + String fullPath = prefix + normalizePath(info.path()); + router.register(HttpMethod.valueOf(info.method()), fullPath, handler); + System.out.printf("Registered: %-6s %-30s -> %s.%s%n", + info.method(), fullPath, clazz.getSimpleName(), method.getName()); + + } catch (IllegalAccessException e) { + throw new RuntimeException("Konnte Methode nicht registrieren: " + method, e); + } + } + } + + private static String normalizePrefix(String p) { + if (p == null || p.isEmpty()) return ""; + return p.startsWith("/") ? p : "/" + p; + } + + private static RouteInfo extractRoute(Method m) { + Route r = m.getAnnotation(Route.class); + if (r != null) return new RouteInfo(r.method(), r.path()); + + GET get = m.getAnnotation(GET.class); + if (get != null) return new RouteInfo("GET", get.value()); + + POST post = m.getAnnotation(POST.class); + if (post != null) return new RouteInfo("POST", post.value()); + + PUT put = m.getAnnotation(PUT.class); + if (put != null) return new RouteInfo("PUT", put.value()); + + DELETE del = m.getAnnotation(DELETE.class); + if (del != null) return new RouteInfo("DELETE", del.value()); + + return null; + } + + private static void validateSignature(Method m) { + Class[] params = m.getParameterTypes(); + if (params.length != 2 || params[0] != Request.class || params[1] != Response.class) { + throw new IllegalArgumentException( + "Handler-Methode " + m + " muss Signatur (Request, Response) haben"); + } + if (m.getReturnType() != void.class) { + throw new IllegalArgumentException( + "Handler-Methode " + m + " muss void zurückgeben"); + } + } + + private static String normalizePath(String p) { + if (p == null || p.isEmpty()) return ""; + return p.startsWith("/") ? p : "/" + p; + } + + private record RouteInfo(String method, String path) { + } +} \ No newline at end of file diff --git a/src/main/java/dev/coph/nextusweb/server/annotation/Controller.java b/src/main/java/dev/coph/nextusweb/server/annotation/Controller.java new file mode 100644 index 0000000..a3d9e96 --- /dev/null +++ b/src/main/java/dev/coph/nextusweb/server/annotation/Controller.java @@ -0,0 +1,12 @@ +package dev.coph.nextusweb.server.annotation; + +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 Controller { + String value() default ""; +} \ No newline at end of file diff --git a/src/main/java/dev/coph/nextusweb/server/annotation/DELETE.java b/src/main/java/dev/coph/nextusweb/server/annotation/DELETE.java new file mode 100644 index 0000000..87d69e0 --- /dev/null +++ b/src/main/java/dev/coph/nextusweb/server/annotation/DELETE.java @@ -0,0 +1,12 @@ +package dev.coph.nextusweb.server.annotation; + +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.METHOD) +public @interface DELETE { + String value(); +} \ No newline at end of file diff --git a/src/main/java/dev/coph/nextusweb/server/annotation/GET.java b/src/main/java/dev/coph/nextusweb/server/annotation/GET.java new file mode 100644 index 0000000..41bbfd7 --- /dev/null +++ b/src/main/java/dev/coph/nextusweb/server/annotation/GET.java @@ -0,0 +1,12 @@ +package dev.coph.nextusweb.server.annotation; + +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.METHOD) +public @interface GET { + String value(); +} \ No newline at end of file diff --git a/src/main/java/dev/coph/nextusweb/server/annotation/POST.java b/src/main/java/dev/coph/nextusweb/server/annotation/POST.java new file mode 100644 index 0000000..0883f2a --- /dev/null +++ b/src/main/java/dev/coph/nextusweb/server/annotation/POST.java @@ -0,0 +1,12 @@ +package dev.coph.nextusweb.server.annotation; + +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.METHOD) +public @interface POST { + String value(); +} \ No newline at end of file diff --git a/src/main/java/dev/coph/nextusweb/server/annotation/PUT.java b/src/main/java/dev/coph/nextusweb/server/annotation/PUT.java new file mode 100644 index 0000000..df31d97 --- /dev/null +++ b/src/main/java/dev/coph/nextusweb/server/annotation/PUT.java @@ -0,0 +1,12 @@ +package dev.coph.nextusweb.server.annotation; + +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.METHOD) +public @interface PUT { + String value(); +} \ No newline at end of file diff --git a/src/main/java/dev/coph/nextusweb/server/annotation/Route.java b/src/main/java/dev/coph/nextusweb/server/annotation/Route.java new file mode 100644 index 0000000..5ba56af --- /dev/null +++ b/src/main/java/dev/coph/nextusweb/server/annotation/Route.java @@ -0,0 +1,14 @@ +package dev.coph.nextusweb.server.annotation; + +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.METHOD) +public @interface Route { + String method(); + + String path(); +} \ No newline at end of file diff --git a/src/main/java/dev/coph/nextusweb/server/json/Json.java b/src/main/java/dev/coph/nextusweb/server/json/Json.java new file mode 100644 index 0000000..f149b27 --- /dev/null +++ b/src/main/java/dev/coph/nextusweb/server/json/Json.java @@ -0,0 +1,14 @@ +package dev.coph.nextusweb.server.json; + +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + + + +public final class Json { + public static final ObjectMapper MAPPER = JsonMapper.builder() + // .addModule(new JavaTimeModule()) + .build(); + + private Json() {} +} \ No newline at end of file diff --git a/src/main/java/dev/coph/nextusweb/server/router/Request.java b/src/main/java/dev/coph/nextusweb/server/router/Request.java new file mode 100644 index 0000000..c82c58f --- /dev/null +++ b/src/main/java/dev/coph/nextusweb/server/router/Request.java @@ -0,0 +1,86 @@ +package dev.coph.nextusweb.server.router; + +import dev.coph.nextusweb.server.json.Json; +import dev.coph.nextusweb.server.router.exception.BadRequestException; +import io.netty.handler.codec.http.*; +import io.netty.util.CharsetUtil; +import tools.jackson.core.JacksonException; +import tools.jackson.databind.JsonNode; + +import java.util.*; + +public final class Request { + + private final FullHttpRequest raw; + private final Map pathParams; + private Map> queryParams; + private JsonNode jsonCache; + + public Request(FullHttpRequest raw, Map pathParams) { + this.raw = raw; + this.pathParams = pathParams; + } + + public String pathParam(String name) { + return pathParams.get(name); + } + + public String queryParam(String name) { + if (queryParams == null) { + queryParams = new QueryStringDecoder(raw.uri()).parameters(); + } + var values = queryParams.get(name); + return values == null || values.isEmpty() ? null : values.getFirst(); + } + + public List queryParams(String name) { + if (queryParams == null) { + queryParams = new QueryStringDecoder(raw.uri()).parameters(); + } + return queryParams.getOrDefault(name, List.of()); + } + + public String header(String name) { + return raw.headers().get(name); + } + + public String body() { + return raw.content().toString(CharsetUtil.UTF_8); + } + + public JsonNode json() { + if (jsonCache == null) { + try { + byte[] bytes = new byte[raw.content().readableBytes()]; + raw.content().getBytes(raw.content().readerIndex(), bytes); + if (bytes.length == 0) { + jsonCache = Json.MAPPER.nullNode(); + } else { + jsonCache = Json.MAPPER.readTree(bytes); + } + } catch (JacksonException e) { + throw new BadRequestException("Invalid JSON: " + e.getOriginalMessage()); + } + } + return jsonCache; + } + + public T jsonAs(Class type) { + try { + byte[] bytes = new byte[raw.content().readableBytes()]; + raw.content().getBytes(raw.content().readerIndex(), bytes); + return Json.MAPPER.readValue(bytes, type); + } catch (JacksonException e) { + throw new BadRequestException( + "Could not deserialize body as " + type.getSimpleName() + ": " + e.getOriginalMessage()); + } + } + + public HttpMethod method() { + return raw.method(); + } + + public String path() { + return new QueryStringDecoder(raw.uri()).path(); + } +} \ No newline at end of file diff --git a/src/main/java/dev/coph/nextusweb/server/router/Response.java b/src/main/java/dev/coph/nextusweb/server/router/Response.java new file mode 100644 index 0000000..88eec36 --- /dev/null +++ b/src/main/java/dev/coph/nextusweb/server/router/Response.java @@ -0,0 +1,46 @@ +package dev.coph.nextusweb.server.router; + +import dev.coph.nextusweb.server.json.Json; +import io.netty.handler.codec.http.*; +import io.netty.util.CharsetUtil; +import tools.jackson.core.JacksonException; + +public final class Response { + + private int status = 200; + private final HttpHeaders headers = new DefaultHttpHeaders(); + private byte[] body = new byte[0]; + + public Response status(int s) { this.status = s; return this; } + + public Response header(String name, String value) { + headers.set(name, value); + return this; + } + + public Response text(String s) { + this.body = s.getBytes(CharsetUtil.UTF_8); + headers.set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=utf-8"); + return this; + } + + public Response json(String json) { + this.body = json.getBytes(CharsetUtil.UTF_8); + headers.set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=utf-8"); + return this; + } + + public Response json(Object value) { + try { + this.body = Json.MAPPER.writeValueAsBytes(value); + headers.set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=utf-8"); + } catch (JacksonException e) { + throw new RuntimeException("JSON serialization failed", e); + } + return this; + } + + public int status() { return status; } + public HttpHeaders headers() { return headers; } + public byte[] body() { return body; } +} \ No newline at end of file diff --git a/src/main/java/dev/coph/nextusweb/server/router/Router.java b/src/main/java/dev/coph/nextusweb/server/router/Router.java new file mode 100644 index 0000000..8022d89 --- /dev/null +++ b/src/main/java/dev/coph/nextusweb/server/router/Router.java @@ -0,0 +1,132 @@ +package dev.coph.nextusweb.server.router; + +import io.netty.handler.codec.http.HttpMethod; + +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.BiConsumer; + +public final class Router { + + private final Node root = new Node(); + private final List> middlewares = new ArrayList<>(); + + public Router use(BiConsumer middleware) { + middlewares.add(middleware); + return this; + } + + public Router get(String path, Handler h) { + return register(HttpMethod.GET, path, h); + } + + public Router register(HttpMethod method, String path, Handler h) { + Node node = root; + for (String segment : split(path)) { + if (segment.startsWith("{") && segment.endsWith("}")) { + if (node.paramChild == null) { + node.paramChild = new Node(); + node.paramName = segment.substring(1, segment.length() - 1); + } + node = node.paramChild; + } else if (segment.equals("*")) { + if (node.wildcardChild == null) node.wildcardChild = new Node(); + node = node.wildcardChild; + } else { + node = node.children.computeIfAbsent(segment, k -> new Node()); + } + } + node.handlers.put(method, h); + return this; + } + + private static List split(String path) { + List out = new ArrayList<>(); + int start = path.startsWith("/") ? 1 : 0; + for (int i = start; i < path.length(); i++) { + if (path.charAt(i) == '/') { + if (i > start) out.add(path.substring(start, i)); + start = i + 1; + } + } + if (start < path.length()) out.add(path.substring(start)); + return out; + } + + public Router post(String path, Handler h) { + return register(HttpMethod.POST, path, h); + } + + public Router put(String path, Handler h) { + return register(HttpMethod.PUT, path, h); + } + + public Router delete(String path, Handler h) { + return register(HttpMethod.DELETE, path, h); + } + + /** + * Resolve den Pfad zu einem Handler. Liefert: + * - Match wenn Pfad + Methode passen + * - MethodNotAllowed wenn der Pfad existiert, aber nicht für diese Methode + * - NotFound wenn der Pfad gar nicht registriert ist + */ + public Resolution resolve(HttpMethod method, String path) { + Map params = new HashMap<>(4); + Node node = root; + for (String segment : split(path)) { + Node next = node.children.get(segment); + if (next != null) { + node = next; + } else if (node.paramChild != null) { + params.put(node.paramName, segment); + node = node.paramChild; + } else if (node.wildcardChild != null) { + node = node.wildcardChild; + } else { + return new Resolution.NotFound(); + } + } + + Handler h = node.handlers.get(method); + if (h != null) { + return new Resolution.Match(h, params); + } + + // Pfad existiert, aber nicht für diese Methode + if (!node.handlers.isEmpty()) { + return new Resolution.MethodNotAllowed( + Collections.unmodifiableSet(node.handlers.keySet())); + } + + return new Resolution.NotFound(); + } + + public List> middlewares() { + return middlewares; + } + + public sealed interface Resolution { + record Match(Handler handler, Map pathParams) implements Resolution { + } + + record MethodNotAllowed(Set allowedMethods) implements Resolution { + } + + record NotFound() implements Resolution { + } + } + + @FunctionalInterface + public interface Handler { + void handle(Request req, Response res) throws Exception; + } + + private static final class Node { + final Map children = new ConcurrentHashMap<>(); + final Map handlers = new ConcurrentHashMap<>(); + Node paramChild; // für {id} + String paramName; + Node wildcardChild; // für * + } +} \ No newline at end of file diff --git a/src/main/java/dev/coph/nextusweb/server/router/exception/BadRequestException.java b/src/main/java/dev/coph/nextusweb/server/router/exception/BadRequestException.java new file mode 100644 index 0000000..da55197 --- /dev/null +++ b/src/main/java/dev/coph/nextusweb/server/router/exception/BadRequestException.java @@ -0,0 +1,5 @@ +package dev.coph.nextusweb.server.router.exception; + +public final class BadRequestException extends RuntimeException { + public BadRequestException(String message) { super(message); } +} \ No newline at end of file