Initial Commit
This commit is contained in:
+57
@@ -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
|
||||||
Generated
+10
@@ -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
|
||||||
Generated
+16
@@ -0,0 +1,16 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="GradleSettings">
|
||||||
|
<option name="linkedExternalProjectsSettings">
|
||||||
|
<GradleProjectSettings>
|
||||||
|
<option name="externalProjectPath" value="$PROJECT_DIR$" />
|
||||||
|
<option name="modules">
|
||||||
|
<set>
|
||||||
|
<option value="$PROJECT_DIR$" />
|
||||||
|
</set>
|
||||||
|
</option>
|
||||||
|
<option name="myGradleHome" value="" />
|
||||||
|
</GradleProjectSettings>
|
||||||
|
</option>
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
Generated
+10
@@ -0,0 +1,10 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
||||||
|
<component name="FrameworkDetectionExcludesConfiguration">
|
||||||
|
<file type="web" url="file://$PROJECT_DIR$" />
|
||||||
|
</component>
|
||||||
|
<component name="ProjectRootManager" version="2" languageLevel="JDK_26" default="true" project-jdk-name="openjdk-26" project-jdk-type="JavaSDK">
|
||||||
|
<output url="file://$PROJECT_DIR$/out" />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
Generated
+6
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="VcsDirectoryMappings">
|
||||||
|
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
@@ -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'
|
||||||
|
}
|
||||||
|
|
||||||
Vendored
BIN
Binary file not shown.
+6
@@ -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
|
||||||
@@ -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" "$@"
|
||||||
Vendored
+89
@@ -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
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
rootProject.name = 'NexusWeb'
|
||||||
@@ -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<FullHttpRequest> {
|
||||||
|
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<? extends ServerChannel> 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<SocketChannel>() {
|
||||||
|
@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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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) {
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 "";
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
@@ -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() {}
|
||||||
|
}
|
||||||
@@ -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<String, String> pathParams;
|
||||||
|
private Map<String, List<String>> queryParams;
|
||||||
|
private JsonNode jsonCache;
|
||||||
|
|
||||||
|
public Request(FullHttpRequest raw, Map<String, String> 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<String> 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> T jsonAs(Class<T> 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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; }
|
||||||
|
}
|
||||||
@@ -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<BiConsumer<Request, Response>> middlewares = new ArrayList<>();
|
||||||
|
|
||||||
|
public Router use(BiConsumer<Request, Response> 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<String> split(String path) {
|
||||||
|
List<String> 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<String, String> 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<BiConsumer<Request, Response>> middlewares() {
|
||||||
|
return middlewares;
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed interface Resolution {
|
||||||
|
record Match(Handler handler, Map<String, String> pathParams) implements Resolution {
|
||||||
|
}
|
||||||
|
|
||||||
|
record MethodNotAllowed(Set<HttpMethod> 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<String, Node> children = new ConcurrentHashMap<>();
|
||||||
|
final Map<HttpMethod, Handler> handlers = new ConcurrentHashMap<>();
|
||||||
|
Node paramChild; // für {id}
|
||||||
|
String paramName;
|
||||||
|
Node wildcardChild; // für *
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
package dev.coph.nextusweb.server.router.exception;
|
||||||
|
|
||||||
|
public final class BadRequestException extends RuntimeException {
|
||||||
|
public BadRequestException(String message) { super(message); }
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user