upgrade to Gradle 8.0.2, simplify module methods, simplify thread pool, cleanup router
This commit is contained in:
parent
93ac72ea0c
commit
43558479e7
28 changed files with 194 additions and 259 deletions
21
build.gradle
21
build.gradle
|
@ -1,22 +1,13 @@
|
||||||
buildscript {
|
|
||||||
repositories {
|
|
||||||
maven {
|
|
||||||
url 'https://xbib.org/repository'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
dependencies {
|
|
||||||
classpath "org.xbib.gradle.plugin:gradle-plugin-shadow:1.1.1"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
plugins {
|
plugins {
|
||||||
id "de.marcphilipp.nexus-publish" version "0.4.0"
|
|
||||||
id "io.codearte.nexus-staging" version "0.21.1"
|
|
||||||
id "org.xbib.gradle.plugin.asciidoctor" version "2.5.2.1"
|
|
||||||
id "org.cyclonedx.bom" version "1.7.2"
|
|
||||||
id "com.github.spotbugs" version "5.0.13"
|
|
||||||
id "checkstyle"
|
id "checkstyle"
|
||||||
id "pmd"
|
id "pmd"
|
||||||
|
id 'maven-publish'
|
||||||
|
id 'signing'
|
||||||
|
id "io.github.gradle-nexus.publish-plugin" version "1.3.0"
|
||||||
|
id "com.github.spotbugs" version "5.0.14"
|
||||||
|
id "org.cyclonedx.bom" version "1.7.2"
|
||||||
|
id "org.xbib.gradle.plugin.asciidoctor" version "2.5.2.2"
|
||||||
}
|
}
|
||||||
|
|
||||||
wrapper {
|
wrapper {
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
group = org.xbib
|
group = org.xbib
|
||||||
name = net-http
|
name = net-http
|
||||||
version = 3.1.0
|
version = 3.2.0
|
||||||
|
|
||||||
org.gradle.warning.mode = ALL
|
org.gradle.warning.mode = ALL
|
||||||
|
|
|
@ -2,6 +2,8 @@ apply plugin: 'java-library'
|
||||||
|
|
||||||
java {
|
java {
|
||||||
modularity.inferModulePath.set(true)
|
modularity.inferModulePath.set(true)
|
||||||
|
withSourcesJar()
|
||||||
|
withJavadocJar()
|
||||||
}
|
}
|
||||||
|
|
||||||
compileJava {
|
compileJava {
|
||||||
|
@ -21,20 +23,6 @@ jar {
|
||||||
duplicatesStrategy = DuplicatesStrategy.INCLUDE
|
duplicatesStrategy = DuplicatesStrategy.INCLUDE
|
||||||
}
|
}
|
||||||
|
|
||||||
task sourcesJar(type: Jar, dependsOn: classes) {
|
|
||||||
classifier 'sources'
|
|
||||||
from sourceSets.main.allSource
|
|
||||||
}
|
|
||||||
|
|
||||||
task javadocJar(type: Jar, dependsOn: javadoc) {
|
|
||||||
classifier 'javadoc'
|
|
||||||
from javadoc.destinationDir
|
|
||||||
}
|
|
||||||
|
|
||||||
artifacts {
|
|
||||||
archives sourcesJar, javadocJar
|
|
||||||
}
|
|
||||||
|
|
||||||
tasks.withType(JavaCompile) {
|
tasks.withType(JavaCompile) {
|
||||||
options.compilerArgs.add('-Xlint:all,-exports')
|
options.compilerArgs.add('-Xlint:all,-exports')
|
||||||
options.encoding = 'UTF-8'
|
options.encoding = 'UTF-8'
|
||||||
|
|
|
@ -1,13 +1,10 @@
|
||||||
|
|
||||||
apply plugin: "de.marcphilipp.nexus-publish"
|
|
||||||
|
|
||||||
publishing {
|
publishing {
|
||||||
publications {
|
publications {
|
||||||
mavenJava(MavenPublication) {
|
"${project.name}"(MavenPublication) {
|
||||||
from components.java
|
from components.java
|
||||||
artifact sourcesJar
|
|
||||||
artifact javadocJar
|
|
||||||
pom {
|
pom {
|
||||||
|
artifactId = project.name
|
||||||
name = project.name
|
name = project.name
|
||||||
description = rootProject.ext.description
|
description = rootProject.ext.description
|
||||||
url = rootProject.ext.url
|
url = rootProject.ext.url
|
||||||
|
@ -49,18 +46,6 @@ publishing {
|
||||||
if (project.hasProperty("signing.keyId")) {
|
if (project.hasProperty("signing.keyId")) {
|
||||||
apply plugin: 'signing'
|
apply plugin: 'signing'
|
||||||
signing {
|
signing {
|
||||||
sign publishing.publications.mavenJava
|
sign publishing.publications."${project.name}"
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (project.hasProperty('ossrhUsername') && project.hasProperty('ossrhPassword')) {
|
|
||||||
nexusPublishing {
|
|
||||||
repositories {
|
|
||||||
sonatype {
|
|
||||||
username = project.property('ossrhUsername')
|
|
||||||
password = project.property('ossrhPassword')
|
|
||||||
packageGroup = "org.xbib"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,11 +1,11 @@
|
||||||
|
|
||||||
if (project.hasProperty('ossrhUsername') && project.hasProperty('ossrhPassword')) {
|
if (project.hasProperty('ossrhUsername') && project.hasProperty('ossrhPassword')) {
|
||||||
|
nexusPublishing {
|
||||||
apply plugin: 'io.codearte.nexus-staging'
|
repositories {
|
||||||
|
sonatype {
|
||||||
nexusStaging {
|
username = project.property('ossrhUsername')
|
||||||
username = project.property('ossrhUsername')
|
password = project.property('ossrhPassword')
|
||||||
password = project.property('ossrhPassword')
|
packageGroup = "org.xbib"
|
||||||
packageGroup = "org.xbib"
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Binary file not shown.
3
gradle/wrapper/gradle-wrapper.properties
vendored
3
gradle/wrapper/gradle-wrapper.properties
vendored
|
@ -1,5 +1,6 @@
|
||||||
distributionBase=GRADLE_USER_HOME
|
distributionBase=GRADLE_USER_HOME
|
||||||
distributionPath=wrapper/dists
|
distributionPath=wrapper/dists
|
||||||
distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-all.zip
|
distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.2-all.zip
|
||||||
|
networkTimeout=10000
|
||||||
zipStoreBase=GRADLE_USER_HOME
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
zipStorePath=wrapper/dists
|
zipStorePath=wrapper/dists
|
||||||
|
|
12
gradlew
vendored
12
gradlew
vendored
|
@ -55,7 +55,7 @@
|
||||||
# Darwin, MinGW, and NonStop.
|
# Darwin, MinGW, and NonStop.
|
||||||
#
|
#
|
||||||
# (3) This script is generated from the Groovy template
|
# (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
|
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||||
# within the Gradle project.
|
# within the Gradle project.
|
||||||
#
|
#
|
||||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||||
|
@ -80,10 +80,10 @@ do
|
||||||
esac
|
esac
|
||||||
done
|
done
|
||||||
|
|
||||||
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
|
# This is normally unused
|
||||||
|
# shellcheck disable=SC2034
|
||||||
APP_NAME="Gradle"
|
|
||||||
APP_BASE_NAME=${0##*/}
|
APP_BASE_NAME=${0##*/}
|
||||||
|
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
|
||||||
|
|
||||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
# 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"'
|
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||||
|
@ -143,12 +143,16 @@ fi
|
||||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||||
case $MAX_FD in #(
|
case $MAX_FD in #(
|
||||||
max*)
|
max*)
|
||||||
|
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||||
|
# shellcheck disable=SC3045
|
||||||
MAX_FD=$( ulimit -H -n ) ||
|
MAX_FD=$( ulimit -H -n ) ||
|
||||||
warn "Could not query maximum file descriptor limit"
|
warn "Could not query maximum file descriptor limit"
|
||||||
esac
|
esac
|
||||||
case $MAX_FD in #(
|
case $MAX_FD in #(
|
||||||
'' | soft) :;; #(
|
'' | soft) :;; #(
|
||||||
*)
|
*)
|
||||||
|
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||||
|
# shellcheck disable=SC3045
|
||||||
ulimit -n "$MAX_FD" ||
|
ulimit -n "$MAX_FD" ||
|
||||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||||
esac
|
esac
|
||||||
|
|
1
gradlew.bat
vendored
1
gradlew.bat
vendored
|
@ -26,6 +26,7 @@ if "%OS%"=="Windows_NT" setlocal
|
||||||
|
|
||||||
set DIRNAME=%~dp0
|
set DIRNAME=%~dp0
|
||||||
if "%DIRNAME%"=="" set DIRNAME=.
|
if "%DIRNAME%"=="" set DIRNAME=.
|
||||||
|
@rem This is normally unused
|
||||||
set APP_BASE_NAME=%~n0
|
set APP_BASE_NAME=%~n0
|
||||||
set APP_HOME=%DIRNAME%
|
set APP_HOME=%DIRNAME%
|
||||||
|
|
||||||
|
|
|
@ -6,9 +6,9 @@ import org.xbib.config.ConfigLoader;
|
||||||
import org.xbib.config.ConfigLogger;
|
import org.xbib.config.ConfigLogger;
|
||||||
import org.xbib.config.ConfigParams;
|
import org.xbib.config.ConfigParams;
|
||||||
import org.xbib.config.SystemConfigLogger;
|
import org.xbib.config.SystemConfigLogger;
|
||||||
|
import org.xbib.net.http.server.HttpRequest;
|
||||||
import org.xbib.net.http.server.application.Application;
|
import org.xbib.net.http.server.application.Application;
|
||||||
import org.xbib.net.http.server.application.BaseApplicationModule;
|
import org.xbib.net.http.server.application.BaseApplicationModule;
|
||||||
import org.xbib.net.http.server.HttpRequest;
|
|
||||||
import org.xbib.net.http.server.HttpServerContext;
|
import org.xbib.net.http.server.HttpServerContext;
|
||||||
import org.xbib.net.http.server.service.HttpService;
|
import org.xbib.net.http.server.service.HttpService;
|
||||||
import org.xbib.settings.Settings;
|
import org.xbib.settings.Settings;
|
||||||
|
@ -24,27 +24,21 @@ public class ConfigApplicationModule extends BaseApplicationModule {
|
||||||
bootLogger = optionalBootLogger.orElse(new SystemConfigLogger());
|
bootLogger = optionalBootLogger.orElse(new SystemConfigLogger());
|
||||||
}
|
}
|
||||||
|
|
||||||
private ConfigParams configParams;
|
private final ConfigParams configParams;
|
||||||
|
|
||||||
private ConfigLoader configLoader;
|
private final ConfigLoader configLoader;
|
||||||
|
|
||||||
private Settings settings;
|
private final Settings settings;
|
||||||
|
|
||||||
public ConfigApplicationModule(Application application, String name, Settings settings) {
|
public ConfigApplicationModule(Application application, String name, Settings settings) {
|
||||||
super(application, name, settings);
|
super(application, name, settings);
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onOpen(Application application, Settings settings) {
|
|
||||||
String profile = System.getProperty("application.profile");
|
String profile = System.getProperty("application.profile");
|
||||||
if (profile == null) {
|
if (profile == null) {
|
||||||
profile = "developer";
|
profile = "developer";
|
||||||
}
|
}
|
||||||
String[] args = profile.split(";");
|
|
||||||
this.configParams = new ConfigParams()
|
this.configParams = new ConfigParams()
|
||||||
.withArgs(args)
|
.withDirectoryName(name)
|
||||||
.withDirectoryName("application")
|
.withFileNamesWithoutSuffix(profile)
|
||||||
.withFileNamesWithoutSuffix(args[0])
|
|
||||||
.withSystemEnvironment()
|
.withSystemEnvironment()
|
||||||
.withSystemProperties();
|
.withSystemProperties();
|
||||||
this.configLoader = ConfigLoader.getInstance()
|
this.configLoader = ConfigLoader.getInstance()
|
||||||
|
@ -53,14 +47,9 @@ public class ConfigApplicationModule extends BaseApplicationModule {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onOpen(Application application, HttpServerContext httpServerContext, HttpService httpService) {
|
public void onOpen(HttpServerContext httpServerContext, HttpService httpService, HttpRequest httpRequest) {
|
||||||
httpServerContext.getAttributes().put("configparams", configParams);
|
httpServerContext.getAttributes().put("configparams", configParams);
|
||||||
httpServerContext.getAttributes().put("configloader", configLoader);
|
httpServerContext.getAttributes().put("configloader", configLoader);
|
||||||
httpServerContext.getAttributes().put("settings", settings);
|
httpServerContext.getAttributes().put("settings", settings);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onOpen(Application application, HttpServerContext httpServerContext, HttpService httpService, HttpRequest httpRequest) {
|
|
||||||
// do nothing
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -16,20 +16,16 @@ import java.util.Properties;
|
||||||
import java.util.logging.Level;
|
import java.util.logging.Level;
|
||||||
import java.util.logging.Logger;
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
public class DatabaseApplicationModule<A extends Application> extends BaseApplicationModule {
|
public class DatabaseApplicationModule extends BaseApplicationModule {
|
||||||
|
|
||||||
private static final Logger logger = Logger.getLogger(DatabaseApplicationModule.class.getName());
|
private static final Logger logger = Logger.getLogger(DatabaseApplicationModule.class.getName());
|
||||||
|
|
||||||
private DataSource dataSource;
|
private final DataSource dataSource;
|
||||||
|
|
||||||
private DatabaseProvider databaseProvider;
|
private final DatabaseProvider databaseProvider;
|
||||||
|
|
||||||
public DatabaseApplicationModule(Application application, String name, Settings settings) {
|
public DatabaseApplicationModule(Application application, String name, Settings settings) {
|
||||||
super(application, name, settings);
|
super(application, name, settings);
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onOpen(Application application, Settings settings) throws Exception {
|
|
||||||
this.dataSource = createDataSource();
|
this.dataSource = createDataSource();
|
||||||
String flavor = System.getProperty("database.flavor");
|
String flavor = System.getProperty("database.flavor");
|
||||||
this.databaseProvider = flavor != null ?
|
this.databaseProvider = flavor != null ?
|
||||||
|
@ -37,7 +33,7 @@ public class DatabaseApplicationModule<A extends Application> extends BaseApplic
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onOpen(Application application, HttpServerContext httpServerContext, HttpService httpService) {
|
public void onOpen(HttpServerContext httpServerContext, HttpService httpService, HttpRequest httpRequest) {
|
||||||
if (dataSource != null) {
|
if (dataSource != null) {
|
||||||
httpServerContext.getAttributes().put("datasource", dataSource);
|
httpServerContext.getAttributes().put("datasource", dataSource);
|
||||||
}
|
}
|
||||||
|
@ -46,12 +42,7 @@ public class DatabaseApplicationModule<A extends Application> extends BaseApplic
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
private DataSource createDataSource() {
|
||||||
public void onOpen(Application application, HttpServerContext httpServerContext, HttpService httpService, HttpRequest httpRequest) {
|
|
||||||
// nothing
|
|
||||||
}
|
|
||||||
|
|
||||||
private DataSource createDataSource() throws Exception {
|
|
||||||
Properties properties = new Properties();
|
Properties properties = new Properties();
|
||||||
System.getProperties().forEach((key, value) -> {
|
System.getProperties().forEach((key, value) -> {
|
||||||
if (key.toString().startsWith("database.") && !key.toString().equals("database.flavor")) {
|
if (key.toString().startsWith("database.") && !key.toString().equals("database.flavor")) {
|
||||||
|
@ -72,7 +63,11 @@ public class DatabaseApplicationModule<A extends Application> extends BaseApplic
|
||||||
config.setConnectionTimeout(getAsLong(properties, "timeout", 15L * 1000L)); // 15 seconds
|
config.setConnectionTimeout(getAsLong(properties, "timeout", 15L * 1000L)); // 15 seconds
|
||||||
config.setHousekeepingPeriodMs(getAsLong(properties, "housekeeping", 600L * 1000L)); // 10 minutes
|
config.setHousekeepingPeriodMs(getAsLong(properties, "housekeeping", 600L * 1000L)); // 10 minutes
|
||||||
config.setAutoCommit(getAsBoolean(properties, "autocommit", true));
|
config.setAutoCommit(getAsBoolean(properties, "autocommit", true));
|
||||||
return new PoolDataSource(config);
|
try {
|
||||||
|
return new PoolDataSource(config);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new IllegalStateException(e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private int getAsInt(Properties properties, String key, int defaultValue) {
|
private int getAsInt(Properties properties, String key, int defaultValue) {
|
||||||
|
|
|
@ -67,7 +67,7 @@ public class NettyHttpServer implements HttpServer {
|
||||||
logger.log(Level.FINE, "parent event loop group = " + parentEventLoopGroup +
|
logger.log(Level.FINE, "parent event loop group = " + parentEventLoopGroup +
|
||||||
" child event loop group = " + childEventLoopGroup +
|
" child event loop group = " + childEventLoopGroup +
|
||||||
" socket channel class = " + socketChannelClass +
|
" socket channel class = " + socketChannelClass +
|
||||||
" router addresses = " + getApplication().getAddresses());
|
" router addresses = " + builder.application.getAddresses());
|
||||||
}
|
}
|
||||||
|
|
||||||
public static NettyHttpServerBuilder builder() {
|
public static NettyHttpServerBuilder builder() {
|
||||||
|
@ -84,8 +84,8 @@ public class NettyHttpServer implements HttpServer {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void bind() throws BindException {
|
public void bind() throws BindException {
|
||||||
Set<HttpAddress> httpAddressSet = getApplication().getAddresses();
|
Set<HttpAddress> httpAddressSet = builder.application.getAddresses();
|
||||||
logger.log(Level.FINE, "http adresses = " + httpAddressSet);
|
logger.log(Level.FINE, "http addresses = " + httpAddressSet);
|
||||||
for (HttpAddress httpAddress : httpAddressSet) {
|
for (HttpAddress httpAddress : httpAddressSet) {
|
||||||
SocketConfig socketConfig = httpAddress.getSocketConfig();
|
SocketConfig socketConfig = httpAddress.getSocketConfig();
|
||||||
ServerBootstrap bootstrap = new ServerBootstrap()
|
ServerBootstrap bootstrap = new ServerBootstrap()
|
||||||
|
@ -198,8 +198,7 @@ public class NettyHttpServer implements HttpServer {
|
||||||
channelFuture.cancel(true);
|
channelFuture.cancel(true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// close application
|
builder.application.close();
|
||||||
getApplication().close();
|
|
||||||
logger.log(Level.INFO, "server shutdown complete");
|
logger.log(Level.INFO, "server shutdown complete");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -26,8 +26,6 @@ import java.util.Locale;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.concurrent.CountDownLatch;
|
import java.util.concurrent.CountDownLatch;
|
||||||
import java.util.concurrent.ExecutorService;
|
|
||||||
import java.util.concurrent.Executors;
|
|
||||||
import java.util.logging.Level;
|
import java.util.logging.Level;
|
||||||
import java.util.logging.Logger;
|
import java.util.logging.Logger;
|
||||||
import java.util.regex.Matcher;
|
import java.util.regex.Matcher;
|
||||||
|
@ -39,13 +37,10 @@ public class NioHttpServer implements HttpServer {
|
||||||
|
|
||||||
private final NioHttpServerBuilder builder;
|
private final NioHttpServerBuilder builder;
|
||||||
|
|
||||||
private final ExecutorService workerPool;
|
|
||||||
|
|
||||||
private final Map<HttpAddress, ServerSocketChannel> serverSockets;
|
private final Map<HttpAddress, ServerSocketChannel> serverSockets;
|
||||||
|
|
||||||
NioHttpServer(NioHttpServerBuilder builder) {
|
NioHttpServer(NioHttpServerBuilder builder) {
|
||||||
this.builder = builder;
|
this.builder = builder;
|
||||||
this.workerPool = Executors.newCachedThreadPool();
|
|
||||||
this.serverSockets = new HashMap<>();
|
this.serverSockets = new HashMap<>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -55,7 +50,7 @@ public class NioHttpServer implements HttpServer {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void bind() throws BindException {
|
public void bind() throws BindException {
|
||||||
for (HttpAddress httpAddress : getApplication().getAddresses()) {
|
for (HttpAddress httpAddress : builder.application.getAddresses()) {
|
||||||
try {
|
try {
|
||||||
logger.log(Level.INFO, () -> "trying to bind to " + httpAddress);
|
logger.log(Level.INFO, () -> "trying to bind to " + httpAddress);
|
||||||
ServerSocketChannel channel = ServerSocketChannel.open();
|
ServerSocketChannel channel = ServerSocketChannel.open();
|
||||||
|
@ -106,7 +101,7 @@ public class NioHttpServer implements HttpServer {
|
||||||
httpAddress,
|
httpAddress,
|
||||||
(InetSocketAddress) socketChannel.getLocalAddress(),
|
(InetSocketAddress) socketChannel.getLocalAddress(),
|
||||||
(InetSocketAddress) socketChannel.getRemoteAddress());
|
(InetSocketAddress) socketChannel.getRemoteAddress());
|
||||||
handle(requestBuilder, responseBuilder);
|
builder.application.dispatch(requestBuilder, responseBuilder);
|
||||||
socketChannel.close();
|
socketChannel.close();
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
logger.log(Level.SEVERE, e.getMessage(), e);
|
logger.log(Level.SEVERE, e.getMessage(), e);
|
||||||
|
@ -137,10 +132,6 @@ public class NioHttpServer implements HttpServer {
|
||||||
return builder.application;
|
return builder.application;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void handle(HttpRequestBuilder httpRequestBuilder, HttpResponseBuilder httpResponseBuilder) throws IOException {
|
|
||||||
getApplication().dispatch(httpRequestBuilder, httpResponseBuilder);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void close() throws IOException {
|
public void close() throws IOException {
|
||||||
for (Map.Entry<HttpAddress, ServerSocketChannel> entry : serverSockets.entrySet()) {
|
for (Map.Entry<HttpAddress, ServerSocketChannel> entry : serverSockets.entrySet()) {
|
||||||
|
|
|
@ -55,7 +55,7 @@ public class SimpleHttpServer implements HttpServer {
|
||||||
@Override
|
@Override
|
||||||
public void bind() throws BindException {
|
public void bind() throws BindException {
|
||||||
// bind only once per HttpAddress in all domains
|
// bind only once per HttpAddress in all domains
|
||||||
for (HttpAddress httpAddress : getApplication().getAddresses()) {
|
for (HttpAddress httpAddress : builder.application.getAddresses()) {
|
||||||
logger.log(Level.INFO, () -> "trying to bind to " + httpAddress);
|
logger.log(Level.INFO, () -> "trying to bind to " + httpAddress);
|
||||||
try {
|
try {
|
||||||
InetSocketAddress inetSocketAddress = httpAddress.getInetSocketAddress();
|
InetSocketAddress inetSocketAddress = httpAddress.getInetSocketAddress();
|
||||||
|
@ -76,7 +76,7 @@ public class SimpleHttpServer implements HttpServer {
|
||||||
if (serverSocket.isBound()) {
|
if (serverSocket.isBound()) {
|
||||||
serverSockets.put(httpAddress, serverSocket);
|
serverSockets.put(httpAddress, serverSocket);
|
||||||
logger.log(Level.INFO, () -> "server socket = " + serverSocket +
|
logger.log(Level.INFO, () -> "server socket = " + serverSocket +
|
||||||
" domains = " + getApplication().getAddresses() + " bound, listening on " + inetSocketAddress);
|
" domains = " + builder.application.getAddresses() + " bound, listening on " + inetSocketAddress);
|
||||||
} else {
|
} else {
|
||||||
logger.log(Level.WARNING, "server socket " + serverSocket + " not bound, something is wrong");
|
logger.log(Level.WARNING, "server socket " + serverSocket + " not bound, something is wrong");
|
||||||
}
|
}
|
||||||
|
@ -108,7 +108,7 @@ public class SimpleHttpServer implements HttpServer {
|
||||||
httpAddress,
|
httpAddress,
|
||||||
(InetSocketAddress) socket.getLocalSocketAddress(),
|
(InetSocketAddress) socket.getLocalSocketAddress(),
|
||||||
(InetSocketAddress) socket.getRemoteSocketAddress());
|
(InetSocketAddress) socket.getRemoteSocketAddress());
|
||||||
getApplication().dispatch(httpRequestBuilder, httpResponseBuilder);
|
builder.application.dispatch(httpRequestBuilder, httpResponseBuilder);
|
||||||
} catch (Throwable t) {
|
} catch (Throwable t) {
|
||||||
logger.log(Level.SEVERE, t.getMessage(), t);
|
logger.log(Level.SEVERE, t.getMessage(), t);
|
||||||
} finally {
|
} finally {
|
||||||
|
|
|
@ -56,8 +56,7 @@ public class HttpRouterTest {
|
||||||
.setMethod(HttpMethod.DELETE)
|
.setMethod(HttpMethod.DELETE)
|
||||||
.setRequestURI("/demo")
|
.setRequestURI("/demo")
|
||||||
.addHeader(HttpHeaderNames.HOST, httpAddress.hostAndPort());
|
.addHeader(HttpHeaderNames.HOST, httpAddress.hostAndPort());
|
||||||
router.setApplication(BaseApplication.builder().build());
|
router.route(BaseApplication.builder().build(), httpRequest, httpResponse);
|
||||||
router.route(httpRequest, httpResponse);
|
|
||||||
String string = outputStream.toString(StandardCharsets.UTF_8);
|
String string = outputStream.toString(StandardCharsets.UTF_8);
|
||||||
Logger.getAnonymousLogger().log(Level.INFO, "the response string is = " + string);
|
Logger.getAnonymousLogger().log(Level.INFO, "the response string is = " + string);
|
||||||
assertTrue(string.contains("/demo"));
|
assertTrue(string.contains("/demo"));
|
||||||
|
|
|
@ -38,13 +38,19 @@ public interface Application extends SessionListener, Resolver<Path>, Closeable
|
||||||
Collection<ApplicationModule> getModules();
|
Collection<ApplicationModule> getModules();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Dispatch a regular request.
|
* Dispatch a request.
|
||||||
* @param requestBuilder the request
|
* @param requestBuilder the request
|
||||||
* @param responseBuilder the response
|
* @param responseBuilder the response
|
||||||
*/
|
*/
|
||||||
void dispatch(HttpRequestBuilder requestBuilder,
|
void dispatch(HttpRequestBuilder requestBuilder,
|
||||||
HttpResponseBuilder responseBuilder);
|
HttpResponseBuilder responseBuilder);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Dispatch a status.
|
||||||
|
* @param requestBuilder the request
|
||||||
|
* @param responseBuilder the response
|
||||||
|
* @param httpResponseStatus the status
|
||||||
|
*/
|
||||||
void dispatch(HttpRequestBuilder requestBuilder,
|
void dispatch(HttpRequestBuilder requestBuilder,
|
||||||
HttpResponseBuilder responseBuilder,
|
HttpResponseBuilder responseBuilder,
|
||||||
HttpResponseStatus httpResponseStatus);
|
HttpResponseStatus httpResponseStatus);
|
||||||
|
|
|
@ -3,6 +3,7 @@ package org.xbib.net.http.server.application;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.time.ZoneId;
|
import java.time.ZoneId;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
|
import java.util.concurrent.ThreadPoolExecutor;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
import org.xbib.net.http.server.route.HttpRouter;
|
import org.xbib.net.http.server.route.HttpRouter;
|
||||||
import org.xbib.net.mime.MimeTypeService;
|
import org.xbib.net.mime.MimeTypeService;
|
||||||
|
@ -17,6 +18,8 @@ public interface ApplicationBuilder {
|
||||||
|
|
||||||
ApplicationBuilder setKeepAliveTimeUnit(TimeUnit keepAliveTimeUnit);
|
ApplicationBuilder setKeepAliveTimeUnit(TimeUnit keepAliveTimeUnit);
|
||||||
|
|
||||||
|
ApplicationBuilder setExecutor(ThreadPoolExecutor executor);
|
||||||
|
|
||||||
ApplicationBuilder setHome(Path home);
|
ApplicationBuilder setHome(Path home);
|
||||||
|
|
||||||
ApplicationBuilder setContextPath(String contextPath);
|
ApplicationBuilder setContextPath(String contextPath);
|
||||||
|
|
|
@ -3,5 +3,5 @@ package org.xbib.net.http.server.application;
|
||||||
import java.util.concurrent.Callable;
|
import java.util.concurrent.Callable;
|
||||||
import org.xbib.net.buffer.Releasable;
|
import org.xbib.net.buffer.Releasable;
|
||||||
|
|
||||||
public interface RouterCallable extends Callable<Boolean>, Releasable {
|
public interface ApplicationCallable<T> extends Callable<T>, Releasable {
|
||||||
}
|
}
|
|
@ -4,25 +4,20 @@ import org.xbib.net.http.server.HttpRequest;
|
||||||
import org.xbib.net.http.server.HttpServerContext;
|
import org.xbib.net.http.server.HttpServerContext;
|
||||||
import org.xbib.net.http.server.service.HttpService;
|
import org.xbib.net.http.server.service.HttpService;
|
||||||
import org.xbib.net.http.server.session.Session;
|
import org.xbib.net.http.server.session.Session;
|
||||||
import org.xbib.settings.Settings;
|
|
||||||
|
|
||||||
public interface ApplicationModule {
|
public interface ApplicationModule {
|
||||||
|
|
||||||
String getName();
|
String getName();
|
||||||
|
|
||||||
void onOpen(Application application, Settings settings) throws Exception;
|
void onOpen(HttpServerContext httpServerContext);
|
||||||
|
|
||||||
void onOpen(Application application, HttpServerContext httpServerContext);
|
void onOpen(HttpServerContext httpServerContext, HttpService httpService, HttpRequest httpRequest);
|
||||||
|
|
||||||
void onOpen(Application application, HttpServerContext httpServerContext, HttpService httpService);
|
void onClose(HttpServerContext httpServerContext);
|
||||||
|
|
||||||
void onOpen(Application application, HttpServerContext httpServerContext, HttpService httpService, HttpRequest httpRequest);
|
void onOpen(Session session);
|
||||||
|
|
||||||
void onClose(Application application, HttpServerContext httpServerContext);
|
void onClose(Session session);
|
||||||
|
|
||||||
void onOpen(Application application, Session session);
|
void onClose();
|
||||||
|
|
||||||
void onClose(Application application, Session session);
|
|
||||||
|
|
||||||
void onClose(Application application);
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -3,11 +3,11 @@ package org.xbib.net.http.server.application;
|
||||||
import java.util.concurrent.Callable;
|
import java.util.concurrent.Callable;
|
||||||
import java.util.concurrent.FutureTask;
|
import java.util.concurrent.FutureTask;
|
||||||
|
|
||||||
public class RouterTask<T> extends FutureTask<T> {
|
public class ApplicationTask<T> extends FutureTask<T> {
|
||||||
|
|
||||||
private final Callable<T> callable;
|
private final Callable<T> callable;
|
||||||
|
|
||||||
public RouterTask(Callable<T> callable) {
|
public ApplicationTask(Callable<T> callable) {
|
||||||
super(callable);
|
super(callable);
|
||||||
this.callable = callable;
|
this.callable = callable;
|
||||||
}
|
}
|
|
@ -15,8 +15,10 @@ public class ApplicationThreadPoolExecutor extends ThreadPoolExecutor {
|
||||||
|
|
||||||
private final Logger logger = Logger.getLogger(ApplicationThreadPoolExecutor.class.getName());
|
private final Logger logger = Logger.getLogger(ApplicationThreadPoolExecutor.class.getName());
|
||||||
|
|
||||||
public ApplicationThreadPoolExecutor(int nThreads, int maxQueue,
|
public ApplicationThreadPoolExecutor(int nThreads,
|
||||||
long keepAliveTime, TimeUnit timeUnit,
|
int maxQueue,
|
||||||
|
long keepAliveTime,
|
||||||
|
TimeUnit timeUnit,
|
||||||
ThreadFactory threadFactory) {
|
ThreadFactory threadFactory) {
|
||||||
super(nThreads, nThreads, keepAliveTime, timeUnit, createBlockingQueue(maxQueue), threadFactory);
|
super(nThreads, nThreads, keepAliveTime, timeUnit, createBlockingQueue(maxQueue), threadFactory);
|
||||||
logger.log(Level.FINE, () -> "threadpool executor up with nThreads = " + nThreads +
|
logger.log(Level.FINE, () -> "threadpool executor up with nThreads = " + nThreads +
|
||||||
|
@ -26,13 +28,13 @@ public class ApplicationThreadPoolExecutor extends ThreadPoolExecutor {
|
||||||
" threadFactory = " + threadFactory);
|
" threadFactory = " + threadFactory);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static BlockingQueue<Runnable> createBlockingQueue(int max) {
|
private static BlockingQueue<Runnable> createBlockingQueue(int maxQueue) {
|
||||||
return max == Integer.MAX_VALUE ? new SynchronousQueue<>(true) : new ArrayBlockingQueue<>(max);
|
return maxQueue == 0 ? new SynchronousQueue<>(true) : new ArrayBlockingQueue<>(maxQueue);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
|
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
|
||||||
return new RouterTask<>(callable);
|
return new ApplicationTask<>(callable);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@ -43,10 +45,10 @@ public class ApplicationThreadPoolExecutor extends ThreadPoolExecutor {
|
||||||
logger.log(Level.SEVERE, terminationCause.getMessage(), terminationCause);
|
logger.log(Level.SEVERE, terminationCause.getMessage(), terminationCause);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (runnable instanceof RouterTask<?> routerTask) {
|
if (runnable instanceof ApplicationTask<?> applicationTask) {
|
||||||
RouterCallable routerCallable = (RouterCallable) routerTask.getCallable();
|
ApplicationCallable<?> applicationCallable = (ApplicationCallable<?>) applicationTask.getCallable();
|
||||||
logger.log(Level.FINEST, () -> "releasing " + routerCallable);
|
logger.log(Level.FINEST, () -> "releasing " + applicationCallable);
|
||||||
routerCallable.release();
|
applicationCallable.release();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -35,7 +35,6 @@ import org.xbib.net.http.server.session.Session;
|
||||||
import org.xbib.net.http.server.session.memory.MemoryPropertiesSessionCodec;
|
import org.xbib.net.http.server.session.memory.MemoryPropertiesSessionCodec;
|
||||||
import org.xbib.net.http.server.validate.HttpRequestValidator;
|
import org.xbib.net.http.server.validate.HttpRequestValidator;
|
||||||
import org.xbib.net.mime.MimeTypeService;
|
import org.xbib.net.mime.MimeTypeService;
|
||||||
import org.xbib.net.util.NamedThreadFactory;
|
|
||||||
import org.xbib.net.util.RandomUtil;
|
import org.xbib.net.util.RandomUtil;
|
||||||
import org.xbib.settings.Settings;
|
import org.xbib.settings.Settings;
|
||||||
|
|
||||||
|
@ -45,8 +44,6 @@ public class BaseApplication implements Application {
|
||||||
|
|
||||||
protected BaseApplicationBuilder builder;
|
protected BaseApplicationBuilder builder;
|
||||||
|
|
||||||
private final ApplicationThreadPoolExecutor executor;
|
|
||||||
|
|
||||||
private final HttpRequestValidator httpRequestValidator;
|
private final HttpRequestValidator httpRequestValidator;
|
||||||
|
|
||||||
protected final String sessionName;
|
protected final String sessionName;
|
||||||
|
@ -65,11 +62,6 @@ public class BaseApplication implements Application {
|
||||||
|
|
||||||
protected BaseApplication(BaseApplicationBuilder builder) {
|
protected BaseApplication(BaseApplicationBuilder builder) {
|
||||||
this.builder = builder;
|
this.builder = builder;
|
||||||
this.executor = new ApplicationThreadPoolExecutor(builder.blockingThreadCount, builder.blockingThreadQueueCount,
|
|
||||||
builder.blockingThreadKeepAliveTime, builder.blockingThreadKeepAliveTimeUnit,
|
|
||||||
new NamedThreadFactory("org-xbib-net-http-server-application"));
|
|
||||||
this.executor.setRejectedExecutionHandler((runnable, threadPoolExecutor) ->
|
|
||||||
logger.log(Level.SEVERE, "rejected " + runnable + " for thread pool executor = " + threadPoolExecutor));
|
|
||||||
this.sessionName = getSettings().get("session.name", "SESS");
|
this.sessionName = getSettings().get("session.name", "SESS");
|
||||||
this.httpRequestValidator = newRequestValidator();
|
this.httpRequestValidator = newRequestValidator();
|
||||||
this.incomingCookieHandler = newIncomingCookieHandler();
|
this.incomingCookieHandler = newIncomingCookieHandler();
|
||||||
|
@ -139,10 +131,11 @@ public class BaseApplication implements Application {
|
||||||
@Override
|
@Override
|
||||||
public void dispatch(HttpRequestBuilder httpRequestBuilder,
|
public void dispatch(HttpRequestBuilder httpRequestBuilder,
|
||||||
HttpResponseBuilder httpResponseBuilder) {
|
HttpResponseBuilder httpResponseBuilder) {
|
||||||
RouterCallable routerCallable = new RouterCallable() {
|
final Application application = this;
|
||||||
|
ApplicationCallable<?> applicationCallable = new ApplicationCallable<>() {
|
||||||
@Override
|
@Override
|
||||||
public Boolean call() {
|
public Object call() {
|
||||||
getRouter().route(httpRequestBuilder, httpResponseBuilder);
|
getRouter().route(application, httpRequestBuilder, httpResponseBuilder);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -152,7 +145,7 @@ public class BaseApplication implements Application {
|
||||||
httpResponseBuilder.release();
|
httpResponseBuilder.release();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
Future<?> future = executor.submit(routerCallable);
|
Future<?> future = builder.executor.submit(applicationCallable);
|
||||||
logger.log(Level.FINEST, "dispatched " + future);
|
logger.log(Level.FINEST, "dispatched " + future);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -161,9 +154,9 @@ public class BaseApplication implements Application {
|
||||||
HttpResponseBuilder httpResponseBuilder,
|
HttpResponseBuilder httpResponseBuilder,
|
||||||
HttpResponseStatus httpResponseStatus) {
|
HttpResponseStatus httpResponseStatus) {
|
||||||
HttpServerContext httpServerContext = createContext(null, httpRequestBuilder, httpResponseBuilder);
|
HttpServerContext httpServerContext = createContext(null, httpRequestBuilder, httpResponseBuilder);
|
||||||
RouterCallable routerCallable = new RouterCallable() {
|
ApplicationCallable<?> applicationCallable = new ApplicationCallable<>() {
|
||||||
@Override
|
@Override
|
||||||
public Boolean call() {
|
public Object call() {
|
||||||
getRouter().routeStatus(httpResponseStatus, httpServerContext);
|
getRouter().routeStatus(httpResponseStatus, httpServerContext);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
@ -174,7 +167,7 @@ public class BaseApplication implements Application {
|
||||||
httpResponseBuilder.release();
|
httpResponseBuilder.release();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
Future<?> future = executor.submit(routerCallable);
|
Future<?> future = builder.executor.submit(applicationCallable);
|
||||||
logger.log(Level.FINEST, "dispatched status " + future);
|
logger.log(Level.FINEST, "dispatched status " + future);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -249,13 +242,13 @@ public class BaseApplication implements Application {
|
||||||
@Override
|
@Override
|
||||||
public void onCreated(Session session) {
|
public void onCreated(Session session) {
|
||||||
logger.log(Level.FINER, "session name = " + sessionName + " created = " + session);
|
logger.log(Level.FINER, "session name = " + sessionName + " created = " + session);
|
||||||
builder.applicationModuleList.forEach(module -> module.onOpen(this, session));
|
builder.applicationModuleList.forEach(module -> module.onOpen(session));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onDestroy(Session session) {
|
public void onDestroy(Session session) {
|
||||||
logger.log(Level.FINER, "session name = " + sessionName + " destroyed = " + session);
|
logger.log(Level.FINER, "session name = " + sessionName + " destroyed = " + session);
|
||||||
builder.applicationModuleList.forEach(module -> module.onClose(this, session));
|
builder.applicationModuleList.forEach(module -> module.onClose(session));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@ -271,7 +264,7 @@ public class BaseApplication implements Application {
|
||||||
incomingSessionHandler.handle(httpServerContext);
|
incomingSessionHandler.handle(httpServerContext);
|
||||||
}
|
}
|
||||||
// call modules after request/cookie/session setup
|
// call modules after request/cookie/session setup
|
||||||
builder.applicationModuleList.forEach(module -> module.onOpen(this, httpServerContext));
|
builder.applicationModuleList.forEach(module -> module.onOpen(httpServerContext));
|
||||||
} catch (HttpException e) {
|
} catch (HttpException e) {
|
||||||
getRouter().routeException(e);
|
getRouter().routeException(e);
|
||||||
httpServerContext.fail();
|
httpServerContext.fail();
|
||||||
|
@ -285,7 +278,7 @@ public class BaseApplication implements Application {
|
||||||
public void onClose(HttpServerContext httpServerContext) {
|
public void onClose(HttpServerContext httpServerContext) {
|
||||||
try {
|
try {
|
||||||
// call modules before session/cookie
|
// call modules before session/cookie
|
||||||
builder.applicationModuleList.forEach(module -> module.onClose(this, httpServerContext));
|
builder.applicationModuleList.forEach(module -> module.onClose(httpServerContext));
|
||||||
if (builder.sessionsEnabled && outgoingSessionHandler != null) {
|
if (builder.sessionsEnabled && outgoingSessionHandler != null) {
|
||||||
outgoingSessionHandler.handle(httpServerContext);
|
outgoingSessionHandler.handle(httpServerContext);
|
||||||
}
|
}
|
||||||
|
@ -329,19 +322,19 @@ public class BaseApplication implements Application {
|
||||||
public void close() throws IOException {
|
public void close() throws IOException {
|
||||||
logger.log(Level.INFO, "application closing");
|
logger.log(Level.INFO, "application closing");
|
||||||
// stop dispatching and stop dispatched requests
|
// stop dispatching and stop dispatched requests
|
||||||
executor.shutdown();
|
builder.executor.shutdown();
|
||||||
try {
|
try {
|
||||||
if (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
|
if (!builder.executor.awaitTermination(10, TimeUnit.SECONDS)) {
|
||||||
List<Runnable> list = executor.shutdownNow();
|
List<Runnable> list = builder.executor.shutdownNow();
|
||||||
logger.log(Level.WARNING, "unable to stop runnables " + list);
|
logger.log(Level.WARNING, "unable to stop runnables " + list);
|
||||||
}
|
}
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
List<Runnable> list = executor.shutdownNow();
|
List<Runnable> list = builder.executor.shutdownNow();
|
||||||
logger.log(Level.WARNING, "unable to stop runnables " + list);
|
logger.log(Level.WARNING, "unable to stop runnables " + list);
|
||||||
}
|
}
|
||||||
builder.applicationModuleList.forEach(module -> {
|
builder.applicationModuleList.forEach(module -> {
|
||||||
logger.log(Level.FINE, "application closing module " + module);
|
logger.log(Level.FINE, "application closing module " + module);
|
||||||
module.onClose(this);
|
module.onClose();
|
||||||
});
|
});
|
||||||
if (outgoingSessionHandler != null && (outgoingSessionHandler instanceof Closeable)) {
|
if (outgoingSessionHandler != null && (outgoingSessionHandler instanceof Closeable)) {
|
||||||
logger.log(Level.FINE, "application closing outgoing session handler");
|
logger.log(Level.FINE, "application closing outgoing session handler");
|
||||||
|
|
|
@ -10,6 +10,7 @@ import java.util.Map;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.ServiceLoader;
|
import java.util.ServiceLoader;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
import java.util.concurrent.ThreadPoolExecutor;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
import java.util.logging.Level;
|
import java.util.logging.Level;
|
||||||
import java.util.logging.Logger;
|
import java.util.logging.Logger;
|
||||||
|
@ -19,6 +20,7 @@ import org.xbib.config.ConfigParams;
|
||||||
import org.xbib.config.SystemConfigLogger;
|
import org.xbib.config.SystemConfigLogger;
|
||||||
import org.xbib.net.http.server.route.HttpRouter;
|
import org.xbib.net.http.server.route.HttpRouter;
|
||||||
import org.xbib.net.mime.MimeTypeService;
|
import org.xbib.net.mime.MimeTypeService;
|
||||||
|
import org.xbib.net.util.NamedThreadFactory;
|
||||||
import org.xbib.settings.Settings;
|
import org.xbib.settings.Settings;
|
||||||
|
|
||||||
public class BaseApplicationBuilder implements ApplicationBuilder {
|
public class BaseApplicationBuilder implements ApplicationBuilder {
|
||||||
|
@ -44,6 +46,8 @@ public class BaseApplicationBuilder implements ApplicationBuilder {
|
||||||
|
|
||||||
protected TimeUnit blockingThreadKeepAliveTimeUnit;
|
protected TimeUnit blockingThreadKeepAliveTimeUnit;
|
||||||
|
|
||||||
|
protected ThreadPoolExecutor executor;
|
||||||
|
|
||||||
protected Path home;
|
protected Path home;
|
||||||
|
|
||||||
protected String contextPath;
|
protected String contextPath;
|
||||||
|
@ -73,7 +77,7 @@ public class BaseApplicationBuilder implements ApplicationBuilder {
|
||||||
protected BaseApplicationBuilder() {
|
protected BaseApplicationBuilder() {
|
||||||
this.classLoader = getClass().getClassLoader();
|
this.classLoader = getClass().getClassLoader();
|
||||||
this.blockingThreadCount = Runtime.getRuntime().availableProcessors();
|
this.blockingThreadCount = Runtime.getRuntime().availableProcessors();
|
||||||
this.blockingThreadQueueCount = Integer.MAX_VALUE;
|
this.blockingThreadQueueCount = 0; // use fair synchronous queue
|
||||||
this.blockingThreadKeepAliveTime = 60;
|
this.blockingThreadKeepAliveTime = 60;
|
||||||
this.blockingThreadKeepAliveTimeUnit = TimeUnit.SECONDS;
|
this.blockingThreadKeepAliveTimeUnit = TimeUnit.SECONDS;
|
||||||
this.home = Paths.get(System.getProperties().containsKey("application.home") ? System.getProperty("application.home") : ".");
|
this.home = Paths.get(System.getProperties().containsKey("application.home") ? System.getProperty("application.home") : ".");
|
||||||
|
@ -115,6 +119,12 @@ public class BaseApplicationBuilder implements ApplicationBuilder {
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public BaseApplicationBuilder setExecutor(ThreadPoolExecutor executor) {
|
||||||
|
this.executor = executor;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public BaseApplicationBuilder setHome(Path home) {
|
public BaseApplicationBuilder setHome(Path home) {
|
||||||
this.home = home;
|
this.home = home;
|
||||||
|
@ -205,12 +215,16 @@ public class BaseApplicationBuilder implements ApplicationBuilder {
|
||||||
if (staticFileSuffixes == null) {
|
if (staticFileSuffixes == null) {
|
||||||
staticFileSuffixes = DEFAULT_SUFFIXES;
|
staticFileSuffixes = DEFAULT_SUFFIXES;
|
||||||
}
|
}
|
||||||
|
if (this.executor == null) {
|
||||||
|
this.executor = new ApplicationThreadPoolExecutor(blockingThreadCount, blockingThreadQueueCount,
|
||||||
|
blockingThreadKeepAliveTime, blockingThreadKeepAliveTimeUnit,
|
||||||
|
new NamedThreadFactory("org-xbib-net-http-server-application"));
|
||||||
|
this.executor.setRejectedExecutionHandler((runnable, threadPoolExecutor) ->
|
||||||
|
logger.log(Level.SEVERE, "rejected " + runnable + " for thread pool executor = " + threadPoolExecutor));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void setupApplication(Application application) {
|
protected void setupApplication(Application application) {
|
||||||
if (router != null) {
|
|
||||||
router.setApplication(application);
|
|
||||||
}
|
|
||||||
for (Map.Entry<String, Settings> entry : settings.getGroups("module").entrySet()) {
|
for (Map.Entry<String, Settings> entry : settings.getGroups("module").entrySet()) {
|
||||||
String moduleName = entry.getKey();
|
String moduleName = entry.getKey();
|
||||||
Settings moduleSettings = entry.getValue();
|
Settings moduleSettings = entry.getValue();
|
||||||
|
@ -223,7 +237,6 @@ public class BaseApplicationBuilder implements ApplicationBuilder {
|
||||||
ApplicationModule applicationModule = clazz.getConstructor(Application.class, String.class, Settings.class)
|
ApplicationModule applicationModule = clazz.getConstructor(Application.class, String.class, Settings.class)
|
||||||
.newInstance(application, moduleName, moduleSettings);
|
.newInstance(application, moduleName, moduleSettings);
|
||||||
applicationModuleList.add(applicationModule);
|
applicationModuleList.add(applicationModule);
|
||||||
applicationModule.onOpen(application, moduleSettings);
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.log(Level.WARNING, e.getMessage(), e);
|
logger.log(Level.WARNING, e.getMessage(), e);
|
||||||
throw new IllegalArgumentException("class not found or not loadable: " + e.getMessage());
|
throw new IllegalArgumentException("class not found or not loadable: " + e.getMessage());
|
||||||
|
|
|
@ -26,34 +26,26 @@ public abstract class BaseApplicationModule implements ApplicationModule {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onOpen(Application application, Settings settings) throws Exception {
|
public void onOpen(HttpServerContext httpServerContext) {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onOpen(Application application, HttpServerContext httpServerContext) {
|
public void onOpen(HttpServerContext httpServerContext, HttpService httpService, HttpRequest httpRequest) {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onOpen(Application application, HttpServerContext httpServerContext, HttpService httpService) {
|
public void onClose(HttpServerContext httpServerContext) {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onOpen(Application application, HttpServerContext httpServerContext, HttpService httpService, HttpRequest httpRequest) {
|
public void onOpen(Session session) {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onClose(Application application, HttpServerContext httpServerContext) {
|
public void onClose(Session session) {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onOpen(Application application, Session session) {
|
public void onClose() {
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onClose(Application application, Session session) {
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onClose(Application application) {
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -39,8 +39,6 @@ public class BaseHttpRouter implements HttpRouter {
|
||||||
|
|
||||||
private final HttpRouteResolver<HttpService> httpRouteResolver;
|
private final HttpRouteResolver<HttpService> httpRouteResolver;
|
||||||
|
|
||||||
private Application application;
|
|
||||||
|
|
||||||
protected BaseHttpRouter(BaseHttpRouterBuilder builder) {
|
protected BaseHttpRouter(BaseHttpRouterBuilder builder) {
|
||||||
this.builder = builder;
|
this.builder = builder;
|
||||||
HttpRouteResolver.Builder<HttpService> httpRouteResolverBuilder = newHttpRouteResolverBuilder();
|
HttpRouteResolver.Builder<HttpService> httpRouteResolverBuilder = newHttpRouteResolverBuilder();
|
||||||
|
@ -69,12 +67,6 @@ public class BaseHttpRouter implements HttpRouter {
|
||||||
return BaseHttpRouteResolver.builder();
|
return BaseHttpRouteResolver.builder();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setApplication(Application application) {
|
|
||||||
Objects.requireNonNull(application);
|
|
||||||
this.application = application;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Collection<HttpDomain> getDomains() {
|
public Collection<HttpDomain> getDomains() {
|
||||||
return builder.domains;
|
return builder.domains;
|
||||||
|
@ -86,7 +78,8 @@ public class BaseHttpRouter implements HttpRouter {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void route(HttpRequestBuilder requestBuilder,
|
public void route(Application application,
|
||||||
|
HttpRequestBuilder requestBuilder,
|
||||||
HttpResponseBuilder responseBuilder) {
|
HttpResponseBuilder responseBuilder) {
|
||||||
Objects.requireNonNull(requestBuilder);
|
Objects.requireNonNull(requestBuilder);
|
||||||
Objects.requireNonNull(requestBuilder.getRequestURI());
|
Objects.requireNonNull(requestBuilder.getRequestURI());
|
||||||
|
@ -104,64 +97,64 @@ public class BaseHttpRouter implements HttpRouter {
|
||||||
true);
|
true);
|
||||||
httpRouteResolver.resolve(httpRoute, httpRouteResolverResults::add);
|
httpRouteResolver.resolve(httpRoute, httpRouteResolverResults::add);
|
||||||
HttpServerContext httpServerContext = application.createContext(httpDomain, requestBuilder, responseBuilder);
|
HttpServerContext httpServerContext = application.createContext(httpDomain, requestBuilder, responseBuilder);
|
||||||
route(httpServerContext, httpRouteResolverResults);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected void route(HttpServerContext httpServerContext,
|
|
||||||
List<HttpRouteResolver.Result<HttpService>> httpRouteResolverResults) {
|
|
||||||
application.onOpen(httpServerContext);
|
application.onOpen(httpServerContext);
|
||||||
try {
|
try {
|
||||||
if (httpServerContext.isFailed()) {
|
route(application, httpServerContext, httpRouteResolverResults);
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (httpRouteResolverResults.isEmpty()) {
|
|
||||||
logger.log(Level.FINE, "route resolver results is empty, generating a not found message");
|
|
||||||
httpServerContext.setResolverResult(null);
|
|
||||||
routeStatus(NOT_FOUND, httpServerContext);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
for (HttpRouteResolver.Result<HttpService> httpRouteResolverResult : httpRouteResolverResults) {
|
|
||||||
try {
|
|
||||||
// first: create the final request
|
|
||||||
httpServerContext.setResolverResult(httpRouteResolverResult);
|
|
||||||
HttpService httpService = httpRouteResolverResult.getValue();
|
|
||||||
HttpRequest httpRequest = httpServerContext.httpRequest();
|
|
||||||
application.getModules().forEach(module -> module.onOpen(application, httpServerContext, httpService, httpRequest));
|
|
||||||
// second: security check, authentication etc.
|
|
||||||
if (httpService.getSecurityDomain() != null) {
|
|
||||||
logger.log(Level.FINEST, () -> "handling security domain service " + httpService);
|
|
||||||
for (HttpHandler httpHandler : httpService.getSecurityDomain().getHandlers()) {
|
|
||||||
logger.log(Level.FINEST, () -> "handling security domain handler " + httpHandler);
|
|
||||||
httpHandler.handle(httpServerContext);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (httpServerContext.isDone() || httpServerContext.isFailed()) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
// after security checks, accept service, open and execute service
|
|
||||||
httpServerContext.getAttributes().put("service", httpService);
|
|
||||||
application.getModules().forEach(module -> module.onOpen(application, httpServerContext, httpService));
|
|
||||||
logger.log(Level.FINEST, () -> "handling service " + httpService);
|
|
||||||
httpService.handle(httpServerContext);
|
|
||||||
// if service signals that work is done, break
|
|
||||||
if (httpServerContext.isDone() || httpServerContext.isFailed()) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
} catch (HttpException e) {
|
|
||||||
logger.log(Level.SEVERE, e.getMessage(), e);
|
|
||||||
routeException(e);
|
|
||||||
break;
|
|
||||||
} catch (Throwable t) {
|
|
||||||
logger.log(Level.SEVERE, t.getMessage(), t);
|
|
||||||
routeToErrorHandler(httpServerContext, t);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} finally {
|
} finally {
|
||||||
application.onClose(httpServerContext);
|
application.onClose(httpServerContext);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected void route(Application application,
|
||||||
|
HttpServerContext httpServerContext,
|
||||||
|
List<HttpRouteResolver.Result<HttpService>> httpRouteResolverResults) {
|
||||||
|
if (httpServerContext.isFailed()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (httpRouteResolverResults.isEmpty()) {
|
||||||
|
logger.log(Level.FINE, "route resolver results is empty, generating a not found message");
|
||||||
|
httpServerContext.setResolverResult(null);
|
||||||
|
routeStatus(NOT_FOUND, httpServerContext);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (HttpRouteResolver.Result<HttpService> httpRouteResolverResult : httpRouteResolverResults) {
|
||||||
|
try {
|
||||||
|
// first: create the final request
|
||||||
|
httpServerContext.setResolverResult(httpRouteResolverResult);
|
||||||
|
HttpService httpService = httpRouteResolverResult.getValue();
|
||||||
|
HttpRequest httpRequest = httpServerContext.httpRequest();
|
||||||
|
application.getModules().forEach(module -> module.onOpen(httpServerContext, httpService, httpRequest));
|
||||||
|
// second: security check, authentication etc.
|
||||||
|
if (httpService.getSecurityDomain() != null) {
|
||||||
|
logger.log(Level.FINEST, () -> "handling security domain service " + httpService);
|
||||||
|
for (HttpHandler httpHandler : httpService.getSecurityDomain().getHandlers()) {
|
||||||
|
logger.log(Level.FINEST, () -> "handling security domain handler " + httpHandler);
|
||||||
|
httpHandler.handle(httpServerContext);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (httpServerContext.isDone() || httpServerContext.isFailed()) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
// after security checks, accept service, open and execute service
|
||||||
|
httpServerContext.getAttributes().put("service", httpService);
|
||||||
|
logger.log(Level.FINEST, () -> "handling service " + httpService);
|
||||||
|
httpService.handle(httpServerContext);
|
||||||
|
// if service signals that work is done, break
|
||||||
|
if (httpServerContext.isDone() || httpServerContext.isFailed()) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} catch (HttpException e) {
|
||||||
|
logger.log(Level.SEVERE, e.getMessage(), e);
|
||||||
|
routeException(e);
|
||||||
|
break;
|
||||||
|
} catch (Throwable t) {
|
||||||
|
logger.log(Level.SEVERE, t.getMessage(), t);
|
||||||
|
routeToErrorHandler(httpServerContext, t);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void routeException(HttpException e) {
|
public void routeException(HttpException e) {
|
||||||
routeStatus(e.getResponseStatus(), e.getHttpServerContext());
|
routeStatus(e.getResponseStatus(), e.getHttpServerContext());
|
||||||
|
|
|
@ -15,13 +15,12 @@ public interface HttpRouter {
|
||||||
|
|
||||||
DomainsByAddress getDomainsByAddress();
|
DomainsByAddress getDomainsByAddress();
|
||||||
|
|
||||||
void setApplication(Application application);
|
void route(Application application, HttpRequestBuilder requestBuilder, HttpResponseBuilder responseBuilder);
|
||||||
|
|
||||||
void route(HttpRequestBuilder requestBuilder, HttpResponseBuilder responseBuilder);
|
|
||||||
|
|
||||||
void routeException(HttpException e);
|
|
||||||
|
|
||||||
void routeStatus(HttpResponseStatus httpResponseStatus, HttpServerContext httpServerContext);
|
void routeStatus(HttpResponseStatus httpResponseStatus, HttpServerContext httpServerContext);
|
||||||
|
|
||||||
void routeToErrorHandler(HttpServerContext httpServerContext, Throwable t);
|
void routeToErrorHandler(HttpServerContext httpServerContext, Throwable t);
|
||||||
|
|
||||||
|
void routeException(HttpException e);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -18,16 +18,12 @@ public class GroovyTemplateApplicationModule extends BaseApplicationModule {
|
||||||
|
|
||||||
private static final Logger logger = Logger.getLogger(GroovyTemplateApplicationModule.class.getName());
|
private static final Logger logger = Logger.getLogger(GroovyTemplateApplicationModule.class.getName());
|
||||||
|
|
||||||
private GroovyMarkupTemplateHandler groovyMarkupTemplateHandler;
|
private final GroovyMarkupTemplateHandler groovyMarkupTemplateHandler;
|
||||||
|
|
||||||
private GroovyTemplateRenderer groovyTemplateRenderer;
|
private final GroovyTemplateRenderer groovyTemplateRenderer;
|
||||||
|
|
||||||
public GroovyTemplateApplicationModule(Application application, String name, Settings settings) {
|
public GroovyTemplateApplicationModule(Application application, String name, Settings settings) {
|
||||||
super(application, name, settings);
|
super(application, name, settings);
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onOpen(Application application, Settings settings) {
|
|
||||||
ClassLoader classLoader = GroovyMarkupTemplateHandler.class.getClassLoader();
|
ClassLoader classLoader = GroovyMarkupTemplateHandler.class.getClassLoader();
|
||||||
String defaultMarkupTemplate = settings.get("markup.templateClass",
|
String defaultMarkupTemplate = settings.get("markup.templateClass",
|
||||||
"org.xbib.net.http.template.DefaultMarkupTemplate");
|
"org.xbib.net.http.template.DefaultMarkupTemplate");
|
||||||
|
@ -54,7 +50,7 @@ public class GroovyTemplateApplicationModule extends BaseApplicationModule {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onOpen(Application application, HttpServerContext httpServerContext) {
|
public void onOpen(HttpServerContext httpServerContext) {
|
||||||
try {
|
try {
|
||||||
groovyMarkupTemplateHandler.handle(httpServerContext);
|
groovyMarkupTemplateHandler.handle(httpServerContext);
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
|
@ -63,14 +59,14 @@ public class GroovyTemplateApplicationModule extends BaseApplicationModule {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onOpen(Application application, HttpServerContext httpServerContext, HttpService httpService, HttpRequest httpRequest) {
|
public void onOpen(HttpServerContext httpServerContext, HttpService httpService, HttpRequest httpRequest) {
|
||||||
httpServerContext.getAttributes().put("request", httpRequest);
|
httpServerContext.getAttributes().put("request", httpRequest);
|
||||||
httpServerContext.getAttributes().put("params", httpRequest.getParameter().asSingleValuedMap());
|
httpServerContext.getAttributes().put("params", httpRequest.getParameter().asSingleValuedMap());
|
||||||
application.getModules().forEach(module -> httpServerContext.getAttributes().put(module.getName(), module));
|
application.getModules().forEach(module -> httpServerContext.getAttributes().put(module.getName(), module));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onClose(Application application, HttpServerContext httpServerContext) {
|
public void onClose(HttpServerContext httpServerContext) {
|
||||||
try {
|
try {
|
||||||
groovyTemplateRenderer.handle(httpServerContext);
|
groovyTemplateRenderer.handle(httpServerContext);
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
|
|
|
@ -1,14 +1,14 @@
|
||||||
dependencyResolutionManagement {
|
dependencyResolutionManagement {
|
||||||
versionCatalogs {
|
versionCatalogs {
|
||||||
libs {
|
libs {
|
||||||
version('gradle', '7.5.1')
|
version('gradle', '8.0.2')
|
||||||
version('junit', '5.9.2')
|
version('junit', '5.9.2')
|
||||||
version('groovy', '4.0.10')
|
version('groovy', '4.0.11')
|
||||||
version('netty', '4.1.90.Final')
|
version('netty', '4.1.90.Final')
|
||||||
version('netty-tcnative', '2.0.59.Final')
|
version('netty-tcnative', '2.0.59.Final')
|
||||||
version('datastructures', '2.0.0')
|
version('datastructures', '2.0.0')
|
||||||
version('config', '5.0.2')
|
version('config', '5.0.2')
|
||||||
version('net', '3.1.0')
|
version('net', '3.2.0')
|
||||||
library('junit-jupiter-api', 'org.junit.jupiter', 'junit-jupiter-api').versionRef('junit')
|
library('junit-jupiter-api', 'org.junit.jupiter', 'junit-jupiter-api').versionRef('junit')
|
||||||
library('junit-jupiter-params', 'org.junit.jupiter', 'junit-jupiter-params').versionRef('junit')
|
library('junit-jupiter-params', 'org.junit.jupiter', 'junit-jupiter-params').versionRef('junit')
|
||||||
library('junit-jupiter-engine', 'org.junit.jupiter', 'junit-jupiter-engine').versionRef('junit')
|
library('junit-jupiter-engine', 'org.junit.jupiter', 'junit-jupiter-engine').versionRef('junit')
|
||||||
|
|
Loading…
Reference in a new issue