rename attributes() to getAttributes()

This commit is contained in:
Jörg Prante 2023-03-26 22:23:46 +02:00
parent b3b4568a6e
commit 407f8ad2f8
44 changed files with 135 additions and 121 deletions

View file

@ -1,9 +1,6 @@
handlers=java.util.logging.FileHandler, java.util.logging.ConsoleHandler handlers=java.util.logging.ConsoleHandler
.level=ALL .level=ALL
java.util.logging.SimpleFormatter.format=%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS.%1$tL %4$-7s [%3$s] %5$s %6$s%n java.util.logging.SimpleFormatter.format=%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS.%1$tL %4$-7s [%3$s] %5$s %6$s%n
java.util.logging.ConsoleHandler.level=ALL java.util.logging.ConsoleHandler.level=ALL
java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter
java.util.logging.FileHandler.level=ALL
java.util.logging.FileHandler.formatter=java.util.logging.SimpleFormatter
java.util.logging.FileHandler.pattern=build/net.log
jdk.event.security.level=INFO jdk.event.security.level=INFO

View file

@ -54,9 +54,9 @@ public class ConfigApplicationModule extends BaseApplicationModule {
@Override @Override
public void onOpen(Application application, HttpServerContext httpServerContext, HttpService httpService) { public void onOpen(Application application, HttpServerContext httpServerContext, HttpService httpService) {
httpServerContext.attributes().put("configparams", configParams); httpServerContext.getAttributes().put("configparams", configParams);
httpServerContext.attributes().put("configloader", configLoader); httpServerContext.getAttributes().put("configloader", configLoader);
httpServerContext.attributes().put("settings", settings); httpServerContext.getAttributes().put("settings", settings);
} }
@Override @Override

View file

@ -39,10 +39,10 @@ public class DatabaseApplicationModule<A extends Application> extends BaseApplic
@Override @Override
public void onOpen(Application application, HttpServerContext httpServerContext, HttpService httpService) { public void onOpen(Application application, HttpServerContext httpServerContext, HttpService httpService) {
if (dataSource != null) { if (dataSource != null) {
httpServerContext.attributes().put("datasource", dataSource); httpServerContext.getAttributes().put("datasource", dataSource);
} }
if (databaseProvider != null) { if (databaseProvider != null) {
httpServerContext.attributes().put("databaseprovider", databaseProvider); httpServerContext.getAttributes().put("databaseprovider", databaseProvider);
} }
} }

View file

@ -141,7 +141,7 @@ public final class Bootstrap {
" SSL session = " + ctx.httpRequest().as(HttpsRequest.class).getSSLSession() + " SSL session = " + ctx.httpRequest().as(HttpsRequest.class).getSSLSession() +
" base URL = " + ctx.httpRequest().getBaseURL() + " base URL = " + ctx.httpRequest().getBaseURL() +
" parameter = " + ctx.httpRequest().getParameter().allToString() + " parameter = " + ctx.httpRequest().getParameter().allToString() +
" attributes = " + ctx.attributes() + " attributes = " + ctx.getAttributes() +
" local address = " + ctx.httpRequest().getLocalAddress() + " local address = " + ctx.httpRequest().getLocalAddress() +
" remote address = " + ctx.httpRequest().getRemoteAddress()); " remote address = " + ctx.httpRequest().getRemoteAddress());
ctx.done(); ctx.done();

View file

@ -35,7 +35,7 @@ public class WebApplication extends BaseApplication {
protected HttpHandler buildIncomingSessionHandler(HttpServerContext httpServerContext) { protected HttpHandler buildIncomingSessionHandler(HttpServerContext httpServerContext) {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Codec<Session> sessionCodec = httpServerContext.attributes().get(Codec.class, "sessioncodec"); Codec<Session> sessionCodec = httpServerContext.getAttributes().get(Codec.class, "sessioncodec");
return new IncomingSessionHandler( return new IncomingSessionHandler(
getSecret(), getSecret(),
"HmacSHA1", "HmacSHA1",
@ -49,7 +49,7 @@ public class WebApplication extends BaseApplication {
protected OutgoingSessionHandler buildOutgoingSessionHandler(HttpServerContext httpServerContext) { protected OutgoingSessionHandler buildOutgoingSessionHandler(HttpServerContext httpServerContext) {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Codec<Session> sessionCodec = httpServerContext.attributes().get(Codec.class, "sessioncodec"); Codec<Session> sessionCodec = httpServerContext.getAttributes().get(Codec.class, "sessioncodec");
return new OutgoingSessionHandler( return new OutgoingSessionHandler(
getSecret(), getSecret(),
"HmacSHA1", "HmacSHA1",

View file

@ -74,7 +74,7 @@ public class NettyHttpsServerMultiRequestLoadTest {
" SSL peer host = " + ctx.httpRequest().as(HttpsRequest.class).getSSLSession() + " SSL peer host = " + ctx.httpRequest().as(HttpsRequest.class).getSSLSession() +
" base URL = " + ctx.httpRequest().getBaseURL() + " base URL = " + ctx.httpRequest().getBaseURL() +
" parameter = " + ctx.httpRequest().getParameter().allToString() + " parameter = " + ctx.httpRequest().getParameter().allToString() +
" attributes = " + ctx.attributes() + " attributes = " + ctx.getAttributes() +
" local address = " + ctx.httpRequest().getLocalAddress() + " local address = " + ctx.httpRequest().getLocalAddress() +
" remote address = " + ctx.httpRequest().getRemoteAddress()); " remote address = " + ctx.httpRequest().getRemoteAddress());
}) })
@ -158,7 +158,7 @@ public class NettyHttpsServerMultiRequestLoadTest {
" SSL session = " + ctx.httpRequest().as(HttpsRequest.class).getSSLSession() + " SSL session = " + ctx.httpRequest().as(HttpsRequest.class).getSSLSession() +
" base URL = " + ctx.httpRequest().getBaseURL() + " base URL = " + ctx.httpRequest().getBaseURL() +
" parameter = " + ctx.httpRequest().getParameter().allToString() + " parameter = " + ctx.httpRequest().getParameter().allToString() +
" attributes = " + ctx.attributes() + " attributes = " + ctx.getAttributes() +
" local address = " + ctx.httpRequest().getLocalAddress() + " local address = " + ctx.httpRequest().getLocalAddress() +
" remote address = " + ctx.httpRequest().getRemoteAddress()); " remote address = " + ctx.httpRequest().getRemoteAddress());
}) })

View file

@ -77,7 +77,7 @@ public class NettyHttpsServerTest {
" SSL peer host = " + ctx.httpRequest().as(HttpsRequest.class).getSSLSession() + " SSL peer host = " + ctx.httpRequest().as(HttpsRequest.class).getSSLSession() +
" base URL = " + ctx.httpRequest().getBaseURL() + " base URL = " + ctx.httpRequest().getBaseURL() +
" parameter = " + ctx.httpRequest().getParameter().allToString() + " parameter = " + ctx.httpRequest().getParameter().allToString() +
" attributes = " + ctx.attributes() + " attributes = " + ctx.getAttributes() +
" local address = " + ctx.httpRequest().getLocalAddress() + " local address = " + ctx.httpRequest().getLocalAddress() +
" remote address = " + ctx.httpRequest().getRemoteAddress()); " remote address = " + ctx.httpRequest().getRemoteAddress());
}) })
@ -152,7 +152,7 @@ public class NettyHttpsServerTest {
" SSL session = " + ctx.httpRequest().as(HttpsRequest.class).getSSLSession() + " SSL session = " + ctx.httpRequest().as(HttpsRequest.class).getSSLSession() +
" base URL = " + ctx.httpRequest().getBaseURL() + " base URL = " + ctx.httpRequest().getBaseURL() +
" parameter = " + ctx.httpRequest().getParameter().allToString() + " parameter = " + ctx.httpRequest().getParameter().allToString() +
" attributes = " + ctx.attributes() + " attributes = " + ctx.getAttributes() +
" local address = " + ctx.httpRequest().getLocalAddress() + " local address = " + ctx.httpRequest().getLocalAddress() +
" remote address = " + ctx.httpRequest().getRemoteAddress()); " remote address = " + ctx.httpRequest().getRemoteAddress());
}) })

View file

@ -53,7 +53,7 @@ public class NettyHttp2ServerMultiRequestLoadTest {
ctx.write("domain: " + ctx.write("domain: " +
" base URL = " + ctx.httpRequest().getBaseURL() + " base URL = " + ctx.httpRequest().getBaseURL() +
" parameter = " + ctx.httpRequest().getParameter().allToString() + " parameter = " + ctx.httpRequest().getParameter().allToString() +
" attributes = " + ctx.attributes() + " attributes = " + ctx.getAttributes() +
" local address = " + ctx.httpRequest().getLocalAddress() + " local address = " + ctx.httpRequest().getLocalAddress() +
" remote address = " + ctx.httpRequest().getRemoteAddress()); " remote address = " + ctx.httpRequest().getRemoteAddress());
}) })

View file

@ -60,7 +60,7 @@ public class NettyHttpServerFailureTest {
" parameter = " + ctx.httpRequest().getParameter().allToString() + " parameter = " + ctx.httpRequest().getParameter().allToString() +
" local address = " + ctx.httpRequest().getLocalAddress() + " local address = " + ctx.httpRequest().getLocalAddress() +
" remote address = " + ctx.httpRequest().getRemoteAddress() + " remote address = " + ctx.httpRequest().getRemoteAddress() +
" attributes = " + ctx.attributes() " attributes = " + ctx.getAttributes()
); );
}) })
.build()) .build())

View file

@ -53,7 +53,7 @@ public class NettyHttpServerMultiRequestLoadTest {
ctx.write("domain: " + ctx.write("domain: " +
" base URL = " + ctx.httpRequest().getBaseURL() + " base URL = " + ctx.httpRequest().getBaseURL() +
" parameter = " + ctx.httpRequest().getParameter().allToString() + " parameter = " + ctx.httpRequest().getParameter().allToString() +
" attributes = " + ctx.attributes() + " attributes = " + ctx.getAttributes() +
" local address = " + ctx.httpRequest().getLocalAddress() + " local address = " + ctx.httpRequest().getLocalAddress() +
" remote address = " + ctx.httpRequest().getRemoteAddress()); " remote address = " + ctx.httpRequest().getRemoteAddress());
}) })

View file

@ -54,7 +54,7 @@ public class NettyHttpServerTest {
" parameter = " + ctx.httpRequest().getParameter().allToString() + " parameter = " + ctx.httpRequest().getParameter().allToString() +
" local address = " + ctx.httpRequest().getLocalAddress() + " local address = " + ctx.httpRequest().getLocalAddress() +
" remote address = " + ctx.httpRequest().getRemoteAddress() + " remote address = " + ctx.httpRequest().getRemoteAddress() +
" attributes = " + ctx.attributes() " attributes = " + ctx.getAttributes()
); );
}) })
.build()) .build())

View file

@ -1,4 +1,4 @@
handlers=java.util.logging.FileHandler, java.util.logging.ConsoleHandler handlers=java.util.logging.ConsoleHandler
.level=ALL .level=ALL
java.util.logging.ConsoleHandler.level=ALL java.util.logging.ConsoleHandler.level=ALL
java.util.logging.ConsoleHandler.formatter=org.xbib.net.util.ThreadLoggingFormatter java.util.logging.ConsoleHandler.formatter=org.xbib.net.util.ThreadLoggingFormatter

View file

@ -1,9 +1,5 @@
handlers=java.util.logging.FileHandler, java.util.logging.ConsoleHandler handlers=java.util.logging.ConsoleHandler
.level=ALL .level=ALL
java.util.logging.SimpleFormatter.format=%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS.%1$tL %4$-7s [%3$s] %5$s %6$s%n
java.util.logging.ConsoleHandler.level=ALL java.util.logging.ConsoleHandler.level=ALL
java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter java.util.logging.ConsoleHandler.formatter=org.xbib.net.util.ThreadLoggingFormatter
java.util.logging.FileHandler.level=ALL
java.util.logging.FileHandler.formatter=java.util.logging.SimpleFormatter
java.util.logging.FileHandler.pattern=build/net.log
jdk.event.security.level=INFO jdk.event.security.level=INFO

View file

@ -3,4 +3,5 @@ dependencies {
api libs.config api libs.config
implementation libs.settings.datastructures.json implementation libs.settings.datastructures.json
implementation libs.settings.datastructures.yaml implementation libs.settings.datastructures.yaml
implementation libs.datastructures.json.tiny
} }

View file

@ -24,6 +24,7 @@ module org.xbib.net.http.server {
requires org.xbib.net.mime; requires org.xbib.net.mime;
requires org.xbib.net.http; requires org.xbib.net.http;
requires org.xbib.datastructures.common; requires org.xbib.datastructures.common;
requires org.xbib.datastructures.json.tiny;
requires org.xbib.config; requires org.xbib.config;
requires java.logging; requires java.logging;
requires java.naming; requires java.naming;

View file

@ -143,7 +143,7 @@ public class BaseApplication implements Application {
HttpResponseStatus httpResponseStatus) { HttpResponseStatus httpResponseStatus) {
Future<?> future = executor.submit(() -> { Future<?> future = executor.submit(() -> {
HttpServerContext httpServerContext = createContext(null, httpRequestBuilder, httpResponseBuilder); HttpServerContext httpServerContext = createContext(null, httpRequestBuilder, httpResponseBuilder);
httpServerContext.attributes().put("responsebuilder", httpResponseBuilder); httpServerContext.getAttributes().put("responsebuilder", httpResponseBuilder);
try { try {
getRouter().routeStatus(httpResponseStatus, httpServerContext); getRouter().routeStatus(httpResponseStatus, httpServerContext);
} catch (Throwable t) { } catch (Throwable t) {
@ -159,11 +159,11 @@ public class BaseApplication implements Application {
HttpRequestBuilder requestBuilder, HttpRequestBuilder requestBuilder,
HttpResponseBuilder responseBuilder) { HttpResponseBuilder responseBuilder) {
HttpServerContext httpServerContext = new BaseHttpServerContext(this, domain, requestBuilder, responseBuilder); HttpServerContext httpServerContext = new BaseHttpServerContext(this, domain, requestBuilder, responseBuilder);
httpServerContext.attributes().put("requestbuilder", requestBuilder); httpServerContext.getAttributes().put("requestbuilder", requestBuilder);
httpServerContext.attributes().put("responsebuilder", responseBuilder); httpServerContext.getAttributes().put("responsebuilder", responseBuilder);
this.sessionCodec = buildSessionCodec(httpServerContext); this.sessionCodec = buildSessionCodec(httpServerContext);
if (sessionCodec != null) { if (sessionCodec != null) {
httpServerContext.attributes().put("sessioncodec", sessionCodec); httpServerContext.getAttributes().put("sessioncodec", sessionCodec);
} }
this.incomingSessionHandler = buildIncomingSessionHandler(httpServerContext); this.incomingSessionHandler = buildIncomingSessionHandler(httpServerContext);
this.outgoingSessionHandler = buildOutgoingSessionHandler(httpServerContext); this.outgoingSessionHandler = buildOutgoingSessionHandler(httpServerContext);
@ -188,7 +188,7 @@ public class BaseApplication implements Application {
protected HttpHandler buildIncomingSessionHandler(HttpServerContext httpServerContext) { protected HttpHandler buildIncomingSessionHandler(HttpServerContext httpServerContext) {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Codec<Session> sessionCodec = httpServerContext.attributes().get(Codec.class, "sessioncodec"); Codec<Session> sessionCodec = httpServerContext.getAttributes().get(Codec.class, "sessioncodec");
return new IncomingSessionHandler( return new IncomingSessionHandler(
getSecret(), getSecret(),
"HmacSHA1", "HmacSHA1",
@ -202,7 +202,7 @@ public class BaseApplication implements Application {
protected HttpHandler buildOutgoingSessionHandler(HttpServerContext httpServerContext) { protected HttpHandler buildOutgoingSessionHandler(HttpServerContext httpServerContext) {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Codec<Session> sessionCodec = httpServerContext.attributes().get(Codec.class, "sessioncodec"); Codec<Session> sessionCodec = httpServerContext.getAttributes().get(Codec.class, "sessioncodec");
return new OutgoingSessionHandler( return new OutgoingSessionHandler(
getSecret(), getSecret(),
"HmacSHA1", "HmacSHA1",

View file

@ -91,7 +91,7 @@ public abstract class BaseHttpRequest implements HttpRequest {
} }
@Override @Override
public Attributes attributes() { public Attributes getAttributes() {
return attributes; return attributes;
} }
} }

View file

@ -1,10 +1,13 @@
package org.xbib.net.http.server; package org.xbib.net.http.server;
import java.util.Map;
import org.xbib.datastructures.json.tiny.Json;
import org.xbib.net.Attributes; import org.xbib.net.Attributes;
import org.xbib.net.Parameter; import org.xbib.net.Parameter;
import org.xbib.net.ParameterBuilder; import org.xbib.net.ParameterBuilder;
import org.xbib.net.URL; import org.xbib.net.URL;
import org.xbib.net.buffer.DataBuffer; import org.xbib.net.buffer.DataBuffer;
import org.xbib.net.http.HttpHeaderNames;
import org.xbib.net.http.HttpHeaderValues; import org.xbib.net.http.HttpHeaderValues;
import org.xbib.net.http.HttpHeaders; import org.xbib.net.http.HttpHeaders;
import org.xbib.net.http.HttpMethod; import org.xbib.net.http.HttpMethod;
@ -39,14 +42,14 @@ public class BaseHttpServerContext implements HttpServerContext {
private final HttpResponseBuilder httpResponseBuilder; private final HttpResponseBuilder httpResponseBuilder;
private final Attributes attributes;
private HttpRouteResolver.Result<HttpService> pathResolverResult; private HttpRouteResolver.Result<HttpService> pathResolverResult;
private String contextPath; private String contextPath;
private URL contextURL; private URL contextURL;
private Attributes attributes;
private HttpRequest httpRequest; private HttpRequest httpRequest;
private boolean done; private boolean done;
@ -131,12 +134,8 @@ public class BaseHttpServerContext implements HttpServerContext {
return application.resolve(path); return application.resolve(path);
} }
public void setAttributes(Attributes attributes) {
this.attributes = attributes;
}
@Override @Override
public Attributes attributes() { public Attributes getAttributes() {
return attributes; return attributes;
} }
@ -223,6 +222,22 @@ public class BaseHttpServerContext implements HttpServerContext {
formParameterBuilder.addPercentEncodedBody(charBuffer.toString()); formParameterBuilder.addPercentEncodedBody(charBuffer.toString());
} }
} }
String contentType = httpRequestBuilder.getHeaders().get(HttpHeaderNames.CONTENT_TYPE);
if (contentType != null && contentType.contains(HttpHeaderValues.APPLICATION_JSON)) {
String content = httpRequestBuilder.getBodyAsChars(StandardCharsets.UTF_8).toString();
try {
Map<String, Object> map = Json.toMap(content);
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getValue() instanceof Iterable<?> iterable) {
iterable.forEach(it -> formParameterBuilder.add(entry.getKey(), it));
} else {
formParameterBuilder.add(entry.getKey(), entry.getValue());
}
}
} catch (Exception e) {
logger.log(Level.WARNING, "unable to decode json body: " + e.getMessage(), e);
}
}
CookieBox cookieBox = attributes.get(CookieBox.class, "incomingcookies"); CookieBox cookieBox = attributes.get(CookieBox.class, "incomingcookies");
ParameterBuilder cookieParameterBuilder = Parameter.builder().domain(Parameter.Domain.COOKIE); ParameterBuilder cookieParameterBuilder = Parameter.builder().domain(Parameter.Domain.COOKIE);
if (cookieBox != null) { if (cookieBox != null) {

View file

@ -39,5 +39,5 @@ public interface HttpRequest extends Request {
InputStream getInputStream(); InputStream getInputStream();
Attributes attributes(); Attributes getAttributes();
} }

View file

@ -20,7 +20,7 @@ public interface HttpServerContext {
void setResolverResult(HttpRouteResolver.Result<HttpService> result); void setResolverResult(HttpRouteResolver.Result<HttpService> result);
Attributes attributes(); Attributes getAttributes();
void done(); void done();

View file

@ -24,7 +24,7 @@ public class BasicAuthenticationHandler extends LoginAuthenticationHandler imple
@Override @Override
public void handle(HttpServerContext context) throws IOException { public void handle(HttpServerContext context) throws IOException {
HttpRequest httpRequest = context.httpRequest(); HttpRequest httpRequest = context.httpRequest();
UserProfile userProfile = context.attributes().get(UserProfile.class, "userprofile"); UserProfile userProfile = context.getAttributes().get(UserProfile.class, "userprofile");
if (userProfile != null && userProfile.getUserId() != null) { if (userProfile != null && userProfile.getUserId() != null) {
return; return;
} }
@ -41,7 +41,7 @@ public class BasicAuthenticationHandler extends LoginAuthenticationHandler imple
userProfile = new BaseUserProfile(); userProfile = new BaseUserProfile();
try { try {
authenticate(userProfile, tokens[0], tokens[1], httpRequest); authenticate(userProfile, tokens[0], tokens[1], httpRequest);
context.attributes().put("userprofile", userProfile); context.getAttributes().put("userprofile", userProfile);
return; return;
} catch (Exception e) { } catch (Exception e) {
logger.log(Level.WARNING, "authentication error"); logger.log(Level.WARNING, "authentication error");

View file

@ -40,14 +40,14 @@ public class FormAuthenticationHandler extends LoginAuthenticationHandler implem
logger.log(Level.WARNING, "no loginPage configured"); logger.log(Level.WARNING, "no loginPage configured");
return; return;
} }
UserProfile userProfile = context.attributes().get(UserProfile.class, "userprofile"); UserProfile userProfile = context.getAttributes().get(UserProfile.class, "userprofile");
if (userProfile != null && userProfile.getUserId() != null) { if (userProfile != null && userProfile.getUserId() != null) {
logger.log(Level.FINE, "user id already set: " + userProfile.getUserId()); logger.log(Level.FINE, "user id already set: " + userProfile.getUserId());
return; return;
} }
// always add an "anonymous" user profile // always add an "anonymous" user profile
userProfile = new BaseUserProfile(); userProfile = new BaseUserProfile();
context.attributes().put("userprofile", userProfile); context.getAttributes().put("userprofile", userProfile);
Parameter parameter = context.httpRequest().getParameter(); Parameter parameter = context.httpRequest().getParameter();
if (!parameter.containsKey(usernameParameter, Parameter.Domain.FORM)) { if (!parameter.containsKey(usernameParameter, Parameter.Domain.FORM)) {
logger.log(Level.WARNING, "usernameParameter not set, unable to authenticate"); logger.log(Level.WARNING, "usernameParameter not set, unable to authenticate");
@ -76,9 +76,9 @@ public class FormAuthenticationHandler extends LoginAuthenticationHandler implem
// this will redirect internally to login page, and back to the original path. // this will redirect internally to login page, and back to the original path.
// We need a full path resolve against the server URL. // We need a full path resolve against the server URL.
logger.log(Level.FINE, "templatePath = " + loginPage); logger.log(Level.FINE, "templatePath = " + loginPage);
context.attributes().put("templatePath", loginPage); context.getAttributes().put("templatePath", loginPage);
URL loc = context.getContextURL().resolve(context.httpRequest().getRequestURI()).normalize(); URL loc = context.getContextURL().resolve(context.httpRequest().getRequestURI()).normalize();
logger.log(Level.FINE, "context URL = " + context.getContextURL() + " request URI = " + context.httpRequest().getRequestURI() + " loc = " + loc); logger.log(Level.FINE, "context URL = " + context.getContextURL() + " request URI = " + context.httpRequest().getRequestURI() + " loc = " + loc);
context.attributes().put("originalPath", loc.toExternalForm()); context.getAttributes().put("originalPath", loc.toExternalForm());
} }
} }

View file

@ -36,7 +36,7 @@ public class LoginAuthenticationHandler implements HttpHandler {
@Override @Override
public void handle(HttpServerContext context) throws IOException { public void handle(HttpServerContext context) throws IOException {
UserProfile userProfile = context.attributes().get(UserProfile.class, "userprofile"); UserProfile userProfile = context.getAttributes().get(UserProfile.class, "userprofile");
if (userProfile != null && userProfile.getUserId() != null) { if (userProfile != null && userProfile.getUserId() != null) {
return; return;
} }
@ -46,7 +46,7 @@ public class LoginAuthenticationHandler implements HttpHandler {
(String) context.httpRequest().getParameter().get(userParameterName, Parameter.Domain.DEFAULT, Parameter.Domain.FORM), (String) context.httpRequest().getParameter().get(userParameterName, Parameter.Domain.DEFAULT, Parameter.Domain.FORM),
(String) context.httpRequest().getParameter().get(passwordParameterName, Parameter.Domain.DEFAULT, Parameter.Domain.FORM), (String) context.httpRequest().getParameter().get(passwordParameterName, Parameter.Domain.DEFAULT, Parameter.Domain.FORM),
context.httpRequest()); context.httpRequest());
context.attributes().put("userprofile", userProfile); context.getAttributes().put("userprofile", userProfile);
} catch (Exception e) { } catch (Exception e) {
logger.log(Level.SEVERE, "authentication error"); logger.log(Level.SEVERE, "authentication error");
} }

View file

@ -30,7 +30,7 @@ public class IncomingCookieHandler implements HttpHandler {
cookieBox.addAll(CookieDecoder.LAX.decode(cookieString)); cookieBox.addAll(CookieDecoder.LAX.decode(cookieString));
} }
if (!cookieBox.isEmpty()) { if (!cookieBox.isEmpty()) {
context.attributes().put("incomingcookies", cookieBox); context.getAttributes().put("incomingcookies", cookieBox);
} }
} }

View file

@ -18,7 +18,7 @@ public class OutgoingCookieHandler implements HttpHandler {
@Override @Override
public void handle(HttpServerContext context) throws HttpException { public void handle(HttpServerContext context) throws HttpException {
CookieBox cookieBox = context.attributes().get(CookieBox.class, "outgoingcookies"); CookieBox cookieBox = context.getAttributes().get(CookieBox.class, "outgoingcookies");
if (cookieBox != null) { if (cookieBox != null) {
for (Cookie cookie : cookieBox) { for (Cookie cookie : cookieBox) {
context.response().addCookie(cookie); context.response().addCookie(cookie);

View file

@ -18,7 +18,7 @@ public class InternalServerErrorHandler implements HttpErrorHandler {
@Override @Override
public void handle(HttpServerContext context) throws IOException { public void handle(HttpServerContext context) throws IOException {
Throwable throwable = context.attributes().get(Throwable.class, "_throwable"); Throwable throwable = context.getAttributes().get(Throwable.class, "_throwable");
if (throwable != null) { if (throwable != null) {
logger.log(Level.SEVERE, throwable.getMessage(), throwable); logger.log(Level.SEVERE, throwable.getMessage(), throwable);
} }

View file

@ -28,7 +28,7 @@ public class CombinedFormatLogger implements HttpHandler {
HttpResponseStatus httpResponseStatus = httpServerContext.response().getResponseStatus(); HttpResponseStatus httpResponseStatus = httpServerContext.response().getResponseStatus();
int statusInteger = httpResponseStatus != null ? httpResponseStatus.code() : 0; int statusInteger = httpResponseStatus != null ? httpResponseStatus.code() : 0;
Long contentLength = httpServerContext.response().getLength(); Long contentLength = httpServerContext.response().getLength();
UserProfile userProfile = httpServerContext.attributes().get(UserProfile.class, "userprofile"); UserProfile userProfile = httpServerContext.getAttributes().get(UserProfile.class, "userprofile");
String user = userProfile != null ? userProfile.getEffectiveUserId() : ""; String user = userProfile != null ? userProfile.getEffectiveUserId() : "";
String referer = request.getHeaders().get(HttpHeaderNames.REFERER); String referer = request.getHeaders().get(HttpHeaderNames.REFERER);
referer = referer != null ? referer : ""; referer = referer != null ? referer : "";

View file

@ -27,7 +27,7 @@ public class CommonFormatLogger implements HttpHandler {
HttpResponseStatus httpResponseStatus = httpServerContext.response().getResponseStatus(); HttpResponseStatus httpResponseStatus = httpServerContext.response().getResponseStatus();
int statusInteger = httpResponseStatus != null ? httpResponseStatus.code() : 0; int statusInteger = httpResponseStatus != null ? httpResponseStatus.code() : 0;
Long contentLength = httpServerContext.response().getLength(); Long contentLength = httpServerContext.response().getLength();
UserProfile userProfile = httpServerContext.attributes().get(UserProfile.class, "userprofile"); UserProfile userProfile = httpServerContext.getAttributes().get(UserProfile.class, "userprofile");
String user = userProfile != null ? userProfile.getEffectiveUserId() : ""; String user = userProfile != null ? userProfile.getEffectiveUserId() : "";
String message = String.format(Locale.US, LOG_FORMAT, String message = String.format(Locale.US, LOG_FORMAT,
inetAddressString, inetAddressString,

View file

@ -95,22 +95,22 @@ public abstract class AbstractResourceHandler implements HttpHandler {
} }
context.done(); context.done();
} else { } else {
logger.log(Level.FINE, "handle: generate cacheable resource"); logger.log(Level.FINER, "handle: generate cacheable resource");
generateCacheableResource(context, resource); generateCacheableResource(context, resource);
context.done(); context.done();
} }
logger.log(Level.FINE, "handle: done"); logger.log(Level.FINER, "handle: done");
} }
private void generateCacheableResource(HttpServerContext context, Resource resource) throws IOException { private void generateCacheableResource(HttpServerContext context, Resource resource) throws IOException {
// if resource is length of 0, there is nothing to send. Do not send any content, // if resource is length of 0, there is nothing to send. Do not send any content,
if (resource.getLength() == 0) { if (resource.getLength() == 0) {
logger.log(Level.FINE, "the resource length is 0, do nothing"); logger.log(Level.FINER, "the resource length is 0, do nothing");
context.response().build().flush(); context.response().build().flush();
return; return;
} }
HttpHeaders headers = context.request().getHeaders(); HttpHeaders headers = context.request().getHeaders();
logger.log(Level.FINE, "before generating resource, the response headers are " + context.response().getHeaders()); logger.log(Level.FINER, "before generating resource, the response headers are " + context.response().getHeaders());
String contentType = resource.getMimeType(); String contentType = resource.getMimeType();
context.response().addHeader(HttpHeaderNames.CONTENT_TYPE, contentType); context.response().addHeader(HttpHeaderNames.CONTENT_TYPE, contentType);
// heuristic for inline disposition // heuristic for inline disposition

View file

@ -37,8 +37,8 @@ public class FileResourceHandler extends AbstractResourceHandler {
@Override @Override
protected Resource createResource(HttpServerContext httpServerContext) throws IOException { protected Resource createResource(HttpServerContext httpServerContext) throws IOException {
String pathSpec = httpServerContext.attributes().containsKey("templatePath") ? String pathSpec = httpServerContext.getAttributes().containsKey("templatePath") ?
(String) httpServerContext.attributes().get("templatePath") : (String) httpServerContext.getAttributes().get("templatePath") :
pathNameOfResource != null ? pathNameOfResource : httpServerContext.getContextPath(); pathNameOfResource != null ? pathNameOfResource : httpServerContext.getContextPath();
if (pathSpec == null || pathSpec.isEmpty()) { if (pathSpec == null || pathSpec.isEmpty()) {
throw new IllegalArgumentException("path must not be null or empty"); throw new IllegalArgumentException("path must not be null or empty");
@ -106,7 +106,7 @@ public class FileResourceHandler extends AbstractResourceHandler {
protected FileResource(HttpServerContext httpServerContext, String resourcePath) throws IOException { protected FileResource(HttpServerContext httpServerContext, String resourcePath) throws IOException {
this.resourcePath = resourcePath; this.resourcePath = resourcePath;
Application application = httpServerContext.attributes().get(Application.class, "application"); Application application = httpServerContext.getAttributes().get(Application.class, "application");
Path root = application.getHome(); Path root = application.getHome();
if (root == null) { if (root == null) {
throw new IllegalArgumentException("no home path set for template resource resolving"); throw new IllegalArgumentException("no home path set for template resource resolving");

View file

@ -45,7 +45,7 @@ public class HtmlTemplateResource implements HttpServerResource {
HttpServerContext httpServerContext) throws IOException { HttpServerContext httpServerContext) throws IOException {
this.templateResourceHandler = templateResourceHandler; this.templateResourceHandler = templateResourceHandler;
String indexFileName = templateResourceHandler.getIndexFileName(); String indexFileName = templateResourceHandler.getIndexFileName();
Application application = httpServerContext.attributes().get(Application.class, "application"); Application application = httpServerContext.getAttributes().get(Application.class, "application");
this.negotiateLocale = application.getSettings().getAsBoolean("negotiateLocale", false); this.negotiateLocale = application.getSettings().getAsBoolean("negotiateLocale", false);
Path root = templateResourceHandler.getRoot(); Path root = templateResourceHandler.getRoot();
root = root != null ? root : application.getHome(); root = root != null ? root : application.getHome();

View file

@ -29,8 +29,8 @@ public class WebRootResourceResolver implements ResourceResolver {
public Resource resolveResource(HttpServerContext httpServerContext, public Resource resolveResource(HttpServerContext httpServerContext,
String templateName, String templateName,
List<String> indexFiles) throws IOException { List<String> indexFiles) throws IOException {
String pathSpec = httpServerContext.attributes().containsKey("forwardedPath") ? String pathSpec = httpServerContext.getAttributes().containsKey("forwardedPath") ?
(String) httpServerContext.attributes().get("forwardedPath") : (String) httpServerContext.getAttributes().get("forwardedPath") :
templateName != null ? templateName : httpServerContext.httpRequest().getRequestPath(); templateName != null ? templateName : httpServerContext.httpRequest().getRequestPath();
if (pathSpec == null || pathSpec.isEmpty()) { if (pathSpec == null || pathSpec.isEmpty()) {
throw new IllegalArgumentException("path must not be null or empty"); throw new IllegalArgumentException("path must not be null or empty");

View file

@ -73,6 +73,7 @@ public class BaseHttpRouter implements HttpRouter {
@Override @Override
public void setApplication(Application application) { public void setApplication(Application application) {
Objects.requireNonNull(application);
this.application = application; this.application = application;
} }
@ -88,7 +89,6 @@ public class BaseHttpRouter implements HttpRouter {
@Override @Override
public void route(HttpRequestBuilder requestBuilder, HttpResponseBuilder responseBuilder) { public void route(HttpRequestBuilder requestBuilder, HttpResponseBuilder responseBuilder) {
Objects.requireNonNull(application);
Objects.requireNonNull(requestBuilder); Objects.requireNonNull(requestBuilder);
Objects.requireNonNull(requestBuilder.getRequestURI()); Objects.requireNonNull(requestBuilder.getRequestURI());
Objects.requireNonNull(requestBuilder.getBaseURL()); Objects.requireNonNull(requestBuilder.getBaseURL());
@ -139,7 +139,7 @@ public class BaseHttpRouter implements HttpRouter {
break; break;
} }
// after security checks, accept service, open and execute service // after security checks, accept service, open and execute service
httpServerContext.attributes().put("service", httpService); httpServerContext.getAttributes().put("service", httpService);
application.getModules().forEach(module -> module.onOpen(application, httpServerContext, httpService)); application.getModules().forEach(module -> module.onOpen(application, httpServerContext, httpService));
logger.log(Level.FINEST, () -> "handling service " + httpService); logger.log(Level.FINEST, () -> "handling service " + httpService);
httpService.handle(httpServerContext); httpService.handle(httpServerContext);
@ -187,7 +187,7 @@ public class BaseHttpRouter implements HttpRouter {
@Override @Override
public void routeToErrorHandler(HttpServerContext httpServerContext, Throwable t) { public void routeToErrorHandler(HttpServerContext httpServerContext, Throwable t) {
httpServerContext.attributes().put("_throwable", t); httpServerContext.getAttributes().put("_throwable", t);
httpServerContext.fail(); httpServerContext.fail();
routeStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR, httpServerContext); routeStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR, httpServerContext);
} }

View file

@ -73,7 +73,7 @@ public class IncomingSessionHandler implements HttpHandler {
return; return;
} }
Session session = null; Session session = null;
CookieBox cookieBox = context.attributes().get(CookieBox.class, "incomingcookies"); CookieBox cookieBox = context.getAttributes().get(CookieBox.class, "incomingcookies");
if (cookieBox != null) { if (cookieBox != null) {
for (Cookie cookie : cookieBox) { for (Cookie cookie : cookieBox) {
if (cookie.name().equals(sessionCookieName)) { if (cookie.name().equals(sessionCookieName)) {
@ -84,11 +84,11 @@ public class IncomingSessionHandler implements HttpHandler {
session = toSession(payload); session = toSession(payload);
UserProfile userProfile = newUserProfile(payload, session); UserProfile userProfile = newUserProfile(payload, session);
if (userProfile != null) { if (userProfile != null) {
context.attributes().put("userprofile", userProfile); context.getAttributes().put("userprofile", userProfile);
} }
} catch (CookieSignatureException e) { } catch (CookieSignatureException e) {
// set exception in context to discard broken cookie later and render exception message // set exception in context to discard broken cookie later and render exception message
context.attributes().put("_throwable", e); context.getAttributes().put("_throwable", e);
} catch (Exception e) { } catch (Exception e) {
logger.log(Level.SEVERE, e.getMessage(), e); logger.log(Level.SEVERE, e.getMessage(), e);
throw new HttpException("unable to create session", context, HttpResponseStatus.INTERNAL_SERVER_ERROR); throw new HttpException("unable to create session", context, HttpResponseStatus.INTERNAL_SERVER_ERROR);
@ -107,7 +107,7 @@ public class IncomingSessionHandler implements HttpHandler {
throw new HttpException("unable to create session", context, HttpResponseStatus.INTERNAL_SERVER_ERROR); throw new HttpException("unable to create session", context, HttpResponseStatus.INTERNAL_SERVER_ERROR);
} }
} }
context.attributes().put("session", session); context.getAttributes().put("session", session);
logger.log(Level.FINER, "incoming session " + session.id()); logger.log(Level.FINER, "incoming session " + session.id());
} }

View file

@ -88,21 +88,21 @@ public class OutgoingSessionHandler implements HttpHandler {
logger.log(Level.FINE, "suffix " + suffix + " blocking outgoing session handling"); logger.log(Level.FINE, "suffix " + suffix + " blocking outgoing session handling");
return; return;
} }
CookieBox cookieBox = context.attributes().get(CookieBox.class, "outgoingcookies"); CookieBox cookieBox = context.getAttributes().get(CookieBox.class, "outgoingcookies");
if (cookieBox == null) { if (cookieBox == null) {
cookieBox = new CookieBox(); cookieBox = new CookieBox();
} }
Application application = context.attributes().get(Application.class, "application"); Application application = context.getAttributes().get(Application.class, "application");
UserProfile userProfile = context.attributes().get(UserProfile.class, "userprofile"); UserProfile userProfile = context.getAttributes().get(UserProfile.class, "userprofile");
String host = context.getContextURL().getHost(); String host = context.getContextURL().getHost();
String path = application.getContextPath(); String path = application.getContextPath();
Throwable throwable = context.attributes().get(Throwable.class, "_throwable"); Throwable throwable = context.getAttributes().get(Throwable.class, "_throwable");
if (throwable instanceof CookieSignatureException) { if (throwable instanceof CookieSignatureException) {
cookieBox = new CookieBox(); cookieBox = new CookieBox();
cookieBox.add(createEmptyCookie(host, path)); cookieBox.add(createEmptyCookie(host, path));
return; return;
} }
Session session = context.attributes().get(Session.class, "session"); Session session = context.getAttributes().get(Session.class, "session");
if (session != null) { if (session != null) {
try { try {
if (userProfile != null) { if (userProfile != null) {
@ -125,7 +125,7 @@ public class OutgoingSessionHandler implements HttpHandler {
} }
} }
logger.log(Level.FINER, "outgoing cookies = " + cookieBox); logger.log(Level.FINER, "outgoing cookies = " + cookieBox);
context.attributes().put("outgoingcookies", cookieBox); context.getAttributes().put("outgoingcookies", cookieBox);
} }
private Cookie encodeCookie(Session session, String host, String path) throws IOException, private Cookie encodeCookie(Session session, String host, String path) throws IOException,

View file

@ -45,11 +45,11 @@ public abstract class DefaultMarkupTemplate extends BaseTemplate {
this.application = (Application) model.get("application"); this.application = (Application) model.get("application");
Objects.requireNonNull(this.application, "application must not be null"); Objects.requireNonNull(this.application, "application must not be null");
this.responseBuilder = (HttpResponseBuilder) model.get("responsebuilder"); this.responseBuilder = (HttpResponseBuilder) model.get("responsebuilder");
Objects.requireNonNull(this.responseBuilder, "response must not be null"); Objects.requireNonNull(this.responseBuilder, "responsebuilder must not be null");
this.request = (HttpRequest) model.get("request"); this.request = (HttpRequest) model.get("request");
// request can be null in error templates Objects.requireNonNull(this.request, "request must not be null");
this.session = (Session) model.get("session"); this.session = (Session) model.get("session");
// session can be null in error templates // session can be null in environments without sessions
} }
public void setContentType(String contentType) { public void setContentType(String contentType) {
@ -105,23 +105,27 @@ public abstract class DefaultMarkupTemplate extends BaseTemplate {
} }
public String contextPath(String rel) { public String contextPath(String rel) {
return urlProto(rel, false); return url(rel, false);
} }
public String url(String rel) { public String url(String rel) {
return urlProto(rel, true); return url(rel, true);
} }
public String urlProto(String rel, boolean absolute) { public String url(String rel, boolean absolute) {
String prefix = application.getSettings().get("web.prefix", "/"); String prefix = application.getSettings().get("web.prefix", "/");
if (!prefix.endsWith("/")) { if (!prefix.endsWith("/")) {
prefix = prefix + "/"; prefix = prefix + "/";
} }
if (request != null) {
URL url = request.getServerURL().resolve(prefix).resolve(rel); URL url = request.getServerURL().resolve(prefix).resolve(rel);
logger.log(Level.FINE, "server base URL = " + request.getServerURL() + logger.log(Level.FINE, "server base URL = " + request.getServerURL() +
" prefix = " + prefix + " prefix = " + prefix + " rel = " + rel + " --> " + url);
" rel = " + rel + " --> " + url);
return absolute ? url.toExternalForm() : toOrigin(url); return absolute ? url.toExternalForm() : toOrigin(url);
} else {
logger.log(Level.WARNING, "request is null, returning " + prefix + rel);
return prefix + rel;
}
} }
public String encodeUrl(String rel) { public String encodeUrl(String rel) {
@ -213,15 +217,15 @@ public abstract class DefaultMarkupTemplate extends BaseTemplate {
} }
public String bootstrapCss() { public String bootstrapCss() {
return contextPath("webjars/bootstrap/5.2.2/dist/css/bootstrap.min.css"); return contextPath("webjars/bootstrap/5.2.3/css/bootstrap.min.css");
} }
public String bootstrapJs() { public String bootstrapJs() {
return contextPath("webjars/bootstrap/5.2.2/dist/js/bootstrap.min.js"); return contextPath("webjars/bootstrap/5.2.3/js/bootstrap.min.js");
} }
public String jqueryJs() { public String jqueryJs() {
return contextPath("webjars/jquery/3.6.3/dist/jquery.min.js"); return contextPath("webjars/jquery/3.6.4/jquery.min.js");
} }
public String fontawesomeCss() { public String fontawesomeCss() {

View file

@ -32,10 +32,10 @@ class GroovyHttpResonseStatusTemplateResource extends GroovyTemplateResource {
@Override @Override
public void render(HttpServerContext httpServerContext) throws IOException { public void render(HttpServerContext httpServerContext) throws IOException {
logger.log(Level.FINE, "rendering HTTP status by Groovy"); logger.log(Level.FINE, "rendering HTTP status by Groovy");
httpServerContext.attributes().put("_status", httpResponseStatus); httpServerContext.getAttributes().put("_status", httpResponseStatus);
httpServerContext.attributes().put("_message", message); httpServerContext.getAttributes().put("_message", message);
httpServerContext.attributes().put("_resource", this); httpServerContext.getAttributes().put("_resource", this);
Application application = httpServerContext.attributes().get(Application.class, "application"); Application application = httpServerContext.getAttributes().get(Application.class, "application");
GroovyMarkupTemplateHandler groovyMarkupTemplateHandler = new GroovyMarkupTemplateHandler(application); GroovyMarkupTemplateHandler groovyMarkupTemplateHandler = new GroovyMarkupTemplateHandler(application);
logger.log(Level.FINE, "handle groovyMarkupTemplateHandler"); logger.log(Level.FINE, "handle groovyMarkupTemplateHandler");
groovyMarkupTemplateHandler.handle(httpServerContext); groovyMarkupTemplateHandler.handle(httpServerContext);

View file

@ -26,7 +26,7 @@ public class GroovyInternalServerErrorHandler extends GroovyTemplateResourceHand
} }
private String createMessage(HttpServerContext context) throws IOException { private String createMessage(HttpServerContext context) throws IOException {
Throwable throwable = context.attributes().get(Throwable.class, "_throwable"); Throwable throwable = context.getAttributes().get(Throwable.class, "_throwable");
if (throwable != null) { if (throwable != null) {
logger.log(Level.SEVERE, throwable.getMessage(), throwable); logger.log(Level.SEVERE, throwable.getMessage(), throwable);
} }

View file

@ -60,14 +60,14 @@ public class GroovyMarkupTemplateHandler implements HttpHandler {
@Override @Override
public void handle(HttpServerContext context) throws IOException { public void handle(HttpServerContext context) throws IOException {
DefaultTemplateResolver templateResolver = context.attributes().get(DefaultTemplateResolver.class, "templateresolver"); DefaultTemplateResolver templateResolver = context.getAttributes().get(DefaultTemplateResolver.class, "templateresolver");
if (templateResolver == null) { if (templateResolver == null) {
context.attributes().put("templateresolver", this.templateResolver); context.getAttributes().put("templateresolver", this.templateResolver);
logger.log(Level.FINER, "setting templateresolver " + this.templateResolver); logger.log(Level.FINER, "setting templateresolver " + this.templateResolver);
} }
TemplateEngine templateEngine = context.attributes().get(TemplateEngine.class, "templateengine"); TemplateEngine templateEngine = context.getAttributes().get(TemplateEngine.class, "templateengine");
if (templateEngine == null) { if (templateEngine == null) {
context.attributes().put("templateengine", this.templateEngine); context.getAttributes().put("templateengine", this.templateEngine);
logger.log(Level.FINER, "setting templateengine " + this.templateEngine); logger.log(Level.FINER, "setting templateengine " + this.templateEngine);
} }
} }

View file

@ -64,9 +64,9 @@ public class GroovyTemplateApplicationModule extends BaseApplicationModule {
@Override @Override
public void onOpen(Application application, HttpServerContext httpServerContext, HttpService httpService, HttpRequest httpRequest) { public void onOpen(Application application, HttpServerContext httpServerContext, HttpService httpService, HttpRequest httpRequest) {
httpServerContext.attributes().put("request", httpRequest); httpServerContext.getAttributes().put("request", httpRequest);
httpServerContext.attributes().put("params", httpRequest.getParameter().asSingleValuedMap()); httpServerContext.getAttributes().put("params", httpRequest.getParameter().asSingleValuedMap());
application.getModules().forEach(module -> httpServerContext.attributes().put(module.getName(), module)); application.getModules().forEach(module -> httpServerContext.getAttributes().put(module.getName(), module));
} }
@Override @Override

View file

@ -19,14 +19,14 @@ public class GroovyTemplateRenderer implements HttpHandler {
@Override @Override
public void handle(HttpServerContext context) throws IOException { public void handle(HttpServerContext context) throws IOException {
Writable writable = context.attributes().get(Writable.class, "writable"); Writable writable = context.getAttributes().get(Writable.class, "writable");
if (writable != null) { if (writable != null) {
DataBuffer dataBuffer = context.response().getDataBufferFactory().allocateBuffer(); DataBuffer dataBuffer = context.response().getDataBufferFactory().allocateBuffer();
try (OutputStream outputStream = dataBuffer.asOutputStream()) { try (OutputStream outputStream = dataBuffer.asOutputStream()) {
Writer writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8); Writer writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
writable.writeTo(writer); writable.writeTo(writer);
} }
HttpResponseStatus httpResponseStatus = context.attributes().get(HttpResponseStatus.class, "_status", HttpResponseStatus.OK); HttpResponseStatus httpResponseStatus = context.getAttributes().get(HttpResponseStatus.class, "_status", HttpResponseStatus.OK);
context.response() context.response()
.setResponseStatus(httpResponseStatus) .setResponseStatus(httpResponseStatus)
.setHeader("content-length", Integer.toString(dataBuffer.writePosition())) .setHeader("content-length", Integer.toString(dataBuffer.writePosition()))

View file

@ -48,18 +48,18 @@ public class GroovyTemplateResource extends HtmlTemplateResource {
@Override @Override
public void render(HttpServerContext httpServerContext) throws IOException { public void render(HttpServerContext httpServerContext) throws IOException {
logger.log(Level.FINER, "rendering groovy template, path = " + getPath() + " isExists = " + isExists() + " isDirectory =" + isDirectory() ); logger.log(Level.FINER, "rendering groovy template, path = " + getPath() + " isExists = " + isExists() + " isDirectory =" + isDirectory() );
Application application = httpServerContext.attributes().get(Application.class, "application"); Application application = httpServerContext.getAttributes().get(Application.class, "application");
if (application == null) { if (application == null) {
logger.log(Level.WARNING, "application is null"); logger.log(Level.WARNING, "application is null");
return; return;
} }
TemplateEngine templateEngine = httpServerContext.attributes().get(TemplateEngine.class, "templateengine"); TemplateEngine templateEngine = httpServerContext.getAttributes().get(TemplateEngine.class, "templateengine");
if (templateEngine == null) { if (templateEngine == null) {
logger.log(Level.WARNING, "template engine is null"); logger.log(Level.WARNING, "template engine is null");
return; return;
} }
Path templatePath = getPath(); Path templatePath = getPath();
HttpService service = httpServerContext.attributes().get(HttpService.class, "service"); HttpService service = httpServerContext.getAttributes().get(HttpService.class, "service");
if (service instanceof GroovyTemplateService groovyTemplateService) { if (service instanceof GroovyTemplateService groovyTemplateService) {
if (groovyTemplateService.getTemplateName() != null) { if (groovyTemplateService.getTemplateName() != null) {
templatePath = application.resolve(groovyTemplateService.getTemplateName()); templatePath = application.resolve(groovyTemplateService.getTemplateName());
@ -69,7 +69,7 @@ public class GroovyTemplateResource extends HtmlTemplateResource {
} }
} }
// status response handlers have priority // status response handlers have priority
GroovyHttpResonseStatusTemplateResource resource = httpServerContext.attributes().get(GroovyHttpResonseStatusTemplateResource.class, "_resource"); GroovyHttpResonseStatusTemplateResource resource = httpServerContext.getAttributes().get(GroovyHttpResonseStatusTemplateResource.class, "_resource");
if (resource != null) { if (resource != null) {
String indexFileName = resource.getIndexFileName(); String indexFileName = resource.getIndexFileName();
if (indexFileName != null) { if (indexFileName != null) {
@ -78,7 +78,7 @@ public class GroovyTemplateResource extends HtmlTemplateResource {
logger.log(Level.FINER, "rendering Groovy HTTP status response with templatePath = " + templatePath); logger.log(Level.FINER, "rendering Groovy HTTP status response with templatePath = " + templatePath);
} else { } else {
// override if 'templatePath' attribute is set // override if 'templatePath' attribute is set
String overridePath = httpServerContext.attributes().get(String.class, "templatePath"); String overridePath = httpServerContext.getAttributes().get(String.class, "templatePath");
if (overridePath != null) { if (overridePath != null) {
logger.log(Level.FINER, "found override templatePath = " + overridePath); logger.log(Level.FINER, "found override templatePath = " + overridePath);
templatePath = application.resolve(overridePath); templatePath = application.resolve(overridePath);
@ -113,22 +113,22 @@ public class GroovyTemplateResource extends HtmlTemplateResource {
Template template = templates.get(templatePath); Template template = templates.get(templatePath);
Logger templateLogger = Logger.getLogger("template." + getName().replace('/', '.')); Logger templateLogger = Logger.getLogger("template." + getName().replace('/', '.'));
Binding binding = new Binding(); Binding binding = new Binding();
httpServerContext.attributes().forEach(binding::setVariable); httpServerContext.getAttributes().forEach(binding::setVariable);
binding.setVariable("logger", templateLogger); binding.setVariable("logger", templateLogger);
binding.setVariable("log", templateLogger); binding.setVariable("log", templateLogger);
application.getModules().forEach(m -> binding.setVariable(m.getName(), m)); application.getModules().forEach(m -> binding.setVariable(m.getName(), m));
DefaultTemplateResolver templateResolver = httpServerContext.attributes().get(DefaultTemplateResolver.class, "templateresolver"); DefaultTemplateResolver templateResolver = httpServerContext.getAttributes().get(DefaultTemplateResolver.class, "templateresolver");
if (templateResolver == null) { if (templateResolver == null) {
// for Groovy template engines without a resolver, no need to set a locale // for Groovy template engines without a resolver, no need to set a locale
Writable writable = template.make(binding.getVariables()); Writable writable = template.make(binding.getVariables());
httpServerContext.attributes().put("writable", writable); httpServerContext.getAttributes().put("writable", writable);
return; return;
} }
if (!negotiateLocale) { if (!negotiateLocale) {
// if no locale negotiation configured, set always the applicaiton locale. This constant value never changes. // if no locale negotiation configured, set always the applicaiton locale. This constant value never changes.
templateResolver.setLocale(application.getLocale()); templateResolver.setLocale(application.getLocale());
Writable writable = template.make(binding.getVariables()); Writable writable = template.make(binding.getVariables());
httpServerContext.attributes().put("writable", writable); httpServerContext.getAttributes().put("writable", writable);
return; return;
} }
// handle programmatic locale change plus template making under lock so no other request/response can interrupt us // handle programmatic locale change plus template making under lock so no other request/response can interrupt us
@ -146,12 +146,12 @@ public class GroovyTemplateResource extends HtmlTemplateResource {
} }
} }
Writable writable = template.make(binding.getVariables()); Writable writable = template.make(binding.getVariables());
httpServerContext.attributes().put("writable", writable); httpServerContext.getAttributes().put("writable", writable);
} catch (Exception e) { } catch (Exception e) {
// fail silently by ignoring negotation // fail silently by ignoring negotation
templateResolver.setLocale(application.getLocale()); templateResolver.setLocale(application.getLocale());
Writable writable = template.make(binding.getVariables()); Writable writable = template.make(binding.getVariables());
httpServerContext.attributes().put("writable", writable); httpServerContext.getAttributes().put("writable", writable);
} finally { } finally {
lock.unlock(); lock.unlock();
} }

View file

@ -3,4 +3,4 @@ handlers=java.util.logging.ConsoleHandler
java.util.logging.SimpleFormatter.format=%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS.%1$tL %4$-7s [%3$s] %5$s %6$s%n java.util.logging.SimpleFormatter.format=%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS.%1$tL %4$-7s [%3$s] %5$s %6$s%n
java.util.logging.ConsoleHandler.level=ALL java.util.logging.ConsoleHandler.level=ALL
java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter
jdk.event.security.level=ALL jdk.event.security.level=INFO

View file

@ -26,8 +26,8 @@ dependencyResolutionManagement {
library('jna', 'net.java.dev.jna', 'jna').version('5.12.1') library('jna', 'net.java.dev.jna', 'jna').version('5.12.1')
library('oracle', 'com.oracle.database.jdbc', 'ojdbc11').version('21.7.0.0') library('oracle', 'com.oracle.database.jdbc', 'ojdbc11').version('21.7.0.0')
library('groovy-templates', 'org.apache.groovy', 'groovy-templates').versionRef('groovy') library('groovy-templates', 'org.apache.groovy', 'groovy-templates').versionRef('groovy')
library('webjars-bootstrap', 'org.webjars.bower', 'bootstrap').version('5.2.2') library('webjars-bootstrap', 'org.webjars', 'bootstrap').version('5.2.3')
library('webjars-jquery', 'org.webjars.bower', 'jquery').version('3.6.3') library('webjars-jquery', 'org.webjars', 'jquery').version('3.6.4')
library('webjars-fontawesome', 'org.webjars', 'font-awesome').version('6.3.0') library('webjars-fontawesome', 'org.webjars', 'font-awesome').version('6.3.0')
library('net', 'org.xbib', 'net').versionRef('net') library('net', 'org.xbib', 'net').versionRef('net')
library('net-mime', 'org.xbib', 'net-mime').versionRef('net') library('net-mime', 'org.xbib', 'net-mime').versionRef('net')