aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/org/traccar/web
diff options
context:
space:
mode:
authorYuriy Piskarev <yuriy.piskarev@gmail.com>2023-08-24 14:16:17 +0300
committerGitHub <noreply@github.com>2023-08-24 14:16:17 +0300
commitae406c7b49a72de24d81fd74386d9638342c90ee (patch)
tree6fbcf557375b98e926c78af9c757e62c79d72a1b /src/main/java/org/traccar/web
parent56ff656c908b19feb2fa3dcffa48cc3bcdfe9b3b (diff)
parent9aeedc90da24848ff97227d6f281eb4d1e1506ef (diff)
downloadtrackermap-server-ae406c7b49a72de24d81fd74386d9638342c90ee.tar.gz
trackermap-server-ae406c7b49a72de24d81fd74386d9638342c90ee.tar.bz2
trackermap-server-ae406c7b49a72de24d81fd74386d9638342c90ee.zip
Merge branch 'traccar:master' into master
Diffstat (limited to 'src/main/java/org/traccar/web')
-rw-r--r--src/main/java/org/traccar/web/ConsoleServlet.java22
-rw-r--r--src/main/java/org/traccar/web/ModernDefaultServlet.java59
-rw-r--r--src/main/java/org/traccar/web/OverrideFilter.java87
-rw-r--r--src/main/java/org/traccar/web/ResponseWrapper.java83
-rw-r--r--src/main/java/org/traccar/web/ThrottlingFilter.java54
-rw-r--r--src/main/java/org/traccar/web/WebInjectionManagerFactory.java50
-rw-r--r--src/main/java/org/traccar/web/WebModule.java31
-rw-r--r--src/main/java/org/traccar/web/WebServer.java129
8 files changed, 429 insertions, 86 deletions
diff --git a/src/main/java/org/traccar/web/ConsoleServlet.java b/src/main/java/org/traccar/web/ConsoleServlet.java
index 0f3dcd8fd..0012ba077 100644
--- a/src/main/java/org/traccar/web/ConsoleServlet.java
+++ b/src/main/java/org/traccar/web/ConsoleServlet.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2015 - 2020 Anton Tananaev (anton@traccar.org)
+ * Copyright 2015 - 2023 Anton Tananaev (anton@traccar.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,33 +16,39 @@
package org.traccar.web;
import org.h2.server.web.ConnectionInfo;
-import org.h2.server.web.WebServlet;
+import org.h2.server.web.JakartaWebServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.traccar.Context;
+import org.traccar.config.Config;
import org.traccar.config.Keys;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
-public class ConsoleServlet extends WebServlet {
+public class ConsoleServlet extends JakartaWebServlet {
private static final Logger LOGGER = LoggerFactory.getLogger(ConsoleServlet.class);
+ private final Config config;
+
+ public ConsoleServlet(Config config) {
+ this.config = config;
+ }
+
@Override
public void init() {
super.init();
try {
- Field field = WebServlet.class.getDeclaredField("server");
+ Field field = JakartaWebServlet.class.getDeclaredField("server");
field.setAccessible(true);
org.h2.server.web.WebServer server = (org.h2.server.web.WebServer) field.get(this);
ConnectionInfo connectionInfo = new ConnectionInfo("Traccar|"
- + Context.getConfig().getString(Keys.DATABASE_DRIVER) + "|"
- + Context.getConfig().getString(Keys.DATABASE_URL) + "|"
- + Context.getConfig().getString(Keys.DATABASE_USER));
+ + config.getString(Keys.DATABASE_DRIVER) + "|"
+ + config.getString(Keys.DATABASE_URL) + "|"
+ + config.getString(Keys.DATABASE_USER));
Method method;
diff --git a/src/main/java/org/traccar/web/ModernDefaultServlet.java b/src/main/java/org/traccar/web/ModernDefaultServlet.java
new file mode 100644
index 000000000..a7c8cdb29
--- /dev/null
+++ b/src/main/java/org/traccar/web/ModernDefaultServlet.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright 2023 Anton Tananaev (anton@traccar.org)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.traccar.web;
+
+import org.eclipse.jetty.servlet.DefaultServlet;
+import org.eclipse.jetty.util.resource.Resource;
+import org.traccar.config.Config;
+import org.traccar.config.Keys;
+
+import jakarta.inject.Inject;
+import java.io.File;
+import java.io.IOException;
+
+public class ModernDefaultServlet extends DefaultServlet {
+
+ private Resource overrideResource;
+
+ @Inject
+ public ModernDefaultServlet(Config config) {
+ String override = config.getString(Keys.WEB_OVERRIDE);
+ if (override != null) {
+ overrideResource = Resource.newResource(new File(override));
+ }
+ }
+
+ @Override
+ public Resource getResource(String pathInContext) {
+ if (overrideResource != null) {
+ try {
+ Resource override = overrideResource.addPath(pathInContext);
+ if (override.exists()) {
+ return override;
+ }
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ return super.getResource(pathInContext.indexOf('.') < 0 ? "/" : pathInContext);
+ }
+
+ @Override
+ public String getWelcomeFile(String pathInContext) {
+ return super.getWelcomeFile("/");
+ }
+
+}
diff --git a/src/main/java/org/traccar/web/OverrideFilter.java b/src/main/java/org/traccar/web/OverrideFilter.java
new file mode 100644
index 000000000..f870c4147
--- /dev/null
+++ b/src/main/java/org/traccar/web/OverrideFilter.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright 2023 Anton Tananaev (anton@traccar.org)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.traccar.web;
+
+import com.google.inject.Provider;
+import org.traccar.api.security.PermissionsService;
+import org.traccar.model.Server;
+import org.traccar.storage.StorageException;
+
+import jakarta.inject.Inject;
+import jakarta.inject.Singleton;
+import jakarta.servlet.Filter;
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.ServletRequest;
+import jakarta.servlet.ServletResponse;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+@Singleton
+public class OverrideFilter implements Filter {
+
+ private final Provider<PermissionsService> permissionsServiceProvider;
+
+ @Inject
+ public OverrideFilter(Provider<PermissionsService> permissionsServiceProvider) {
+ this.permissionsServiceProvider = permissionsServiceProvider;
+ }
+
+ @Override
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+ throws IOException, ServletException {
+
+ if (((HttpServletRequest) request).getServletPath().startsWith("/api")) {
+ chain.doFilter(request, response);
+ return;
+ }
+
+ ResponseWrapper wrappedResponse = new ResponseWrapper((HttpServletResponse) response);
+
+ chain.doFilter(request, wrappedResponse);
+
+ byte[] bytes = wrappedResponse.getCapture();
+ if (bytes != null) {
+ if (wrappedResponse.getContentType() != null && wrappedResponse.getContentType().contains("text/html")
+ || ((HttpServletRequest) request).getPathInfo().endsWith("manifest.json")) {
+
+ Server server;
+ try {
+ server = permissionsServiceProvider.get().getServer();
+ } catch (StorageException e) {
+ throw new RuntimeException(e);
+ }
+
+ String title = server.getString("title", "Traccar");
+ String description = server.getString("description", "Traccar GPS Tracking System");
+ String colorPrimary = server.getString("colorPrimary", "#1a237e");
+
+ String alteredContent = new String(wrappedResponse.getCapture())
+ .replace("${title}", title)
+ .replace("${description}", description)
+ .replace("${colorPrimary}", colorPrimary);
+
+ response.setContentLength(alteredContent.length());
+ response.getOutputStream().write(alteredContent.getBytes());
+
+ } else {
+ response.getOutputStream().write(bytes);
+ }
+ }
+ }
+
+}
diff --git a/src/main/java/org/traccar/web/ResponseWrapper.java b/src/main/java/org/traccar/web/ResponseWrapper.java
new file mode 100644
index 000000000..a0eaf6788
--- /dev/null
+++ b/src/main/java/org/traccar/web/ResponseWrapper.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright 2023 Anton Tananaev (anton@traccar.org)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.traccar.web;
+
+import jakarta.servlet.ServletOutputStream;
+import jakarta.servlet.WriteListener;
+import jakarta.servlet.http.HttpServletResponse;
+import jakarta.servlet.http.HttpServletResponseWrapper;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+
+public class ResponseWrapper extends HttpServletResponseWrapper {
+
+ private final ByteArrayOutputStream capture;
+ private ServletOutputStream output;
+
+ public ResponseWrapper(HttpServletResponse response) {
+ super(response);
+ capture = new ByteArrayOutputStream(response.getBufferSize());
+ }
+
+ @Override
+ public ServletOutputStream getOutputStream() {
+ if (output == null) {
+ output = new ServletOutputStream() {
+ @Override
+ public boolean isReady() {
+ return true;
+ }
+
+ @Override
+ public void setWriteListener(WriteListener writeListener) {
+ }
+
+ @Override
+ public void write(int b) {
+ capture.write(b);
+ }
+
+ @Override
+ public void flush() throws IOException {
+ capture.flush();
+ }
+
+ @Override
+ public void close() throws IOException {
+ capture.close();
+ }
+ };
+ }
+ return output;
+ }
+
+ @Override
+ public void flushBuffer() throws IOException {
+ super.flushBuffer();
+ if (output != null) {
+ output.flush();
+ }
+ }
+
+ public byte[] getCapture() throws IOException {
+ if (output != null) {
+ output.close();
+ return capture.toByteArray();
+ }
+ return null;
+ }
+
+}
diff --git a/src/main/java/org/traccar/web/ThrottlingFilter.java b/src/main/java/org/traccar/web/ThrottlingFilter.java
new file mode 100644
index 000000000..1bad33db6
--- /dev/null
+++ b/src/main/java/org/traccar/web/ThrottlingFilter.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright 2022 - 2023 Anton Tananaev (anton@traccar.org)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.traccar.web;
+
+import org.eclipse.jetty.servlets.DoSFilter;
+import org.traccar.config.Config;
+import org.traccar.config.Keys;
+
+import jakarta.inject.Inject;
+import jakarta.inject.Singleton;
+import jakarta.servlet.FilterConfig;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.ServletRequest;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpSession;
+
+@Singleton
+public class ThrottlingFilter extends DoSFilter {
+
+ @Inject
+ private Config config;
+
+ @Override
+ public void init(FilterConfig filterConfig) throws ServletException {
+ super.init(filterConfig);
+ if (config.hasKey(Keys.WEB_MAX_REQUESTS_PER_SECOND)) {
+ setMaxRequestsPerSec(config.getInteger(Keys.WEB_MAX_REQUESTS_PER_SECOND));
+ }
+ setMaxRequestMs(config.getInteger(Keys.WEB_MAX_REQUEST_SECONDS) * 1000L);
+ }
+
+ @Override
+ protected String extractUserId(ServletRequest request) {
+ HttpSession session = ((HttpServletRequest) request).getSession(false);
+ if (session != null) {
+ var userId = session.getAttribute("userId");
+ return userId != null ? userId.toString() : null;
+ }
+ return null;
+ }
+}
diff --git a/src/main/java/org/traccar/web/WebInjectionManagerFactory.java b/src/main/java/org/traccar/web/WebInjectionManagerFactory.java
new file mode 100644
index 000000000..3e73c41ad
--- /dev/null
+++ b/src/main/java/org/traccar/web/WebInjectionManagerFactory.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright 2022 Anton Tananaev (anton@traccar.org)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.traccar.web;
+
+import org.glassfish.hk2.api.ServiceLocator;
+import org.glassfish.jersey.inject.hk2.Hk2InjectionManagerFactory;
+import org.glassfish.jersey.internal.inject.InjectionManager;
+import org.glassfish.jersey.internal.inject.InjectionManagerFactory;
+import org.jvnet.hk2.guice.bridge.api.GuiceBridge;
+import org.jvnet.hk2.guice.bridge.api.GuiceIntoHK2Bridge;
+import org.traccar.Main;
+
+import jakarta.annotation.Priority;
+
+@Priority(20)
+public class WebInjectionManagerFactory implements InjectionManagerFactory {
+
+ private final InjectionManagerFactory originalFactory = new Hk2InjectionManagerFactory();
+
+ private InjectionManager injectGuiceBridge(InjectionManager injectionManager) {
+ var serviceLocator = injectionManager.getInstance(ServiceLocator.class);
+ GuiceBridge.getGuiceBridge().initializeGuiceBridge(serviceLocator);
+ var guiceBridge = serviceLocator.getService(GuiceIntoHK2Bridge.class);
+ guiceBridge.bridgeGuiceInjector(Main.getInjector());
+ return injectionManager;
+ }
+
+ @Override
+ public InjectionManager create() {
+ return injectGuiceBridge(originalFactory.create());
+ }
+
+ @Override
+ public InjectionManager create(Object parent) {
+ return injectGuiceBridge(originalFactory.create(parent));
+ }
+}
diff --git a/src/main/java/org/traccar/web/WebModule.java b/src/main/java/org/traccar/web/WebModule.java
new file mode 100644
index 000000000..a32a6f447
--- /dev/null
+++ b/src/main/java/org/traccar/web/WebModule.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright 2022 - 2023 Anton Tananaev (anton@traccar.org)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.traccar.web;
+
+import com.google.inject.servlet.ServletModule;
+import org.traccar.api.AsyncSocketServlet;
+import org.traccar.api.MediaFilter;
+
+public class WebModule extends ServletModule {
+
+ @Override
+ protected void configureServlets() {
+ filter("/*").through(OverrideFilter.class);
+ filter("/api/*").through(ThrottlingFilter.class);
+ filter("/api/media/*").through(MediaFilter.class);
+ serve("/api/socket").with(AsyncSocketServlet.class);
+ }
+}
diff --git a/src/main/java/org/traccar/web/WebServer.java b/src/main/java/org/traccar/web/WebServer.java
index 0ed5d013e..5f27f7662 100644
--- a/src/main/java/org/traccar/web/WebServer.java
+++ b/src/main/java/org/traccar/web/WebServer.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2012 - 2022 Anton Tananaev (anton@traccar.org)
+ * Copyright 2012 - 2023 Anton Tananaev (anton@traccar.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,6 +15,8 @@
*/
package org.traccar.web;
+import com.google.inject.Injector;
+import com.google.inject.servlet.GuiceFilter;
import org.eclipse.jetty.http.HttpCookie;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpStatus;
@@ -35,35 +37,27 @@ import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.websocket.server.config.JettyWebSocketServletContainerInitializer;
-import org.glassfish.jersey.inject.hk2.ImmediateHk2InjectionManager;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.server.ResourceConfig;
-import org.glassfish.jersey.server.spi.Container;
-import org.glassfish.jersey.server.spi.ContainerLifecycleListener;
import org.glassfish.jersey.servlet.ServletContainer;
-import org.jvnet.hk2.guice.bridge.api.GuiceBridge;
-import org.jvnet.hk2.guice.bridge.api.GuiceIntoHK2Bridge;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.traccar.Context;
import org.traccar.LifecycleObject;
-import org.traccar.Main;
-import org.traccar.api.DateParameterConverterProvider;
-import org.traccar.config.Config;
-import org.traccar.api.AsyncSocketServlet;
import org.traccar.api.CorsResponseFilter;
-import org.traccar.api.MediaFilter;
-import org.traccar.api.ObjectMapperProvider;
+import org.traccar.api.DateParameterConverterProvider;
import org.traccar.api.ResourceErrorHandler;
-import org.traccar.api.security.SecurityRequestFilter;
import org.traccar.api.resource.ServerResource;
+import org.traccar.api.security.SecurityRequestFilter;
+import org.traccar.config.Config;
import org.traccar.config.Keys;
-
-import javax.servlet.DispatcherType;
-import javax.servlet.ServletException;
-import javax.servlet.SessionCookieConfig;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
+import org.traccar.helper.ObjectMapperContextResolver;
+
+import jakarta.servlet.DispatcherType;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.SessionCookieConfig;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.io.Writer;
@@ -74,10 +68,13 @@ public class WebServer implements LifecycleObject {
private static final Logger LOGGER = LoggerFactory.getLogger(WebServer.class);
- private Server server;
-
- private void initServer(Config config) {
+ private final Injector injector;
+ private final Config config;
+ private final Server server;
+ public WebServer(Injector injector, Config config) {
+ this.injector = injector;
+ this.config = config;
String address = config.getString(Keys.WEB_ADDRESS);
int port = config.getInteger(Keys.WEB_PORT);
if (address == null) {
@@ -85,22 +82,19 @@ public class WebServer implements LifecycleObject {
} else {
server = new Server(new InetSocketAddress(address, port));
}
- }
-
- public WebServer(Config config) {
-
- initServer(config);
ServletContextHandler servletHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
+ JettyWebSocketServletContainerInitializer.configure(servletHandler, null);
+ servletHandler.addFilter(GuiceFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
- initApi(config, servletHandler);
- initSessionConfig(config, servletHandler);
+ initApi(servletHandler);
+ initSessionConfig(servletHandler);
if (config.getBoolean(Keys.WEB_CONSOLE)) {
- servletHandler.addServlet(new ServletHolder(new ConsoleServlet()), "/console/*");
+ servletHandler.addServlet(new ServletHolder(new ConsoleServlet(config)), "/console/*");
}
- initWebApp(config, servletHandler);
+ initWebApp(servletHandler);
servletHandler.setErrorHandler(new ErrorHandler() {
@Override
@@ -112,12 +106,12 @@ public class WebServer implements LifecycleObject {
});
HandlerList handlers = new HandlerList();
- initClientProxy(config, handlers);
+ initClientProxy(handlers);
handlers.addHandler(servletHandler);
handlers.addHandler(new GzipHandler());
server.setHandler(handlers);
- if (config.getBoolean(Keys.WEB_REQUEST_LOG_ENABLE)) {
+ if (config.hasKey(Keys.WEB_REQUEST_LOG_PATH)) {
RequestLogWriter logWriter = new RequestLogWriter(config.getString(Keys.WEB_REQUEST_LOG_PATH));
logWriter.setAppend(true);
logWriter.setRetainDays(config.getInteger(Keys.WEB_REQUEST_LOG_RETAIN_DAYS));
@@ -126,7 +120,7 @@ public class WebServer implements LifecycleObject {
}
}
- private void initClientProxy(Config config, HandlerList handlers) {
+ private void initClientProxy(HandlerList handlers) {
int port = config.getInteger(Keys.PROTOCOL_PORT.withPrefix("osmand"));
if (port != 0) {
ServletContextHandler servletHandler = new ServletContextHandler() {
@@ -139,15 +133,15 @@ public class WebServer implements LifecycleObject {
}
}
};
- ServletHolder servletHolder = new ServletHolder(new AsyncProxyServlet.Transparent());
+ ServletHolder servletHolder = new ServletHolder(AsyncProxyServlet.Transparent.class);
servletHolder.setInitParameter("proxyTo", "http://localhost:" + port);
servletHandler.addServlet(servletHolder, "/");
handlers.addHandler(servletHandler);
}
}
- private void initWebApp(Config config, ServletContextHandler servletHandler) {
- ServletHolder servletHolder = new ServletHolder(DefaultServlet.class);
+ private void initWebApp(ServletContextHandler servletHandler) {
+ ServletHolder servletHolder = new ServletHolder(new ModernDefaultServlet(config));
servletHolder.setInitParameter("resourceBase", new File(config.getString(Keys.WEB_PATH)).getAbsolutePath());
servletHolder.setInitParameter("dirAllowed", "false");
if (config.getBoolean(Keys.WEB_DEBUG)) {
@@ -162,10 +156,7 @@ public class WebServer implements LifecycleObject {
servletHandler.addServlet(servletHolder, "/*");
}
- private void initApi(Config config, ServletContextHandler servletHandler) {
- servletHandler.addServlet(new ServletHolder(new AsyncSocketServlet()), "/api/socket");
- JettyWebSocketServletContainerInitializer.configure(servletHandler, null);
-
+ private void initApi(ServletContextHandler servletHandler) {
String mediaPath = config.getString(Keys.MEDIA_PATH);
if (mediaPath != null) {
ServletHolder servletHolder = new ServletHolder(DefaultServlet.class);
@@ -173,39 +164,27 @@ public class WebServer implements LifecycleObject {
servletHolder.setInitParameter("dirAllowed", "false");
servletHolder.setInitParameter("pathInfoOnly", "true");
servletHandler.addServlet(servletHolder, "/api/media/*");
- servletHandler.addFilter(MediaFilter.class, "/api/media/*", EnumSet.allOf(DispatcherType.class));
}
ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig.registerClasses(
- JacksonFeature.class, ObjectMapperProvider.class, ResourceErrorHandler.class,
- SecurityRequestFilter.class, CorsResponseFilter.class, DateParameterConverterProvider.class);
+ JacksonFeature.class,
+ ObjectMapperContextResolver.class,
+ DateParameterConverterProvider.class,
+ SecurityRequestFilter.class,
+ CorsResponseFilter.class,
+ ResourceErrorHandler.class);
resourceConfig.packages(ServerResource.class.getPackage().getName());
- resourceConfig.register(new ContainerLifecycleListener() {
- @Override
- public void onStartup(Container container) {
- var injectionManager = container.getApplicationHandler().getInjectionManager();
- var serviceLocator = ((ImmediateHk2InjectionManager) injectionManager).getServiceLocator();
- GuiceBridge.getGuiceBridge().initializeGuiceBridge(serviceLocator);
- var guiceBridge = serviceLocator.getService(GuiceIntoHK2Bridge.class);
- guiceBridge.bridgeGuiceInjector(Main.getInjector());
- }
-
- @Override
- public void onReload(Container container) {
- }
-
- @Override
- public void onShutdown(Container container) {
- }
- });
+ if (resourceConfig.getClasses().stream().filter(ServerResource.class::equals).findAny().isEmpty()) {
+ LOGGER.warn("Failed to load API resources");
+ }
servletHandler.addServlet(new ServletHolder(new ServletContainer(resourceConfig)), "/api/*");
}
- private void initSessionConfig(Config config, ServletContextHandler servletHandler) {
+ private void initSessionConfig(ServletContextHandler servletHandler) {
if (config.getBoolean(Keys.WEB_PERSIST_SESSION)) {
DatabaseAdaptor databaseAdaptor = new DatabaseAdaptor();
- databaseAdaptor.setDatasource(Context.getDataManager().getDataSource());
+ databaseAdaptor.setDatasource(injector.getInstance(DataSource.class));
JDBCSessionDataStoreFactory jdbcSessionDataStoreFactory = new JDBCSessionDataStoreFactory();
jdbcSessionDataStoreFactory.setDatabaseAdaptor(databaseAdaptor);
SessionHandler sessionHandler = servletHandler.getSessionHandler();
@@ -214,14 +193,16 @@ public class WebServer implements LifecycleObject {
sessionHandler.setSessionCache(sessionCache);
}
+ SessionCookieConfig sessionCookieConfig = servletHandler.getServletContext().getSessionCookieConfig();
+
int sessionTimeout = config.getInteger(Keys.WEB_SESSION_TIMEOUT);
if (sessionTimeout > 0) {
servletHandler.getSessionHandler().setMaxInactiveInterval(sessionTimeout);
+ sessionCookieConfig.setMaxAge(sessionTimeout);
}
String sameSiteCookie = config.getString(Keys.WEB_SAME_SITE_COOKIE);
if (sameSiteCookie != null) {
- SessionCookieConfig sessionCookieConfig = servletHandler.getServletContext().getSessionCookieConfig();
switch (sameSiteCookie.toLowerCase()) {
case "lax":
sessionCookieConfig.setComment(HttpCookie.SAME_SITE_LAX_COMMENT);
@@ -240,21 +221,13 @@ public class WebServer implements LifecycleObject {
}
@Override
- public void start() {
- try {
- server.start();
- } catch (Exception error) {
- LOGGER.warn("Web server start failed", error);
- }
+ public void start() throws Exception {
+ server.start();
}
@Override
- public void stop() {
- try {
- server.stop();
- } catch (Exception error) {
- LOGGER.warn("Web server stop failed", error);
- }
+ public void stop() throws Exception {
+ server.stop();
}
}