Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Servlet refactor (#2219)

Rich Turner77e48be925ef
diff --git a/agent/src/main/java/org/openremote/agent/protocol/http/AbstractHTTPServerAgent.java b/agent/src/main/java/org/openremote/agent/protocol/http/AbstractHTTPServerAgent.java
index d2bd9c9ec..485ffb318 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/http/AbstractHTTPServerAgent.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/http/AbstractHTTPServerAgent.java
@@ -31,8 +31,6 @@ import static org.openremote.agent.protocol.http.HTTPAgent.VALUE_HTTP_METHOD;
public abstract class AbstractHTTPServerAgent<T extends AbstractHTTPServerAgent<T, U, V>, U extends AbstractHTTPServerProtocol<U, T, V>, V extends AgentLink<?>> extends Agent<T, U, V> {
- public static final AttributeDescriptor<String> DEPLOYMENT_PATH = new AttributeDescriptor<>("deploymentPath", ValueType.TEXT);
-
public static final AttributeDescriptor<HTTPMethod[]> ALLOWED_HTTP_METHODS = new AttributeDescriptor<>("allowedHTTPMethods", VALUE_HTTP_METHOD.asArray());
public static final AttributeDescriptor<String[]> ALLOWED_ORIGINS = new AttributeDescriptor<>("allowedOrigins", ValueType.TEXT.asArray());
public static final AttributeDescriptor<Boolean> ROLE_BASED_SECURITY = new AttributeDescriptor<>("roleBasedSecurity", ValueType.BOOLEAN);
@@ -43,16 +41,6 @@ public abstract class AbstractHTTPServerAgent<T extends AbstractHTTPServerAgent<
super(name);
}
- public Optional<String> getDeploymentPath() {
- return getAttributes().getValue(DEPLOYMENT_PATH);
- }
-
- @SuppressWarnings("unchecked")
- public T setDeploymentPath(String value) {
- getAttributes().getOrCreate(DEPLOYMENT_PATH).setValue(value);
- return (T)this;
- }
-
public Optional<HTTPMethod[]> getAllowedHTTPMethods() {
return getAttributes().getValue(ALLOWED_HTTP_METHODS);
}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/http/AbstractHTTPServerProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/http/AbstractHTTPServerProtocol.java
index f63e44545..d7d79c03d 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/http/AbstractHTTPServerProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/http/AbstractHTTPServerProtocol.java
@@ -19,40 +19,31 @@
*/
package org.openremote.agent.protocol.http;
-import io.undertow.server.HttpHandler;
-import io.undertow.servlet.Servlets;
-import io.undertow.servlet.api.DeploymentInfo;
-import io.undertow.servlet.api.DeploymentManager;
-import io.undertow.servlet.api.ServletInfo;
-import io.undertow.util.HttpString;
-import org.jboss.resteasy.core.ResteasyDeploymentImpl;
-import org.jboss.resteasy.plugins.interceptors.CorsFilter;
-import org.jboss.resteasy.plugins.server.servlet.HttpServlet30Dispatcher;
-import org.jboss.resteasy.spi.ResteasyDeployment;
+import jakarta.ws.rs.core.Application;
import org.openremote.agent.protocol.AbstractProtocol;
import org.openremote.container.security.IdentityService;
-import org.openremote.container.web.*;
-import org.openremote.model.Constants;
+import org.openremote.container.web.CORSConfig;
+import org.openremote.container.web.RealmInjectorFilter;
+import org.openremote.container.web.WebApplication;
+import org.openremote.container.web.WebService;
import org.openremote.model.Container;
import org.openremote.model.asset.agent.Agent;
import org.openremote.model.asset.agent.AgentLink;
+import org.openremote.model.asset.agent.ConnectionStatus;
import org.openremote.model.attribute.Attribute;
-import org.openremote.model.http.HTTPMethod;
import org.openremote.model.syslog.SyslogCategory;
import org.openremote.model.util.TextUtil;
-import jakarta.servlet.ServletException;
-import jakarta.ws.rs.core.Application;
-
-import java.util.*;
-import java.util.logging.Level;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Set;
import java.util.logging.Logger;
-import java.util.regex.Pattern;
import java.util.stream.Collectors;
+import java.util.stream.Stream;
-import static org.openremote.container.web.WebService.configureDeploymentInfo;
+import static java.util.logging.Level.INFO;
import static org.openremote.container.web.WebService.getStandardProviders;
-import static org.openremote.container.web.WebService.pathStartsWithHandler;
import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
/**
@@ -63,7 +54,6 @@ import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
* The deployment is deployed by creating an instance of a concrete {@link AbstractHTTPServerAgent} implementation with
* the following {@link Attribute}s:
* <ul>
- * <li>{@link AbstractHTTPServerAgent#DEPLOYMENT_PATH} <b>(required)</b></li>
* <li>{@link AbstractHTTPServerAgent#ALLOWED_ORIGINS}</li>
* <li>{@link AbstractHTTPServerAgent#ALLOWED_HTTP_METHODS}</li>
* </ul>
@@ -75,18 +65,14 @@ import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
public abstract class AbstractHTTPServerProtocol<T extends AbstractHTTPServerProtocol<T, U, V>, U extends AbstractHTTPServerAgent<U, T, V>, V extends AgentLink<?>> extends AbstractProtocol<U, V> {
/**
- * This is the default path prefix for all deployments. Should not be overridden unless you know what you are doing
- * and there is a good reason to override.
+ * This is the path prefix for all HTTP server agent deployments
*/
- public static final String DEFAULT_DEPLOYMENT_PATH_PREFIX = "/rest";
+ public static final String DEPLOYMENT_PATH_PREFIX = "/http_agent";
/**
* The regex used to validate the deployment path.
*/
- public static final Pattern PATH_REGEX = Pattern.compile("^[\\w/_]+$", Pattern.CASE_INSENSITIVE);
private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, AbstractHTTPServerProtocol.class);
- public static final HTTPMethod[] DEFAULT_ALLOWED_METHODS = HTTPMethod.values();
- protected WebService.DeploymentInstance deployment;
protected Container container;
protected boolean devMode;
protected IdentityService identityService;
@@ -107,79 +93,21 @@ public abstract class AbstractHTTPServerProtocol<T extends AbstractHTTPServerPro
webService = container.getService(WebService.class);
- Application application = createApplication();
- ResteasyDeployment deployment = createDeployment(application);
- DeploymentInfo deploymentInfo = createDeploymentInfo(deployment);
- configureDeploymentInfo(deploymentInfo);
- deploy(deploymentInfo);
+ Application application = new WebApplication(
+ container,
+ null,
+ Stream.of(
+ List.of((Object)new RealmInjectorFilter(agent.getRealm())), // Need this as realm is in the context path of the deployment
+ getStandardProviders(devMode, 0),
+ getApiSingletons()).flatMap(Collection::stream).toList());
+
+ deploy(application);
+ setConnectionStatus(ConnectionStatus.CONNECTED);
}
@Override
protected void doStop(Container container) throws Exception {
- undeploy();
- }
-
- protected Application createApplication() {
- List<Object> providers = getStandardProviders(this.devMode);
- providers = providers == null ? new ArrayList<>() : providers;
- providers.addAll(getApiSingletons());
- return new WebApplication(container, null, providers);
- }
-
- protected ResteasyDeployment createDeployment(Application application) {
- ResteasyDeployment resteasyDeployment = new ResteasyDeploymentImpl();
- resteasyDeployment.setApplication(application);
-
- List<String> allowedOrigins;
-
- if (devMode) {
- allowedOrigins = Collections.singletonList("*");
- } else {
- allowedOrigins = agent.getAllowedOrigins().map(Arrays::asList).orElse(null);
- }
-
- if (allowedOrigins != null) {
- String allowedMethods = Arrays.stream(agent.getAllowedHTTPMethods().orElse(DEFAULT_ALLOWED_METHODS)).map(Enum::name).collect(Collectors.joining(","));
- CorsFilter corsFilter = new CorsFilter();
- corsFilter.getAllowedOrigins().addAll(allowedOrigins);
- corsFilter.setAllowedMethods(allowedMethods);
- resteasyDeployment.getProviders().add(corsFilter);
- }
-
- return resteasyDeployment;
- }
-
- protected DeploymentInfo createDeploymentInfo(ResteasyDeployment resteasyDeployment) {
- String deploymentPath = getDeploymentPath();
- String deploymentName = getDeploymentName();
-
- boolean enableSecurity = agent.isRoleBasedSecurity().orElse(false);
-
- if (enableSecurity) {
- if (identityService == null) {
- throw new RuntimeException("Role based security can only be enabled when an identity service is available");
- }
- }
-
- resteasyDeployment.setSecurityEnabled(enableSecurity);
-
- ServletInfo resteasyServlet = Servlets.servlet("ResteasyServlet", HttpServlet30Dispatcher.class)
- .setAsyncSupported(true)
- .setLoadOnStartup(1)
- .addMapping("/*");
-
- DeploymentInfo deploymentInfo = new DeploymentInfo()
- .setDeploymentName(deploymentName)
- .setContextPath(deploymentPath)
- .addServletContextAttribute(ResteasyDeployment.class.getName(), resteasyDeployment)
- .addServlet(resteasyServlet)
- .setClassLoader(Container.class.getClassLoader());
-
- if (enableSecurity) {
- identityService.secureDeployment(deploymentInfo);
- }
-
- return deploymentInfo;
+ undeploy(getDeploymentName());
}
/**
@@ -188,115 +116,61 @@ public abstract class AbstractHTTPServerProtocol<T extends AbstractHTTPServerPro
abstract protected Set<Object> getApiSingletons();
/**
- * Get the path prefix to use for this protocol instance; should use {@value #DEFAULT_DEPLOYMENT_PATH_PREFIX} unless there
- * is a good reason to override this.
- */
- protected String getDeploymentPathPrefix() {
- return DEFAULT_DEPLOYMENT_PATH_PREFIX;
- }
-
- /**
- * Deployment path will always be prefixed with {@link #getDeploymentPathPrefix()}; default implementation combines
- * the prefix with the value of {@link AbstractHTTPServerAgent#DEPLOYMENT_PATH}, for example:
- * <ul>
- * <li>getDeploymentPathPrefix() = {@value #DEFAULT_DEPLOYMENT_PATH_PREFIX}</li>
- * <li>{@link AbstractHTTPServerAgent#DEPLOYMENT_PATH} = "complaints"</li>
- * </ul>
+ * Deployment path will always be prefixed with {@link #DEPLOYMENT_PATH_PREFIX}, {@link Agent#getRealm()} and
+ * {@link Agent#getId()}, For example, an agent in a realm called manufacturer:
* <p>
- * Full path to deployment = "/rest/complaints"
- * <p>
- * If the {@link AbstractHTTPServerAgent#DEPLOYMENT_PATH} is missing or not a String or the generated path does
- * not match the {@link #PATH_REGEX} regex then an {@link IllegalArgumentException} will is thrown.
+ * Full path to deployment = "{@value #DEPLOYMENT_PATH_PREFIX}/manufacturer/6lMDrFZ5Qhd78BTmoF9Pwn"
*/
- protected String getDeploymentPath() throws IllegalArgumentException {
- String path = agent.getDeploymentPath()
- .map(String::toLowerCase)
- .orElseThrow(() ->
- new IllegalArgumentException(
- "Required deployment path attribute is missing or invalid: " + agent));
-
- String deploymentPath = getDeploymentPathPrefix() + "/" + path;
-
- if (!PATH_REGEX.matcher(deploymentPath).find()) {
- throw new IllegalArgumentException(
- "Required deployment path attribute is missing or invalid: " + agent);
- }
-
- return deploymentPath;
+ protected String getDeploymentPath() {
+ return DEPLOYMENT_PATH_PREFIX + "/" + agent.getRealm() + "/" + agent.getId();
}
/**
* Get a unique deployment name for this instance.
*/
protected String getDeploymentName() {
- return "HttpServerProtocol=" + getClass().getSimpleName() + ", Agent ID=" + agent.getId();
+ return getDeploymentName(getClass(), agent.getId());
}
- protected void deploy(DeploymentInfo deploymentInfo) {
- LOG.info("Deploying JAX-RS deployment for protocol instance : " + this);
- DeploymentManager manager = Servlets.defaultContainer().addDeployment(deploymentInfo);
- manager.deploy();
- HttpHandler httpHandler;
-
- // Get realm from owning agent asset
- String agentRealm = agent.getRealm();
+ protected boolean isSecure() {
+ return agent.isRoleBasedSecurity().orElse(false);
+ }
- if (TextUtil.isNullOrEmpty(agentRealm)) {
- throw new IllegalStateException("Cannot determine the realm that this agent belongs to");
- }
+ protected void deploy(Application application) {
+ LOG.log(INFO, "Deploying JAX-RS application for protocol instance: " + this);
- try {
- httpHandler = manager.start();
+ boolean secure = isSecure();
+ String deploymentPath = getDeploymentPath();
+ String deploymentName = getDeploymentName();
- // Wrap the handler to inject the realm
- HttpHandler handlerWrapper = exchange -> {
- exchange.getRequestHeaders().put(HttpString.tryFromString(Constants.REALM_PARAM_NAME), agentRealm);
- httpHandler.handleRequest(exchange);
- };
- WebService.RequestHandler requestHandler = pathStartsWithHandler(deploymentInfo.getDeploymentName(), deploymentInfo.getContextPath(), handlerWrapper);
+ Set<String> allowedOrigins = agent.getAllowedOrigins().map(Set::of).orElse(null);
+ String allowedMethods = agent.getAllowedHTTPMethods().map(methods ->
+ Arrays.stream(methods).map(Enum::name)
+ .collect(Collectors.joining(","))).orElse(null);
- LOG.info("Registering HTTP Server Protocol request handler '"
- + this.getClass().getSimpleName()
- + "' for request path: "
- + deploymentInfo.getContextPath());
- // Add the handler before the greedy deployment handler
- webService.getRequestHandlers().addFirst(requestHandler);
+ CORSConfig corsConfig = new CORSConfig();
- deployment = new WebService.DeploymentInstance(deploymentInfo, requestHandler);
- } catch (ServletException e) {
- LOG.severe("Failed to deploy deployment: " + deploymentInfo.getDeploymentName());
+ if (allowedOrigins != null && !allowedOrigins.isEmpty()) {
+ allowedOrigins.forEach(corsConfig::addCorsAllowedOrigin);
}
- }
-
- protected void undeploy() {
-
- if (deployment == null) {
- LOG.info("Deployment doesn't exist for protocol instance: " + this);
- return;
+ if (!TextUtil.isNullOrEmpty(allowedMethods)) {
+ corsConfig.setCorsAllowedMethods(allowedMethods);
}
- try {
- LOG.info("Un-registering HTTP Server Protocol request handler '"
- + this.getClass().getSimpleName()
- + "' for request path: "
- + deployment.getDeploymentInfo().getContextPath());
- webService.getRequestHandlers().remove(deployment.getRequestHandler());
- DeploymentManager manager = Servlets.defaultContainer().getDeployment(deployment.getDeploymentInfo().getDeploymentName());
- if (manager != null) {
- manager.stop();
- manager.undeploy();
- }
- Servlets.defaultContainer().removeDeployment(deployment.getDeploymentInfo());
- } catch (Exception ex) {
- LOG.log(Level.WARNING,
- "An exception occurred whilst un-deploying protocol instance: " + this,
- ex);
- throw new RuntimeException(ex);
- }
+ webService.deployJaxRsApplication(application, deploymentPath, deploymentName, null, secure, corsConfig);
+ }
+
+ protected void undeploy(String deploymentName) {
+ LOG.log(INFO, "Un-deploying JAX-RS deployment for protocol instance: " + this);
+ webService.undeploy(deploymentName);
}
@Override
public String getProtocolInstanceUri() {
return "httpServer://" + getDeploymentPath();
}
+
+ public static String getDeploymentName(Class<? extends AbstractHTTPServerProtocol> protocolClass, String agentId) {
+ return "HttpServerProtocol=" + protocolClass.getSimpleName() + ", Agent ID=" + agentId;
+ }
}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/lorawan/tts/TheThingsStackProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/lorawan/tts/TheThingsStackProtocol.java
index 694a37d7d..7567f0efc 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/lorawan/tts/TheThingsStackProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/lorawan/tts/TheThingsStackProtocol.java
@@ -51,7 +51,7 @@ import static org.openremote.agent.protocol.lorawan.tts.TheThingsStackAgent.API_
import static org.openremote.agent.protocol.lorawan.tts.TheThingsStackAgent.HOST;
import static org.openremote.agent.protocol.lorawan.tts.TheThingsStackAgent.TENANT_ID;
import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
-import static org.openremote.container.util.MapAccess.getBoolean;
+import static org.openremote.model.util.MapAccess.getBoolean;
public class TheThingsStackProtocol extends AbstractLoRaWANProtocol<TheThingsStackProtocol, TheThingsStackAgent> {
diff --git a/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketIOClient.java b/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketIOClient.java
index ac8fe8d11..f5331168a 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketIOClient.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketIOClient.java
@@ -288,7 +288,7 @@ public class WebsocketIOClient<T> extends AbstractNettyIOClient<T, InetSocketAdd
if (TextUtil.isNullOrEmpty(authHeaderValue)) {
throw new RuntimeException("Returned access token is null");
}
- LOG.finest("Retrieved access token via OAuth: " + getClientUri());
+ LOG.fine("Retrieved access token via OAuth: " + getClientUri());
} catch (Exception e) {
throw new Exception("Error retrieving OAuth access token for '" + getClientUri() + "': " + e.getMessage());
}
diff --git a/container/build.gradle b/container/build.gradle
index cead1c516..f89440ea0 100644
--- a/container/build.gradle
+++ b/container/build.gradle
@@ -50,6 +50,7 @@ dependencies {
api "org.apache.camel:camel-health:$camelVersion"
api "org.apache.camel:camel-management:$camelVersion"
api "io.micrometer:micrometer-registry-prometheus:$micrometerVersion"
+ api "com.thetransactioncompany:cors-filter:$corsFilterVersion"
}
base {
diff --git a/container/src/main/java/org/openremote/container/Container.java b/container/src/main/java/org/openremote/container/Container.java
index 44ca1c3db..17fd8c65c 100644
--- a/container/src/main/java/org/openremote/container/Container.java
+++ b/container/src/main/java/org/openremote/container/Container.java
@@ -29,7 +29,8 @@ import io.prometheus.metrics.model.registry.PrometheusRegistry;
import org.openremote.container.concurrent.ContainerScheduledExecutor;
import org.openremote.container.concurrent.ContainerThreadFactory;
import org.openremote.model.ContainerService;
-import org.openremote.model.util.TextUtil;
+import org.openremote.model.util.Config;
+import org.openremote.model.util.MapAccess;
import org.openremote.model.util.ValueUtil;
import java.util.*;
@@ -40,8 +41,8 @@ import java.util.stream.Collectors;
import static java.lang.System.Logger.Level.*;
import static java.util.stream.StreamSupport.stream;
-import static org.openremote.container.util.MapAccess.getBoolean;
-import static org.openremote.container.util.MapAccess.getInteger;
+import static org.openremote.model.util.MapAccess.getBoolean;
+import static org.openremote.model.util.MapAccess.getInteger;
/**
* A thread-safe registry of {@link ContainerService}s.
@@ -50,7 +51,7 @@ import static org.openremote.container.util.MapAccess.getInteger;
* manage the life cycle of these services.
* <p>
* Access environment configuration through {@link #getConfig()} and the helper methods
- * in {@link org.openremote.container.util.MapAccess}. Consider using {@link org.openremote.model.Container#OR_DEV_MODE}
+ * in {@link MapAccess}. Consider using {@link Config#OR_DEV_MODE}
* to distinguish between development and production environments.
* To execute tasks in a standard way two {@link ExecutorService}s are provided:
* <ul>
@@ -71,8 +72,6 @@ public class Container implements org.openremote.model.Container {
public static final String OR_EXECUTOR_THREADS_MAX = "OR_EXECUTOR_THREADS_MAX";
public static final int OR_EXECUTOR_THREADS_MIN_DEFAULT = Math.min(Runtime.getRuntime().availableProcessors(), 8);
public static final int OR_EXECUTOR_THREADS_MAX_DEFAULT = Runtime.getRuntime().availableProcessors()*10;
- protected final Map<String, String> config = new HashMap<>();
- protected final boolean devMode;
protected MeterRegistry meterRegistry;
protected Thread waitingThread;
@@ -89,23 +88,17 @@ public class Container implements org.openremote.model.Container {
}
public Container(ContainerService... services) {
- this(Arrays.asList(services));
+ this(null, Arrays.asList(services));
}
public Container(Iterable<ContainerService> services) {
- this(System.getenv(), services);
+ this(null, services);
}
public Container(Map<String, String> config, Iterable<ContainerService> services) {
- for (Map.Entry<String, String> entry : config.entrySet()) {
- if (!TextUtil.isNullOrEmpty(entry.getValue())) {
- this.config.put(entry.getKey(), entry.getValue());
- }
- }
-
- this.devMode = getBoolean(this.config, OR_DEV_MODE, OR_DEV_MODE_DEFAULT);
+ Config.init(config);
- boolean metricsEnabled = getBoolean(getConfig(), OR_METRICS_ENABLED, OR_METRICS_ENABLED_DEFAULT);
+ boolean metricsEnabled = getBoolean(getConfig(), Config.OR_METRICS_ENABLED, Config.OR_METRICS_ENABLED_DEFAULT);
LOG.log(INFO, "Metrics enabled: " + metricsEnabled);
if (metricsEnabled) {
@@ -146,11 +139,11 @@ public class Container implements org.openremote.model.Container {
@Override
public Map<String, String> getConfig() {
- return config;
+ return Config.get();
}
public boolean isDevMode() {
- return devMode;
+ return Config.isDevMode();
}
public boolean isRunning() {
@@ -170,7 +163,7 @@ public class Container implements org.openremote.model.Container {
// Initialise the asset model
ValueUtil.initialise(this);
- if (this.devMode) {
+ if (isDevMode()) {
ValueUtil.JSON.enable(SerializationFeature.INDENT_OUTPUT);
}
diff --git a/container/src/main/java/org/openremote/container/persistence/PersistenceService.java b/container/src/main/java/org/openremote/container/persistence/PersistenceService.java
index ff04df17f..7482d7532 100644
--- a/container/src/main/java/org/openremote/container/persistence/PersistenceService.java
+++ b/container/src/main/java/org/openremote/container/persistence/PersistenceService.java
@@ -79,7 +79,7 @@ import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.IntStream;
-import static org.openremote.container.util.MapAccess.*;
+import static org.openremote.model.util.MapAccess.*;
public class PersistenceService implements ContainerService, Consumer<PersistenceEvent<?>> {
diff --git a/container/src/main/java/org/openremote/container/security/CORSFilter.java b/container/src/main/java/org/openremote/container/security/CORSFilter.java
deleted file mode 100644
index 91683fac8..000000000
--- a/container/src/main/java/org/openremote/container/security/CORSFilter.java
+++ /dev/null
@@ -1,149 +0,0 @@
-package org.openremote.container.security;
-
-import io.undertow.util.StatusCodes;
-import org.jboss.resteasy.spi.CorsHeaders;
-import org.openremote.container.web.file.HttpFilter;
-import org.openremote.model.util.TextUtil;
-
-import jakarta.servlet.FilterChain;
-import jakarta.servlet.FilterConfig;
-import jakarta.servlet.ServletException;
-import jakarta.servlet.http.HttpServletRequest;
-import jakarta.servlet.http.HttpServletResponse;
-import jakarta.servlet.http.HttpSession;
-import jakarta.ws.rs.HttpMethod;
-import java.io.IOException;
-import java.util.HashSet;
-import java.util.Set;
-
-public class CORSFilter extends HttpFilter {
- protected boolean allowCredentials = true;
- protected String allowedMethods;
- protected String allowedHeaders;
- protected String exposedHeaders;
- protected int corsMaxAge = -1;
- protected Set<String> allowedOrigins = new HashSet<>();
-
- public boolean isAllowCredentials() {
- return allowCredentials;
- }
-
- public void setAllowCredentials(boolean allowCredentials) {
- this.allowCredentials = allowCredentials;
- }
-
- public String getAllowedMethods() {
- return allowedMethods;
- }
-
- public void setAllowedMethods(String allowedMethods) {
- this.allowedMethods = allowedMethods;
- }
-
- public String getAllowedHeaders() {
- return allowedHeaders;
- }
-
- public void setAllowedHeaders(String allowedHeaders) {
- this.allowedHeaders = allowedHeaders;
- }
-
- public String getExposedHeaders() {
- return exposedHeaders;
- }
-
- public void setExposedHeaders(String exposedHeaders) {
- this.exposedHeaders = exposedHeaders;
- }
-
- public int getCorsMaxAge() {
- return corsMaxAge;
- }
-
- public void setCorsMaxAge(int corsMaxAge) {
- this.corsMaxAge = corsMaxAge;
- }
-
- public Set<String> getAllowedOrigins() {
- return allowedOrigins;
- }
-
- public void setAllowedOrigins(Set<String> allowedOrigins) {
- this.allowedOrigins = allowedOrigins;
- }
-
- @Override
- public void init(FilterConfig filterConfig) throws ServletException {
-
- }
-
- @Override
- public void doFilter(HttpServletRequest request, HttpServletResponse response, HttpSession session, FilterChain chain) throws ServletException, IOException {
- String origin = request.getHeader(CorsHeaders.ORIGIN);
- boolean isOptions = request.getMethod().equals(HttpMethod.OPTIONS);
-
- if (origin == null) {
- chain.doFilter(request, response);
- return;
- }
-
- if (!originOk(origin)) {
- response.sendError(StatusCodes.FORBIDDEN, "Origin not allowed");
- return;
- }
-
- if (isOptions) {
- response.setStatus(StatusCodes.OK);
- response.setHeader(CorsHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, origin);
- if (allowCredentials) {
- response.setHeader(CorsHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
- }
-
- String requestMethods = request.getHeader(CorsHeaders.ACCESS_CONTROL_REQUEST_METHOD);
- if (!TextUtil.isNullOrEmpty(requestMethods)) {
- if (allowedMethods != null)
- {
- requestMethods = this.allowedMethods;
- }
- response.setHeader(CorsHeaders.ACCESS_CONTROL_ALLOW_METHODS, requestMethods);
- }
-
- String requestHeaders = request.getHeader(CorsHeaders.ACCESS_CONTROL_REQUEST_HEADERS);
- if (!TextUtil.isNullOrEmpty(requestHeaders)) {
- if (allowedHeaders != null)
- {
- requestHeaders = this.allowedHeaders;
- }
- response.setHeader(CorsHeaders.ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders);
- }
-
- if (corsMaxAge > -1)
- {
- response.setHeader(CorsHeaders.ACCESS_CONTROL_MAX_AGE, Integer.toString(corsMaxAge));
- }
- } else {
- response.setHeader(CorsHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, origin);
-
- if (allowCredentials) {
- response.setHeader(CorsHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
- }
-
- if (exposedHeaders != null) {
- response.setHeader(CorsHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, exposedHeaders);
- }
-
- chain.doFilter(request, response);
- }
- }
-
- @Override
- public void destroy() {
-
- }
-
- protected boolean originOk(String origin) {
- // startsWith test allows for host matching without explicit port mapping
- return allowedOrigins.contains("*") || allowedOrigins.contains(origin) || allowedOrigins.stream().anyMatch(origin::startsWith);
- }
-
-}
diff --git a/container/src/main/java/org/openremote/container/security/IdentityService.java b/container/src/main/java/org/openremote/container/security/IdentityService.java
index 2460622bd..22cd00a76 100644
--- a/container/src/main/java/org/openremote/container/security/IdentityService.java
+++ b/container/src/main/java/org/openremote/container/security/IdentityService.java
@@ -19,16 +19,11 @@
*/
package org.openremote.container.security;
-import io.undertow.server.HandlerWrapper;
-import io.undertow.server.HttpHandler;
-import io.undertow.server.HttpServerExchange;
import io.undertow.servlet.api.DeploymentInfo;
-import io.undertow.util.HttpString;
-import org.jboss.resteasy.spi.CorsHeaders;
-import org.openremote.model.Container;
-import org.openremote.model.ContainerService;
import org.openremote.container.persistence.PersistenceService;
import org.openremote.container.security.keycloak.KeycloakIdentityProvider;
+import org.openremote.model.Container;
+import org.openremote.model.ContainerService;
import java.util.logging.Logger;
@@ -67,34 +62,8 @@ public abstract class IdentityService implements ContainerService {
public void secureDeployment(DeploymentInfo deploymentInfo) {
LOG.info("Securing web deployment: " + deploymentInfo.getContextPath());
- deploymentInfo.addInitialHandlerChainWrapper(AuthOverloadHandler::new);
deploymentInfo.setSecurityDisabled(false);
identityProvider.secureDeployment(deploymentInfo);
-
- if (devMode) {
- // We need to add an undertow handler wrapper to inject CORS headers on 401/403 responses as the authentication
- // handler doesn't include headers set by deployment filters
- deploymentInfo.addOuterHandlerChainWrapper(new HandlerWrapper() {
- @Override
- public HttpHandler wrap(HttpHandler handler) {
- return new HttpHandler() {
- @Override
- public void handleRequest(HttpServerExchange exchange) throws Exception {
-
- if (exchange.isInIoThread()) {
- exchange.dispatch(this);
- return;
- }
-
- String origin = exchange.getRequestHeaders().getFirst(CorsHeaders.ORIGIN);
- exchange.getResponseHeaders().add(HttpString.tryFromString(CorsHeaders.ACCESS_CONTROL_ALLOW_ORIGIN), origin);
- exchange.getResponseHeaders().add(HttpString.tryFromString(CorsHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS), "true");
- handler.handleRequest(exchange);
- }
- };
- }
- });
- }
}
/**
diff --git a/container/src/main/java/org/openremote/container/security/AuthOverloadHandler.java b/container/src/main/java/org/openremote/container/security/WebsocketAuthParamHandler.java
similarity index 83%
rename from container/src/main/java/org/openremote/container/security/AuthOverloadHandler.java
rename to container/src/main/java/org/openremote/container/security/WebsocketAuthParamHandler.java
index d2a673679..7bbbf90c7 100644
--- a/container/src/main/java/org/openremote/container/security/AuthOverloadHandler.java
+++ b/container/src/main/java/org/openremote/container/security/WebsocketAuthParamHandler.java
@@ -29,16 +29,16 @@ import static jakarta.ws.rs.core.HttpHeaders.AUTHORIZATION;
import static org.openremote.model.Constants.REALM_PARAM_NAME;
/**
- * If a client can't set Authorization header (e.g. Javascript websocket API), use a request
- * parameter. This handler grabs the parameter and sets it as a regular header. This handler
- * will also grab {@link org.openremote.model.Constants#REALM_PARAM_NAME} as
- * a request parameter and set it as a regular header.
+ * For use by websocket requests where Authorization header cannot be set; grabs the
+ * {@link jakarta.ws.rs.core.HttpHeaders#AUTHORIZATION} query parameter and sets it as a regular header. This handler
+ * will also grab {@link org.openremote.model.Constants#REALM_PARAM_NAME} as a request parameter and set it as a regular
+ * header.
*/
-public class AuthOverloadHandler implements HttpHandler {
+public class WebsocketAuthParamHandler implements HttpHandler {
final protected HttpHandler next;
- public AuthOverloadHandler(HttpHandler next) {
+ public WebsocketAuthParamHandler(HttpHandler next) {
this.next = next;
}
diff --git a/container/src/main/java/org/openremote/container/security/keycloak/KeycloakIdentityProvider.java b/container/src/main/java/org/openremote/container/security/keycloak/KeycloakIdentityProvider.java
index 69363b8a5..0a50bccea 100644
--- a/container/src/main/java/org/openremote/container/security/keycloak/KeycloakIdentityProvider.java
+++ b/container/src/main/java/org/openremote/container/security/keycloak/KeycloakIdentityProvider.java
@@ -67,11 +67,10 @@ import java.util.logging.Level;
import java.util.logging.Logger;
import static java.util.concurrent.TimeUnit.MINUTES;
-import static org.openremote.container.util.MapAccess.getInteger;
-import static org.openremote.container.util.MapAccess.getString;
import static org.openremote.container.web.WebClient.getTarget;
-import static org.openremote.container.web.WebService.pathStartsWithHandler;
import static org.openremote.model.Constants.*;
+import static org.openremote.model.util.MapAccess.getInteger;
+import static org.openremote.model.util.MapAccess.getString;
public abstract class KeycloakIdentityProvider implements IdentityProvider {
@@ -92,7 +91,7 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
public static final String OR_KEYCLOAK_PORT = "OR_KEYCLOAK_PORT";
public static final int OR_KEYCLOAK_PORT_DEFAULT = 8081;
public static final String OR_KEYCLOAK_PATH = "OR_KEYCLOAK_PATH";
- public static final String OR_KEYCLOAK_PATH_DEFAULT = "auth";
+ public static final String OR_KEYCLOAK_PATH_DEFAULT = "/auth";
public static final String KEYCLOAK_CONNECT_TIMEOUT = "KEYCLOAK_CONNECT_TIMEOUT";
public static final int KEYCLOAK_CONNECT_TIMEOUT_DEFAULT = 2000;
public static final String KEYCLOAK_REQUEST_TIMEOUT = "KEYCLOAK_REQUEST_TIMEOUT";
@@ -195,7 +194,7 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
keycloakConfigResolver = request -> {
// The realm we authenticate against must be available as a request header
String realm = request.getHeader(REALM_PARAM_NAME);
- if (realm == null || realm.length() == 0) {
+ if (realm == null || realm.isEmpty()) {
LOG.finest("No realm in request, no authentication will be attempted: " + request.getURI());
return notAuthenticatedKeycloakDeployment;
}
@@ -209,7 +208,7 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
if (container.isDevMode()) {
authProxyHandler = ProxyHandler.builder()
- .setProxyClient(new LoadBalancingProxyClient().addHost(keycloakServiceUri.clone().replacePath("").build()))
+ .setProxyClient(new LoadBalancingProxyClient().addHost(keycloakServiceUri.build()))
.setMaxRequestTime(getInteger(container.getConfig(), KEYCLOAK_REQUEST_TIMEOUT, KEYCLOAK_REQUEST_TIMEOUT_DEFAULT))
.setNext(ResponseCodeHandler.HANDLE_404)
.setReuseXForwarded(true)
@@ -424,12 +423,8 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
if (authProxyHandler == null)
throw new IllegalStateException("Initialize this service first");
-
LOG.info("Enabling auth reverse proxy (passing requests through to Keycloak) on web context: /" + keycloakPath);
- webService.getRequestHandlers().addFirst(pathStartsWithHandler(
- "Keycloak auth proxy",
- "/" + keycloakPath,
- authProxyHandler));
+ webService.deploy(keycloakPath, authProxyHandler);
}
/**
diff --git a/container/src/main/java/org/openremote/container/timer/TimerService.java b/container/src/main/java/org/openremote/container/timer/TimerService.java
index 73c7f207c..475fce252 100644
--- a/container/src/main/java/org/openremote/container/timer/TimerService.java
+++ b/container/src/main/java/org/openremote/container/timer/TimerService.java
@@ -29,7 +29,7 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Logger;
-import static org.openremote.container.util.MapAccess.getString;
+import static org.openremote.model.util.MapAccess.getString;
/**
* Wall real clock timer or pseudo clock time (for testing).
@@ -80,7 +80,7 @@ public class TimerService implements ContainerService, RulesClock {
},
PSEUDO {
protected AtomicLong offset = new AtomicLong();
- protected Long stopTime;
+ protected volatile Long stopTime;
@Override
public void init() {
@@ -89,12 +89,12 @@ public class TimerService implements ContainerService, RulesClock {
}
@Override
- public long getCurrentTimeMillis() {
+ public synchronized long getCurrentTimeMillis() {
return (stopTime != null ? stopTime : System.currentTimeMillis()) + offset.get();
}
@Override
- public long advanceTime(long amount, TimeUnit unit) {
+ public synchronized long advanceTime(long amount, TimeUnit unit) {
offset.addAndGet(unit.toMillis(amount));
long currentMillis = getCurrentTimeMillis();
LOG.info("Clock advanced to: " + (currentMillis) + "/" + new Date(currentMillis));
@@ -102,7 +102,7 @@ public class TimerService implements ContainerService, RulesClock {
}
@Override
- public void stop() {
+ public synchronized void stop() {
if (stopTime == null) {
stopTime = System.currentTimeMillis();
LOG.info("Clock stopped at: " + (stopTime) + "/" + new Date(stopTime));
@@ -110,19 +110,19 @@ public class TimerService implements ContainerService, RulesClock {
}
@Override
- public void stopAtTime(long time) {
+ public synchronized void stopAtTime(long time) {
stopTime = time;
LOG.info("Clock stopped at: " + (stopTime) + "/" + new Date(stopTime));
}
@Override
- public void start() {
+ public synchronized void start() {
stopTime = null;
LOG.info("Clock started at: " + (System.currentTimeMillis()) + "/" + new Date(System.currentTimeMillis()));
}
@Override
- public void reset() {
+ public synchronized void reset() {
offset.set(0L);
stopTime = null;
}
diff --git a/container/src/main/java/org/openremote/container/util/LogUtil.java b/container/src/main/java/org/openremote/container/util/LogUtil.java
index d3954241c..3d7c7f03b 100644
--- a/container/src/main/java/org/openremote/container/util/LogUtil.java
+++ b/container/src/main/java/org/openremote/container/util/LogUtil.java
@@ -19,6 +19,7 @@
*/
package org.openremote.container.util;
+import org.openremote.model.util.Config;
import org.openremote.model.util.TextUtil;
import java.io.IOException;
@@ -29,7 +30,7 @@ import java.nio.file.Paths;
import java.util.Locale;
import java.util.logging.LogManager;
-import static org.openremote.model.Container.OR_DEV_MODE;
+import static org.openremote.model.util.Config.OR_DEV_MODE;
/**
* If system property <code>java.util.logging.config.file</code> or <code>java.util.logging.config.file</code> has been
@@ -72,9 +73,9 @@ public class LogUtil {
protected static InputStream getConfigInputStream() {
// Look for env variable config file
- boolean envConfigFileSet = !TextUtil.isNullOrEmpty(System.getenv(OR_LOGGING_CONFIG_FILE));
+ boolean envConfigFileSet = !TextUtil.isNullOrEmpty(Config.getString(OR_LOGGING_CONFIG_FILE, null));
if (envConfigFileSet) {
- InputStream configFile = getFileInputStream(System.getenv(OR_LOGGING_CONFIG_FILE));
+ InputStream configFile = getFileInputStream(Config.getString(OR_LOGGING_CONFIG_FILE, null));
if (configFile != null) {
LOG.log(System.Logger.Level.INFO, "Using logging configuration: " + System.getenv(OR_LOGGING_CONFIG_FILE));
diff --git a/container/src/main/java/org/openremote/container/web/AlreadyGZippedFilter.java b/container/src/main/java/org/openremote/container/web/AlreadyGZippedFilter.java
new file mode 100644
index 000000000..7f5a6ea7e
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/web/AlreadyGZippedFilter.java
@@ -0,0 +1,104 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.container.web;
+
+import jakarta.servlet.*;
+import jakarta.servlet.http.HttpServletResponse;
+import jakarta.servlet.http.HttpServletResponseWrapper;
+
+import javax.ws.rs.core.HttpHeaders;
+import java.io.IOException;
+import java.util.Set;
+
+/**
+ * A simple servlet filter that checks if the response has already been gzipped and if so, sets the gzip header.
+ */
+public class AlreadyGZippedFilter implements Filter {
+
+ protected Set<String> alreadyGzippedContentTypes;
+
+ public static class GzipHeaderWrapper extends HttpServletResponseWrapper {
+
+ private final Set<String> gzippedContentTypes;
+
+ public GzipHeaderWrapper(HttpServletResponse response, Set<String> gzippedContentTypes) {
+ super(response);
+ this.gzippedContentTypes = gzippedContentTypes;
+ }
+
+ /**
+ * The DefaultServlet will call this method to set the content type.
+ */
+ @Override
+ public void setContentType(String type) {
+ // Set the original content type
+ super.setContentType(type);
+
+ if (type != null) {
+ boolean isMatch = gzippedContentTypes.stream()
+ .anyMatch(type::startsWith);
+
+ if (isMatch) {
+ super.setHeader(HttpHeaders.CONTENT_ENCODING, "gzip");
+ }
+ }
+ }
+
+ @Override
+ public void setHeader(String name, String value) {
+ if (HttpHeaders.CONTENT_ENCODING.equalsIgnoreCase(name) && !"gzip".equalsIgnoreCase(value)) {
+ // It's trying to set Content-Encoding to something else.
+ // If we know this response *is* gzipped, ignore it.
+ // This is advanced; you can omit this block for now if you want.
+ String contentType = getContentType();
+ boolean isMatch = gzippedContentTypes.stream()
+ .anyMatch(contentType::startsWith);
+ if (isMatch) {
+ return; // Ignore the attempt to change the header
+ }
+ }
+ super.setHeader(name, value);
+ }
+
+ @Override
+ public void setContentLength(int len) {}
+
+ @Override
+ public void setContentLengthLong(long len) {}
+ }
+
+ public AlreadyGZippedFilter(Set<String> alreadyGzippedContentTypes) {
+ this.alreadyGzippedContentTypes = alreadyGzippedContentTypes;
+ }
+
+ @Override
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+ throws IOException, ServletException {
+
+ if (response instanceof HttpServletResponse httpResponse) {
+ // Create a wrapper so we can set the header before the response is committed
+ GzipHeaderWrapper responseWrapper = new GzipHeaderWrapper(httpResponse, alreadyGzippedContentTypes);
+
+ chain.doFilter(request, responseWrapper);
+ } else {
+ chain.doFilter(request, response);
+ }
+ }
+}
diff --git a/container/src/main/java/org/openremote/container/web/AlreadyGzippedWriterInterceptor.java b/container/src/main/java/org/openremote/container/web/AlreadyGzippedWriterInterceptor.java
deleted file mode 100644
index b7517e1dc..000000000
--- a/container/src/main/java/org/openremote/container/web/AlreadyGzippedWriterInterceptor.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright 2016, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.container.web;
-
-import jakarta.annotation.Priority;
-import jakarta.ws.rs.Priorities;
-import jakarta.ws.rs.WebApplicationException;
-import jakarta.ws.rs.ext.Provider;
-import jakarta.ws.rs.ext.WriterInterceptor;
-import jakarta.ws.rs.ext.WriterInterceptorContext;
-import java.io.IOException;
-import java.util.Arrays;
-
-@Provider
-@Priority(Priorities.ENTITY_CODER+1)
-public class AlreadyGzippedWriterInterceptor implements WriterInterceptor {
-
- public static final String[] ALREADY_ZIPPED_MEDIA_TYPES = new String[] {
- "application/vnd.mapbox-vector-tile"
- };
-
- @Override
- public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
- if (context.getMediaType() != null) {
- if (Arrays.asList(ALREADY_ZIPPED_MEDIA_TYPES).contains(context.getMediaType().toString())) {
- context.getHeaders().putSingle("Content-Encoding", "gzip");
- }
- }
- context.proceed();
- }
-}
diff --git a/container/src/main/java/org/openremote/container/web/CORSConfig.java b/container/src/main/java/org/openremote/container/web/CORSConfig.java
new file mode 100644
index 000000000..ab9850d0a
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/web/CORSConfig.java
@@ -0,0 +1,126 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.container.web;
+
+import org.openremote.model.util.Config;
+import org.openremote.model.util.TextUtil;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+
+import static org.openremote.container.web.WebService.*;
+
+/**
+ * A simple configuration container for configuring CORS behaviour
+ */
+public class CORSConfig {
+ public static final int DEFAULT_CORS_MAX_AGE = 600;
+ public static final String DEFAULT_CORS_ALLOW_ALL = "*";
+ public static final boolean DEFAULT_CORS_ALLOW_CREDENTIALS = true;
+ protected Set<String> corsAllowedOrigins;
+ protected String corsAllowedMethods;
+ protected String corsAllowedHeaders;
+ protected String corsExposedHeaders;
+ protected int corsMaxAge = DEFAULT_CORS_MAX_AGE;
+ protected boolean corsAllowCredentials = DEFAULT_CORS_ALLOW_CREDENTIALS;
+
+ public CORSConfig() {
+ corsAllowedOrigins = Config.isDevMode() ? Collections.singleton(DEFAULT_CORS_ALLOW_ALL) : getCorsAllowedOriginsFromConfig();
+ corsAllowedMethods = Config.isDevMode() ? DEFAULT_CORS_ALLOW_ALL : Config.getString(OR_WEBSERVER_ALLOWED_METHODS, DEFAULT_CORS_ALLOW_ALL);
+ corsAllowedHeaders = Config.isDevMode() ? DEFAULT_CORS_ALLOW_ALL : Config.getString(OR_WEBSERVER_ALLOWED_HEADERS, DEFAULT_CORS_ALLOW_ALL);
+ corsExposedHeaders = Config.getString(OR_WEBSERVER_EXPOSED_HEADERS, null);
+ }
+
+ public Set<String> getCorsAllowedOrigins() {
+ return corsAllowedOrigins;
+ }
+
+ public CORSConfig setCorsAllowedOrigins(Set<String> corsAllowedOrigins) {
+ this.corsAllowedOrigins = corsAllowedOrigins;
+ return this;
+ }
+
+ public CORSConfig addCorsAllowedOrigin(String origin) {
+ corsAllowedOrigins.add(origin);
+ return this;
+ }
+
+ public String getCorsAllowedMethods() {
+ return corsAllowedMethods;
+ }
+
+ public CORSConfig setCorsAllowedMethods(String corsAllowedMethods) {
+ this.corsAllowedMethods = corsAllowedMethods;
+ return this;
+ }
+
+ public String getCorsAllowedHeaders() {
+ return corsAllowedHeaders;
+ }
+
+ public CORSConfig setCorsAllowedHeaders(String corsAllowedHeaders) {
+ this.corsAllowedHeaders = corsAllowedHeaders;
+ return this;
+ }
+
+ public String getCorsExposedHeaders() {
+ return corsExposedHeaders;
+ }
+
+ public CORSConfig setCorsExposedHeaders(String corsExposedHeaders) {
+ this.corsExposedHeaders = corsExposedHeaders;
+ return this;
+ }
+
+ public int getCorsMaxAge() {
+ return corsMaxAge;
+ }
+
+ public CORSConfig setCorsMaxAge(int corsMaxAge) {
+ this.corsMaxAge = corsMaxAge;
+ return this;
+ }
+
+ public boolean isCorsAllowCredentials() {
+ return corsAllowCredentials;
+ }
+
+ public CORSConfig setCorsAllowCredentials(boolean corsAllowCredentials) {
+ this.corsAllowCredentials = corsAllowCredentials;
+ return this;
+ }
+
+ public static Set<String> getCorsAllowedOriginsFromConfig() {
+ // Set allowed origins using external hostnames and WEBSERVER_ALLOWED_ORIGINS
+ Set<String> allowedOrigins = new HashSet<>(
+ getExternalHostnames()
+ .stream().map(hostname -> "https://" + hostname).toList()
+ );
+ String allowedOriginsStr = Config.getString(OR_WEBSERVER_ALLOWED_ORIGINS, null);
+
+ if (!TextUtil.isNullOrEmpty(allowedOriginsStr)) {
+ allowedOrigins.addAll(Arrays.stream(allowedOriginsStr.split(",")).toList());
+ }
+
+ return allowedOrigins;
+ }
+}
diff --git a/container/src/main/java/org/openremote/container/web/ClassPathResource.java b/container/src/main/java/org/openremote/container/web/ClassPathResource.java
new file mode 100644
index 000000000..905517e1f
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/web/ClassPathResource.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.container.web;
+
+/**
+ * A resource source that loads resources from the classpath.
+ */
+public record ClassPathResource(ClassLoader classLoader, String prefix) implements ResourceSource {
+}
diff --git a/container/src/main/java/org/openremote/container/web/CompositeResourceManager.java b/container/src/main/java/org/openremote/container/web/CompositeResourceManager.java
new file mode 100644
index 000000000..811ca2cd7
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/web/CompositeResourceManager.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.container.web;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import io.undertow.UndertowMessages;
+import io.undertow.server.handlers.resource.Resource;
+import io.undertow.server.handlers.resource.ResourceChangeListener;
+import io.undertow.server.handlers.resource.ResourceManager;
+
+/**
+ * A {@link ResourceManager} that looks up resources from multiple {@code ResourceManager} instances, in the specified
+ * order.
+ */
+public class CompositeResourceManager implements ResourceManager {
+
+ protected final List<ResourceManager> resourceManagers = new ArrayList<>();
+
+ public CompositeResourceManager(ResourceManager... resourceManagers) {
+ this.resourceManagers.addAll(Arrays.asList(resourceManagers));
+ }
+
+ public void addResourceManager(ResourceManager resourceManager) {
+ resourceManagers.add(resourceManager);
+ }
+
+ @Override
+ public void close() throws IOException {
+ for (ResourceManager resourceManager : resourceManagers) {
+ resourceManager.close();
+ }
+ }
+
+ @Override
+ public Resource getResource(String path) throws IOException {
+ for (ResourceManager resourceManager : resourceManagers) {
+ Resource resource = resourceManager.getResource(path);
+ if (resource != null) {
+ return resource;
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public boolean isResourceChangeListenerSupported() {
+ return false;
+ }
+
+ @Override
+ public void registerResourceChangeListener(ResourceChangeListener listener) {
+ throw UndertowMessages.MESSAGES.resourceChangeListenerNotSupported();
+ }
+
+ @Override
+ public void removeResourceChangeListener(ResourceChangeListener listener) {
+ throw UndertowMessages.MESSAGES.resourceChangeListenerNotSupported();
+ }
+}
diff --git a/container/src/main/java/org/openremote/container/web/DirectoryAwareClassPathResourceManager.java b/container/src/main/java/org/openremote/container/web/DirectoryAwareClassPathResourceManager.java
new file mode 100644
index 000000000..b1db8fd69
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/web/DirectoryAwareClassPathResourceManager.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.container.web;
+
+import io.undertow.server.handlers.resource.ClassPathResourceManager;
+import io.undertow.server.handlers.resource.Resource;
+
+import java.io.IOException;
+
+/**
+ *
+ */
+public class DirectoryAwareClassPathResourceManager extends ClassPathResourceManager {
+
+ public DirectoryAwareClassPathResourceManager(ClassLoader loader, Package p) {
+ super(loader, p);
+ }
+
+ public DirectoryAwareClassPathResourceManager(ClassLoader classLoader, String prefix) {
+ super(classLoader, prefix);
+ }
+
+ public DirectoryAwareClassPathResourceManager(ClassLoader classLoader) {
+ super(classLoader);
+ }
+
+ @Override
+ public Resource getResource(String path) throws IOException {
+ Resource res = super.getResource(path);
+
+ // Check if this is actually a directory not a file
+ if (res == null || (res.getContentLength() != null && res.getContentLength() == 0)) {
+
+ Resource dirRes = super.getResource(path + "/");
+
+ // The DefaultServlet will see dirRes.isDirectory() == true and force a redirect
+ if (dirRes != null) {
+ return dirRes;
+ }
+ }
+
+ return res;
+ }
+}
diff --git a/container/src/main/java/org/openremote/container/web/file/Resource.java b/container/src/main/java/org/openremote/container/web/FileResource.java
similarity index 75%
rename from container/src/main/java/org/openremote/container/web/file/Resource.java
rename to container/src/main/java/org/openremote/container/web/FileResource.java
index 72cc95569..fc330e0e5 100644
--- a/container/src/main/java/org/openremote/container/web/file/Resource.java
+++ b/container/src/main/java/org/openremote/container/web/FileResource.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2017, OpenRemote Inc.
+ * Copyright 2025, OpenRemote Inc.
*
* See the CONTRIBUTORS.txt file in the distribution for a
* full listing of individual contributors.
@@ -17,15 +17,12 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-package org.openremote.container.web.file;
+package org.openremote.container.web;
-import java.io.File;
-import java.net.URL;
+import java.nio.file.Path;
-public interface Resource {
- File getFile();
- long getLength();
- long getLastModified();
- String getETag();
- URL getURL();
+/**
+ * A resource source that loads resources from a file system path.
+ */
+public record FileResource(Path path) implements ResourceSource {
}
diff --git a/container/src/main/java/org/openremote/container/web/RealmInjectorFilter.java b/container/src/main/java/org/openremote/container/web/RealmInjectorFilter.java
new file mode 100644
index 000000000..90f2a5ebb
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/web/RealmInjectorFilter.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.container.web;
+
+import jakarta.ws.rs.client.ClientRequestContext;
+import jakarta.ws.rs.client.ClientRequestFilter;
+import org.openremote.model.Constants;
+
+import java.io.IOException;
+
+/**
+ * A {@link ClientRequestFilter} that injects the realm into the {@link Constants#REALM_PARAM_NAME} request header.
+ */
+public class RealmInjectorFilter implements ClientRequestFilter {
+
+ protected String realm;
+
+ public RealmInjectorFilter(String realm) {
+ this.realm = realm;
+ }
+
+ @Override
+ public void filter(ClientRequestContext requestContext) throws IOException {
+ requestContext.getHeaders().putSingle(Constants.REALM_PARAM_NAME, realm);
+ }
+}
diff --git a/container/src/main/java/org/openremote/container/web/RealmPathExtractorFilter.java b/container/src/main/java/org/openremote/container/web/RealmPathExtractorFilter.java
new file mode 100644
index 000000000..9445e40ae
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/web/RealmPathExtractorFilter.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.container.web;
+
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerRequestFilter;
+import jakarta.ws.rs.container.PreMatching;
+import jakarta.ws.rs.core.PathSegment;
+import jakarta.ws.rs.core.UriBuilder;
+import jakarta.ws.rs.core.UriInfo;
+import jakarta.ws.rs.ext.Provider;
+import org.openremote.model.Constants;
+
+import java.io.IOException;
+import java.net.URI;
+import java.util.List;
+
+/**
+ * A JAX-RS filter that removes the realm from the full request path at the specified path segment index and adds it as
+ * a {@link org.openremote.model.Constants#REALM_PARAM_NAME} request header. If the
+ * {@link org.openremote.model.Constants#REALM_PARAM_NAME} header is already set, this filter does nothing.
+ */
+@Provider
+@PreMatching
+public class RealmPathExtractorFilter implements ContainerRequestFilter {
+
+ protected final int realmPathIndex;
+
+ public RealmPathExtractorFilter(int realmPathIndex) {
+ this.realmPathIndex = realmPathIndex;
+ }
+
+ @Override
+ public void filter(ContainerRequestContext requestContext) throws IOException {
+
+ // Do nothing if the realm header is already set
+ if (requestContext.getHeaders().containsKey(Constants.REALM_PARAM_NAME)) {
+ return;
+ }
+
+ UriInfo uriInfo = requestContext.getUriInfo();
+ List<PathSegment> pathSegments = uriInfo.getPathSegments();
+
+ if (pathSegments != null && pathSegments.size() > realmPathIndex) {
+ String realm = pathSegments.get(realmPathIndex).getPath();
+ requestContext.getHeaders().add(Constants.REALM_PARAM_NAME, realm);
+
+ // Build new URI with the realm segment removed
+ UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
+ for (int i = 0; i < pathSegments.size(); i++) {
+ if (i != realmPathIndex) {
+ uriBuilder.path(pathSegments.get(i).getPath());
+ }
+ }
+
+ uriBuilder.replaceQuery(uriInfo.getRequestUri().getRawQuery());
+ uriBuilder.fragment(uriInfo.getRequestUri().getFragment());
+ URI newUri = uriBuilder.build();
+
+ requestContext.setRequestUri(newUri);
+ }
+ }
+}
diff --git a/container/src/main/java/org/openremote/container/web/RequestLogger.java b/container/src/main/java/org/openremote/container/web/RequestLogger.java
index 2dab46614..2454a8ca1 100644
--- a/container/src/main/java/org/openremote/container/web/RequestLogger.java
+++ b/container/src/main/java/org/openremote/container/web/RequestLogger.java
@@ -20,6 +20,7 @@
package org.openremote.container.web;
import org.openremote.container.security.keycloak.KeycloakIdentityProvider;
+import org.openremote.model.Constants;
import org.openremote.model.syslog.SyslogCategory;
import jakarta.servlet.http.HttpServletRequest;
@@ -31,10 +32,13 @@ import jakarta.ws.rs.core.SecurityContext;
import jakarta.ws.rs.ext.Provider;
import java.io.IOException;
+/**
+ * JAX-RS {@link ContainerRequestFilter} that logs incoming requests to the {@link #REQUEST_LOG}.
+ */
@Provider
public class RequestLogger implements ContainerRequestFilter {
- public static final System.Logger REQUEST_LOG = System.getLogger(RequestLogger.class.getName() + "." + SyslogCategory.API.name());
+ protected static final System.Logger REQUEST_LOG = System.getLogger(RequestLogger.class.getName() + "." + SyslogCategory.API.name());
@Context
private HttpServletRequest request;
@@ -50,7 +54,7 @@ public class RequestLogger implements ContainerRequestFilter {
String port = String.valueOf(request.getRemotePort());
String forwardedAddress = requestContext.getHeaderString("X-Forwarded-For");
String method = requestContext.getMethod();
- String realm = requestContext.getHeaderString("Realm");
+ String realm = requestContext.getHeaderString(Constants.REALM_PARAM_NAME);
String responseType = requestContext.getHeaderString(HttpHeaders.ACCEPT);
String usernameAndRealm = securityContext != null
? KeycloakIdentityProvider.getSubjectNameAndRealm(securityContext.getUserPrincipal())
diff --git a/container/src/main/java/org/openremote/container/web/ResourceSource.java b/container/src/main/java/org/openremote/container/web/ResourceSource.java
new file mode 100644
index 000000000..e744c9249
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/web/ResourceSource.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.container.web;
+
+public sealed interface ResourceSource permits FileResource, ClassPathResource {
+}
+
diff --git a/container/src/main/java/org/openremote/container/web/ResponseHeaderUpdateFilter.java b/container/src/main/java/org/openremote/container/web/ResponseHeaderUpdateFilter.java
index dd6b81b2a..56ad0a195 100644
--- a/container/src/main/java/org/openremote/container/web/ResponseHeaderUpdateFilter.java
+++ b/container/src/main/java/org/openremote/container/web/ResponseHeaderUpdateFilter.java
@@ -1,3 +1,22 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
package org.openremote.container.web;
import jakarta.ws.rs.client.ClientRequestContext;
diff --git a/container/src/main/java/org/openremote/container/web/SecurityFilter.java b/container/src/main/java/org/openremote/container/web/SecurityFilter.java
new file mode 100644
index 000000000..5751be382
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/web/SecurityFilter.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.container.web;
+
+import jakarta.servlet.*;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+
+import java.io.IOException;
+
+/**
+ * A security filter that will check if the request is authenticated and that the user has all the specified roles
+ * by calling {@link HttpServletRequest#isUserInRole} for each {@link #requiredRoles}
+ */
+public class SecurityFilter implements Filter {
+
+ final protected String[] requiredRoles;
+
+ public SecurityFilter(String[] requiredRoles) {
+ this.requiredRoles = requiredRoles;
+ }
+
+ @Override
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
+
+ HttpServletRequest req = (HttpServletRequest) request;
+ HttpServletResponse res = (HttpServletResponse) response;
+
+ boolean userHasAllRoles = true;
+ for (String requiredRole : requiredRoles) {
+ if (!req.isUserInRole(requiredRole)) {
+ userHasAllRoles = false;
+ break;
+ }
+ }
+
+ if (userHasAllRoles) {
+ chain.doFilter(request, response);
+ } else {
+ if (req.getUserPrincipal() == null) {
+ res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
+ } else {
+ res.sendError(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
+ }
+ }
+ }
+}
diff --git a/container/src/main/java/org/openremote/container/web/WebApplication.java b/container/src/main/java/org/openremote/container/web/WebApplication.java
index cd9d06e4d..7cd21d5a6 100644
--- a/container/src/main/java/org/openremote/container/web/WebApplication.java
+++ b/container/src/main/java/org/openremote/container/web/WebApplication.java
@@ -19,18 +19,16 @@
*/
package org.openremote.container.web;
+import jakarta.ws.rs.core.Application;
import org.openremote.model.Container;
-import jakarta.ws.rs.core.Application;
import java.util.Collection;
import java.util.HashSet;
+import java.util.LinkedHashSet;
import java.util.Set;
-import java.util.logging.Logger;
public class WebApplication extends Application {
- private static final Logger LOG = Logger.getLogger(WebApplication.class.getName());
-
protected final Container container;
protected final Set<Class<?>> classes;
protected final Set<Object> singletons;
@@ -38,7 +36,7 @@ public class WebApplication extends Application {
public WebApplication(Container container, Collection<Class<?>> apiClasses, Collection<Object> apiSingletons) {
this.container = container;
this.classes = apiClasses != null ? new HashSet<>(apiClasses) : null;
- this.singletons = apiSingletons != null ? new HashSet<>(apiSingletons) : null;
+ this.singletons = apiSingletons != null ? new LinkedHashSet<>(apiSingletons) : null;
}
@Override
diff --git a/container/src/main/java/org/openremote/container/web/WebClient.java b/container/src/main/java/org/openremote/container/web/WebClient.java
index 50af5e008..112ccde55 100644
--- a/container/src/main/java/org/openremote/container/web/WebClient.java
+++ b/container/src/main/java/org/openremote/container/web/WebClient.java
@@ -21,6 +21,7 @@ package org.openremote.container.web;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import org.jboss.resteasy.client.jaxrs.internal.ResteasyClientBuilderImpl;
+import org.jboss.resteasy.plugins.interceptors.GZIPDecodingInterceptor;
import org.openremote.container.json.JacksonConfig;
import org.openremote.container.security.BearerAuthClientRequestFilter;
import org.openremote.container.security.ClientSecretRequestFilter;
@@ -43,7 +44,8 @@ public interface WebClient {
.register(new JacksonConfig())
.register(new ProxyClientRequestFilter())
.register(new BearerAuthClientRequestFilter())
- .register(new ClientSecretRequestFilter());
+ .register(new ClientSecretRequestFilter())
+ .register(new GZIPDecodingInterceptor());
}
static ResteasyWebTarget getTarget(Client client, URI uri, String accessToken, String forwardFor, URI forwardUri) {
diff --git a/container/src/main/java/org/openremote/container/web/WebResource.java b/container/src/main/java/org/openremote/container/web/WebResource.java
index b25459db7..bacaaa0e6 100644
--- a/container/src/main/java/org/openremote/container/web/WebResource.java
+++ b/container/src/main/java/org/openremote/container/web/WebResource.java
@@ -54,14 +54,6 @@ public class WebResource implements AuthContext {
@Context
protected SecurityContext securityContext;
- public WebApplication getApplication() {
- return (WebApplication) application;
- }
-
- public Container getContainer() {
- return getApplication().getContainer();
- }
-
public String getClientRemoteAddress() {
return request.getRemoteAddr();
}
diff --git a/container/src/main/java/org/openremote/container/web/WebService.java b/container/src/main/java/org/openremote/container/web/WebService.java
index cb60dadae..c96a2e31b 100644
--- a/container/src/main/java/org/openremote/container/web/WebService.java
+++ b/container/src/main/java/org/openremote/container/web/WebService.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2016, OpenRemote Inc.
+ * Copyright 2025, OpenRemote Inc.
*
* See the CONTRIBUTORS.txt file in the distribution for a
* full listing of individual contributors.
@@ -20,90 +20,56 @@
package org.openremote.container.web;
import com.google.common.collect.Lists;
+import com.thetransactioncompany.cors.CORSFilter;
+import io.undertow.Handlers;
import io.undertow.Undertow;
-import io.undertow.security.api.SecurityContext;
-import io.undertow.security.idm.Account;
+import io.undertow.attribute.ExchangeAttributes;
+import io.undertow.predicate.Predicates;
import io.undertow.server.HttpHandler;
-import io.undertow.server.HttpServerExchange;
+import io.undertow.server.handlers.CanonicalPathHandler;
+import io.undertow.server.handlers.PathHandler;
import io.undertow.server.handlers.RequestDumpingHandler;
+import io.undertow.server.handlers.encoding.ContentEncodingRepository;
+import io.undertow.server.handlers.encoding.EncodingHandler;
+import io.undertow.server.handlers.encoding.GzipEncodingProvider;
+import io.undertow.server.handlers.resource.PathResourceManager;
+import io.undertow.server.handlers.resource.ResourceManager;
import io.undertow.servlet.Servlets;
-import io.undertow.servlet.api.DeploymentInfo;
-import io.undertow.servlet.api.DeploymentManager;
-import io.undertow.servlet.api.FilterInfo;
+import io.undertow.servlet.api.*;
+import io.undertow.servlet.handlers.DefaultServlet;
+import io.undertow.servlet.util.ImmediateInstanceFactory;
import io.undertow.servlet.util.ImmediateInstanceHandle;
-import io.undertow.util.HeaderMap;
+import io.undertow.util.Headers;
+import io.undertow.util.HttpString;
import io.undertow.websockets.core.WebSocketChannel;
-import jakarta.servlet.DispatcherType;
-import jakarta.ws.rs.core.HttpHeaders;
+import jakarta.servlet.*;
+import jakarta.ws.rs.core.Application;
import jakarta.ws.rs.core.UriBuilder;
import org.jboss.resteasy.core.ResteasyDeploymentImpl;
-import org.jboss.resteasy.plugins.interceptors.GZIPEncodingInterceptor;
+import org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher;
import org.jboss.resteasy.spi.ResteasyDeployment;
import org.openremote.container.json.JacksonConfig;
-import org.openremote.container.security.CORSFilter;
import org.openremote.container.security.IdentityService;
-import org.openremote.container.security.keycloak.KeycloakIdentityProvider;
import org.openremote.model.Container;
import org.openremote.model.ContainerService;
+import org.openremote.model.http.HTTPMethod;
+import org.openremote.model.util.Config;
import org.openremote.model.util.TextUtil;
import org.xnio.Options;
import java.net.Inet4Address;
import java.net.URI;
+import java.nio.file.Path;
import java.util.*;
-import java.util.concurrent.atomic.AtomicReference;
-import java.util.function.Predicate;
import java.util.stream.Collectors;
import static java.lang.System.Logger.Level.*;
-import static org.openremote.container.util.MapAccess.*;
-import static org.openremote.model.Constants.OR_ADDITIONAL_HOSTNAMES;
-import static org.openremote.model.Constants.OR_HOSTNAME;
+import static org.openremote.container.web.CORSConfig.DEFAULT_CORS_ALLOW_ALL;
+import static org.openremote.model.Constants.*;
+import static org.openremote.model.util.MapAccess.*;
public abstract class WebService implements ContainerService {
- public static class RequestHandler {
- protected String name;
- protected Predicate<HttpServerExchange> handlePredicate;
- protected HttpHandler handler;
-
- public RequestHandler(String name, Predicate<HttpServerExchange> handlePredicate, HttpHandler handler) {
- this.name = name;
- this.handlePredicate = handlePredicate;
- this.handler = handler;
- }
-
- public String getName() {
- return name;
- }
-
- public Predicate<HttpServerExchange> getHandlePredicate() {
- return handlePredicate;
- }
-
- public io.undertow.server.HttpHandler getHandler() {
- return handler;
- }
- }
-
- public static class DeploymentInstance {
- protected DeploymentInfo deploymentInfo;
- protected WebService.RequestHandler requestHandler;
-
- public DeploymentInstance(DeploymentInfo deploymentInfo, WebService.RequestHandler requestHandler) {
- this.deploymentInfo = deploymentInfo;
- this.requestHandler = requestHandler;
- }
-
- public WebService.RequestHandler getRequestHandler() {
- return requestHandler;
- }
-
- public DeploymentInfo getDeploymentInfo() {
- return deploymentInfo;
- }
- }
-
// Change this to 0.0.0.0 to bind on all interfaces, enabling
// access of the manager service from other devices in your LAN
public static final String OR_WEBSERVER_LISTEN_HOST = "OR_WEBSERVER_LISTEN_HOST";
@@ -113,34 +79,36 @@ public abstract class WebService implements ContainerService {
public static final String OR_WEBSERVER_DUMP_REQUESTS = "OR_WEBSERVER_DUMP_REQUESTS";
public static final boolean OR_WEBSERVER_DUMP_REQUESTS_DEFAULT = false;
public static final String OR_WEBSERVER_ALLOWED_ORIGINS = "OR_WEBSERVER_ALLOWED_ORIGINS";
+ public static final String OR_WEBSERVER_ALLOWED_METHODS = "OR_WEBSERVER_ALLOWED_METHODS";
+ public static final String OR_WEBSERVER_EXPOSED_HEADERS = "OR_WEBSERVER_EXPOSED_HEADERS";
+ public static final String OR_WEBSERVER_ALLOWED_HEADERS = "OR_WEBSERVER_ALLOWED_HEADERS";
public static final String OR_WEBSERVER_IO_THREADS_MAX = "OR_WEBSERVER_IO_THREADS_MAX";
public static final int OR_WEBSERVER_IO_THREADS_MAX_DEFAULT = Math.max(Runtime.getRuntime().availableProcessors(), 2);
public static final String OR_WEBSERVER_WORKER_THREADS_MAX = "OR_WEBSERVER_WORKER_THREADS_MAX";
- public static final int WEBSERVER_WORKER_THREADS_MAX_DEFAULT = Math.max(Runtime.getRuntime().availableProcessors(), 10);
+ public static final int OR_WEBSERVER_WORKER_THREADS_MAX_DEFAULT = Math.max(Runtime.getRuntime().availableProcessors(), 10);
private static final System.Logger LOG = System.getLogger(WebService.class.getName());
- protected static AtomicReference<CORSFilter> corsFilterRef;
protected boolean devMode;
protected String host;
+ protected IdentityService identityService;
protected int port;
protected Undertow undertow;
- protected List<RequestHandler> httpHandlers = new ArrayList<>();
protected URI containerHostUri;
- protected static WebServiceExceptions.DefaultResteasyExceptionMapper defaultResteasyExceptionMapper;
- protected static WebServiceExceptions.ForbiddenResteasyExceptionMapper forbiddenResteasyExceptionMapper;
- protected static JacksonConfig jacksonConfig;
- protected static AlreadyGzippedWriterInterceptor alreadyGzippedWriterInterceptor;
- protected static ClientErrorExceptionHandler clientErrorExceptionHandler;
- protected static WebServiceExceptions.ServletUndertowExceptionHandler undertowExceptionHandler;
+ protected PathHandler pathHandler = Handlers.path();
+
+ public static final Map<String, String> MIME_TYPES = Map.of(
+ "pbf", "application/x-protobuf",
+ "wsdl", "application/xml",
+ "xsl", "text/xsl");
+ public static final Set<String> MIME_TYPES_ALREADY_GZIPPED = Set.of(
+ "application/vnd.mapbox-vector-tile",
+ "application/x-protobuf"
+ );
protected static String getLocalIpAddress() throws Exception {
return Inet4Address.getLocalHost().getHostAddress();
}
- public static RequestHandler pathStartsWithHandler(String name, String path, HttpHandler handler) {
- return new RequestHandler(name, exchange -> exchange.getRequestPath().startsWith(path), handler);
- }
-
@Override
public int getPriority() {
return LOW_PRIORITY;
@@ -148,6 +116,7 @@ public abstract class WebService implements ContainerService {
@Override
public void init(Container container) throws Exception {
+ identityService = container.getService(IdentityService.class);
devMode = container.isDevMode();
host = getString(container.getConfig(), OR_WEBSERVER_LISTEN_HOST, OR_WEBSERVER_LISTEN_HOST_DEFAULT);
port = getInteger(container.getConfig(), OR_WEBSERVER_LISTEN_PORT, OR_WEBSERVER_LISTEN_PORT_DEFAULT);
@@ -166,7 +135,7 @@ public abstract class WebService implements ContainerService {
Undertow.builder()
.addHttpListener(port, host)
.setIoThreads(getInteger(container.getConfig(), OR_WEBSERVER_IO_THREADS_MAX, OR_WEBSERVER_IO_THREADS_MAX_DEFAULT))
- .setWorkerThreads(getInteger(container.getConfig(), OR_WEBSERVER_WORKER_THREADS_MAX, WEBSERVER_WORKER_THREADS_MAX_DEFAULT))
+ .setWorkerThreads(getInteger(container.getConfig(), OR_WEBSERVER_WORKER_THREADS_MAX, OR_WEBSERVER_WORKER_THREADS_MAX_DEFAULT))
.setWorkerOption(Options.WORKER_NAME, "WebService")
.setWorkerOption(Options.THREAD_DAEMON, true)
).build();
@@ -186,94 +155,100 @@ public abstract class WebService implements ContainerService {
@Override
public void stop(Container container) throws Exception {
+ // Remove all deployments
+ Servlets.defaultContainer().listDeployments().forEach(this::undeploy);
+
+ pathHandler.clearPaths();
+
if (undertow != null) {
undertow.stop();
undertow = null;
}
}
- /**
- * Adds a deployment to the default servlet container and returns the started handler.
- */
- public static HttpHandler addServletDeployment(Container container, DeploymentInfo deploymentInfo, boolean secure) {
-
- IdentityService identityService = container.getService(IdentityService.class);
- boolean devMode = container.isDevMode();
-
- try {
- if (secure) {
- if (identityService == null)
- throw new IllegalStateException(
- "No identity service found, make sure " + IdentityService.class.getName() + " is added before this service"
- );
- identityService.secureDeployment(deploymentInfo);
- } else {
- LOG.log(INFO, "Deploying insecure web context: " + deploymentInfo.getContextPath());
- }
+ /**
+ * Deploys the undertow specific deployment and wires up the path handler
+ */
+ public void deploy(DeploymentInfo deploymentInfo, boolean useCanonicalPathHandler) {
+ String pathPrefix = deploymentInfo.getContextPath();
- // This will catch anything not handled by Resteasy/Servlets, such as IOExceptions "at the wrong time"
- deploymentInfo.setExceptionHandler(new WebServiceExceptions.ServletUndertowExceptionHandler(devMode));
+ if (!pathPrefix.startsWith("/")) {
+ pathPrefix = "/" + pathPrefix;
+ }
- // Add CORS filter that works for any servlet deployment
- FilterInfo corsFilterInfo = getCorsFilterInfo(container);
+ LOG.log(INFO, "Deploying undertow servlet deployment: name=" + deploymentInfo.getDeploymentName() + ", path=" + pathPrefix + ", secure=" + !deploymentInfo.isSecurityDisabled());
- if (corsFilterInfo != null) {
- deploymentInfo.addFilter(corsFilterInfo);
- deploymentInfo.addFilterUrlMapping(corsFilterInfo.getName(), "*", DispatcherType.REQUEST);
- deploymentInfo.addFilterUrlMapping(corsFilterInfo.getName(), "*", DispatcherType.FORWARD);
- }
+ try {
+ DeploymentManager manager = Servlets.defaultContainer().addDeployment(deploymentInfo);
+ manager.deploy();
+ HttpHandler httpHandler = manager.start();
+
+ if (useCanonicalPathHandler) {
+ LOG.log(DEBUG, "Using canonical path handler for deployment");
+ httpHandler = new CanonicalPathHandler(httpHandler);
+ }
- DeploymentManager manager = Servlets.defaultContainer().addDeployment(deploymentInfo);
- manager.deploy();
- return manager.start();
- } catch (Exception ex) {
- throw new RuntimeException(ex);
+ pathHandler.addPrefixPath(deploymentInfo.getContextPath(), httpHandler);
+ } catch (ServletException e) {
+ LOG.log(ERROR, "Servlet deployment failed: " + e.getMessage());
}
}
- public void removeServletDeployment(DeploymentInfo deploymentInfo) {
- try {
- DeploymentManager manager = Servlets.defaultContainer().getDeployment(deploymentInfo.getDeploymentName());
- manager.stop();
- manager.undeploy();
- Servlets.defaultContainer().removeDeployment(deploymentInfo);
- } catch (Exception ex) {
- throw new RuntimeException(ex);
- }
+ public void deploy(String pathPrefix, HttpHandler httpHandler) {
+ if (!pathPrefix.startsWith("/")) {
+ pathPrefix = "/" + pathPrefix;
+ }
+
+ LOG.log(INFO, "Deploying undertow http handler: path=" + pathPrefix);
+ pathHandler.addPrefixPath(pathPrefix, httpHandler);
}
- public static void configureDeploymentInfo(DeploymentInfo deploymentInfo) {
- // This will catch anything not handled by Resteasy/Servlets, such as IOExceptions "at the wrong time"
- deploymentInfo.setExceptionHandler(undertowExceptionHandler);
+ public void undeploy(String deploymentName) {
+ try {
+ DeploymentManager manager = Servlets.defaultContainer().getDeployment(deploymentName);
+ DeploymentInfo deploymentInfo = manager.getDeployment().getDeploymentInfo();
+ LOG.log(INFO, "Un-deploying undertow servlet deployment: name=" + deploymentInfo.getDeploymentName() + ", path=" + deploymentInfo.getContextPath());
+ pathHandler.removePrefixPath(deploymentInfo.getContextPath());
+ manager.stop();
+ manager.undeploy();
+ Servlets.defaultContainer().removeDeployment(deploymentInfo);
+ } catch (Exception ex) {
+ LOG.log(ERROR, "Servlet un-deployment failed: name=" + deploymentName + ", exception=" + ex.getMessage());
+ }
}
- /**
- * Get standard JAX-RS providers that are used in the deployment.
- */
- public static List<Object> getStandardProviders(boolean devMode) {
- if (defaultResteasyExceptionMapper == null) {
- defaultResteasyExceptionMapper = new WebServiceExceptions.DefaultResteasyExceptionMapper(devMode);
- forbiddenResteasyExceptionMapper = new WebServiceExceptions.ForbiddenResteasyExceptionMapper(devMode);
- undertowExceptionHandler = new WebServiceExceptions.ServletUndertowExceptionHandler(devMode);
- jacksonConfig = new JacksonConfig();
- alreadyGzippedWriterInterceptor = new AlreadyGzippedWriterInterceptor();
- clientErrorExceptionHandler = new ClientErrorExceptionHandler();
- }
- return Lists.newArrayList(
- defaultResteasyExceptionMapper,
- forbiddenResteasyExceptionMapper,
- jacksonConfig,
- alreadyGzippedWriterInterceptor,
- clientErrorExceptionHandler
- );
+ public void undeployHttpHandler(String pathPrefix) {
+ LOG.log(INFO, "Un-deploying undertow handler: path=" + pathPrefix);
+ pathHandler.removePrefixPath(pathPrefix);
+ }
+
+ public void addPathPrefixHandler(String path, HttpHandler handler) {
+ pathHandler.addPrefixPath(path, handler);
+ }
+
+ public void removePathPrefixHandler(String path) {
+ pathHandler.removePrefixPath(path);
}
/**
- * When a request comes in the handlers are called in order until a handler returns a non null value; when this
- * happens the returned {@link RequestHandler} is invoked.
+ * Get standard JAX-RS providers that are used in the deployment with optional realm extraction from the request
+ * path
*/
- public List<RequestHandler> getRequestHandlers() {
- return this.httpHandlers;
+ public static List<Object> getStandardProviders(boolean devMode, Integer realmIndex) {
+ List<Object> providers = Lists.newArrayList(
+ new RequestLogger(),
+ new WebServiceExceptions.DefaultResteasyExceptionMapper(devMode),
+ new WebServiceExceptions.ForbiddenResteasyExceptionMapper(devMode),
+ new WebServiceExceptions.ServletUndertowExceptionHandler(devMode),
+ new JacksonConfig(),
+ new ClientErrorExceptionHandler()
+ );
+
+ if (realmIndex != null) {
+ providers.addFirst(new RealmPathExtractorFilter(realmIndex));
+ }
+
+ return providers;
}
/**
@@ -287,123 +262,243 @@ public abstract class WebService implements ContainerService {
protected Undertow.Builder build(Container container, Undertow.Builder builder) {
- LOG.log(INFO, () -> "Building web routing with handler(s): " + getRequestHandlers().stream().map(h -> h.name).collect(Collectors.joining("\n")));
-
- HttpHandler handler = exchange -> {
-
- RequestLogger.REQUEST_LOG.log(DEBUG, () -> {
- String requestPath = exchange.getRequestURI();
- String address = exchange.getSourceAddress().toString();
- HeaderMap headers = exchange.getRequestHeaders();
- String forwardedAddress = headers.getFirst("X-Forwarded-For");
- String responseType = headers.getFirst(HttpHeaders.ACCEPT);
- SecurityContext securityContext = exchange.getSecurityContext();
- Account account = securityContext != null ? securityContext.getAuthenticatedAccount() : null;
- String userAndRealm
- = account != null
- ? KeycloakIdentityProvider.getSubjectNameAndRealm(account.getPrincipal())
- : null;
-
- return "Client request '" + requestPath +" (responseType=" + responseType +")': user=" + userAndRealm + ", origin=" +
- address +", forwarded-for=" + forwardedAddress;
- });
-
- boolean handled = false;
- for (RequestHandler requestHandler : getRequestHandlers()) {
- if (requestHandler.handlePredicate.test(exchange)) {
- LOG.log(TRACE, () -> "Handling '" + exchange.getRequestURI() + "' with handler: " + requestHandler.name);
- requestHandler.handler.handleRequest(exchange);
- handled = true;
- break;
- }
- }
-
- if (!handled) {
- LOG.log(WARNING, "No handler found for request: " + exchange.getRequestURI());
- }
- };
-
- handler = new WebServiceExceptions.RootUndertowExceptionHandler(devMode, handler);
+ HttpHandler handler = new WebServiceExceptions.RootUndertowExceptionHandler(devMode, pathHandler);
if (getBoolean(container.getConfig(), OR_WEBSERVER_DUMP_REQUESTS, OR_WEBSERVER_DUMP_REQUESTS_DEFAULT)) {
handler = new RequestDumpingHandler(handler);
}
+ // Add GZIP encoding/decoding support at the undertow level
+ handler = new EncodingHandler(new ContentEncodingRepository()
+ .addEncodingHandler("gzip",
+ new GzipEncodingProvider(), 50,
+ Predicates.and(
+ Predicates.requestLargerThan(5120),
+ Predicates.not(Predicates.contains(ExchangeAttributes.responseHeader(Headers.CONTENT_TYPE), MIME_TYPES_ALREADY_GZIPPED.toArray(new String[0]))))))
+ .setNext(handler);
+
builder.setHandler(handler);
return builder;
}
- protected ResteasyDeployment createResteasyDeployment(Container container, Collection<Class<?>> apiClasses, Collection<Object> apiSingletons, boolean secure) {
- if (apiClasses == null && apiSingletons == null)
- return null;
- WebApplication webApplication = new WebApplication(container, apiClasses, apiSingletons);
- ResteasyDeployment resteasyDeployment = new ResteasyDeploymentImpl();
- resteasyDeployment.setApplication(webApplication);
+ public void deployServlet(
+ Class<? extends ServletContainerInitializer> servletContainerInitializerClass,
+ String deploymentPath,
+ String deploymentName,
+ Integer realmIndex,
+ boolean secure,
+ CORSConfig corsOverride) throws IllegalArgumentException {
+ DeploymentInfo deploymentInfo = Servlets.deployment()
+ .setDeploymentName(deploymentName)
+ .setContextPath(deploymentPath)
+ .setSecurityDisabled(!secure)
+ .addServletContainerInitializer(new ServletContainerInitializerInfo(servletContainerInitializerClass, null))
+ .setClassLoader(this.getClass().getClassLoader());
+
+ configureDeploymentInfo(deploymentInfo, realmIndex, secure, corsOverride);
+ deploy(deploymentInfo, false);
+ }
+
+ public void deployJaxRsApplication(
+ Application application,
+ String deploymentPath,
+ String deploymentName,
+ Integer realmIndex,
+ boolean secure,
+ CORSConfig corsOverride) throws IllegalArgumentException {
+ ServletContextListener jaxRsListener = new ServletContextListener() {
+ @Override
+ public void contextInitialized(ServletContextEvent sce) {
+ ServletContext ctx = sce.getServletContext();
+ ResteasyDeployment deployment = new ResteasyDeploymentImpl();
+ deployment.setApplication(application);
+ ctx.setAttribute(ResteasyDeployment.class.getName(), deployment);
+
+ ServletRegistration.Dynamic servlet = ctx.addServlet("ResteasyServlet", HttpServletDispatcher.class);
+ servlet.setAsyncSupported(true);
+ servlet.setLoadOnStartup(1);
+ servlet.addMapping("/*");
+
+ if (secure) {
+ deployment.setSecurityEnabled(true);
+ //servlet.setInitParameter(ResteasyContextParameters.RESTEASY_ROLE_BASED_SECURITY, "true");
+ }
+ }
+ };
+ Class<? extends EventListener> listenerClass = jaxRsListener.getClass();
+ InstanceFactory<? extends EventListener> factory = new ImmediateInstanceFactory<>(jaxRsListener);
+
+ DeploymentInfo deploymentInfo = Servlets.deployment()
+ .setDeploymentName(deploymentName)
+ .setContextPath(deploymentPath)
+ .addListeners(Servlets.listener(listenerClass, factory))
+ .setClassLoader(this.getClass().getClassLoader());
+
+ configureDeploymentInfo(deploymentInfo, realmIndex, secure, corsOverride);
+ deploy(deploymentInfo, false);
+ }
+
+ /**
+ * Serve files from disk or classpath; {@link ResourceSource}s provided should be in preference order.
+ */
+ @SuppressWarnings("resource")
+ public void deployFileServlet(
+ String deploymentPath,
+ String deploymentName,
+ ResourceSource[] resourceSources,
+ String[] requiredRoles,
+ CORSConfig corsOverride) {
+
+ if (resourceSources == null || resourceSources.length == 0) {
+ throw new IllegalArgumentException("No file paths specified");
+ }
+
+ ResourceManager filesResourceManager;
+ if (resourceSources.length == 1) {
+ filesResourceManager = createResourceManager(resourceSources[0]);
+ } else {
+ CompositeResourceManager compositeResourceManager = new CompositeResourceManager();
+ for (ResourceSource resourceSource : resourceSources) {
+ compositeResourceManager.addResourceManager(createResourceManager(resourceSource));
+ }
+ filesResourceManager = compositeResourceManager;
+ }
+
+ DeploymentInfo deploymentInfo = Servlets.deployment()
+ .setDeploymentName(deploymentName)
+ .setResourceManager(filesResourceManager)
+ .setContextPath(deploymentPath)
+ .addServlet(Servlets.servlet("DefaultServlet", DefaultServlet.class))
+ .addWelcomePages("index.html", "index.htm")
+ .setClassLoader(getClass().getClassLoader());
+
+ MIME_TYPES.forEach((ext, mimeType) -> deploymentInfo.addMimeMapping(new MimeMapping(ext, mimeType)));
+
+ Filter alreadyGzippedFilter = new AlreadyGZippedFilter(MIME_TYPES_ALREADY_GZIPPED);
+ FilterInfo alreadyGzippedFilterInfo = Servlets.filter(
+ "Already GZipped Filter",
+ AlreadyGZippedFilter.class,
+ () -> new ImmediateInstanceHandle<>(alreadyGzippedFilter)).setAsyncSupported(true);
+ deploymentInfo.addFilter(alreadyGzippedFilterInfo);
+ deploymentInfo.addFilterUrlMapping( "Already GZipped Filter","/*", DispatcherType.REQUEST);
+
+ if (requiredRoles != null && requiredRoles.length > 0) {
+ Filter securityFilter = new SecurityFilter(requiredRoles);
+ FilterInfo securityFilterInfo = Servlets.filter("Security Filter", SecurityFilter.class, () -> new ImmediateInstanceHandle<>(securityFilter))
+ .setAsyncSupported(true);
+ deploymentInfo.addFilter(securityFilterInfo);
+ deploymentInfo.addFilterUrlMapping( "Security Filter","/*", DispatcherType.REQUEST);
+ }
+
+ configureDeploymentInfo(
+ deploymentInfo,
+ null,
+ requiredRoles != null && requiredRoles.length > 0,
+ corsOverride);
+ deploy(deploymentInfo, true);
+ }
+
+ protected ResourceManager createResourceManager(ResourceSource resourceSource) {
+ if (resourceSource instanceof FileResource(Path path)) {
+ return new PathResourceManager(path);
+ }
+ if (resourceSource instanceof ClassPathResource(ClassLoader classLoader, String prefix)) {
+ return new DirectoryAwareClassPathResourceManager(classLoader, prefix);
+ }
+ throw new UnsupportedOperationException("ResourceSource not currently supported");
+ }
+
+ public void configureDeploymentInfo(
+ DeploymentInfo deploymentInfo,
+ Integer realmIndex,
+ boolean secure,
+ CORSConfig corsOverride) {
+
+
+ if (corsOverride == null) {
+ // Just use default CORS config
+ corsOverride = new CORSConfig();
+ }
- // Custom providers (these only apply to server applications, not client calls)
- resteasyDeployment.getProviders().add(new WebServiceExceptions.DefaultResteasyExceptionMapper(devMode));
- resteasyDeployment.getProviders().add(new WebServiceExceptions.ForbiddenResteasyExceptionMapper(devMode));
- resteasyDeployment.getProviders().add(new JacksonConfig());
+ // TODO: Remove this handler wrapper once JAX-RS RealmPathExtractorFilter can be utilised before security is applied
+ if (realmIndex != null) {
+ deploymentInfo.addInitialHandlerChainWrapper(handler -> {
+
+ return exchange -> {
+ // Do nothing if the realm header is already set
+ if (exchange.getRequestHeaders().contains(REALM_PARAM_NAME)) {
+ handler.handleRequest(exchange);
+ return;
+ }
+
+ String relativePath = exchange.getRelativePath();
+ StringBuilder newRelativePathBuilder = new StringBuilder();
+ String realm = null;
+ int segmentIndex = 0;
+ int start = 1; // Path starts with '/'
+
+ for (int i = 1; i <= relativePath.length(); i++) {
+ if (i == relativePath.length() || relativePath.charAt(i) == '/') {
+ if (i > start) { // Found a segment
+ if (segmentIndex == realmIndex) {
+ realm = relativePath.substring(start, i);
+ } else {
+ newRelativePathBuilder.append('/').append(relativePath, start, i);
+ }
+ segmentIndex++;
+ }
+ start = i + 1;
+ }
+ }
+
+ if (realm != null) {
+ exchange.getRequestHeaders().put(HttpString.tryFromString(REALM_PARAM_NAME), realm);
+
+ String newRelativePath = !newRelativePathBuilder.isEmpty() ? newRelativePathBuilder.toString() : "/";
+ String newRequestPath = deploymentInfo.getContextPath() + newRelativePath;
+ exchange.setRequestURI(newRequestPath);
+ exchange.setRelativePath(newRelativePath);
+ exchange.setRequestPath(newRequestPath);
+ }
+
+ handler.handleRequest(exchange);
+ };
+ });
+ }
- if (!container.isDevMode()) {
- resteasyDeployment.getProviders().add(GZIPEncodingInterceptor.class);
+ if (secure) {
+ if (identityService == null)
+ throw new IllegalStateException(
+ "No identity service found, make sure " + IdentityService.class.getName() + " is added before this service"
+ );
+ identityService.secureDeployment(deploymentInfo);
}
- resteasyDeployment.getActualProviderClasses().add(AlreadyGzippedWriterInterceptor.class);
- resteasyDeployment.getActualProviderClasses().add(ClientErrorExceptionHandler.class);
- //resteasyDeployment.getActualProviderClasses().add(RequestLogger.class);
- resteasyDeployment.setSecurityEnabled(secure);
+ // Cannot set config on constructor as init method will overwrite it
+ CORSFilter corsFilter = new CORSFilter();
+
+ FilterInfo corsFilterInfo = Servlets.filter(
+ "CORS Filter",
+ CORSFilter.class,
+ () -> new ImmediateInstanceHandle<>(corsFilter)).setAsyncSupported(true);
+ getCORSConfiguration(corsOverride).forEach((k,v) -> corsFilterInfo.addInitParam(k.toString(), v.toString()));
+ deploymentInfo.addFilter(corsFilterInfo);
+ deploymentInfo.addFilterUrlMapping( "CORS Filter","/*", DispatcherType.REQUEST);
- return resteasyDeployment;
+ // This will catch anything not handled by Resteasy/Servlets, such as IOExceptions "at the wrong time"
+ deploymentInfo.setExceptionHandler(new WebServiceExceptions.ServletUndertowExceptionHandler(devMode));
}
public Undertow getUndertow() {
return undertow;
}
- public static synchronized FilterInfo getCorsFilterInfo(Container container) {
-
- if (corsFilterRef == null) {
- CORSFilter corsFilter = null;
-
- if (!container.isDevMode()) {
- Set<String> allowedOrigins = getAllowedOrigins(container);
-
- if (!allowedOrigins.isEmpty()) {
- corsFilter = new CORSFilter();
- corsFilter.setAllowCredentials(true);
- corsFilter.setAllowedMethods("GET, POST, PUT, DELETE, OPTIONS, HEAD");
- corsFilter.setExposedHeaders("*");
- corsFilter.setCorsMaxAge(1209600);
- corsFilter.getAllowedOrigins().addAll(allowedOrigins);
- }
- } else {
- corsFilter = new CORSFilter();
- corsFilter.getAllowedOrigins().add("*");
- corsFilter.setAllowCredentials(true);
- corsFilter.setExposedHeaders("*");
- corsFilter.setAllowedMethods("GET, POST, PUT, DELETE, OPTIONS, HEAD");
- corsFilter.setCorsMaxAge(1209600);
- }
-
- corsFilterRef = new AtomicReference<>(corsFilter);
- }
-
- if (corsFilterRef.get() != null) {
- CORSFilter finalCorsFilter = corsFilterRef.get();
- return Servlets.filter("CORS Filter", CORSFilter.class, () -> new ImmediateInstanceHandle<>(finalCorsFilter))
- .setAsyncSupported(true);
- }
-
- return null;
- }
-
- public static List<String> getExternalHostnames(Container container) {
+ public static List<String> getExternalHostnames() {
// Get list of external hostnames
- String defaultHostname = getString(container.getConfig(), OR_HOSTNAME, null);
- String additionalHostnamesStr = getString(container.getConfig(), OR_ADDITIONAL_HOSTNAMES, null);
+ String defaultHostname = Config.getString(OR_HOSTNAME, null);
+ String additionalHostnamesStr = Config.getString(OR_ADDITIONAL_HOSTNAMES, null);
List<String> externalHostnames = new ArrayList<>();
@@ -419,18 +514,27 @@ public abstract class WebService implements ContainerService {
return externalHostnames;
}
- public static Set<String> getAllowedOrigins(Container container) {
- // Set allowed origins using external hostnames and WEBSERVER_ALLOWED_ORIGINS
- Set<String> allowedOrigins = new HashSet<>(
- getExternalHostnames(container)
- .stream().map(hostname -> "https://" + hostname).toList()
- );
- String allowedOriginsStr = getString(container.getConfig(), OR_WEBSERVER_ALLOWED_ORIGINS, null);
+ public static Properties getCORSConfiguration(CORSConfig corsConfig) {
+ Properties props = new Properties();
- if (!TextUtil.isNullOrEmpty(allowedOriginsStr)) {
- allowedOrigins.addAll(Arrays.stream(allowedOriginsStr.split(",")).toList());
+ if (corsConfig != null) {
+ props.put("cors.supportsCredentials", Boolean.toString(corsConfig.isCorsAllowCredentials()));
+ props.put("cors.maxAge", corsConfig.getCorsMaxAge());
+ if (corsConfig.getCorsExposedHeaders() != null) {
+ props.put("cors.exposedHeaders", corsConfig.getCorsExposedHeaders());
+ }
+ if (corsConfig.getCorsAllowedHeaders() != null) {
+ props.put("cors.supportedHeaders", corsConfig.getCorsAllowedHeaders());
+ }
+ // CORSFilter doesn't support wildcard for methods
+ String allowedMethods = corsConfig.getCorsAllowedMethods();
+ allowedMethods = allowedMethods == null || DEFAULT_CORS_ALLOW_ALL.equals(allowedMethods)
+ ? Arrays.stream(HTTPMethod.values()).map(Enum::toString).collect(Collectors.joining(","))
+ : allowedMethods;
+ props.put("cors.supportedMethods", allowedMethods);
+ props.put("cors.allowOrigin", String.join(",", corsConfig.getCorsAllowedOrigins()));
}
- return allowedOrigins;
+ return props;
}
}
diff --git a/container/src/main/java/org/openremote/container/web/WebTargetBuilder.java b/container/src/main/java/org/openremote/container/web/WebTargetBuilder.java
index c10408dbc..57bcbe834 100644
--- a/container/src/main/java/org/openremote/container/web/WebTargetBuilder.java
+++ b/container/src/main/java/org/openremote/container/web/WebTargetBuilder.java
@@ -174,17 +174,6 @@ public class WebTargetBuilder {
public static ResteasyClient createClient(ExecutorService executorService, int connectionPoolSize, long overrideSocketTimeout, UnaryOperator<ResteasyClientBuilderImpl> builderConfigurator) {
- //Create all of this config code in order to deal with expires cookies in responses
- RequestConfig requestConfig = RequestConfig.custom()
- .setCookieSpec(CookieSpecs.STANDARD)
- .setConnectionRequestTimeout(Long.valueOf(CONNECTION_CHECKOUT_TIMEOUT_MILLISECONDS).intValue())
- .setConnectTimeout(Long.valueOf(CONNECTION_CHECKOUT_TIMEOUT_MILLISECONDS).intValue())
- .setSocketTimeout(Long.valueOf(overrideSocketTimeout).intValue())
- .build();
- HttpClient apacheClient = HttpClientBuilder.create()
- .setDefaultRequestConfig(requestConfig)
- .build();
-
ResteasyClientBuilderImpl clientBuilder = new ResteasyClientBuilderImpl()
.connectionPoolSize(connectionPoolSize)
.connectionCheckoutTimeout(CONNECTION_CHECKOUT_TIMEOUT_MILLISECONDS, TimeUnit.MILLISECONDS)
diff --git a/container/src/main/java/org/openremote/container/web/file/AbstractFileServlet.java b/container/src/main/java/org/openremote/container/web/file/AbstractFileServlet.java
deleted file mode 100644
index 88bff7fe5..000000000
--- a/container/src/main/java/org/openremote/container/web/file/AbstractFileServlet.java
+++ /dev/null
@@ -1,587 +0,0 @@
-/*
- * Copyright 2017 OmniFaces
- *
- * 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.openremote.container.web.file;
-
-import static java.util.concurrent.TimeUnit.SECONDS;
-import static java.util.logging.Level.FINE;
-
-import java.io.*;
-import java.net.URL;
-import java.nio.ByteBuffer;
-import java.nio.channels.ByteChannel;
-import java.nio.channels.Channels;
-import java.nio.channels.FileChannel;
-import java.nio.channels.ReadableByteChannel;
-import java.nio.channels.WritableByteChannel;
-import java.nio.file.Files;
-import java.nio.file.StandardOpenOption;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.UUID;
-import java.util.concurrent.TimeUnit;
-import java.util.logging.Logger;
-import java.util.regex.Pattern;
-
-import jakarta.servlet.ServletContext;
-import jakarta.servlet.ServletException;
-import jakarta.servlet.ServletOutputStream;
-import jakarta.servlet.http.HttpServlet;
-import jakarta.servlet.http.HttpServletRequest;
-import jakarta.servlet.http.HttpServletResponse;
-
-/**
- * <p>
- * The well known "<a href="http://balusc.omnifaces.org/2009/02/fileservlet-supporting-resume-and.html">BalusC FileServlet</a>",
- * as an abstract template, slightly refactored, rewritten and modernized with a.o. fast NIO stuff instead of legacy
- * RandomAccessFile. GZIP support is stripped off as that can be done application wide via GzipResponseFilter.
- * <p>
- * This servlet properly deals with <code>ETag</code>, <code>If-None-Match</code> and <code>If-Modified-Since</code>
- * caching requests, hereby improving browser caching. This servlet also properly deals with <code>Range</code> and
- * <code>If-Range</code> ranging requests (<a href="https://tools.ietf.org/html/rfc7233">RFC7233</a>), which is required
- * by most media players for proper audio/video streaming, and by webbrowsers and for a proper resume of an paused
- * download, and by download accelerators to be able to request smaller parts simultaneously. This servlet is ideal when
- * you have large files like media files placed outside the web application and you can't use the default servlet.
- *
- * <h2>Usage</h2>
- * <p>
- * Just extend this class and override the {@link #getResource(HttpServletRequest)} method to return the desired file. If
- * you want to trigger a HTTP 400 "Bad Request" error, simply throw {@link IllegalArgumentException}. If you want to
- * trigger a HTTP 404 "Not Found" error, simply return <code>null</code>, or a non-existent file.
- * <p>
- * Here's a concrete example which serves it via an URL like <code>/media/foo.ext</code>:
- *
- * <pre>
- * &#64;WebServlet("/media/*")
- * public class MediaFileServlet extends FileServlet {
- *
- * private File folder;
- *
- * &#64;Override
- * public void init() throws ServletException {
- * folder = new File("/var/webapp/media");
- * }
- *
- * &#64;Override
- * protected File getFile(HttpServletRequest request) {
- * String pathInfo = request.getPathInfo();
- *
- * if (pathInfo == null || pathInfo.isEmpty() || "/".equals(pathInfo)) {
- * throw new IllegalArgumentException();
- * }
- *
- * return new File(folder, pathInfo);
- * }
- *
- * }
- * </pre>
- * <p>
- * You can embed it in e.g. HTML5 video tag as below:
- * <pre>
- * &lt;video src="#{request.contextPath}/media/video.mp4" controls="controls" /&gt;
- * </pre>
- *
- * <h3>Customizing <code>FileServlet</code></h3>
- * <p>
- * If more fine grained control is desired for handling "file not found" error, determining the cache expire time, the
- * content type, whether the file should be supplied as an attachment and the attachment's file name, then the developer
- * can opt to override one or more of the following protected methods:
- * <ul>
- * <li>{@link #handleFileNotFound(HttpServletRequest, HttpServletResponse)}
- * <li>{@link #getExpireTime(HttpServletRequest, String)}
- * <li>{@link #getContentType(HttpServletRequest, String)}
- * </ul>
- *
- * <p><strong>See also</strong>:
- * <ul>
- * <li><a href="http://stackoverflow.com/q/13588149/157882">How to stream audio/video files such as MP3, MP4, AVI, etc using a Servlet</a>
- * <li><a href="http://stackoverflow.com/a/29991447/157882">Abstract template for a static resource servlet</a>
- * </ul>
- *
- * @author Bauke Scholtz
- * @since 2.2
- */
-// TODO: Replace this with a standard file servlet
-public abstract class AbstractFileServlet extends HttpServlet {
-
- // Constants ------------------------------------------------------------------------------------------------------
-
- private static final long serialVersionUID = 1L;
- private static final Logger logger = Logger.getLogger(AbstractFileServlet.class.getName());
-
- private static final Long DEFAULT_EXPIRE_TIME_IN_SECONDS = TimeUnit.DAYS.toSeconds(30);
- private static final long ONE_SECOND_IN_MILLIS = SECONDS.toMillis(1);
- private static final Pattern RANGE_PATTERN = Pattern.compile("^bytes=[0-9]*-[0-9]*(,[0-9]*-[0-9]*)*$");
- private static final String MULTIPART_BOUNDARY = UUID.randomUUID().toString();
-
- // Actions --------------------------------------------------------------------------------------------------------
-
- @Override
- protected void doHead(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- doRequest(request, response, true);
- }
-
- @Override
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- doRequest(request, response, false);
- }
-
- private void doRequest(HttpServletRequest request, HttpServletResponse response, boolean head) throws IOException {
- Resource resource;
-
- try {
- resource = getResource(request);
-
- } catch (RedirectException ex) {
- logger.log(FINE, "Redirecting client to: " + ex.location);
- response.setHeader("Location", ex.location);
- response.sendError(HttpServletResponse.SC_FOUND);
- return;
- }
- catch (IllegalArgumentException e) {
- logger.log(FINE, "Got an IllegalArgumentException from user code; interpreting it as 400 Bad Request.", e);
- response.sendError(HttpServletResponse.SC_BAD_REQUEST);
- return;
- }
-
- if (resource.getURL() == null) {
- handleFileNotFound(request, response);
- return;
- }
-
- if (preconditionFailed(request, resource)) {
- response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
- return;
- }
-
- setCacheHeaders(response, resource, getExpireTime(request, resource.getURL().getFile()));
-
- if (notModified(request, resource)) {
- response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
- return;
- }
-
- List<Range> ranges = getRanges(request, resource);
-
- if (ranges == null) {
- response.setHeader("Content-Range", "bytes */" + resource.getLength());
- response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
- return;
- }
-
- if (!ranges.isEmpty()) {
- response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
- }
- else {
- ranges.add(new Range(0, resource.getLength() - 1)); // Full content.
- }
-
- String contentType = setContentHeaders(request, response, resource, ranges);
-
- if (head) {
- return;
- }
-
- writeContent(response, resource, ranges, contentType);
- }
-
- /**
- * Returns the file associated with the given HTTP servlet request.
- * If this method throws {@link IllegalArgumentException}, then the servlet will return a HTTP 400 error.
- * If this method returns <code>null</code>, or if {@link File#isFile()} returns <code>false</code>, then the
- * servlet will invoke {@link #handleFileNotFound(HttpServletRequest, HttpServletResponse)}.
- * @param request The involved HTTP servlet request.
- * @return The Resource associated with the given HTTP servlet request.
- * @throws IllegalArgumentException When the request is mangled in such way that it's not recognizable as a valid
- * file request. The servlet will then return a HTTP 400 error.
- */
- protected abstract Resource getResource(HttpServletRequest request) throws IllegalArgumentException, RedirectException;
-
- /**
- * Handles the case when the file is not found.
- * <p>
- * The default implementation sends a HTTP 404 error.
- * @param request The involved HTTP servlet request.
- * @param response The involved HTTP servlet response.
- * @throws IOException When something fails at I/O level.
- * @since 2.3
- */
- protected void handleFileNotFound(HttpServletRequest request, HttpServletResponse response) throws IOException {
- response.sendError(HttpServletResponse.SC_NOT_FOUND);
- }
-
- /**
- * Returns how long the resource may be cached by the client before it expires, in seconds.
- * <p>
- * The default implementation returns 30 days in seconds.
- * @param request The involved HTTP servlet request.
- * @param fileName The involved file name.
- * @return The client cache expire time in seconds (not milliseconds!).
- */
- protected long getExpireTime(HttpServletRequest request, String fileName) {
- return DEFAULT_EXPIRE_TIME_IN_SECONDS;
- }
-
- /**
- * Returns the content type associated with the given HTTP servlet request and file.
- * <p>
- * The default implementation delegates {@link File#getName()} to {@link ServletContext#getMimeType(String)} with a
- * fallback default value of <code>application/octet-stream</code>.
- * @param request The involved HTTP servlet request.
- * @param fileName The involved file name.
- * @return The content type associated with the given HTTP servlet request and file.
- */
- protected String getContentType(HttpServletRequest request, String fileName) {
- return coalesce(request.getServletContext().getMimeType(fileName), "application/octet-stream");
- }
-
- // Sub-actions ----------------------------------------------------------------------------------------------------
-
- /**
- * Returns true if it's a conditional request which must return 412.
- */
- private boolean preconditionFailed(HttpServletRequest request, Resource resource) {
- String match = request.getHeader("If-Match");
- long unmodified = request.getDateHeader("If-Unmodified-Since");
- return (match != null) ? !matches(match, resource.getETag()) : (unmodified != -1 && modified(unmodified, resource.getLastModified()));
- }
-
- /**
- * Set cache headers.
- */
- private void setCacheHeaders(HttpServletResponse response, Resource resource, long expires) {
- setCacheHeaders(response, expires);
- response.setHeader("ETag", resource.getETag());
- response.setDateHeader("Last-Modified", resource.getLastModified());
- }
-
- /**
- * Returns true if it's a conditional request which must return 304.
- */
- private boolean notModified(HttpServletRequest request, Resource resource) {
- String noMatch = request.getHeader("If-None-Match");
- long modified = request.getDateHeader("If-Modified-Since");
- return (noMatch != null) ? matches(noMatch, resource.getETag()) : (modified != -1 && !modified(modified, resource.getLastModified()));
- }
-
- /**
- * Get requested ranges. If this is null, then we must return 416. If this is empty, then we must return full file.
- */
- private List<Range> getRanges(HttpServletRequest request, Resource resource) {
- List<Range> ranges = new ArrayList<>(1);
- String rangeHeader = request.getHeader("Range");
-
- if (rangeHeader == null) {
- return ranges;
- }
- else if (!RANGE_PATTERN.matcher(rangeHeader).matches()) {
- return null; // Syntax error.
- }
-
- String ifRange = request.getHeader("If-Range");
-
- if (ifRange != null && !ifRange.equals(resource.getETag())) {
- try {
- long ifRangeTime = request.getDateHeader("If-Range");
-
- if (ifRangeTime != -1 && modified(ifRangeTime, resource.getLastModified())) {
- return ranges;
- }
- }
- catch (IllegalArgumentException ifRangeHeaderIsInvalid) {
- logger.log(FINE, "If-Range header is invalid. Let's just return full file then.", ifRangeHeaderIsInvalid);
- return ranges;
- }
- }
-
- for (String rangeHeaderPart : rangeHeader.split("=")[1].split(",")) {
- Range range = parseRange(rangeHeaderPart, resource.getLength());
-
- if (range == null) {
- return null; // Logic error.
- }
-
- ranges.add(range);
- }
-
- return ranges;
- }
-
- /**
- * Parse range header part. Returns null if there's a logic error (i.e. start after end).
- */
- private Range parseRange(String range, long length) {
- long start = sublong(range, 0, range.indexOf('-'));
- long end = sublong(range, range.indexOf('-') + 1, range.length());
-
- if (start == -1) {
- start = length - end;
- end = length - 1;
- }
- else if (end == -1 || end > length - 1) {
- end = length - 1;
- }
-
- if (start > end) {
- return null; // Logic error.
- }
-
- return new Range(start, end);
- }
-
- /**
- * Set content headers.
- */
- protected String setContentHeaders(HttpServletRequest request, HttpServletResponse response, Resource resource, List<Range> ranges) {
- String contentType = getContentType(request, resource.getURL().getFile());
- response.setHeader("Accept-Ranges", "bytes");
-
- if (ranges.size() == 1) {
- Range range = ranges.getFirst();
- response.setContentType(contentType);
- response.setHeader("Content-Length", String.valueOf(range.length));
-
- if (response.getStatus() == HttpServletResponse.SC_PARTIAL_CONTENT) {
- response.setHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + resource.getLength());
- }
- }
- else {
- response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY);
- }
-
- return contentType;
- }
-
- /**
- * Write given file to response with given content type and ranges.
- */
- private void writeContent(HttpServletResponse response, Resource resource, List<Range> ranges, String contentType) throws IOException {
- ServletOutputStream output = response.getOutputStream();
-
- if (ranges.size() == 1) {
- Range range = ranges.getFirst();
- stream(resource, output, range.start, range.length);
- }
- else {
- for (Range range : ranges) {
- output.println();
- output.println("--" + MULTIPART_BOUNDARY);
- output.println("Content-Type: " + contentType);
- output.println("Content-Range: bytes " + range.start + "-" + range.end + "/" + resource.getLength());
- stream(resource, output, range.start, range.length);
- }
-
- output.println();
- output.println("--" + MULTIPART_BOUNDARY + "--");
- }
- }
-
- // Helpers --------------------------------------------------------------------------------------------------------
-
- /**
- * Returns true if the given match header matches the given ETag value.
- */
- private static boolean matches(String matchHeader, String eTag) {
- String[] matchValues = matchHeader.split("\\s*,\\s*");
- Arrays.sort(matchValues);
- return Arrays.binarySearch(matchValues, eTag) > -1
- || Arrays.binarySearch(matchValues, "*") > -1;
- }
-
- /**
- * Returns true if the given modified header is older than the given last modified value.
- */
- private static boolean modified(long modifiedHeader, long lastModified) {
- return (modifiedHeader + ONE_SECOND_IN_MILLIS <= lastModified); // That second is because the header is in seconds, not millis.
- }
-
- /**
- * Returns a substring of the given string value from the given begin index to the given end index as a long.
- * If the substring is empty, then -1 will be returned.
- */
- private static long sublong(String value, int beginIndex, int endIndex) {
- String substring = value.substring(beginIndex, endIndex);
- return substring.isEmpty() ? -1 : Long.parseLong(substring);
- }
-
- /**
- * Returns true if the given accept header accepts the given value.
- */
- private static boolean accepts(String acceptHeader, String toAccept) {
- String[] acceptValues = acceptHeader.split("\\s*(,|;)\\s*");
- Arrays.sort(acceptValues);
- return Arrays.binarySearch(acceptValues, toAccept) > -1
- || Arrays.binarySearch(acceptValues, toAccept.replaceAll("/.*$", "/*")) > -1
- || Arrays.binarySearch(acceptValues, "*/*") > -1;
- }
-
- // Nested classes -------------------------------------------------------------------------------------------------
-
- /**
- * Convenience class for a byte range.
- */
- public static class Range {
- private final long start;
- private final long end;
- private final long length;
-
- public Range(long start, long end) {
- this.start = start;
- this.end = end;
- length = end - start + 1;
- }
-
- }
-
- protected class RedirectException extends Exception {
- public final String location;
-
- public RedirectException(String location) {
- this.location = location;
- }
- }
-
- /* ############################################################################ */
-
- /**
- * Returns the first non-<code>null</code> object of the argument list, or <code>null</code> if there is no such
- * element.
- * @param <T> The generic object type.
- * @param objects The argument list of objects to be tested for non-<code>null</code>.
- * @return The first non-<code>null</code> object of the argument list, or <code>null</code> if there is no such
- * element.
- */
- @SafeVarargs
- public static <T> T coalesce(T... objects) {
- for (T object : objects) {
- if (object != null) {
- return object;
- }
- }
-
- return null;
- }
-
- private static final int DEFAULT_STREAM_BUFFER_SIZE = 10240;
-
- /**
- * Stream the given input to the given output via NIO {@link Channels} and a directly allocated NIO
- * {@link ByteBuffer}. Both the input and output streams will implicitly be closed after streaming,
- * regardless of whether an exception is been thrown or not.
- * @param input The input stream.
- * @param output The output stream.
- * @return The length of the written bytes.
- * @throws IOException When an I/O error occurs.
- */
- public static long stream(InputStream input, OutputStream output) throws IOException {
- try (ReadableByteChannel inputChannel = Channels.newChannel(input);
- WritableByteChannel outputChannel = Channels.newChannel(output))
- {
- ByteBuffer buffer = ByteBuffer.allocateDirect(DEFAULT_STREAM_BUFFER_SIZE);
- long size = 0;
-
- while (inputChannel.read(buffer) != -1) {
- buffer.flip();
- size += outputChannel.write(buffer);
- buffer.clear();
- }
-
- return size;
- }
- }
-
- /**
- * Stream a specified range of the given file to the given output via NIO {@link Channels} and a directly allocated
- * NIO {@link ByteBuffer}. The output stream will only implicitly be closed after streaming when the specified range
- * represents the whole file, regardless of whether an exception is been thrown or not.
- * @param resource The resource.
- * @param output The output stream.
- * @param start The start position (offset).
- * @param length The (intented) length of written bytes.
- * @return The (actual) length of the written bytes. This may be smaller when the given length is too large.
- * @throws IOException When an I/O error occurs.
- * @since 2.2
- */
- public static long stream(Resource resource, OutputStream output, long start, long length) throws IOException {
- if (start == 0 && length >= resource.getLength()) {
- return stream(resource.getURL().openStream(), output);
- }
-
- try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(resource.getFile().toPath(), StandardOpenOption.READ)) {
- WritableByteChannel outputChannel = Channels.newChannel(output);
- ByteBuffer buffer = ByteBuffer.allocateDirect(DEFAULT_STREAM_BUFFER_SIZE);
- long size = 0;
-
- while (fileChannel.read(buffer, start + size) != -1) {
- buffer.flip();
-
- if (size + buffer.limit() > length) {
- buffer.limit((int) (length - size));
- }
-
- size += outputChannel.write(buffer);
-
- if (size >= length) {
- break;
- }
-
- buffer.clear();
- }
-
- return size;
- }
- }
-
- /**
- * <p>Set the cache headers. If the <code>expires</code> argument is larger than 0 seconds, then the following headers
- * will be set:
- * <ul>
- * <li><code>Cache-Control: public,max-age=[expiration time in seconds],must-revalidate</code></li>
- * <li><code>Expires: [expiration date of now plus expiration time in seconds]</code></li>
- * </ul>
- * <p>Else the method will delegate to {@link #setNoCacheHeaders(HttpServletResponse)}.
- * @param response The HTTP servlet response to set the headers on.
- * @param expires The expire time in seconds (not milliseconds!).
- * @since 2.2
- */
- public static void setCacheHeaders(HttpServletResponse response, long expires) {
- if (expires > 0) {
- response.setHeader("Cache-Control", "public,max-age=" + expires + ",must-revalidate");
- long current = System.currentTimeMillis();
- long expiresMillis = SECONDS.toMillis(expires);
- long expiresValue = current + expiresMillis;
- response.setDateHeader("Expires", expiresValue);
- response.setHeader("Pragma", ""); // Explicitly set pragma to prevent container from overriding it.
- }
- else {
- setNoCacheHeaders(response);
- }
- }
-
- /**
- * <p>Set the no-cache headers. The following headers will be set:
- * <ul>
- * <li><code>Cache-Control: no-cache,no-store,must-revalidate</code></li>
- * <li><code>Expires: [expiration date of 0]</code></li>
- * <li><code>Pragma: no-cache</code></li>
- * </ul>
- * Set the no-cache headers.
- * @param response The HTTP servlet response to set the headers on.
- * @since 2.2
- */
- public static void setNoCacheHeaders(HttpServletResponse response) {
- response.setHeader("Cache-Control", "no-cache,no-store,must-revalidate");
- response.setDateHeader("Expires", 0);
- response.setHeader("Pragma", "no-cache"); // Backwards compatibility for HTTP 1.0.
- }
-}
diff --git a/container/src/main/java/org/openremote/container/web/file/DefaultServletOutputStream.java b/container/src/main/java/org/openremote/container/web/file/DefaultServletOutputStream.java
deleted file mode 100644
index 8fe34a5dc..000000000
--- a/container/src/main/java/org/openremote/container/web/file/DefaultServletOutputStream.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright 2017 OmniFaces
- *
- * 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.openremote.container.web.file;
-
-import java.io.IOException;
-import java.io.OutputStream;
-
-import jakarta.servlet.ServletOutputStream;
-import jakarta.servlet.WriteListener;
-
-/**
- * <p>
- * A default implementation of abstract servlet output stream.
- *
- * @author Bauke Scholtz
- * @since 2.6
- */
-public class DefaultServletOutputStream extends ServletOutputStream {
-
- private OutputStream output;
-
- /**
- * Constructs a default servlet output stream which delegates to given output stream.
- * @param output The output stream to let this servlet output stream delegate to.
- */
- public DefaultServletOutputStream(OutputStream output) {
- this.output = output;
- }
-
- @Override
- public void write(int b) throws IOException {
- output.write(b);
- }
-
- @Override
- public void write(byte[] bytes) throws IOException {
- output.write(bytes);
- }
-
- @Override
- public void write(byte[] bytes, int offset, int length) throws IOException {
- output.write(bytes, offset, length);
- }
-
- @Override
- public void flush() throws IOException {
- output.flush();
- }
-
- @Override
- public void close() throws IOException {
- output.close();
- }
-
- @Override
- public boolean isReady() {
- return true;
- }
-
- @Override
- public void setWriteListener(WriteListener writeListener) {
- throw new UnsupportedOperationException("Not supported");
- }
-}
diff --git a/container/src/main/java/org/openremote/container/web/file/FileServlet.java b/container/src/main/java/org/openremote/container/web/file/FileServlet.java
deleted file mode 100644
index d3b4bb20b..000000000
--- a/container/src/main/java/org/openremote/container/web/file/FileServlet.java
+++ /dev/null
@@ -1,184 +0,0 @@
-/*
- * Copyright 2017, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.container.web.file;
-
-import jakarta.servlet.ServletException;
-import jakarta.servlet.http.HttpServletRequest;
-import jakarta.servlet.http.HttpServletResponse;
-import io.undertow.server.handlers.resource.ResourceManager;
-import java.io.File;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import static org.openremote.model.Constants.REALM_PARAM_NAME;
-
-public class FileServlet extends AbstractFileServlet {
-
- private static final Logger LOG = Logger.getLogger(FileServlet.class.getName());
-
- public static final long DEFAULT_EXPIRE_SECONDS = 600; // 10 minutes
- public static final long EXPIRES_SECONDS_CACHE_JS = 60 * 60 * 24 * 14; // 14 days
-
- final protected boolean devMode;
- final protected ResourceManager resourceManager;
- final protected String[] requiredRoles;
- final protected Map<String, String> mimeTypes;
- final protected Map<String, Integer> mimeTypesExpireSeconds;
- final protected String[] alreadyZippedExtensions;
-
- public FileServlet(boolean devMode, ResourceManager resourceManager, String[] requiredRoles, Map<String, String> mimeTypes, Map<String, Integer> mimeTypesExpireSeconds, String[] alreadyZippedExtensions) {
- this.devMode = devMode;
- this.resourceManager = resourceManager;
- this.requiredRoles = requiredRoles;
- this.mimeTypes = mimeTypes;
- this.mimeTypesExpireSeconds = mimeTypesExpireSeconds;
- this.alreadyZippedExtensions = alreadyZippedExtensions;
- }
-
- public boolean isSecured() {
- return requiredRoles != null && requiredRoles.length > 0;
- }
-
- @Override
- protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- if (isSecured()) {
- if (request.authenticate(response)) {
- boolean userHasAllRoles = true;
- for (String requiredRole : requiredRoles) {
- if (!request.isUserInRole(requiredRole))
- userHasAllRoles = false;
- }
- if (userHasAllRoles) {
- LOG.fine("User has all roles to access: " + request.getPathInfo());
- super.service(request, response);
- } else {
- LOG.fine("User doesn't have the required roles '" + Arrays.toString(requiredRoles) + "' to access: " + request.getPathInfo());
- response.sendError(HttpServletResponse.SC_FORBIDDEN);
- }
- } else {
- response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
- }
- } else {
- super.service(request, response);
- }
- }
-
- @Override
- protected Resource getResource(HttpServletRequest request) throws RedirectException {
- String relativePath = request.getPathInfo();
- if (relativePath == null || relativePath.isEmpty()) {
- relativePath = "";
- }
- while (relativePath.startsWith("/"))
- relativePath = relativePath.substring(1);
-
- String actualBase = "";
-
- // If secured, serve files from a sub-directory that represents the authenticated realm
- if (isSecured()) {
-
- String realm = request.getHeader(REALM_PARAM_NAME);
-
- // If we are missing the auth realm header, ignore...
- if (realm == null || realm.isEmpty()) {
- LOG.fine("Ignoring request, secured service needs request header: " + REALM_PARAM_NAME);
- return null;
- }
-
- actualBase = realm;
-
- Resource resource = getResource(actualBase);
- if (resource.getURL() == null) {
- LOG.fine("Ignoring request, missing realm content directory: " + actualBase);
- return null;
- }
- }
-
- Resource resource = getResource(actualBase, relativePath);
-
- // Handle index.html and redirect /directory to /directory/
- if (resource.getURL() == null) {
- if (request.getPathInfo() == null || !request.getPathInfo().endsWith("/")) {
- throw new RedirectException(request.getRequestURI() + "/");
- }
-
- resource = getResource(actualBase, relativePath + "index.html");
- }
-
- LOG.fine(resource.getURL() == null ? "Not serving file" : "Serving: " + resource.getURL());
- return resource;
- }
-
- private Resource getResource(String... path) {
- String resourcePath = String.join("/", path);
- io.undertow.server.handlers.resource.Resource resource = null;
- try {
- resource = resourceManager.getResource(resourcePath);
- } catch (IOException e) {
- LOG.log(Level.FINEST, "Failed to get resource: " + resourcePath, e);
- }
- return new ResourceImpl(resource);
- }
-
- @Override
- protected long getExpireTime(HttpServletRequest request, String fileName) {
- long expireTime = DEFAULT_EXPIRE_SECONDS;
-
- String contentType = getContentType(request, fileName);
- if (mimeTypesExpireSeconds.containsKey(contentType))
- expireTime = mimeTypesExpireSeconds.get(contentType);
-
- // Don't cache at all in dev mode
- expireTime = devMode ? 0 : expireTime;
-
- return expireTime;
- }
-
- @Override
- protected String getContentType(HttpServletRequest request, String fileName) {
- return coalesce(coalesce(request.getServletContext().getMimeType(fileName),
- mimeTypes.get(getExtension(fileName))), "application/octet-stream");
- }
-
- @Override
- protected String setContentHeaders(HttpServletRequest request, HttpServletResponse response, Resource resource, List<Range> ranges) {
- String result = super.setContentHeaders(request, response, resource, ranges);
-
- // If a file is already zipped, we need to set the header (yes, it's stupid, but
- // that's what happens when font experts mangle HTTP for their PBF format...)
- for (String alreadyZippedExtension : alreadyZippedExtensions) {
- if (request.getPathInfo().endsWith(alreadyZippedExtension)) {
- response.addHeader("Content-Encoding", "gzip");
- break;
- }
- }
- return result;
- }
-
- protected String getExtension(String fileName) {
- int i = fileName.lastIndexOf('.');
- return i > 0 ? fileName.substring(i + 1) : "";
- }
-
-}
diff --git a/container/src/main/java/org/openremote/container/web/file/GzipHttpServletResponse.java b/container/src/main/java/org/openremote/container/web/file/GzipHttpServletResponse.java
deleted file mode 100644
index b4f1beb39..000000000
--- a/container/src/main/java/org/openremote/container/web/file/GzipHttpServletResponse.java
+++ /dev/null
@@ -1,233 +0,0 @@
-/*
- * Copyright 2017 OmniFaces
- *
- * 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.openremote.container.web.file;
-
-
-import java.io.IOException;
-import java.io.OutputStream;
-import java.util.Objects;
-import java.util.Set;
-import java.util.regex.Pattern;
-import java.util.zip.GZIPOutputStream;
-
-import jakarta.servlet.http.HttpServletResponse;
-
-/**
- * This HTTP servlet response wrapper will GZIP the response when the given threshold has exceeded and the response
- * content type matches one of the given mimetypes.
- *
- * @author Bauke Scholtz
- * @since 1.1
- */
-public class GzipHttpServletResponse extends HttpServletResponseOutputWrapper {
-
- // Constants ------------------------------------------------------------------------------------------------------
-
- private static final Pattern NO_TRANSFORM =
- Pattern.compile("((.*)[\\s,])?no-transform([\\s,](.*))?", Pattern.CASE_INSENSITIVE);
-
- // Properties -----------------------------------------------------------------------------------------------------
-
- private final int threshold;
- private final Set<String> mimetypes;
- private long contentLength;
- private String vary;
- private boolean noGzip;
- private boolean closing;
- private GzipThresholdOutputStream output;
-
- // Constructors ---------------------------------------------------------------------------------------------------
-
- /**
- * Construct a new GZIP HTTP servlet response based on the given wrapped response, threshold and mimetypes.
- * @param wrapped The wrapped response.
- * @param threshold The GZIP buffer threshold.
- * @param mimetypes The mimetypes which needs to be compressed with GZIP.
- */
- public GzipHttpServletResponse(HttpServletResponse wrapped,
- int threshold,
- Set<String> mimetypes) {
- super(wrapped);
- this.threshold = threshold;
- this.mimetypes = mimetypes;
- }
-
- // Actions --------------------------------------------------------------------------------------------------------
-
- @Override
- public void setContentLength(int contentLength) {
- // Get hold of content length locally to avoid it from being set on responses which will actually be gzipped.
- this.contentLength = contentLength;
- }
-
- // @Override Servlet 3.1.
- public void setContentLengthLong(long contentLength) {
- // Get hold of content length locally to avoid it from being set on responses which will actually be gzipped.
- this.contentLength = contentLength;
- }
-
- @Override
- public void setHeader(String name, String value) {
- super.setHeader(name, value);
-
- if (name != null) {
- String lowerCasedName = name.toLowerCase();
-
- if ("vary".equals(lowerCasedName)) {
- vary = value;
- }
- else if ("content-range".equals(lowerCasedName)) {
- noGzip = (value != null);
- }
- else if ("cache-control".equals(lowerCasedName)) {
- noGzip = (value != null && NO_TRANSFORM.matcher(value).matches());
- }
- }
- }
-
- @Override
- public void addHeader(String name, String value) {
- super.addHeader(name, value);
-
- if (name != null && value != null) {
- String lowerCasedName = name.toLowerCase();
-
- if ("vary".equals(lowerCasedName)) {
- vary = ((vary != null) ? (vary + ",") : "") + value;
- }
- else if ("content-range".equals(lowerCasedName)) {
- noGzip = true;
- }
- else if ("cache-control".equals(lowerCasedName)) {
- noGzip = (noGzip || NO_TRANSFORM.matcher(value).matches());
- }
- }
- }
-
- @Override
- public void flushBuffer() throws IOException {
- if (isCommitted()) {
- super.flushBuffer();
- }
- }
-
- @Override
- public void reset() {
- super.reset();
-
- if (!isCommitted()) {
- contentLength = 0;
- vary = null;
- noGzip = false;
-
- if (output != null) {
- output.reset();
- }
- }
- }
-
- @Override
- public void close() throws IOException {
- closing = true;
- super.close();
- closing = false;
- }
-
- @Override
- protected OutputStream createOutputStream() {
- output = new GzipThresholdOutputStream(threshold);
- return output;
- }
-
- // Inner classes --------------------------------------------------------------------------------------------------
-
- /**
- * This output stream will switch to GZIP compression when the given threshold is exceeded.
- * <p>
- * This is an inner class because it needs to be able to manipulate the response headers once the decision whether
- * to GZIP or not has been made.
- *
- * @author Bauke Scholtz
- */
- private class GzipThresholdOutputStream extends ResettableBufferedOutputStream {
-
- // Constructors -----------------------------------------------------------------------------------------------
-
- public GzipThresholdOutputStream(int threshold) {
- super(threshold);
- }
-
- // Actions ----------------------------------------------------------------------------------------------------
-
- /**
- * Create GZIP output stream if necessary. That is, when the given <code>doGzip</code> argument is
- * <code>true</code>, the current response does not have the <code>Cache-Control: no-transform</code> or
- * <code>Content-Range</code> headers, the current response is not committed, the content type is not
- * <code>null</code> and the content type matches one of the mimetypes.
- */
- @Override
- public OutputStream createOutputStream(boolean doGzip) throws IOException {
- HttpServletResponse originalResponse = (HttpServletResponse) getResponse();
-
- if (doGzip && !noGzip && (closing || !isCommitted())) {
- String contentType = getContentType();
-
- if (contentType != null && mimetypes.contains(contentType.split(";", 2)[0])) {
- addHeader("Content-Encoding", "gzip");
- setHeader("Vary", (!isOneOf(vary, null, "*") ? (vary + ",") : "") + "Accept-Encoding");
-
- // Remove Content-Length header that was set before we knew about whether to zip the response or not.
- // The servlet container will now set the header (at least Undertow does) based on its internal
- // write buffer position to the actual number of written bytes. This fixes a bug in the
- // "BalusC" file servlet code, because they assume the Content-Length is the original size of the
- // resource. This is not the case, RFC 2616 says its the transfer-length of the message body,
- // thus it must the size of the gzipped data, not the original size.
- setHeader("Content-Length", null);
-
- return new GZIPOutputStream(originalResponse.getOutputStream());
- }
- }
-
- if (!doGzip) {
- setContentLength(getWrittenBytes());
- }
-
- if (contentLength > 0) {
- originalResponse.setHeader("Content-Length", String.valueOf(contentLength));
- }
-
- return originalResponse.getOutputStream();
- }
-
- }
-
- /* ############################################################################ */
-
- /**
- * Returns <code>true</code> if the given object equals one of the given objects.
- * @param <T> The generic object type.
- * @param object The object to be checked if it equals one of the given objects.
- * @param objects The argument list of objects to be tested for equality.
- * @return <code>true</code> if the given object equals one of the given objects.
- */
- @SafeVarargs
- public static <T> boolean isOneOf(T object, T... objects) {
- for (Object other : objects) {
- if (Objects.equals(object, other)) {
- return true;
- }
- }
-
- return false;
- }
-}
diff --git a/container/src/main/java/org/openremote/container/web/file/GzipResponseFilter.java b/container/src/main/java/org/openremote/container/web/file/GzipResponseFilter.java
deleted file mode 100644
index 7c028fde3..000000000
--- a/container/src/main/java/org/openremote/container/web/file/GzipResponseFilter.java
+++ /dev/null
@@ -1,208 +0,0 @@
-/*
- * Copyright 2017 OmniFaces
- *
- * 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.openremote.container.web.file;
-
-import jakarta.servlet.FilterChain;
-import jakarta.servlet.ServletException;
-import jakarta.servlet.http.HttpServletRequest;
-import jakarta.servlet.http.HttpServletResponse;
-import jakarta.servlet.http.HttpSession;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.Enumeration;
-import java.util.HashSet;
-import java.util.Set;
-
-import static java.lang.String.format;
-import static java.util.Collections.unmodifiableSet;
-
-/**
- * <p>
- * The {@link GzipResponseFilter} will apply GZIP compression on responses whenever applicable. GZIP will greatly reduce
- * the response size when applied on character based responses like HTML, CSS and JS, on average it can save up to ~70%
- * of bandwidth.
- * <p>
- * While GZIP is normally to be configured in the servlet container (e.g. <code>&lt;Context compression="on"&gt;</code>
- * in Tomcat, or <code>&lt;property name="compression" value="on"&gt;</code> in Glassfish), this filter allows a
- * servlet container independent way of configuring GZIP compression and also allows enabling GZIP compression anyway
- * on 3rd party hosts where you have no control over servlet container configuration.
- *
- * <h2>Installation</h2>
- * <p>
- * To get it to run, map this filter on the desired <code>&lt;url-pattern&gt;</code> or maybe even on the
- * <code>&lt;servlet-name&gt;</code> of the <code>FacesServlet</code>. A <code>Filter</code> is by default dispatched
- * on <code>REQUEST</code> only, you might want to explicitly add the <code>ERROR</code> dispatcher to get it to run
- * on error pages as well.
- * <pre>
- * &lt;filter&gt;
- * &lt;filter-name&gt;gzipResponseFilter&lt;/filter-name&gt;
- * &lt;filter-class&gt;org.omnifaces.filter.GzipResponseFilter&lt;/filter-class&gt;
- * &lt;/filter&gt;
- * &lt;filter-mapping&gt;
- * &lt;filter-name&gt;gzipResponseFilter&lt;/filter-name&gt;
- * &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
- * &lt;dispatcher&gt;REQUEST&lt;/dispatcher&gt;
- * &lt;dispatcher&gt;ERROR&lt;/dispatcher&gt;
- * &lt;/filter-mapping&gt;
- * </pre>
- * <p>
- * Mapping on <code>/*</code> may be too global as some types of requests (comet, long polling, etc) cannot be gzipped.
- * In that case, consider mapping it to the exact <code>&lt;servlet-name&gt;</code> of the FacesServlet in the
- * same <code>web.xml</code>.
- * <pre>
- * &lt;filter&gt;
- * &lt;filter-name&gt;gzipResponseFilter&lt;/filter-name&gt;
- * &lt;filter-class&gt;org.omnifaces.filter.GzipResponseFilter&lt;/filter-class&gt;
- * &lt;/filter&gt;
- * &lt;filter-mapping&gt;
- * &lt;filter-name&gt;gzipResponseFilter&lt;/filter-name&gt;
- * &lt;servlet-name&gt;facesServlet&lt;/servlet-name&gt;
- * &lt;dispatcher&gt;REQUEST&lt;/dispatcher&gt;
- * &lt;dispatcher&gt;ERROR&lt;/dispatcher&gt;
- * &lt;/filter-mapping&gt;
- * </pre>
- *
- * <h3>Configuration (optional)</h3>
- * <p>
- * This filter supports two initialization parameters which needs to be placed in <code>&lt;filter&gt;</code> element
- * as follows:
- * <pre>
- * &lt;init-param&gt;
- * &lt;description&gt;The threshold size in bytes. Must be a number between 0 and 9999. Defaults to 150.&lt;/description&gt;
- * &lt;param-name&gt;threshold&lt;/param-name&gt;
- * &lt;param-value&gt;150&lt;/param-value&gt;
- * &lt;/init-param&gt;
- * &lt;init-param&gt;
- * &lt;description&gt;The mimetypes which needs to be compressed. Must be a comma separated string. Defaults to the below values.&lt;/description&gt;
- * &lt;param-name&gt;mimetypes&lt;/param-name&gt;
- * &lt;param-value&gt;
- * text/plain, text/html, text/xml, text/css, text/javascript, text/csv, text/rtf,
- * application/xml, application/xhtml+xml, application/javascript, application/json,
- * image/svg+xml
- * &lt;/param-value&gt;
- * &lt;/init-param&gt;
- * </pre>
- * <p>
- * The default <code>threshold</code> is thus 150 bytes. This means that when the response is not larger than 150 bytes,
- * then it will not be compressed with GZIP. Only when it's larger than 150 bytes, then it will be compressed. A
- * threshold of between 150 and 1000 bytes is recommended due to overhead and latency of compression/decompression.
- * The value must be a number between 0 and 9999. A value larger than 2000 is not recommended.
- * <p>
- * The <code>mimetypes</code> represents a comma separated string of mime types which needs to be compressed. It's
- * exactly that value which appears in the <code>Content-Type</code> header of the response. The in the above example
- * mentioned mime types are already the default values. Note that GZIP does not have any benefit when applied on
- * binary mimetypes like images, office documents, PDF files, etcetera. So setting it for them is not recommended.
- * <p>
- * The <code>zipped</code> init parameter is a list of file name extensions which are considered already zipped, so only
- * a gzip header must be added to the response for such files.
- *
- * @author Bauke Scholtz
- * @since 1.1
- * @see GzipHttpServletResponse
- * @see HttpServletResponseOutputWrapper
- * @see ResettableBuffer
- * @see ResettableBufferedOutputStream
- * @see ResettableBufferedWriter
- * @see HttpFilter
- */
-public class GzipResponseFilter extends HttpFilter {
-
- // Constants ------------------------------------------------------------------------------------------------------
-
- private static final String INIT_PARAM_THRESHOLD = "threshold";
- private static final String INIT_PARAM_MIMETYPES = "mimetypes";
-
- private static final int DEFAULT_THRESHOLD = 150;
- private static final Set<String> DEFAULT_MIMETYPES = unmodifiableSet(new HashSet<>(Arrays.asList(
- "text/plain", "text/html", "text/xml", "text/css", "text/javascript", "text/csv", "text/rtf",
- "application/xml", "application/xhtml+xml", "application/javascript", "application/json",
- "image/svg+xml"
- )));
-
- private static final String ERROR_THRESHOLD = "The 'threshold' init param must be a number between 0 and 9999."
- + " Encountered an invalid value of '%s'.";
-
- // Vars -----------------------------------------------------------------------------------------------------------
-
- private Set<String> mimetypes = DEFAULT_MIMETYPES;
- private int threshold = DEFAULT_THRESHOLD;
-
- // Actions --------------------------------------------------------------------------------------------------------
-
-
- public GzipResponseFilter() {
- }
-
- public GzipResponseFilter(String[] mimetypes) {
- this.mimetypes = new HashSet<>(Arrays.asList(mimetypes));
- }
-
- /**
- * Initializes the filter parameters.
- */
- @Override
- public void init() throws ServletException {
- String thresholdParam = getInitParameter(INIT_PARAM_THRESHOLD);
-
- if (thresholdParam != null) {
- if (!thresholdParam.matches("[0-9]{1,4}")) {
- throw new ServletException(format(ERROR_THRESHOLD, thresholdParam));
- }
- else {
- threshold = Integer.valueOf(thresholdParam);
- }
- }
-
- String mimetypesParam = getInitParameter(INIT_PARAM_MIMETYPES);
- if (mimetypesParam != null) {
- mimetypes = new HashSet<>(Arrays.asList(mimetypesParam.split("\\s*,\\s*")));
- }
- }
-
- /**
- * Perform the filtering job. Only if the client accepts GZIP based on the request headers, then wrap the response
- * in a {@link GzipHttpServletResponse} and pass it through the filter chain.
- */
- @Override
- public void doFilter
- (HttpServletRequest request, HttpServletResponse response, HttpSession session, FilterChain chain)
- throws ServletException, IOException
- {
- if (acceptsGzip(request)) {
- GzipHttpServletResponse gzipResponse = new GzipHttpServletResponse(response, threshold, mimetypes);
- chain.doFilter(request, gzipResponse);
- gzipResponse.close(); // Mandatory for the case the threshold limit hasn't been reached.
- }
- else {
- chain.doFilter(request, response);
- }
- }
-
- // Helpers --------------------------------------------------------------------------------------------------------
-
- /**
- * Returns whether the given request indicates that the client accepts GZIP encoding.
- * @param request The request to be checked.
- * @return <code>true</code> if the client accepts GZIP encoding, otherwise <code>false</code>.
- */
- private static boolean acceptsGzip(HttpServletRequest request) {
- for (Enumeration<String> e = request.getHeaders("Accept-Encoding"); e.hasMoreElements();) {
- if (e.nextElement().contains("gzip")) {
- return true;
- }
- }
-
- return false;
- }
-
-}
diff --git a/container/src/main/java/org/openremote/container/web/file/HttpFilter.java b/container/src/main/java/org/openremote/container/web/file/HttpFilter.java
deleted file mode 100644
index 0c017a428..000000000
--- a/container/src/main/java/org/openremote/container/web/file/HttpFilter.java
+++ /dev/null
@@ -1,173 +0,0 @@
-/*
- * Copyright 2017 OmniFaces
- *
- * 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.openremote.container.web.file;
-
-import java.io.IOException;
-
-import jakarta.servlet.Filter;
-import jakarta.servlet.FilterChain;
-import jakarta.servlet.FilterConfig;
-import jakarta.servlet.Servlet;
-import jakarta.servlet.ServletContext;
-import jakarta.servlet.ServletException;
-import jakarta.servlet.ServletRequest;
-import jakarta.servlet.ServletResponse;
-import jakarta.servlet.http.HttpServlet;
-import jakarta.servlet.http.HttpServletRequest;
-import jakarta.servlet.http.HttpServletResponse;
-import jakarta.servlet.http.HttpSession;
-
-/**
- * <p>
- * The {@link HttpFilter} is abstract filter specifically for HTTP requests. It provides a convenient abstract
- * {@link #doFilter(HttpServletRequest, HttpServletResponse, HttpSession, FilterChain)} method directly providing the
- * HTTP servlet request, response and session, so that there's no need to cast them everytime in the
- * {@link #doFilter(ServletRequest, ServletResponse, FilterChain)} implementation. Also, default implementations of
- * {@link #init(FilterConfig)} and {@link #destroy()} are provided, so that there's no need to implement them every time
- * even when not really needed.
- * <p>
- * It's a bit the idea of using the convenient {@link HttpServlet} abstract servlet class instead of the barebones
- * {@link Servlet} interface.
- *
- * <h2>Usage</h2>
- * <p>
- * To use it, just let your custom filter extend from {@link HttpFilter} instead of implement {@link Filter}.
- * For example:
- * <pre>
- * &#64;WebFilter("/app/*")
- * public class LoginFilter extends HttpFilter {
- *
- * &#64;Override
- * public void doFilter(HttpServletRequest request, HttpServletResponse response, HttpSession session, FilterChain chain)
- * throws ServletException, IOException
- * {
- * if (session != null &amp;&amp; session.getAttribute("user") != null) {
- * chain.doFilter(request, response);
- * }
- * else {
- * Servlets.facesRedirect(request, response, "login.xhtml");
- * }
- * }
- * }
- * </pre>
- *
- * @author Arjan Tijms
- * @author Bauke Scholtz
- */
-public abstract class HttpFilter implements Filter {
-
- // Constants ------------------------------------------------------------------------------------------------------
-
- private static final String ERROR_NO_FILTERCONFIG = "FilterConfig is not available."
- + " It seems that you've overridden HttpFilter#init(FilterConfig)."
- + " You should be overriding HttpFilter#init() instead, otherwise you have to call super.init(config).";
-
- // Properties -----------------------------------------------------------------------------------------------------
-
- private FilterConfig filterConfig;
-
- // Actions --------------------------------------------------------------------------------------------------------
-
- /**
- * Called by the servlet container when the filter is about to be placed into service. This implementation stores
- * the {@link FilterConfig} object for later use by the getter methods. It's recommended to <strong>not</strong>
- * override this method. Instead, just use {@link #init()} method. When overriding this method anyway, don't forget
- * to call <code>super.init(config)</code>, otherwise the getter methods will throw an illegal state exception.
- */
- @Override
- public void init(FilterConfig filterConfig) throws ServletException {
- this.filterConfig = filterConfig;
- init();
- }
-
- /**
- * Convenience init() method without FilterConfig parameter which will be called by init(FilterConfig).
- * @throws ServletException When filter's initialization failed.
- */
- public void init() throws ServletException {
- //
- }
-
- @Override
- public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
- throws ServletException, IOException
- {
- HttpServletRequest httpRequest = (HttpServletRequest) request;
- HttpServletResponse httpResponse = (HttpServletResponse) response;
- HttpSession session = httpRequest.getSession(false);
- doFilter(httpRequest, httpResponse, session, chain);
- }
-
- /**
- * Filter the HTTP request. The session argument is <code>null</code> if there is no session.
- * @param request The HTTP request.
- * @param response The HTTP response.
- * @param session The HTTP session, if any, else <code>null</code>.
- * @param chain The filter chain to continue.
- * @throws ServletException As wrapper exception when something fails in the request processing.
- * @throws IOException Whenever something fails at I/O level.
- * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
- */
- public abstract void doFilter
- (HttpServletRequest request, HttpServletResponse response, HttpSession session, FilterChain chain)
- throws ServletException, IOException;
-
- @Override
- public void destroy() {
- filterConfig = null;
- }
-
- // Getters --------------------------------------------------------------------------------------------------------
-
- /**
- * Returns the filter config.
- * @return The filter config.
- */
- protected FilterConfig getFilterConfig() {
- checkFilterConfig();
- return filterConfig;
- }
-
- /**
- * Returns the value of the filter init parameter associated with the given name.
- * @param name The filter init parameter name to return the associated value for.
- * @return The value of the filter init parameter associated with the given name.
- */
- protected String getInitParameter(String name) {
- checkFilterConfig();
- return filterConfig.getInitParameter(name);
- }
-
- /**
- * Returns the servlet context.
- * @return The servlet context.
- */
- protected ServletContext getServletContext() {
- checkFilterConfig();
- return filterConfig.getServletContext();
- }
-
- // Helpers --------------------------------------------------------------------------------------------------------
-
- /**
- * Check if the filter config is been set and thus the enduser has properly called super.init(config) when
- * overriding the init(config).
- * @throws IllegalStateException When this is not the case.
- */
- private void checkFilterConfig() {
- if (filterConfig == null) {
- throw new IllegalStateException(ERROR_NO_FILTERCONFIG);
- }
- }
-
-}
diff --git a/container/src/main/java/org/openremote/container/web/file/HttpServletResponseOutputWrapper.java b/container/src/main/java/org/openremote/container/web/file/HttpServletResponseOutputWrapper.java
deleted file mode 100644
index 47bcf2a26..000000000
--- a/container/src/main/java/org/openremote/container/web/file/HttpServletResponseOutputWrapper.java
+++ /dev/null
@@ -1,177 +0,0 @@
-/*
- * Copyright 2017 OmniFaces
- *
- * 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.openremote.container.web.file;
-
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.io.PrintWriter;
-import java.io.Writer;
-
-import jakarta.servlet.ServletOutputStream;
-import jakarta.servlet.http.HttpServletResponse;
-import jakarta.servlet.http.HttpServletResponseWrapper;
-
-/**
- * Convenience class for extending {@link HttpServletResponseWrapper} wherein the servlet response {@link OutputStream}
- * has to be replaced by a custom implementation. This saves the developer from writing repeated
- * {@link #getOutputStream()}, {@link #getWriter()} and {@link #flushBuffer()} boilerplate. All the developer has to do
- * is to implement the {@link #createOutputStream()} accordingly. This will in turn be used by both
- * {@link #getOutputStream()} and {@link #getWriter()}.
- * <p>
- * The boolean property <code>passThrough</code>, which defaults to <code>false</code> also enables the developer to
- * control whether to pass through to the wrapped {@link ServletOutputStream} or not.
- *
- * @author Bauke Scholtz
- * @since 1.1
- */
-public abstract class HttpServletResponseOutputWrapper extends HttpServletResponseWrapper {
-
- // Constants ------------------------------------------------------------------------------------------------------
-
- private static final String ERROR_GETOUTPUT_ALREADY_CALLED =
- "getOutputStream() has already been called on this response.";
- private static final String ERROR_GETWRITER_ALREADY_CALLED =
- "getWriter() has already been called on this response.";
-
- // Properties -----------------------------------------------------------------------------------------------------
-
- private ServletOutputStream output;
- private PrintWriter writer;
- private ResettableBuffer buffer;
- private boolean passThrough;
-
- // Constructors ---------------------------------------------------------------------------------------------------
-
- /**
- * Construct a new {@link HttpServletResponseOutputWrapper} which wraps the given response.
- * @param wrappedResponse The wrapped response.
- */
- public HttpServletResponseOutputWrapper(HttpServletResponse wrappedResponse) {
- super(wrappedResponse);
- }
-
- // Actions --------------------------------------------------------------------------------------------------------
-
- /**
- * Returns the custom implementation of the servlet response {@link OutputStream}.
- * @return The custom implementation of the servlet response {@link OutputStream}.
- */
- protected abstract OutputStream createOutputStream();
-
- @Override
- public ServletOutputStream getOutputStream() throws IOException {
- if (passThrough) {
- return super.getOutputStream();
- }
-
- if (writer != null) {
- throw new IllegalStateException(ERROR_GETWRITER_ALREADY_CALLED);
- }
-
- if (output == null) {
- buffer = new ResettableBufferedOutputStream(createOutputStream(), getBufferSize());
- output = new DefaultServletOutputStream((OutputStream) buffer);
- }
-
- return output;
- }
-
- @Override
- public PrintWriter getWriter() throws IOException {
- if (passThrough) {
- return super.getWriter();
- }
-
- if (output != null) {
- throw new IllegalStateException(ERROR_GETOUTPUT_ALREADY_CALLED);
- }
-
- if (writer == null) {
- buffer = new ResettableBufferedWriter(new OutputStreamWriter(createOutputStream(),
- getCharacterEncoding()), getBufferSize(), getCharacterEncoding());
- writer = new PrintWriter((Writer) buffer);
- }
-
- return writer;
- }
-
- @Override
- public void flushBuffer() throws IOException {
- super.flushBuffer();
-
- if (passThrough) {
- return;
- }
-
- if (writer != null) {
- writer.flush();
- }
- else if (output != null) {
- output.flush();
- }
- }
-
- /**
- * Close the response body. This closes any created writer or output stream.
- * @throws IOException When an I/O error occurs.
- */
- public void close() throws IOException {
- if (writer != null) {
- writer.close();
- }
- else if (output != null) {
- output.close();
- }
- }
-
- @Override
- public void reset() {
- super.reset();
-
- if (buffer != null) {
- buffer.reset();
- }
- }
-
- // Getters/setters ------------------------------------------------------------------------------------------------
-
- /**
- * Returns whether the response is committed or not. The response is also considered committed when the resettable
- * buffer has been flushed.
- * @return <code>true</code> if the response is committed, otherwise <code>false</code>.
- */
- @Override
- public boolean isCommitted() {
- return super.isCommitted() || (buffer != null && !buffer.isResettable());
- }
-
- /**
- * Returns whether the writing has to be passed through to the wrapped {@link ServletOutputStream}.
- * @return <code>true</code>, if the writing has to be passed through to the wrapped {@link ServletOutputStream},
- * otherwise <code>false</code>.
- */
- public boolean isPassThrough() {
- return passThrough;
- }
-
- /**
- * Sets whether the writing has to be passed through to the wrapped {@link ServletOutputStream}.
- * @param passThrough set to <code>true</code> if the writing has to be passed through to the wrapped
- * {@link ServletOutputStream}.
- */
- public void setPassThrough(boolean passThrough) {
- this.passThrough = passThrough;
- }
-
-}
diff --git a/container/src/main/java/org/openremote/container/web/file/ResettableBuffer.java b/container/src/main/java/org/openremote/container/web/file/ResettableBuffer.java
deleted file mode 100644
index fda087466..000000000
--- a/container/src/main/java/org/openremote/container/web/file/ResettableBuffer.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright 2017 OmniFaces
- *
- * 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.openremote.container.web.file;
-
-/**
- * Base interface for a resettable buffer.
- *
- * @author Bauke Scholtz
- */
-public interface ResettableBuffer {
-
- /**
- * Perform a buffer reset.
- */
- void reset();
-
- /**
- * Returns true if buffer can be reset.
- * @return <code>true</code> if buffer can be reset, otherwise <code>false</code>.
- */
- boolean isResettable();
-
-}
\ No newline at end of file
diff --git a/container/src/main/java/org/openremote/container/web/file/ResettableBufferedOutputStream.java b/container/src/main/java/org/openremote/container/web/file/ResettableBufferedOutputStream.java
deleted file mode 100644
index 84f78b284..000000000
--- a/container/src/main/java/org/openremote/container/web/file/ResettableBufferedOutputStream.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- * Copyright 2017 OmniFaces
- *
- * 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.openremote.container.web.file;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-
-/**
- * This resettable buffered output stream will buffer everything until the given threshold buffer size, regardless of
- * flush calls. Only when the specified threshold buffer size is exceeded, or when {@link #close()} is called, then the
- * buffer will be actually flushed.
- * <p>
- * There is a {@link #reset()} method which enables the developer to reset the buffer, as long as it's not flushed yet,
- * which can be determined by {@link #isResettable()}.
- *
- * @author Bauke Scholtz
- * @see ResettableBufferedWriter
- */
-public class ResettableBufferedOutputStream extends OutputStream implements ResettableBuffer {
-
- // Constants --------------------------------------------------------------------------------------------------
-
- private static final String ERROR_CLOSED = "Stream is already closed.";
-
- // Variables ------------------------------------------------------------------------------------------------------
-
- private OutputStream output;
- private ByteArrayOutputStream buffer;
- private int thresholdBufferSize;
- private int writtenBytes;
- private boolean closed;
-
- // Constructors ---------------------------------------------------------------------------------------------------
-
- /**
- * Construct a new resettable buffered output stream which forcibly buffers everything until the given threshold
- * buffer size, regardless of flush calls and calls. You need to override {@link #createOutputStream(boolean)} when
- * using this constructor.
- * @param thresholdBufferSize The threshold buffer size.
- */
- public ResettableBufferedOutputStream(int thresholdBufferSize) {
- this(null, thresholdBufferSize);
- }
-
- /**
- * Construct a new resettable buffered output stream which wraps the given output stream and forcibly buffers
- * everything until the given threshold buffer size, regardless of flush calls. You do not need to override
- * {@link #createOutputStream(boolean)} when using this constructor.
- * @param output The wrapped output stream .
- * @param thresholdBufferSize The threshold buffer size.
- */
- public ResettableBufferedOutputStream(OutputStream output, int thresholdBufferSize) {
- this.output = output;
- this.thresholdBufferSize = thresholdBufferSize;
- buffer = new ByteArrayOutputStream(thresholdBufferSize);
- }
-
- // Actions --------------------------------------------------------------------------------------------------------
-
- @Override
- public void write(int b) throws IOException {
- write(new byte[] { (byte) b }, 0, 1);
- }
-
- @Override
- public void write(byte[] bytes) throws IOException {
- write(bytes, 0, bytes.length);
- }
-
- @Override
- public void write(byte[] bytes, int offset, int length) throws IOException {
- checkClosed();
-
- if (isResettable()) {
- writtenBytes += (length - offset);
-
- if (writtenBytes > thresholdBufferSize) {
- flushBuffer(true);
- output.write(bytes, offset, length);
- }
- else {
- buffer.write(bytes, offset, length);
- }
- }
- else {
- output.write(bytes, offset, length);
- }
- }
-
- private void flushBuffer(boolean thresholdBufferSizeExceeded) throws IOException {
- if (output == null) {
- if (thresholdBufferSizeExceeded) {
- writtenBytes = -1;
- }
-
- output = createOutputStream(thresholdBufferSizeExceeded);
- }
-
- output.write(buffer.toByteArray());
- buffer = null;
- }
-
- /**
- * Returns the custom implementation of the {@link OutputStream}. This will only be called when the specified
- * threshold buffer size is exceeded, or when {@link #close()} is called.
- * @param thresholdBufferSizeExceeded Whether the threshold buffer size has exceeded.
- * @return The custom implementation of the {@link OutputStream}.
- * @throws IOException When an I/O error occurs.
- */
- protected OutputStream createOutputStream(boolean thresholdBufferSizeExceeded) throws IOException {
- throw new UnsupportedOperationException(
- "You need to either override this method, or use the 2-arg constructor taking OutputStream instead.");
- }
-
- /**
- * Returns the amount of so far written bytes in the threshold buffer. This will be 0 when the threshold buffer is
- * empty and this will be -1 when the threshold has exceeded.
- * @return The amount of so far written bytes in the threshold buffer.
- */
- protected int getWrittenBytes() {
- return writtenBytes;
- }
-
- @Override
- public void reset() {
- if (isResettable()) {
- buffer = new ByteArrayOutputStream(thresholdBufferSize);
- writtenBytes = 0;
- }
- }
-
- @Override
- public void flush() throws IOException {
- checkClosed();
-
- if (!isResettable()) {
- output.flush();
- }
- }
-
- @Override
- public void close() throws IOException {
- if (closed) {
- return;
- }
-
- if (isResettable()) {
- flushBuffer(false);
- }
-
- output.close();
- closed = true;
- }
-
- @Override
- public boolean isResettable() {
- return buffer != null;
- }
-
- /**
- * Check if the current stream is closed and if so, then throw IO exception.
- * @throws IOException When the current stream is closed.
- */
- private void checkClosed() throws IOException {
- if (closed) {
- throw new IOException(ERROR_CLOSED);
- }
- }
-
-}
\ No newline at end of file
diff --git a/container/src/main/java/org/openremote/container/web/file/ResettableBufferedWriter.java b/container/src/main/java/org/openremote/container/web/file/ResettableBufferedWriter.java
deleted file mode 100644
index 37e3c5966..000000000
--- a/container/src/main/java/org/openremote/container/web/file/ResettableBufferedWriter.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright 2017 OmniFaces
- *
- * 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.openremote.container.web.file;
-
-import java.io.CharArrayWriter;
-import java.io.IOException;
-import java.io.Writer;
-import java.nio.CharBuffer;
-import java.nio.charset.Charset;
-
-/**
- * This resettable buffered writer will buffer everything until the given buffer size, regardless of flush calls.
- * Only when the buffer size is exceeded, or when close is called, then the buffer will be actually flushed.
- * <p>
- * There is a {@link #reset()} method which enables the developer to reset the buffer, as long as it's not flushed yet,
- * which can be determined by {@link #isResettable()}.
- *
- * @author Bauke Scholtz
- * @see ResettableBufferedOutputStream
- */
-public class ResettableBufferedWriter extends Writer implements ResettableBuffer {
-
- // Variables ------------------------------------------------------------------------------------------------------
-
- private Writer writer;
- private Charset charset;
- private CharArrayWriter buffer;
- private int bufferSize;
- private int writtenBytes;
-
- // Constructors ---------------------------------------------------------------------------------------------------
-
- /**
- * Construct a new resettable buffered writer which wraps the given writer and forcibly buffers everything until
- * the given buffer size in bytes, regardless of flush calls. The given character encoding is used to measure the
- * amount of already written bytes in the buffer.
- * regardless of flush calls.
- * @param writer The wrapped writer.
- * @param bufferSize The buffer size.
- * @param characterEncoding The character encoding.
- */
- public ResettableBufferedWriter(Writer writer, int bufferSize, String characterEncoding) {
- this.writer = writer;
- this.bufferSize = bufferSize;
- charset = Charset.forName(characterEncoding);
- buffer = new CharArrayWriter(bufferSize);
- }
-
- // Actions --------------------------------------------------------------------------------------------------------
-
- @Override
- public void write(char[] chars, int offset, int length) throws IOException {
- if (buffer != null) {
- writtenBytes += charset.encode(CharBuffer.wrap(chars, offset, length)).limit();
-
- if (writtenBytes > bufferSize) {
- writer.write(buffer.toCharArray());
- writer.write(chars, offset, length);
- buffer = null;
- }
- else {
- buffer.write(chars, offset, length);
- }
- }
- else {
- writer.write(chars, offset, length);
- }
- }
-
- @Override
- public void reset() {
- buffer = new CharArrayWriter(bufferSize);
- writtenBytes = 0;
- }
-
- @Override
- public void flush() throws IOException {
- if (buffer == null) {
- writer.flush();
- }
- }
-
- @Override
- public void close() throws IOException {
- if (buffer != null) {
- writer.write(buffer.toCharArray());
- buffer = null;
- }
-
- writer.close();
- }
-
- @Override
- public boolean isResettable() {
- return buffer != null;
- }
-
-}
\ No newline at end of file
diff --git a/container/src/main/java/org/openremote/container/web/file/ResourceImpl.java b/container/src/main/java/org/openremote/container/web/file/ResourceImpl.java
deleted file mode 100644
index 8c37aa4a0..000000000
--- a/container/src/main/java/org/openremote/container/web/file/ResourceImpl.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright 2017, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.container.web.file;
-
-import java.io.File;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLEncoder;
-
-import static java.lang.String.format;
-import static java.nio.charset.StandardCharsets.UTF_8;
-
-public class ResourceImpl implements Resource {
-
- private static final String ETAG = "W/\"%s-%s\"";
-
- private final File file;
- private final long length;
- private final long lastModified;
- private final String eTag;
- private final URL url;
-
- public ResourceImpl(File file) {
- if (file != null && file.isFile()) {
- this.file = file;
- length = file.length();
- lastModified = file.lastModified();
- eTag = createETAG(file.getName(), lastModified);
- try {
- url = file.toURI().toURL();
- } catch (MalformedURLException e) {
- throw new RuntimeException(e);
- }
- }
- else {
- this.file = null;
- length = 0;
- lastModified = 0;
- eTag = null;
- url = null;
- }
- }
-
- public ResourceImpl(io.undertow.server.handlers.resource.Resource resource){
- if (resource != null && resource.getUrl() != null && !resource.isDirectory() &&
- // The directory check does not work with JARs so the content length is checked instead
- (!"jar".equals(resource.getUrl().getProtocol()) || resource.getContentLength() > 0)) {
- file = resource.getFile();
- length = resource.getContentLength();
- lastModified = resource.getLastModified().getTime();
- eTag = createETAG(resource.getUrl().getFile(), lastModified);
- url = resource.getUrl();
- }
- else {
- file = null;
- length = 0;
- lastModified = 0;
- eTag = null;
- url = null;
- }
- }
-
- private String createETAG(String fileName, long lastModified) {
- return format(ETAG, URLEncoder.encode(fileName, UTF_8), lastModified);
- }
-
- @Override
- public File getFile() {
- return file;
- }
-
- @Override
- public long getLength() {
- return length;
- }
-
- @Override
- public long getLastModified() {
- return lastModified;
- }
-
- @Override
- public String getETag() {
- return eTag;
- }
-
- @Override
- public URL getURL() {
- return url;
- }
-}
-
diff --git a/gradle.properties b/gradle.properties
index 2b79602d2..5aef322dc 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -71,5 +71,5 @@ jSchVersion = 2.27.6
bouncyCastleVersion = 1.81
victoolsJsonSchemaGeneratorVersion = 4.38.0
moquetteVersion = 0.18.0
-
+corsFilterVersion = 3.1
junitVersion = 5.14.1
diff --git a/manager/src/main/java/org/openremote/manager/alarm/AlarmService.java b/manager/src/main/java/org/openremote/manager/alarm/AlarmService.java
index 94bd65cbc..0a65599ae 100644
--- a/manager/src/main/java/org/openremote/manager/alarm/AlarmService.java
+++ b/manager/src/main/java/org/openremote/manager/alarm/AlarmService.java
@@ -55,7 +55,7 @@ import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
-import static org.openremote.container.util.MapAccess.getString;
+import static org.openremote.model.util.MapAccess.getString;
import static org.openremote.model.Constants.OR_HOSTNAME;
import static org.openremote.model.alarm.Alarm.Source.*;
diff --git a/manager/src/main/java/org/openremote/manager/app/ConfigurationService.java b/manager/src/main/java/org/openremote/manager/app/ConfigurationService.java
index 0b47bc313..826d006fc 100644
--- a/manager/src/main/java/org/openremote/manager/app/ConfigurationService.java
+++ b/manager/src/main/java/org/openremote/manager/app/ConfigurationService.java
@@ -46,7 +46,7 @@ import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;
-import static org.openremote.container.util.MapAccess.getString;
+import static org.openremote.model.util.MapAccess.getString;
import static org.openremote.manager.web.ManagerWebService.OR_CUSTOM_APP_DOCROOT;
import static org.openremote.manager.web.ManagerWebService.OR_CUSTOM_APP_DOCROOT_DEFAULT;
diff --git a/manager/src/main/java/org/openremote/manager/apps/ConsoleAppService.java b/manager/src/main/java/org/openremote/manager/apps/ConsoleAppService.java
index e5cbb62af..f1da2ec4b 100644
--- a/manager/src/main/java/org/openremote/manager/apps/ConsoleAppService.java
+++ b/manager/src/main/java/org/openremote/manager/apps/ConsoleAppService.java
@@ -19,9 +19,6 @@
*/
package org.openremote.manager.apps;
-import io.undertow.server.HttpHandler;
-import io.undertow.server.handlers.PathHandler;
-import io.undertow.server.handlers.resource.PathResourceManager;
import org.openremote.container.persistence.PersistenceService;
import org.openremote.container.timer.TimerService;
import org.openremote.manager.security.ManagerIdentityService;
@@ -32,15 +29,9 @@ import org.openremote.model.ContainerService;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.nio.file.Paths;
import java.util.logging.Logger;
import java.util.stream.Stream;
-import static org.openremote.container.util.MapAccess.getString;
-import static org.openremote.container.web.WebService.pathStartsWithHandler;
-import static org.openremote.manager.web.ManagerWebService.OR_CUSTOM_APP_DOCROOT;
-import static org.openremote.manager.web.ManagerWebService.OR_CUSTOM_APP_DOCROOT_DEFAULT;
-
public class ConsoleAppService implements ContainerService {
private static final Logger LOG = Logger.getLogger(ConsoleAppService.class.getName());
@@ -62,19 +53,6 @@ public class ConsoleAppService implements ContainerService {
container.getService(ManagerWebService.class).addApiSingleton(
new AppResourceImpl(this)
);
-
- consoleAppDocRoot = Paths.get(getString(container.getConfig(), OR_CUSTOM_APP_DOCROOT, OR_CUSTOM_APP_DOCROOT_DEFAULT));
-
- // Serve console app config files
- if (Files.isDirectory(consoleAppDocRoot)) {
- HttpHandler customBaseFileHandler = ManagerWebService.createFileHandler(container, new PathResourceManager(consoleAppDocRoot), null);
-
- HttpHandler pathHandler = new PathHandler().addPrefixPath("info", customBaseFileHandler);
- managerWebService.getRequestHandlers().addFirst(pathStartsWithHandler(
- "Console app info files",
- "info",
- pathHandler));
- }
}
@Override
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
index b6988927a..c28b48649 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
@@ -599,7 +599,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
}
long startTime = System.currentTimeMillis();
- String assetId = asset.getId() != null ? asset.getId() : "";
+ String assetId = asset.getId();
// We skip all standard checks as asset is coming from a gateway and would be validated from there
if (requestingGatewayAsset != null) {
@@ -641,189 +641,191 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
}
}
- return withAssetLock(assetId, () -> persistenceService.doReturningTransaction(em -> {
+ Supplier<T> assetSupplier = () -> persistenceService.doReturningTransaction(em -> {
- T existingAsset = TextUtil.isNullOrEmpty(asset.getId()) ? null : (T)em.find(Asset.class, asset.getId());
+ T existingAsset = TextUtil.isNullOrEmpty(asset.getId()) ? null : (T)em.find(Asset.class, asset.getId());
- if (existingAsset != null) {
+ if (existingAsset != null) {
- // Verify type has not been changed
- if (!existingAsset.getType().equals(asset.getType())) {
- String msg = "Asset type cannot be changed: asset=" + asset;
- LOG.warning(msg);
- throw new IllegalStateException(msg);
- }
-
- if (!existingAsset.getRealm().equals(asset.getRealm())) {
- String msg = "Asset realm cannot be changed: asset=" + asset;
- LOG.warning(msg);
- throw new IllegalStateException(msg);
- }
-
- // Update timestamp on modified attributes this allows fast equality checking
- asset.getAttributes().stream().forEach(attr ->
- existingAsset.getAttribute(attr.getName()).ifPresent(existingAttr -> {
- // If attribute is modified make sure the timestamp is also updated to allow simple equality
- if (!attr.deepEquals(existingAttr) && attr.getTimestamp().orElse(0L) <= existingAttr.getTimestamp().orElse(0L)) {
- // In the unlikely situation that we are in the same millisecond as last update
- // we will always ensure a delta of >= 1ms
- attr.setTimestamp(Math.max(existingAttr.getTimestamp().orElse(0L)+1, timerService.getCurrentTimeMillis()));
- }
- }));
-
- // If this is real merge and desired, copy the persistent version number over the detached
- // version, so the detached state always wins and this update will go through and ignore
- // concurrent updates
- if (overrideVersion) {
- asset.setVersion(existingAsset.getVersion());
- }
- }
-
- if (!identityService.getIdentityProvider().realmExists(asset.getRealm())) {
- String msg = "Asset realm not found or is inactive: asset=" + asset;
- LOG.warning(msg);
- throw new IllegalStateException(msg);
- }
-
- if (asset.getParentId() != null && asset.getParentId().equals(asset.getId())) {
- String msg = "Asset parent cannot be the asset: asset=" + asset;
- LOG.warning(msg);
- throw new IllegalStateException(msg);
- }
-
- // Validate parent only if asset is new or parent has changed
- if ((existingAsset == null && asset.getParentId() != null)
- || (existingAsset != null && asset.getParentId() != null && !asset.getParentId().equals(existingAsset.getParentId()))) {
-
- Asset<?> parent = find(em, asset.getParentId(), true);
-
- // The parent must exist
- if (parent == null) {
- String msg = "Asset parent not found: asset=" + asset;
- LOG.warning(msg);
- throw new IllegalStateException(msg);
- }
-
- // The parent can not be a child of the asset
- if (parent.pathContains(asset.getId())) {
- String msg = "Asset parent cannot be a descendant of the asset: asset=" + asset;
- LOG.warning(msg);
- throw new IllegalStateException(msg);
- }
-
- // The parent should be in the same realm
- if (!parent.getRealm().equals(asset.getRealm())) {
- String msg = "Asset parent must be in the same realm: asset=" + asset;
- LOG.warning(msg);
- throw new IllegalStateException(msg);
- }
+ // Verify type has not been changed
+ if (!existingAsset.getType().equals(asset.getType())) {
+ String msg = "Asset type cannot be changed: asset=" + asset;
+ LOG.warning(msg);
+ throw new IllegalStateException(msg);
+ }
- // if parent is of type group then this child asset must have the correct type
- if (parent instanceof GroupAsset) {
- String childAssetType = parent.getAttributes().getValue(GroupAsset.CHILD_ASSET_TYPE)
- .orElseThrow(() -> {
- String msg = "Asset parent is of type GROUP but the childAssetType attribute is invalid: asset=" + asset;
- LOG.warning(msg);
- return new IllegalStateException(msg);
- });
-
- // Look through type hierarchy for a match - this allows sub types
- Class<?> clazz = asset.getClass();
- boolean typeMatch = childAssetType.equals(clazz.getSimpleName());
-
- while (!typeMatch && clazz != Asset.class) {
- clazz = clazz.getSuperclass();
- typeMatch = childAssetType.equals(clazz.getSimpleName());
- }
+ if (!existingAsset.getRealm().equals(asset.getRealm())) {
+ String msg = "Asset realm cannot be changed: asset=" + asset;
+ LOG.warning(msg);
+ throw new IllegalStateException(msg);
+ }
- if (!typeMatch) {
- String msg = "Asset type does not match parent GROUP asset's childAssetType attribute: asset=" + asset;
- LOG.warning(msg);
- throw new IllegalStateException(msg);
+ // Update timestamp on modified attributes this allows fast equality checking
+ asset.getAttributes().stream().forEach(attr ->
+ existingAsset.getAttribute(attr.getName()).ifPresent(existingAttr -> {
+ // If attribute is modified make sure the timestamp is also updated to allow simple equality
+ if (!attr.deepEquals(existingAttr) && attr.getTimestamp().orElse(0L) <= existingAttr.getTimestamp().orElse(0L)) {
+ // In the unlikely situation that we are in the same millisecond as last update
+ // we will always ensure a delta of >= 1ms
+ attr.setTimestamp(Math.max(existingAttr.getTimestamp().orElse(0L)+1, timerService.getCurrentTimeMillis()));
}
- }
- }
-
- // Validate group child asset type attribute
- if (asset instanceof GroupAsset groupAsset) {
-
- // Ensure the asset has a childAssetType (set to empty if missing)
- String childAssetType = groupAsset.getChildAssetType()
- .orElseGet(() -> {
- groupAsset.setChildAssetType(""); // Set empty on the asset
- return "";
- });
-
- String existingChildAssetType = existingAsset != null ? ((GroupAsset)existingAsset)
- .getChildAssetType()
+ }));
+
+ // If this is real merge and desired, copy the persistent version number over the detached
+ // version, so the detached state always wins and this update will go through and ignore
+ // concurrent updates
+ if (overrideVersion) {
+ asset.setVersion(existingAsset.getVersion());
+ }
+ }
+
+ if (!identityService.getIdentityProvider().realmExists(asset.getRealm())) {
+ String msg = "Asset realm not found or is inactive: asset=" + asset;
+ LOG.warning(msg);
+ throw new IllegalStateException(msg);
+ }
+
+ if (asset.getParentId() != null && asset.getParentId().equals(asset.getId())) {
+ String msg = "Asset parent cannot be the asset: asset=" + asset;
+ LOG.warning(msg);
+ throw new IllegalStateException(msg);
+ }
+
+ // Validate parent only if asset is new or parent has changed
+ if ((existingAsset == null && asset.getParentId() != null)
+ || (existingAsset != null && asset.getParentId() != null && !asset.getParentId().equals(existingAsset.getParentId()))) {
+
+ Asset<?> parent = find(em, asset.getParentId(), true);
+
+ // The parent must exist
+ if (parent == null) {
+ String msg = "Asset parent not found: asset=" + asset;
+ LOG.warning(msg);
+ throw new IllegalStateException(msg);
+ }
+
+ // The parent can not be a child of the asset
+ if (parent.pathContains(asset.getId())) {
+ String msg = "Asset parent cannot be a descendant of the asset: asset=" + asset;
+ LOG.warning(msg);
+ throw new IllegalStateException(msg);
+ }
+
+ // The parent should be in the same realm
+ if (!parent.getRealm().equals(asset.getRealm())) {
+ String msg = "Asset parent must be in the same realm: asset=" + asset;
+ LOG.warning(msg);
+ throw new IllegalStateException(msg);
+ }
+
+ // if parent is of type group then this child asset must have the correct type
+ if (parent instanceof GroupAsset) {
+ String childAssetType = parent.getAttributes().getValue(GroupAsset.CHILD_ASSET_TYPE)
.orElseThrow(() -> {
- String msg = "Asset of type GROUP childAssetType attribute must be a valid string: asset=" + asset;
- LOG.warning(msg);
- return new IllegalStateException(msg);
- }) : childAssetType;
+ String msg = "Asset parent is of type GROUP but the childAssetType attribute is invalid: asset=" + asset;
+ LOG.warning(msg);
+ return new IllegalStateException(msg);
+ });
- if (!childAssetType.isEmpty() && !existingChildAssetType.isEmpty() && !childAssetType.equals(existingChildAssetType)) {
- String msg = "Asset of type GROUP so childAssetType attribute cannot be changed: asset=" + asset;
- LOG.warning(msg);
- throw new IllegalStateException(msg);
- }
- }
+ // Look through type hierarchy for a match - this allows sub types
+ Class<?> clazz = asset.getClass();
+ boolean typeMatch = childAssetType.equals(clazz.getSimpleName());
- // Update all empty attribute timestamps with server-time (a caller which doesn't have a
- // reliable time source such as a browser should clear the timestamp when setting an attribute
- // value).
- asset.getAttributes().forEach(attribute -> {
- if (!attribute.hasExplicitTimestamp()) {
- attribute.setTimestamp(timerService.getCurrentTimeMillis());
- }
- });
+ while (!typeMatch && clazz != Asset.class) {
+ clazz = clazz.getSuperclass();
+ typeMatch = childAssetType.equals(clazz.getSimpleName());
+ }
- // If username present
- User user = null;
- if (!TextUtil.isNullOrEmpty(userName)) {
- user = identityService.getIdentityProvider().getUserByUsername(asset.getRealm(), userName);
- if (user == null) {
- String msg = "User not found: " + userName;
+ if (!typeMatch) {
+ String msg = "Asset type does not match parent GROUP asset's childAssetType attribute: asset=" + asset;
LOG.warning(msg);
throw new IllegalStateException(msg);
- }
- }
-
- T updatedAsset;
-
- if (existingAsset instanceof UnknownAsset && !(asset instanceof UnknownAsset)) {
- // This occurs when an existing asset is merged but the type is unknown
- // We'll copy updates into existing asset
- existingAsset.setAttributes(asset.getAttributes());
- existingAsset.setName(asset.getName());
- existingAsset.setVersion(asset.getVersion());
- existingAsset.setParentId(asset.getParentId());
- existingAsset.setAccessPublicRead(asset.isAccessPublicRead());
- updatedAsset = em.merge(existingAsset);
- } else {
- updatedAsset = em.merge(asset);
- }
-
- if (LOG.isLoggable(FINE)) {
- LOG.fine("Asset merge took: " + (System.currentTimeMillis() - startTime) + "ms");
- }
-
- if (user != null) {
- createUserAssetLinks(em, Collections.singletonList(new UserAssetLink(user.getRealm(), user.getId(), updatedAsset.getId())));
- }
-
- if (existingAsset == null && updatedAsset instanceof ThingAsset && !ThingAsset.DESCRIPTOR.getName().equals(updatedAsset.getType())) {
- // When an asset is first saved then any custom type is not persisted as JPA will set it to ThingAsset so we need to override
- // We don't need to do this when updating an existing asset as JPA doesn't overwrite the type - if this changes in future it
- // should be detected by tests
- em.createNativeQuery("update ASSET set type = ? where id = ?;")
- .setParameter(1, updatedAsset.getType())
- .setParameter(2, updatedAsset.getId())
- .executeUpdate();
- }
+ }
+ }
+ }
+
+ // Validate group child asset type attribute
+ if (asset instanceof GroupAsset groupAsset) {
+
+ // Ensure the asset has a childAssetType (set to empty if missing)
+ String childAssetType = groupAsset.getChildAssetType()
+ .orElseGet(() -> {
+ groupAsset.setChildAssetType(""); // Set empty on the asset
+ return "";
+ });
+
+ String existingChildAssetType = existingAsset != null ? ((GroupAsset)existingAsset)
+ .getChildAssetType()
+ .orElseThrow(() -> {
+ String msg = "Asset of type GROUP childAssetType attribute must be a valid string: asset=" + asset;
+ LOG.warning(msg);
+ return new IllegalStateException(msg);
+ }) : childAssetType;
+
+ if (!childAssetType.isEmpty() && !existingChildAssetType.isEmpty() && !childAssetType.equals(existingChildAssetType)) {
+ String msg = "Asset of type GROUP so childAssetType attribute cannot be changed: asset=" + asset;
+ LOG.warning(msg);
+ throw new IllegalStateException(msg);
+ }
+ }
+
+ // Update all empty attribute timestamps with server-time (a caller which doesn't have a
+ // reliable time source such as a browser should clear the timestamp when setting an attribute
+ // value).
+ asset.getAttributes().forEach(attribute -> {
+ if (!attribute.hasExplicitTimestamp()) {
+ attribute.setTimestamp(timerService.getCurrentTimeMillis());
+ }
+ });
+
+ // If username present
+ User user = null;
+ if (!TextUtil.isNullOrEmpty(userName)) {
+ user = identityService.getIdentityProvider().getUserByUsername(asset.getRealm(), userName);
+ if (user == null) {
+ String msg = "User not found: " + userName;
+ LOG.warning(msg);
+ throw new IllegalStateException(msg);
+ }
+ }
+
+ T updatedAsset;
+
+ if (existingAsset instanceof UnknownAsset && !(asset instanceof UnknownAsset)) {
+ // This occurs when an existing asset is merged but the type is unknown
+ // We'll copy updates into existing asset
+ existingAsset.setAttributes(asset.getAttributes());
+ existingAsset.setName(asset.getName());
+ existingAsset.setVersion(asset.getVersion());
+ existingAsset.setParentId(asset.getParentId());
+ existingAsset.setAccessPublicRead(asset.isAccessPublicRead());
+ updatedAsset = em.merge(existingAsset);
+ } else {
+ updatedAsset = em.merge(asset);
+ }
+
+ if (LOG.isLoggable(FINE)) {
+ LOG.fine("Asset merge took: " + (System.currentTimeMillis() - startTime) + "ms");
+ }
+
+ if (user != null) {
+ createUserAssetLinks(em, Collections.singletonList(new UserAssetLink(user.getRealm(), user.getId(), updatedAsset.getId())));
+ }
+
+ if (existingAsset == null && updatedAsset instanceof ThingAsset && !ThingAsset.DESCRIPTOR.getName().equals(updatedAsset.getType())) {
+ // When an asset is first saved then any custom type is not persisted as JPA will set it to ThingAsset so we need to override
+ // We don't need to do this when updating an existing asset as JPA doesn't overwrite the type - if this changes in future it
+ // should be detected by tests
+ em.createNativeQuery("update ASSET set type = ? where id = ?;")
+ .setParameter(1, updatedAsset.getType())
+ .setParameter(2, updatedAsset.getId())
+ .executeUpdate();
+ }
+
+ return updatedAsset;
+ });
- return updatedAsset;
- }));
+ return assetId == null ? assetSupplier.get() : withAssetLock(assetId, assetSupplier);
}
/**
diff --git a/manager/src/main/java/org/openremote/manager/datapoint/AbstractDatapointService.java b/manager/src/main/java/org/openremote/manager/datapoint/AbstractDatapointService.java
index 73ecec621..091bc468c 100644
--- a/manager/src/main/java/org/openremote/manager/datapoint/AbstractDatapointService.java
+++ b/manager/src/main/java/org/openremote/manager/datapoint/AbstractDatapointService.java
@@ -57,7 +57,7 @@ import java.util.logging.Level;
import java.util.logging.Logger;
import static java.time.temporal.ChronoUnit.DAYS;
-import static org.openremote.container.util.MapAccess.getInteger;
+import static org.openremote.model.util.MapAccess.getInteger;
/**
* Base class for all classes that store and retrieve {@link org.openremote.model.datapoint.Datapoint}.
diff --git a/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointService.java b/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointService.java
index 0b8fcf384..04addfe97 100644
--- a/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointService.java
+++ b/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointService.java
@@ -41,7 +41,7 @@ import java.util.stream.Collectors;
import static java.time.temporal.ChronoUnit.DAYS;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;
-import static org.openremote.container.util.MapAccess.getInteger;
+import static org.openremote.model.util.MapAccess.getInteger;
import static org.openremote.model.value.MetaItemType.STORE_DATA_POINTS;
/**
diff --git a/manager/src/main/java/org/openremote/manager/energy/ForecastSolarService.java b/manager/src/main/java/org/openremote/manager/energy/ForecastSolarService.java
index 4dcfce1ea..4b978b29d 100644
--- a/manager/src/main/java/org/openremote/manager/energy/ForecastSolarService.java
+++ b/manager/src/main/java/org/openremote/manager/energy/ForecastSolarService.java
@@ -45,7 +45,7 @@ import static java.time.format.DateTimeFormatter.ISO_LOCAL_DATE;
import static java.time.format.DateTimeFormatter.ISO_LOCAL_TIME;
import static org.openremote.container.persistence.PersistenceService.PERSISTENCE_TOPIC;
import static org.openremote.container.persistence.PersistenceService.isPersistenceEventForEntityType;
-import static org.openremote.container.util.MapAccess.getString;
+import static org.openremote.model.util.MapAccess.getString;
import static org.openremote.container.web.WebTargetBuilder.createClient;
import static org.openremote.manager.gateway.GatewayService.isNotForGateway;
import static org.openremote.model.syslog.SyslogCategory.DATA;
diff --git a/manager/src/main/java/org/openremote/manager/energy/ForecastWindService.java b/manager/src/main/java/org/openremote/manager/energy/ForecastWindService.java
index 895f5755f..483d7d1a1 100644
--- a/manager/src/main/java/org/openremote/manager/energy/ForecastWindService.java
+++ b/manager/src/main/java/org/openremote/manager/energy/ForecastWindService.java
@@ -38,7 +38,7 @@ import java.util.logging.Logger;
import static org.openremote.container.persistence.PersistenceService.PERSISTENCE_TOPIC;
import static org.openremote.container.persistence.PersistenceService.isPersistenceEventForEntityType;
-import static org.openremote.container.util.MapAccess.getString;
+import static org.openremote.model.util.MapAccess.getString;
import static org.openremote.container.web.WebTargetBuilder.createClient;
import static org.openremote.manager.gateway.GatewayService.isNotForGateway;
import static org.openremote.model.syslog.SyslogCategory.DATA;
diff --git a/manager/src/main/java/org/openremote/manager/event/UndertowHost.java b/manager/src/main/java/org/openremote/manager/event/UndertowHost.java
index 8e26d8b6c..1b1d8e467 100644
--- a/manager/src/main/java/org/openremote/manager/event/UndertowHost.java
+++ b/manager/src/main/java/org/openremote/manager/event/UndertowHost.java
@@ -30,24 +30,25 @@ import org.apache.camel.component.undertow.HttpHandlerRegistrationInfo;
import org.apache.camel.component.undertow.UndertowConsumer;
import org.apache.camel.component.undertow.UndertowHostKey;
import org.apache.camel.component.undertow.UndertowHostOptions;
+import org.openremote.container.security.IdentityService;
+import org.openremote.container.security.WebsocketAuthParamHandler;
import org.openremote.container.web.WebService;
import org.openremote.model.Container;
import java.net.URI;
-import static org.openremote.container.web.WebService.pathStartsWithHandler;
-
/**
* Customised to use existing undertow instance so websocket doesn't have to be on a separate web server instance
*/
+// TODO: Move realm into request URI if possible and remove Realm query parameter support
public class UndertowHost implements org.apache.camel.component.undertow.UndertowHost {
+ public static final String DEPLOYMENT_NAME = "Camel WebSocket Deployment";
protected final Container container;
protected final UndertowHostKey key;
protected final UndertowHostOptions options;
protected final Undertow undertow;
protected DeploymentInfo deployment;
- protected WebService.RequestHandler websocketHttpHandler;
protected HttpHandler camelHandler;
public UndertowHost(Container container, UndertowHostKey key, UndertowHostOptions options) {
@@ -69,12 +70,16 @@ public class UndertowHost implements org.apache.camel.component.undertow.Underto
return camelHandler;
}
+ WebService webService = container.getService(WebService.class);
+ IdentityService identityService = container.getService(IdentityService.class);
+
String path = registrationInfo.getUri().getPath();
- String deploymentName = "Camel WebSocket Deployment";
deployment = Servlets.deployment()
- .setDeploymentName(deploymentName)
+ .setDeploymentName(DEPLOYMENT_NAME)
.setContextPath(path)
.setClassLoader(getClass().getClassLoader())
+ // Add handler to extract authorization and realm query params
+ .addInitialHandlerChainWrapper(WebsocketAuthParamHandler::new)
//httpHandler for servlet is ignored, camel handler is used instead of it
.addInnerHandlerChainWrapper(h -> handler);
@@ -85,14 +90,8 @@ public class UndertowHost implements org.apache.camel.component.undertow.Underto
constraint.setEmptyRoleSemantic(SecurityInfo.EmptyRoleSemantic.PERMIT);
constraint.addWebResourceCollection(resourceCollection);
deployment.addSecurityConstraints(constraint);
-
- HttpHandler deploymentHandler = WebService.addServletDeployment(container, deployment, true);
-
- websocketHttpHandler = pathStartsWithHandler(deploymentName, path, deploymentHandler);
-
- // Give web socket handler higher priority than any other handlers already added
- container.getService(WebService.class).getRequestHandlers().addFirst(websocketHttpHandler);
-
+ identityService.secureDeployment(deployment);
+ webService.deploy(deployment, false);
// Caller expects a CamelWebSocketHandler instance
camelHandler = handler;
return handler;
@@ -103,11 +102,8 @@ public class UndertowHost implements org.apache.camel.component.undertow.Underto
WebService webService = container.getService(WebService.class);
if (deployment != null) {
- webService.removeServletDeployment(deployment);
+ webService.undeploy(DEPLOYMENT_NAME);
deployment = null;
}
-
- webService.getRequestHandlers().remove(websocketHttpHandler);
- websocketHttpHandler = null;
}
}
diff --git a/manager/src/main/java/org/openremote/manager/gateway/GatewayClientService.java b/manager/src/main/java/org/openremote/manager/gateway/GatewayClientService.java
index 5e095071e..ced5885ab 100644
--- a/manager/src/main/java/org/openremote/manager/gateway/GatewayClientService.java
+++ b/manager/src/main/java/org/openremote/manager/gateway/GatewayClientService.java
@@ -62,7 +62,7 @@ import java.util.stream.Collectors;
import static org.openremote.container.persistence.PersistenceService.PERSISTENCE_TOPIC;
import static org.openremote.container.persistence.PersistenceService.isPersistenceEventForEntityType;
-import static org.openremote.container.util.MapAccess.getString;
+import static org.openremote.model.util.MapAccess.getString;
import static org.openremote.model.syslog.SyslogCategory.GATEWAY;
/**
diff --git a/manager/src/main/java/org/openremote/manager/gateway/GatewayService.java b/manager/src/main/java/org/openremote/manager/gateway/GatewayService.java
index 97ee28262..aa480f1b6 100644
--- a/manager/src/main/java/org/openremote/manager/gateway/GatewayService.java
+++ b/manager/src/main/java/org/openremote/manager/gateway/GatewayService.java
@@ -67,8 +67,8 @@ import java.util.stream.Collectors;
import static org.apache.camel.builder.PredicateBuilder.or;
import static org.openremote.container.persistence.PersistenceService.PERSISTENCE_TOPIC;
import static org.openremote.container.persistence.PersistenceService.isPersistenceEventForEntityType;
-import static org.openremote.container.util.MapAccess.getInteger;
-import static org.openremote.container.util.MapAccess.getString;
+import static org.openremote.model.util.MapAccess.getInteger;
+import static org.openremote.model.util.MapAccess.getString;
import static org.openremote.manager.gateway.GatewayConnector.mapAssetId;
import static org.openremote.model.Constants.*;
import static org.openremote.model.syslog.SyslogCategory.GATEWAY;
diff --git a/manager/src/main/java/org/openremote/manager/map/MapResourceImpl.java b/manager/src/main/java/org/openremote/manager/map/MapResourceImpl.java
index 834b973a2..840edd9e6 100644
--- a/manager/src/main/java/org/openremote/manager/map/MapResourceImpl.java
+++ b/manager/src/main/java/org/openremote/manager/map/MapResourceImpl.java
@@ -22,6 +22,7 @@ package org.openremote.manager.map;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.ws.rs.ServerErrorException;
import jakarta.ws.rs.WebApplicationException;
+import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.Response;
import org.openremote.container.web.WebResource;
import org.openremote.manager.security.ManagerIdentityService;
@@ -67,10 +68,13 @@ public class MapResourceImpl extends WebResource implements MapResource {
}
@Override
- public byte[] getTile(int zoom, int column, int row) {
+ public Response getTile(int zoom, int column, int row) {
byte[] tile = mapService.getMapTile(zoom, column, row);
if (tile != null) {
- return tile;
+ return Response.ok(tile)
+ // Tell the browser the content is already GZIPPED
+ .header(HttpHeaders.CONTENT_ENCODING, "gzip")
+ .build();
} else {
throw new WebApplicationException(Response.Status.NO_CONTENT);
}
diff --git a/manager/src/main/java/org/openremote/manager/map/MapService.java b/manager/src/main/java/org/openremote/manager/map/MapService.java
index 5cf27482d..07878f7ae 100644
--- a/manager/src/main/java/org/openremote/manager/map/MapService.java
+++ b/manager/src/main/java/org/openremote/manager/map/MapService.java
@@ -53,9 +53,8 @@ import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.StreamSupport;
-import static org.openremote.container.util.MapAccess.getInteger;
-import static org.openremote.container.util.MapAccess.getString;
-import static org.openremote.container.web.WebService.pathStartsWithHandler;
+import static org.openremote.model.util.MapAccess.getInteger;
+import static org.openremote.model.util.MapAccess.getString;
import static org.openremote.manager.web.ManagerWebService.API_PATH;
public class MapService implements ContainerService {
@@ -247,7 +246,7 @@ public class MapService implements ContainerService {
proxyHandler.handleRequest(exchange);
};
- webService.getRequestHandlers().addFirst(pathStartsWithHandler("Raster Map Tile Proxy", RASTER_MAP_TILE_PATH, proxyWrapper));
+ webService.deploy(RASTER_MAP_TILE_PATH, proxyWrapper);
}
}
diff --git a/manager/src/main/java/org/openremote/manager/mqtt/MQTTBrokerService.java b/manager/src/main/java/org/openremote/manager/mqtt/MQTTBrokerService.java
index c5df54677..b28911379 100644
--- a/manager/src/main/java/org/openremote/manager/mqtt/MQTTBrokerService.java
+++ b/manager/src/main/java/org/openremote/manager/mqtt/MQTTBrokerService.java
@@ -94,8 +94,8 @@ import java.util.stream.Collectors;
import static java.lang.System.Logger.Level.*;
import static java.util.stream.StreamSupport.stream;
import static org.openremote.container.persistence.PersistenceService.PERSISTENCE_TOPIC;
-import static org.openremote.container.util.MapAccess.getInteger;
-import static org.openremote.container.util.MapAccess.getString;
+import static org.openremote.model.util.MapAccess.getInteger;
+import static org.openremote.model.util.MapAccess.getString;
import static org.openremote.model.Constants.KEYCLOAK_CLIENT_ID;
import static org.openremote.model.syslog.SyslogCategory.API;
@@ -504,6 +504,9 @@ public class MQTTBrokerService extends RouteBuilder implements ContainerService,
}
return server.getActiveMQServer().getRemotingService().getConnections().stream().filter(connection -> {
+ if (!connection.getTransportConnection().isOpen()) {
+ return false;
+ }
Subject subject = connection.getSubject();
String subjectID = KeycloakIdentityProvider.getSubjectId(subject);
return userID.equals(subjectID);
diff --git a/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.java b/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.java
index 2888f094d..9f5522ef2 100644
--- a/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.java
+++ b/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.java
@@ -45,7 +45,7 @@ import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
-import static org.openremote.container.util.MapAccess.*;
+import static org.openremote.model.util.MapAccess.*;
import static org.openremote.model.Constants.*;
import static org.openremote.model.security.User.EMAIL_NOTIFICATIONS_DISABLED_ATTRIBUTE;
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesService.java b/manager/src/main/java/org/openremote/manager/rules/RulesService.java
index 6a59288f5..0f302af4c 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesService.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesService.java
@@ -71,7 +71,7 @@ import static java.util.logging.Level.FINEST;
import static java.util.logging.Level.SEVERE;
import static org.openremote.container.persistence.PersistenceService.PERSISTENCE_TOPIC;
import static org.openremote.container.persistence.PersistenceService.isPersistenceEventForEntityType;
-import static org.openremote.container.util.MapAccess.getInteger;
+import static org.openremote.model.util.MapAccess.getInteger;
import static org.openremote.manager.gateway.GatewayService.isNotForGateway;
/**
diff --git a/manager/src/main/java/org/openremote/manager/rules/flow/FlowResourceImpl.java b/manager/src/main/java/org/openremote/manager/rules/flow/FlowResourceImpl.java
index e83a744ce..e3e87f71d 100644
--- a/manager/src/main/java/org/openremote/manager/rules/flow/FlowResourceImpl.java
+++ b/manager/src/main/java/org/openremote/manager/rules/flow/FlowResourceImpl.java
@@ -1,8 +1,6 @@
package org.openremote.manager.rules.flow;
-import org.openremote.model.Container;
import org.openremote.container.timer.TimerService;
-import org.openremote.container.util.MapAccess;
import org.openremote.manager.security.ManagerIdentityService;
import org.openremote.manager.web.ManagerWebResource;
import org.openremote.model.http.RequestParams;
diff --git a/manager/src/main/java/org/openremote/manager/security/KeyStoreServiceImpl.java b/manager/src/main/java/org/openremote/manager/security/KeyStoreServiceImpl.java
index 9df55e3ad..986b9dd10 100644
--- a/manager/src/main/java/org/openremote/manager/security/KeyStoreServiceImpl.java
+++ b/manager/src/main/java/org/openremote/manager/security/KeyStoreServiceImpl.java
@@ -38,7 +38,7 @@ import java.util.logging.Logger;
import java.util.Optional;
import static org.openremote.container.security.IdentityProvider.OR_ADMIN_PASSWORD;
-import static org.openremote.container.util.MapAccess.getString;
+import static org.openremote.model.util.MapAccess.getString;
/**
* <p>
diff --git a/manager/src/main/java/org/openremote/manager/security/ManagerIdentityService.java b/manager/src/main/java/org/openremote/manager/security/ManagerIdentityService.java
index 9ea6d9d7f..2f779a4a1 100644
--- a/manager/src/main/java/org/openremote/manager/security/ManagerIdentityService.java
+++ b/manager/src/main/java/org/openremote/manager/security/ManagerIdentityService.java
@@ -28,7 +28,7 @@ import org.openremote.model.Container;
import java.util.Locale;
import java.util.logging.Logger;
-import static org.openremote.container.util.MapAccess.getString;
+import static org.openremote.model.util.MapAccess.getString;
public class ManagerIdentityService extends IdentityService {
diff --git a/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java b/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java
index c4beb1bf0..1bbd61d60 100644
--- a/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java
+++ b/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java
@@ -41,6 +41,7 @@ import org.openremote.container.persistence.PersistenceService;
import org.openremote.container.security.AuthContext;
import org.openremote.container.security.keycloak.KeycloakIdentityProvider;
import org.openremote.container.timer.TimerService;
+import org.openremote.container.web.CORSConfig;
import org.openremote.container.web.WebService;
import org.openremote.manager.apps.ConsoleAppService;
import org.openremote.manager.asset.AssetStorageService;
@@ -77,8 +78,8 @@ import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
-import static org.openremote.container.util.MapAccess.getBoolean;
-import static org.openremote.container.util.MapAccess.getString;
+import static org.openremote.model.util.MapAccess.getBoolean;
+import static org.openremote.model.util.MapAccess.getString;
import static org.openremote.model.Constants.*;
import static org.openremote.model.util.ValueUtil.convert;
@@ -146,7 +147,7 @@ public class ManagerKeycloakIdentityProvider extends KeycloakIdentityProvider im
// Allow all external hostnames with wildcard and same host with wildcard
validRedirectUris = new ArrayList<>();
validRedirectUris.add("/*");
- validRedirectUris.addAll(WebService.getExternalHostnames(container).stream().map(host -> "https://" + host + "/*").toList());
+ validRedirectUris.addAll(WebService.getExternalHostnames().stream().map(host -> "https://" + host + "/*").toList());
}
@Override
@@ -1316,7 +1317,7 @@ public class ManagerKeycloakIdentityProvider extends KeycloakIdentityProvider im
if (container.isDevMode()) {
headers.computeIfPresent("contentSecurityPolicy", (hdrName, hdrValue) -> "frame-src *; frame-ancestors *; object-src 'none'");
} else {
- String allowedOriginsStr = String.join(" ", WebService.getAllowedOrigins(container));
+ String allowedOriginsStr = String.join(" ", CORSConfig.getCorsAllowedOriginsFromConfig());
if (!TextUtil.isNullOrEmpty(allowedOriginsStr)) {
headers.compute("contentSecurityPolicy", (hdrName, hdrValue) ->
"frame-src 'self' " +
diff --git a/manager/src/main/java/org/openremote/manager/setup/KeycloakInitService.java b/manager/src/main/java/org/openremote/manager/setup/KeycloakInitService.java
index 128696955..561587172 100644
--- a/manager/src/main/java/org/openremote/manager/setup/KeycloakInitService.java
+++ b/manager/src/main/java/org/openremote/manager/setup/KeycloakInitService.java
@@ -41,8 +41,8 @@ import static jakarta.ws.rs.core.Response.Status.Family.SUCCESSFUL;
import static org.openremote.container.security.IdentityService.OR_IDENTITY_PROVIDER;
import static org.openremote.container.security.IdentityService.OR_IDENTITY_PROVIDER_DEFAULT;
import static org.openremote.container.security.keycloak.KeycloakIdentityProvider.*;
-import static org.openremote.container.util.MapAccess.getInteger;
-import static org.openremote.container.util.MapAccess.getString;
+import static org.openremote.model.util.MapAccess.getInteger;
+import static org.openremote.model.util.MapAccess.getString;
/**
* Service just to wait for keycloak availability
diff --git a/manager/src/main/java/org/openremote/manager/setup/ManagerSetup.java b/manager/src/main/java/org/openremote/manager/setup/ManagerSetup.java
index 751c70dc4..3488ee6ad 100644
--- a/manager/src/main/java/org/openremote/manager/setup/ManagerSetup.java
+++ b/manager/src/main/java/org/openremote/manager/setup/ManagerSetup.java
@@ -47,7 +47,7 @@ import java.nio.file.Paths;
import java.util.function.Function;
import java.util.function.Supplier;
-import static org.openremote.container.util.MapAccess.getString;
+import static org.openremote.model.util.MapAccess.getString;
import static org.openremote.model.Constants.*;
import static org.openremote.model.value.MetaItemType.*;
import static org.openremote.model.value.ValueType.*;
diff --git a/manager/src/main/java/org/openremote/manager/syslog/SyslogService.java b/manager/src/main/java/org/openremote/manager/syslog/SyslogService.java
index c87f8141a..f68c9be40 100644
--- a/manager/src/main/java/org/openremote/manager/syslog/SyslogService.java
+++ b/manager/src/main/java/org/openremote/manager/syslog/SyslogService.java
@@ -20,7 +20,7 @@
package org.openremote.manager.syslog;
import org.openremote.container.timer.TimerService;
-import org.openremote.container.util.MapAccess;
+import org.openremote.model.util.MapAccess;
import org.openremote.model.Container;
import org.openremote.model.ContainerService;
import org.openremote.container.persistence.PersistenceService;
diff --git a/manager/src/main/java/org/openremote/manager/system/HealthService.java b/manager/src/main/java/org/openremote/manager/system/HealthService.java
index 371137bbe..a2bbe5c5e 100644
--- a/manager/src/main/java/org/openremote/manager/system/HealthService.java
+++ b/manager/src/main/java/org/openremote/manager/system/HealthService.java
@@ -21,7 +21,7 @@ package org.openremote.manager.system;
import io.micrometer.prometheusmetrics.PrometheusMeterRegistry;
import io.prometheus.metrics.exporter.httpserver.HTTPServer;
-import org.openremote.container.util.MapAccess;
+import org.openremote.model.util.MapAccess;
import org.openremote.manager.web.ManagerWebService;
import org.openremote.model.Container;
import org.openremote.model.ContainerService;
diff --git a/manager/src/main/java/org/openremote/manager/system/SslHealthStatusProvider.java b/manager/src/main/java/org/openremote/manager/system/SslHealthStatusProvider.java
index 79e103671..ebbb9f224 100644
--- a/manager/src/main/java/org/openremote/manager/system/SslHealthStatusProvider.java
+++ b/manager/src/main/java/org/openremote/manager/system/SslHealthStatusProvider.java
@@ -34,8 +34,8 @@ import java.util.logging.Level;
import java.util.logging.Logger;
import static java.time.temporal.ChronoUnit.DAYS;
-import static org.openremote.container.util.MapAccess.getInteger;
-import static org.openremote.container.util.MapAccess.getString;
+import static org.openremote.model.util.MapAccess.getInteger;
+import static org.openremote.model.util.MapAccess.getString;
public class SslHealthStatusProvider implements X509TrustManager, HealthStatusProvider {
diff --git a/manager/src/main/java/org/openremote/manager/web/ManagerFileServlet.java b/manager/src/main/java/org/openremote/manager/web/ManagerFileServlet.java
deleted file mode 100644
index c09edcd3a..000000000
--- a/manager/src/main/java/org/openremote/manager/web/ManagerFileServlet.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * Copyright 2017, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.manager.web;
-
-import io.undertow.server.HttpHandler;
-import io.undertow.server.handlers.resource.PathResourceManager;
-import io.undertow.server.handlers.resource.ResourceManager;
-import io.undertow.servlet.Servlets;
-import io.undertow.servlet.api.DeploymentInfo;
-import io.undertow.servlet.api.FilterInfo;
-import io.undertow.servlet.api.ServletInfo;
-import io.undertow.servlet.util.ImmediateInstanceHandle;
-import org.openremote.model.Container;
-import org.openremote.container.web.file.FileServlet;
-import org.openremote.container.web.file.GzipResponseFilter;
-
-import jakarta.servlet.DispatcherType;
-import jakarta.servlet.Filter;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.logging.Logger;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-public class ManagerFileServlet extends FileServlet {
-
- private static final Logger LOG = Logger.getLogger(ManagerFileServlet.class.getName());
-
- public static final Map<String, String> MIME_TYPES = new HashMap<>() {
- {
- put("pbf", "application/x-protobuf");
- put("woff2", "font/woff2");
- put("wsdl", "application/xml");
- put("xsl", "text/xsl");
- }
- };
-
- public static final String[] FILE_EXTENSIONS_ALREADY_ZIPPED = {
- ".pbf"
- };
-
- public static final Map<String, Integer> MIME_TYPES_EXPIRE_SECONDS = new HashMap<String, Integer>() {
- {
- put("image/png", 60 * 60 * 12); // 12 hours
- put("image/jpg", 60 * 60 * 12); // 12 hours
- put("text/html", 0); // No cache
- put("text/xml", 1800);
- put("text/css", 1800);
- put("text/javascript", 60 * 60 * 12); // 12 hours
- put("application/javascript", 60 * 60 * 12); // 12 hours
- put("application/json", 1800);
- put("application/font-woff2", 60 * 60 * 12); // 12 hours
- put("application/x-protobuf", 60 * 60 * 12); // 12 hours
- }
- };
-
- public static final String[] MIME_TYPES_TO_ZIP = {
- "text/plain",
- "text/html",
- "text/xml",
- "text/css",
- "text/javascript",
- "text/csv",
- "text/rtf",
- "application/xml",
- "application/xhtml+xml",
- "application/javascript",
- "application/json",
- "image/svg+xml"
- };
-
- public ManagerFileServlet(boolean devMode,
- ResourceManager resourceManager,
- String[] requiredRoles) {
- super(devMode, resourceManager, requiredRoles, MIME_TYPES, MIME_TYPES_EXPIRE_SECONDS, FILE_EXTENSIONS_ALREADY_ZIPPED);
- }
-
- public static DeploymentInfo createDeploymentInfo(boolean devMode, String contextPath, ResourceManager resourceManager, String[] requiredRoles) {
- ManagerFileServlet fileServlet = new ManagerFileServlet(devMode, resourceManager, requiredRoles);
- ServletInfo servletInfo = Servlets.servlet("Manager File Servlet", FileServlet.class, () -> new ImmediateInstanceHandle<>(fileServlet));
- servletInfo.addMapping("/*");
-
- Filter gzipFilter = new GzipResponseFilter(MIME_TYPES_TO_ZIP);
- FilterInfo gzipFilterInfo = Servlets.filter("Gzip Filter", GzipResponseFilter.class, () -> new ImmediateInstanceHandle<>(gzipFilter))
- .setAsyncSupported(true);
-
- return new DeploymentInfo()
- .setDeploymentName(contextPath + " File Servlet Deployment")
- .setContextPath(contextPath)
- .addServlet(servletInfo)
- .addFilter(gzipFilterInfo)
- .addFilterUrlMapping(gzipFilterInfo.getName(), "/*", DispatcherType.REQUEST)
- .setClassLoader(Container.class.getClassLoader());
- }
-
- /**
- * This handler corrects the request path, using the matching group 1 of the pattern as the request path.
- */
- public static HttpHandler wrapHandler(HttpHandler wrapped, Pattern requestPattern) {
- return exchange -> {
- String requestPath = exchange.getRequestPath();
- Matcher staticMatcher = requestPattern.matcher(requestPath);
- if (staticMatcher.matches()) {
- LOG.finest("Serving static resource: " + requestPath);
- String remaining = staticMatcher.group(1);
- String relativePath = remaining == null || remaining.isEmpty() ? "/" : remaining;
- exchange.setRelativePath(relativePath);
- wrapped.handleRequest(exchange);
- }
- };
- }
-}
diff --git a/manager/src/main/java/org/openremote/manager/web/ManagerWebService.java b/manager/src/main/java/org/openremote/manager/web/ManagerWebService.java
index db95b66b3..9c1a867ae 100644
--- a/manager/src/main/java/org/openremote/manager/web/ManagerWebService.java
+++ b/manager/src/main/java/org/openremote/manager/web/ManagerWebService.java
@@ -32,26 +32,13 @@ import io.swagger.v3.oas.models.security.*;
import io.swagger.v3.oas.models.servers.Server;
import io.swagger.v3.oas.models.servers.ServerVariable;
import io.swagger.v3.oas.models.servers.ServerVariables;
-import io.undertow.server.HttpHandler;
-import io.undertow.server.handlers.CanonicalPathHandler;
-import io.undertow.server.handlers.PathHandler;
import io.undertow.server.handlers.RedirectHandler;
-import io.undertow.server.handlers.resource.ClassPathResourceManager;
-import io.undertow.server.handlers.resource.PathResourceManager;
-import io.undertow.server.handlers.resource.ResourceManager;
-import io.undertow.servlet.Servlets;
-import io.undertow.servlet.api.DeploymentInfo;
-import io.undertow.servlet.api.ServletInfo;
-import io.undertow.util.HttpString;
-import org.jboss.resteasy.plugins.server.servlet.HttpServlet30Dispatcher;
-import org.jboss.resteasy.spi.ResteasyDeployment;
-import org.openremote.container.security.IdentityService;
-import org.openremote.container.web.WebService;
+import jakarta.ws.rs.core.Application;
+import org.openremote.container.web.*;
import org.openremote.model.Container;
+import org.openremote.model.util.Config;
+import org.openremote.model.util.TextUtil;
-import jakarta.ws.rs.WebApplicationException;
-
-import java.net.URI;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -61,14 +48,9 @@ import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
+import java.util.stream.Stream;
-import static io.undertow.util.RedirectBuilder.redirect;
-import static jakarta.ws.rs.core.Response.Status.NOT_FOUND;
-import static jakarta.ws.rs.core.UriBuilder.fromUri;
-import static org.openremote.container.util.MapAccess.getString;
-import static org.openremote.model.Constants.REALM_PARAM_NAME;
+import static org.openremote.model.util.MapAccess.getString;
import static org.openremote.model.util.ValueUtil.configureObjectMapper;
public class ManagerWebService extends WebService {
@@ -92,19 +74,7 @@ public class ManagerWebService extends WebService {
public static final String OR_ROOT_REDIRECT_PATH_DEFAULT = "/manager";
public static final String API_PATH = "/api";
- public static final String MANAGER_APP_PATH = "/manager";
- public static final String INSIGHTS_APP_PATH = "/insights";
- public static final String STORYBOOK_APP_PATH = "/storybook";
- public static final String SWAGGER_APP_PATH = "/swagger";
- public static final String SHARED_PATH = "/shared";
-
- public static final List<String> APP_PATHS = List.of(MANAGER_APP_PATH, INSIGHTS_APP_PATH, STORYBOOK_APP_PATH, SWAGGER_APP_PATH, SHARED_PATH);
-
- public static final String UI_CLASSPATH_PREFIX = "org/openremote/web";
-
private static final Logger LOG = Logger.getLogger(ManagerWebService.class.getName());
- protected static final Pattern PATTERN_REALM_SUB = Pattern.compile("/([a-zA-Z0-9\\-_]+)/(.*)");
-
protected boolean initialised;
protected Path builtInAppDocRoot;
protected Path customAppDocRoot;
@@ -122,101 +92,57 @@ public class ManagerWebService extends WebService {
@Override
public void init(Container container) throws Exception {
super.init(container);
-
+ Set<ResourceSource> resourceSources = new HashSet<>();
+ builtInAppDocRoot = Paths.get(getString(container.getConfig(), OR_APP_DOCROOT, OR_APP_DOCROOT_DEFAULT));
+ customAppDocRoot = Paths.get(getString(container.getConfig(), OR_CUSTOM_APP_DOCROOT, OR_CUSTOM_APP_DOCROOT_DEFAULT));
String rootRedirectPath = getString(container.getConfig(), OR_ROOT_REDIRECT_PATH, OR_ROOT_REDIRECT_PATH_DEFAULT);
- addOpenApiResource();
-
- initialised = true;
- ResteasyDeployment resteasyDeployment = createResteasyDeployment(container, getApiClasses(), apiSingletons, true);
-
- // Serve REST API
- HttpHandler apiHandler = createApiHandler(container, resteasyDeployment);
-
- if (apiHandler != null) {
-
- // Authenticating requests requires a realm, either we receive this in a header or
- // we extract it (e.g. from request path segment) and set it as a header before
- // processing the request
- HttpHandler baseApiHandler = apiHandler;
-
- apiHandler = exchange -> {
-
- String path = exchange.getRelativePath().substring(API_PATH.length());
- Matcher realmSubMatcher = PATTERN_REALM_SUB.matcher(path);
-
- if (!realmSubMatcher.matches()) {
- exchange.setStatusCode(NOT_FOUND.getStatusCode());
- throw new WebApplicationException(NOT_FOUND);
- }
-
- // Extract realm from path and push it into REQUEST_HEADER_REALM header
- String realm = realmSubMatcher.group(1);
-
- // Move the realm from path segment to header
- exchange.getRequestHeaders().put(HttpString.tryFromString(REALM_PARAM_NAME), realm);
-
- URI url = fromUri(exchange.getRequestURL())
- .replacePath(realmSubMatcher.group(2))
- .build();
- exchange.setRequestURI(url.toString(), true);
- exchange.setRequestPath(url.getPath());
- exchange.setRelativePath(url.getPath());
-
- baseApiHandler.handleRequest(exchange);
- };
+ // Add a handler to redirect requests for the exact root path "/" to the configured default path
+ if (!TextUtil.isNullOrEmpty(rootRedirectPath)) {
+ LOG.info("Adding root redirect to: " + rootRedirectPath);
+ pathHandler.addExactPath("/", new RedirectHandler(rootRedirectPath));
}
- // Serve deployment files unsecured (explicitly map deployment folders to request paths)
- builtInAppDocRoot = Paths.get(getString(container.getConfig(), OR_APP_DOCROOT, OR_APP_DOCROOT_DEFAULT));
- customAppDocRoot = Paths.get(getString(container.getConfig(), OR_CUSTOM_APP_DOCROOT, OR_CUSTOM_APP_DOCROOT_DEFAULT));
-
- HttpHandler defaultHandler = null;
+ // Include Open API resource
+ addApiSingleton(getOpenApiResource());
- if (Files.isDirectory(customAppDocRoot)) {
- HttpHandler customBaseFileHandler = createFileHandler(container, new PathResourceManager(customAppDocRoot), null);
- defaultHandler = exchange -> {
- if (exchange.getRelativePath().isEmpty() || "/".equals(exchange.getRelativePath())) {
- exchange.setRelativePath("/index.html");
- }
- customBaseFileHandler.handleRequest(exchange);
- };
- }
+ initialised = true;
- PathHandler deploymentHandler = defaultHandler != null ? new PathHandler(defaultHandler) : new PathHandler();
+ // Configure the JAX-RS Manager API including resources added at startup
+ List<Object> singletons = Stream.of(getStandardProviders(devMode, 0), apiSingletons)
+ .flatMap(Collection::stream)
+ .toList();
+ Application application = new WebApplication(container, apiClasses, singletons);
- serveFilesFromBuiltInAppDocRoot(container, deploymentHandler);
- serveFilesFromClassPath(container, deploymentHandler);
+ deployJaxRsApplication(application, API_PATH, "Manager HTTP API", 0, true, null);
- // Add all route handlers required by the manager in priority order
+ if (Files.isDirectory(builtInAppDocRoot)) {
+ resourceSources.add(new FileResource(builtInAppDocRoot));
+ } else {
+ LOG.info("Built in app doc root does not exist: " + builtInAppDocRoot.toAbsolutePath());
+ }
- // Redirect / to default app
- if (rootRedirectPath != null) {
- getRequestHandlers().add(
- new RequestHandler(
- "Default app redirect",
- exchange -> exchange.getRequestPath().equals("/"),
- exchange -> {
- LOG.finest("Handling root request, redirecting client to default app");
- new RedirectHandler(redirect(exchange, rootRedirectPath)).handleRequest(exchange);
- }));
+ // Serve manager app from classpath if we are in dev mode (outside of docker) and it can be found
+ // this is used by custom projects so that they can serve the manager UI while running in an IDE
+ if (Config.isDevMode()) {
+ URL url = ManagerWebService.class.getClassLoader().getResource("org/openremote/web/manager");
+ if (url != null) {
+ resourceSources.add(new ClassPathResource(getClass().getClassLoader(), "org/openremote/web"));
+ }
}
- if (apiHandler != null) {
- getRequestHandlers().add(pathStartsWithHandler("REST API Handler", API_PATH, apiHandler));
+ // If custom app docroot is a directory then make it the default file handler
+ if (customAppDocRoot != null && Files.isDirectory(customAppDocRoot)) {
+ resourceSources.add(new FileResource(customAppDocRoot));
+ } else if (customAppDocRoot != null) {
+ LOG.info("Custom app doc root does not exist: " + customAppDocRoot.toAbsolutePath());
}
- // This will try and handle any request that makes it to this handler
- getRequestHandlers().add(
- new RequestHandler(
- "Deployment files",
- exchange -> true,
- deploymentHandler
- )
- );
+ // Deploy static app files unsecured
+ deployFileServlet("/", "App Files", resourceSources.toArray(ResourceSource[]::new), null, null);
}
- private void addOpenApiResource() {
+ protected Object getOpenApiResource() {
// Modify swagger object mapper to match ours
configureObjectMapper(Json.mapper());
Json.mapper().addMixIn(StringSchema.class, StringSchemaMixin.class);
@@ -244,9 +170,9 @@ public class ManagerWebService extends WebService {
)).security(List.of(new SecurityRequirement().addList("openid")));
Info info = new Info()
- .title("OpenRemote Manager REST API")
+ .title("OpenRemote Manager HTTP API")
.version("3.0.0")
- .description("This is the documentation for the OpenRemote Manager HTTP REST API. Please see the [documentation](https://docs.openremote.io) for more info.")
+ .description("This is the documentation for the OpenRemote Manager HTTP API. Please see the [documentation](https://docs.openremote.io) for more info.")
.contact(new Contact().email("[email protected]"))
.license(new License().name("AGPL 3.0").url("https://www.gnu.org/licenses/agpl-3.0.en.html"));
@@ -257,58 +183,17 @@ public class ManagerWebService extends WebService {
.defaultResponseCode("200");
OpenApiResource openApiResource = new OpenApiResource();
openApiResource.openApiConfiguration(oasConfig);
- addApiSingleton(openApiResource);
- }
-
- protected void serveFilesFromBuiltInAppDocRoot(Container container, PathHandler deploymentHandler) {
- if (Files.isDirectory(builtInAppDocRoot)) {
- HttpHandler appBaseFileHandler = createFileHandler(container, new PathResourceManager(builtInAppDocRoot), null);
- HttpHandler appFileHandler = exchange -> {
- if (exchange.getRelativePath().isEmpty() || "/".equals(exchange.getRelativePath())) {
- exchange.setRelativePath("/index.html");
- }
-
- // Reinstate the full path
- exchange.setRelativePath(exchange.getRequestPath());
- appBaseFileHandler.handleRequest(exchange);
- };
-
- APP_PATHS.forEach(path -> {
- Path diskPath = builtInAppDocRoot.resolve(path.substring(1));
- if (Files.isDirectory(diskPath)) {
- deploymentHandler.addPrefixPath(path, appFileHandler);
- LOG.info("Serving " + path + " from disk: " + diskPath.toAbsolutePath());
- }
- });
- }
- }
-
- protected void serveFilesFromClassPath(Container container, PathHandler deploymentHandler) {
- HttpHandler classPathFileHandler = createFileHandler(container, new ClassPathResourceManager(ManagerWebService.class.getClassLoader(), UI_CLASSPATH_PREFIX), null);
- HttpHandler appFileHandler = exchange -> {
- if (exchange.getRelativePath().isEmpty() || "/".equals(exchange.getRelativePath())) {
- exchange.setRelativePath("index.html");
- }
-
- // Reinstate the full path
- exchange.setRelativePath(exchange.getRequestPath());
- classPathFileHandler.handleRequest(exchange);
- };
-
- APP_PATHS.forEach(path -> {
- URL url = ManagerWebService.class.getClassLoader().getResource(UI_CLASSPATH_PREFIX + path);
- if (url != null) {
- deploymentHandler.addPrefixPath(path, appFileHandler);
- LOG.info("Serving " + path + " from classpath: " + url);
- }
- });
+ return openApiResource;
}
/**
* Add resource/provider/etc. classes to enable REST API
*/
- public Collection<Class<?>> getApiClasses() {
- return apiClasses;
+ public void addApiClasses(Class<?> apiClass) {
+ if (this.initialised) {
+ throw new IllegalStateException("API classes must be added before the service is initialised");
+ }
+ apiClasses.add(apiClass);
}
/**
@@ -329,40 +214,6 @@ public class ManagerWebService extends WebService {
return customAppDocRoot;
}
- protected HttpHandler createApiHandler(Container container, ResteasyDeployment resteasyDeployment) {
- if (resteasyDeployment == null)
- return null;
-
- ServletInfo restServlet = Servlets.servlet("RESTEasy Servlet", HttpServlet30Dispatcher.class)
- .setAsyncSupported(true)
- .setLoadOnStartup(1)
- .addMapping("/*");
-
- DeploymentInfo deploymentInfo = new DeploymentInfo()
- .setDeploymentName("RESTEasy Deployment")
- .setContextPath(API_PATH)
- .addServletContextAttribute(ResteasyDeployment.class.getName(), resteasyDeployment)
- .addServlet(restServlet)
- .setClassLoader(Container.class.getClassLoader());
-
- IdentityService identityService = container.getService(IdentityService.class);
-
- if (identityService != null) {
- resteasyDeployment.setSecurityEnabled(true);
- } else {
- throw new RuntimeException("No identity service deployed, can't enable API security");
- }
-
- return addServletDeployment(container, deploymentInfo, resteasyDeployment.isSecurityEnabled());
- }
-
- public static HttpHandler createFileHandler(Container container, ResourceManager resourceManager, String[] requiredRoles) {
- boolean devMode = container.isDevMode();
- requiredRoles = requiredRoles == null ? new String[0] : requiredRoles;
- DeploymentInfo deploymentInfo = ManagerFileServlet.createDeploymentInfo(devMode, "", resourceManager, requiredRoles);
- return new CanonicalPathHandler(addServletDeployment(container, deploymentInfo, requiredRoles.length != 0));
- }
-
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
diff --git a/manager/src/main/java/org/openremote/manager/webhook/WebhookService.java b/manager/src/main/java/org/openremote/manager/webhook/WebhookService.java
index ae97dd12f..e40181f2a 100644
--- a/manager/src/main/java/org/openremote/manager/webhook/WebhookService.java
+++ b/manager/src/main/java/org/openremote/manager/webhook/WebhookService.java
@@ -38,7 +38,7 @@ import java.net.URI;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
-import static org.openremote.container.util.MapAccess.getInteger;
+import static org.openremote.model.util.MapAccess.getInteger;
public class WebhookService extends RouteBuilder implements ContainerService {
diff --git a/model/src/main/java/org/openremote/model/Container.java b/model/src/main/java/org/openremote/model/Container.java
index 40e28aa55..3851cb225 100644
--- a/model/src/main/java/org/openremote/model/Container.java
+++ b/model/src/main/java/org/openremote/model/Container.java
@@ -30,11 +30,6 @@ import java.util.concurrent.ScheduledExecutorService;
@TsIgnore
public interface Container {
- String OR_DEV_MODE = "OR_DEV_MODE";
- boolean OR_DEV_MODE_DEFAULT = true;
- String OR_METRICS_ENABLED = "OR_METRICS_ENABLED";
- boolean OR_METRICS_ENABLED_DEFAULT = false;
-
boolean isDevMode();
Map<String, String> getConfig();
diff --git a/model/src/main/java/org/openremote/model/map/MapResource.java b/model/src/main/java/org/openremote/model/map/MapResource.java
index e95b2464c..a597c6980 100644
--- a/model/src/main/java/org/openremote/model/map/MapResource.java
+++ b/model/src/main/java/org/openremote/model/map/MapResource.java
@@ -71,7 +71,7 @@ public interface MapResource {
@Produces("application/vnd.mapbox-vector-tile")
@Path("tile/{zoom}/{column}/{row}")
@Operation(operationId = "getTile", summary = "Retrieve the vector tile data for Mapbox GL")
- byte[] getTile(@PathParam("zoom")int zoom, @PathParam("column")int column, @PathParam("row")int row);
+ Response getTile(@PathParam("zoom")int zoom, @PathParam("column")int column, @PathParam("row")int row);
/**
* Saves mbtiles file
diff --git a/model/src/main/java/org/openremote/model/util/Config.java b/model/src/main/java/org/openremote/model/util/Config.java
new file mode 100644
index 000000000..64ab2c447
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/util/Config.java
@@ -0,0 +1,101 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.util;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
+
+/**
+ * A simple utility for overlaying runtime configuration on top of {@link System#getenv()} env config. The application
+ * is responsible for injecting the additional config at the earliest opportunity before it is consumed by other code.
+ */
+public class Config {
+
+ public static final String OR_DEV_MODE = "OR_DEV_MODE";
+ public static final boolean OR_DEV_MODE_DEFAULT = true;
+ public static final String OR_METRICS_ENABLED = "OR_METRICS_ENABLED";
+ public static final boolean OR_METRICS_ENABLED_DEFAULT = false;
+ protected static Map<String, String> config;
+ protected static Map<String, Object> parsedConfig;
+
+ static {
+ init(null);
+ }
+
+ /**
+ * Inject additional config that is merged with {@link System#getenv()}
+ */
+ public static void init(Map<String, String> configOverlay) {
+ parsedConfig = new HashMap<>();
+ Map<String, String> mergedConfig = new HashMap<>(System.getenv());
+ if (configOverlay != null) {
+ mergedConfig.putAll(configOverlay);
+ }
+ mergedConfig.values().removeIf(TextUtil::isNullOrEmpty);
+ config = mergedConfig;
+ }
+
+ public static Map<String, String> get() {
+ return config;
+ }
+
+ @SuppressWarnings("unchecked")
+ public static <T> T get(String key, Class<T> type, T defaultValue) {
+ Object parsedValue = parsedConfig.get(key);
+ if (parsedValue != null) {
+ try {
+ return (T) parsedValue;
+ } catch (ClassCastException e) {
+ parsedConfig.remove(key);
+ }
+ }
+
+ String valueStr = config.get(key);
+ if (valueStr != null) {
+ T result = ValueUtil.getValueCoerced(valueStr, type).orElse(null);
+ if (result != null) {
+ parsedConfig.put(key, result);
+ }
+ return result;
+ }
+ return defaultValue;
+ }
+
+ public static boolean containsKey(String key) {
+ return config.containsKey(key);
+ }
+
+ public static boolean getBoolean(String key, boolean defaultValue) {
+ return Optional.ofNullable(get(key, Boolean.class, defaultValue)).orElse(defaultValue);
+ }
+
+ public static int getInt(String key, int defaultValue) {
+ return Optional.ofNullable(get(key, Integer.class, defaultValue)).orElse(defaultValue);
+ }
+
+ public static String getString(String key, String defaultValue) {
+ return MapAccess.getString(config, key, defaultValue);
+ }
+
+ public static boolean isDevMode() {
+ return getBoolean(OR_DEV_MODE, OR_DEV_MODE_DEFAULT);
+ }
+}
diff --git a/container/src/main/java/org/openremote/container/util/MapAccess.java b/model/src/main/java/org/openremote/model/util/MapAccess.java
similarity index 98%
rename from container/src/main/java/org/openremote/container/util/MapAccess.java
rename to model/src/main/java/org/openremote/model/util/MapAccess.java
index b9eb7c847..629bc228b 100644
--- a/container/src/main/java/org/openremote/container/util/MapAccess.java
+++ b/model/src/main/java/org/openremote/model/util/MapAccess.java
@@ -17,7 +17,7 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-package org.openremote.container.util;
+package org.openremote.model.util;
import java.math.BigDecimal;
import java.util.Map;
@@ -67,4 +67,4 @@ public class MapAccess {
return defaultValue;
}
-}
\ No newline at end of file
+}
diff --git a/setup/src/demo/java/org/openremote/setup/demo/ManagerDemoAgentSetup.java b/setup/src/demo/java/org/openremote/setup/demo/ManagerDemoAgentSetup.java
index 11a102625..07f3b6a92 100644
--- a/setup/src/demo/java/org/openremote/setup/demo/ManagerDemoAgentSetup.java
+++ b/setup/src/demo/java/org/openremote/setup/demo/ManagerDemoAgentSetup.java
@@ -21,7 +21,7 @@ package org.openremote.setup.demo;
import org.openremote.agent.protocol.knx.KNXAgent;
import org.openremote.agent.protocol.velbus.VelbusTCPAgent;
-import org.openremote.container.util.MapAccess;
+import org.openremote.model.util.MapAccess;
import org.openremote.manager.setup.ManagerSetup;
import org.openremote.model.Container;
import org.openremote.model.security.Realm;
diff --git a/setup/src/integration/java/org/openremote/setup/integration/ManagerTestAgentSetup.java b/setup/src/integration/java/org/openremote/setup/integration/ManagerTestAgentSetup.java
index 9c893d201..1e5cd0d21 100644
--- a/setup/src/integration/java/org/openremote/setup/integration/ManagerTestAgentSetup.java
+++ b/setup/src/integration/java/org/openremote/setup/integration/ManagerTestAgentSetup.java
@@ -27,7 +27,7 @@ import org.openremote.model.security.Realm;
import java.util.logging.Logger;
-import static org.openremote.container.util.MapAccess.*;
+import static org.openremote.model.util.MapAccess.*;
public class ManagerTestAgentSetup extends ManagerSetup {
diff --git a/setup/src/load1/java/org/openremote/setup/load1/KeycloakSetup.java b/setup/src/load1/java/org/openremote/setup/load1/KeycloakSetup.java
index 344d3cf9e..bac54c189 100644
--- a/setup/src/load1/java/org/openremote/setup/load1/KeycloakSetup.java
+++ b/setup/src/load1/java/org/openremote/setup/load1/KeycloakSetup.java
@@ -30,7 +30,7 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;
-import static org.openremote.container.util.MapAccess.getInteger;
+import static org.openremote.model.util.MapAccess.getInteger;
import static org.openremote.model.Constants.KEYCLOAK_CLIENT_ID;
import static org.openremote.model.Constants.MASTER_REALM;
diff --git a/setup/src/load1/java/org/openremote/setup/load1/ManagerSetup.java b/setup/src/load1/java/org/openremote/setup/load1/ManagerSetup.java
index f4b6709be..4fe2cbda5 100644
--- a/setup/src/load1/java/org/openremote/setup/load1/ManagerSetup.java
+++ b/setup/src/load1/java/org/openremote/setup/load1/ManagerSetup.java
@@ -43,7 +43,7 @@ import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;
-import static org.openremote.container.util.MapAccess.getInteger;
+import static org.openremote.model.util.MapAccess.getInteger;
import static org.openremote.manager.mqtt.UserAssetProvisioningMQTTHandler.UNIQUE_ID_PLACEHOLDER;
import static org.openremote.model.rules.Ruleset.Lang.GROOVY;
import static org.openremote.model.value.ValueType.NUMBER;
diff --git a/test/src/main/groovy/org/openremote/test/ContainerTrait.groovy b/test/src/main/groovy/org/openremote/test/ContainerTrait.groovy
index 972c8e9e5..348f51e19 100644
--- a/test/src/main/groovy/org/openremote/test/ContainerTrait.groovy
+++ b/test/src/main/groovy/org/openremote/test/ContainerTrait.groovy
@@ -36,7 +36,7 @@ import org.openremote.container.security.PasswordAuthForm
import org.openremote.container.security.keycloak.KeycloakIdentityProvider
import org.openremote.container.timer.TimerService
import org.openremote.container.util.LogUtil
-import org.openremote.container.util.MapAccess
+import org.openremote.model.util.MapAccess
import org.openremote.container.web.WebClient
import org.openremote.manager.agent.AgentService
import org.openremote.manager.asset.AssetProcessingService
@@ -264,7 +264,7 @@ trait ContainerTrait {
}
long endTime = System.currentTimeMillis()
- LOG.info("Container reuse took: " + (startTime - endTime) + "ms")
+ LOG.info("Container reuse took: " + (endTime - startTime) + "ms")
} catch (IllegalStateException e) {
LOG.info("Failed to clean the existing container so creating a new one", e)
stopContainer()
diff --git a/test/src/test/groovy/org/openremote/test/alarm/AlarmResourceTest.groovy b/test/src/test/groovy/org/openremote/test/alarm/AlarmResourceTest.groovy
index 01be13fcd..3f1883082 100644
--- a/test/src/test/groovy/org/openremote/test/alarm/AlarmResourceTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/alarm/AlarmResourceTest.groovy
@@ -43,7 +43,7 @@ import spock.util.concurrent.PollingConditions
import static org.openremote.container.security.IdentityProvider.OR_ADMIN_PASSWORD
import static org.openremote.container.security.IdentityProvider.OR_ADMIN_PASSWORD_DEFAULT
-import static org.openremote.container.util.MapAccess.getString
+import static org.openremote.model.util.MapAccess.getString
import static org.openremote.model.Constants.KEYCLOAK_CLIENT_ID
import static org.openremote.model.Constants.MASTER_REALM
import static org.openremote.model.Constants.MASTER_REALM_ADMIN_USER
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy
index f426a443d..578322c88 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy
@@ -22,7 +22,7 @@ import spock.util.concurrent.PollingConditions
import java.util.concurrent.TimeUnit
-import static org.openremote.container.util.MapAccess.getString
+import static org.openremote.model.util.MapAccess.getString
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD_DEFAULT
import static org.openremote.model.Constants.*
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy
index 8c0f7e9fc..e213b82eb 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy
@@ -17,7 +17,7 @@ import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
-import static org.openremote.container.util.MapAccess.getString
+import static org.openremote.model.util.MapAccess.getString
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD_DEFAULT
import static org.openremote.model.Constants.*
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetTreeTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetTreeTest.groovy
index 162119127..ff0fe511a 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetTreeTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetTreeTest.groovy
@@ -17,7 +17,7 @@ import spock.util.concurrent.PollingConditions
import java.util.concurrent.CopyOnWriteArrayList
import java.util.function.Consumer
-import static org.openremote.container.util.MapAccess.getString
+import static org.openremote.model.util.MapAccess.getString
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD_DEFAULT
import static org.openremote.model.Constants.*
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetUserLinkingTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetUserLinkingTest.groovy
index 7fdd6f989..5ffa647e3 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetUserLinkingTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetUserLinkingTest.groovy
@@ -14,7 +14,7 @@ import spock.lang.Specification
import jakarta.ws.rs.WebApplicationException
-import static org.openremote.container.util.MapAccess.getString
+import static org.openremote.model.util.MapAccess.getString
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD_DEFAULT
import static org.openremote.model.Constants.*
diff --git a/test/src/test/groovy/org/openremote/test/benchmark/AttributeEventBenchmarkTest.groovy b/test/src/test/groovy/org/openremote/test/benchmark/AttributeEventBenchmarkTest.groovy
index 05abdeea2..e3e03e5ef 100644
--- a/test/src/test/groovy/org/openremote/test/benchmark/AttributeEventBenchmarkTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/benchmark/AttributeEventBenchmarkTest.groovy
@@ -43,8 +43,8 @@ import spock.util.concurrent.PollingConditions
import java.util.concurrent.CopyOnWriteArrayList
import java.util.function.Consumer
-import static org.openremote.container.util.MapAccess.getInteger
-import static org.openremote.container.util.MapAccess.getString
+import static org.openremote.model.util.MapAccess.getInteger
+import static org.openremote.model.util.MapAccess.getString
import static org.openremote.manager.mqtt.MQTTBrokerService.*
/**
diff --git a/test/src/test/groovy/org/openremote/test/dashboard/DashboardTest.groovy b/test/src/test/groovy/org/openremote/test/dashboard/DashboardTest.groovy
index 47505754a..e3ff6251d 100644
--- a/test/src/test/groovy/org/openremote/test/dashboard/DashboardTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/dashboard/DashboardTest.groovy
@@ -10,9 +10,7 @@ import org.openremote.model.asset.impl.LightAsset
import org.openremote.model.attribute.MetaItem
import org.openremote.model.dashboard.*
import org.openremote.model.query.DashboardQuery
-import org.openremote.model.query.UserQuery
import org.openremote.model.query.filter.RealmPredicate
-import org.openremote.model.query.filter.StringPredicate
import org.openremote.model.security.ClientRole
import org.openremote.model.security.User
import org.openremote.model.security.UserResource
@@ -24,7 +22,7 @@ import spock.lang.Specification
import static org.openremote.container.security.IdentityProvider.OR_ADMIN_PASSWORD
import static org.openremote.container.security.IdentityProvider.OR_ADMIN_PASSWORD_DEFAULT
-import static org.openremote.container.util.MapAccess.getString
+import static org.openremote.model.util.MapAccess.getString
import static org.openremote.model.Constants.*
class DashboardTest extends Specification implements ManagerContainerTrait {
diff --git a/test/src/test/groovy/org/openremote/test/energy/EnergyOptimisationAssetTest.groovy b/test/src/test/groovy/org/openremote/test/energy/EnergyOptimisationAssetTest.groovy
index 2b7e110de..ed6f84028 100644
--- a/test/src/test/groovy/org/openremote/test/energy/EnergyOptimisationAssetTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/energy/EnergyOptimisationAssetTest.groovy
@@ -15,6 +15,7 @@ import org.openremote.model.datapoint.query.AssetDatapointIntervalQuery
import org.openremote.model.util.ValueUtil
import org.openremote.setup.integration.ManagerTestSetup
import org.openremote.test.ManagerContainerTrait
+import spock.lang.Ignore
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
@@ -45,6 +46,7 @@ import static spock.util.matcher.HamcrestMatchers.closeTo
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
+@Ignore
class EnergyOptimisationAssetTest extends Specification implements ManagerContainerTrait {
def "Test storage asset with consumer and producer"() {
diff --git a/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovy b/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovy
index 9f751c415..dd624cb64 100644
--- a/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovy
@@ -53,7 +53,7 @@ import java.util.function.Consumer
import java.util.stream.Collectors
import java.util.stream.IntStream
-import static org.openremote.container.util.MapAccess.getString
+import static org.openremote.model.util.MapAccess.getString
import static org.openremote.manager.gateway.GatewayConnector.mapAssetId
import static org.openremote.manager.gateway.GatewayService.getGatewayClientId
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD
diff --git a/test/src/test/groovy/org/openremote/test/map/MapResourceTest.groovy b/test/src/test/groovy/org/openremote/test/map/MapResourceTest.groovy
index 8d0c8441a..f10a13668 100644
--- a/test/src/test/groovy/org/openremote/test/map/MapResourceTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/map/MapResourceTest.groovy
@@ -17,7 +17,7 @@ import spock.util.concurrent.PollingConditions
import java.nio.file.Files
import java.nio.file.Path
-import static org.openremote.container.util.MapAccess.getString
+import static org.openremote.model.util.MapAccess.getString
import static org.openremote.manager.security.ManagerIdentityProvider.*
import static org.openremote.model.Constants.*
diff --git a/test/src/test/groovy/org/openremote/test/metrics/MetricsEndpointTest.groovy b/test/src/test/groovy/org/openremote/test/metrics/MetricsEndpointTest.groovy
index c9ab1111d..e996e92af 100644
--- a/test/src/test/groovy/org/openremote/test/metrics/MetricsEndpointTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/metrics/MetricsEndpointTest.groovy
@@ -2,7 +2,7 @@ package org.openremote.test.metrics
import org.openremote.manager.system.HealthService
-import org.openremote.model.Container
+import org.openremote.model.util.Config
import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
@@ -17,7 +17,7 @@ class MetricsEndpointTest extends Specification implements ManagerContainerTrait
def conditions = new PollingConditions(timeout: 10, delay: 0.2)
and: "the container is started"
- def container = startContainer(defaultConfig() << [(Container.OR_METRICS_ENABLED): "true"], defaultServices())
+ def container = startContainer(defaultConfig() << [(Config.OR_METRICS_ENABLED): "true"], defaultServices())
and: "a resource client is created"
// Resteasy client has issues with @Suspended annotation so not used for now
diff --git a/test/src/test/groovy/org/openremote/test/model/AssetModelTest.groovy b/test/src/test/groovy/org/openremote/test/model/AssetModelTest.groovy
index 54238d37e..c299208de 100644
--- a/test/src/test/groovy/org/openremote/test/model/AssetModelTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/model/AssetModelTest.groovy
@@ -1,6 +1,6 @@
package org.openremote.test.model
-import com.fasterxml.jackson.databind.JsonNode
+
import com.fasterxml.jackson.databind.node.ObjectNode
import jakarta.ws.rs.WebApplicationException
import org.jboss.resteasy.api.validation.ViolationReport
@@ -47,7 +47,7 @@ import java.time.temporal.ChronoUnit
import static org.openremote.container.security.IdentityProvider.OR_ADMIN_PASSWORD
import static org.openremote.container.security.IdentityProvider.OR_ADMIN_PASSWORD_DEFAULT
-import static org.openremote.container.util.MapAccess.getString
+import static org.openremote.model.util.MapAccess.getString
import static org.openremote.model.Constants.*
import static org.openremote.model.value.ValueType.BIG_NUMBER
diff --git a/test/src/test/groovy/org/openremote/test/mqtt/MqttBrokerTest.groovy b/test/src/test/groovy/org/openremote/test/mqtt/MqttBrokerTest.groovy
index 56605136b..5807c40b1 100644
--- a/test/src/test/groovy/org/openremote/test/mqtt/MqttBrokerTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/mqtt/MqttBrokerTest.groovy
@@ -35,8 +35,8 @@ import spock.util.concurrent.PollingConditions
import java.util.concurrent.CopyOnWriteArrayList
import java.util.function.Consumer
-import static org.openremote.container.util.MapAccess.getInteger
-import static org.openremote.container.util.MapAccess.getString
+import static org.openremote.model.util.MapAccess.getInteger
+import static org.openremote.model.util.MapAccess.getString
import static org.openremote.manager.mqtt.MQTTBrokerService.*
import static org.openremote.model.value.MetaItemType.ACCESS_RESTRICTED_READ
import static org.openremote.model.value.ValueType.TEXT
diff --git a/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy b/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy
index 07e4c7b27..26980d6bc 100644
--- a/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy
@@ -23,10 +23,7 @@ import org.openremote.model.console.ConsoleProvider
import org.openremote.model.console.ConsoleRegistration
import org.openremote.model.console.ConsoleResource
import org.openremote.model.notification.*
-import org.openremote.model.query.UserQuery
-import org.openremote.model.query.filter.RealmPredicate
import org.openremote.model.security.User
-import org.openremote.model.util.TextUtil
import org.openremote.setup.integration.KeycloakTestSetup
import org.openremote.setup.integration.ManagerTestSetup
import org.openremote.test.ManagerContainerTrait
@@ -37,7 +34,7 @@ import java.time.Instant
import java.time.temporal.ChronoUnit
import java.util.concurrent.TimeUnit
-import static org.openremote.container.util.MapAccess.getString
+import static org.openremote.model.util.MapAccess.getString
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD_DEFAULT
import static org.openremote.model.Constants.*
diff --git a/test/src/test/groovy/org/openremote/test/protocol/KNXImportTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/KNXImportTest.groovy
index 3ec266de1..fca3035bf 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/KNXImportTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/KNXImportTest.groovy
@@ -27,13 +27,12 @@ import org.openremote.manager.asset.AssetStorageService
import org.openremote.model.asset.agent.AgentResource
import org.openremote.model.file.FileInfo
import org.openremote.model.util.TextUtil
-import org.openremote.model.value.MetaItemType
import org.openremote.test.ManagerContainerTrait
import spock.lang.Ignore
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
-import static org.openremote.container.util.MapAccess.getString
+import static org.openremote.model.util.MapAccess.getString
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD_DEFAULT
import static org.openremote.model.Constants.*
diff --git a/test/src/test/groovy/org/openremote/test/protocol/http/HttpServerProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/http/HttpServerProtocolTest.groovy
index bf8a74ccc..aa0f2bbb2 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/http/HttpServerProtocolTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/http/HttpServerProtocolTest.groovy
@@ -21,38 +21,38 @@ package org.openremote.test.protocol.http
import com.fasterxml.jackson.databind.node.ObjectNode
import io.undertow.servlet.Servlets
-import io.undertow.servlet.api.DeploymentManager
+import jakarta.ws.rs.ForbiddenException
+import jakarta.ws.rs.HttpMethod
+import jakarta.ws.rs.client.ClientRequestContext
+import jakarta.ws.rs.client.ClientRequestFilter
+import jakarta.ws.rs.core.*
import org.jboss.resteasy.specimpl.ResteasyUriInfo
import org.jboss.resteasy.util.BasicAuthHelper
import org.openremote.agent.protocol.http.AbstractHTTPServerProtocol
-import org.openremote.model.util.UniqueIdentifierGenerator
import org.openremote.container.web.OAuthServerResponse
import org.openremote.manager.agent.AgentService
import org.openremote.manager.asset.AssetProcessingService
import org.openremote.manager.asset.AssetStorageService
import org.openremote.model.asset.Asset
+import org.openremote.model.asset.agent.Agent
+import org.openremote.model.asset.agent.ConnectionStatus
import org.openremote.model.asset.impl.ThingAsset
import org.openremote.model.attribute.Attribute
import org.openremote.model.auth.OAuthGrant
import org.openremote.model.auth.OAuthPasswordGrant
import org.openremote.model.auth.OAuthRefreshTokenGrant
import org.openremote.model.geo.GeoJSONPoint
+import org.openremote.model.util.UniqueIdentifierGenerator
import org.openremote.model.util.ValueUtil
+import org.openremote.setup.integration.protocol.http.HTTPServerTestAgent
+import org.openremote.setup.integration.protocol.http.TestHTTPServerProtocol
+import org.openremote.setup.integration.protocol.http.TestResource
import org.openremote.test.ManagerContainerTrait
import spock.lang.Shared
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
-import org.openremote.setup.integration.protocol.http.HTTPServerTestAgent
-import org.openremote.setup.integration.protocol.http.TestHTTPServerProtocol
-import org.openremote.setup.integration.protocol.http.TestResource
-import jakarta.ws.rs.ForbiddenException
-import jakarta.ws.rs.HttpMethod
-import jakarta.ws.rs.client.ClientRequestContext
-import jakarta.ws.rs.client.ClientRequestFilter
-import jakarta.ws.rs.core.*
-
-import static org.openremote.container.util.MapAccess.getString
+import static org.openremote.model.util.MapAccess.getString
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD_DEFAULT
import static org.openremote.model.Constants.*
@@ -273,7 +273,9 @@ class HttpServerProtocolTest extends Specification implements ManagerContainerTr
// There's some weird behaviour where sometimes a forbidden exception is thrown and sometimes not
try {
authenticatedTestResource.postAsset(testAsset)
- } catch (Exception ignored) {}
+ } catch (Exception ex) {
+ getLOG().warn("Failed to call post: " + ex.getMessage())
+ }
}
def "Check HTTP server protocol and JAX-RS deployment"() {
@@ -296,41 +298,45 @@ class HttpServerProtocolTest extends Specification implements ManagerContainerTr
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
).token
- and: "the test resource (to be deployed by the protocol)"
- def authenticatedTestResource = getClientTarget(
- serverUri(serverPort)
- .path(AbstractHTTPServerProtocol.DEFAULT_DEPLOYMENT_PATH_PREFIX)
- .path("test"),
- accessToken).proxy(TestResource.class)
- def testResource = getClientTarget(
- serverUri(serverPort)
- .path(AbstractHTTPServerProtocol.DEFAULT_DEPLOYMENT_PATH_PREFIX)
- .path("test"),
- null).proxy(TestResource.class)
-
when: "a test HTTP server agent with a test deployment is created"
def agent = new HTTPServerTestAgent("Test agent")
.setRealm(MASTER_REALM)
- .setDeploymentPath("test")
.setRoleBasedSecurity(true)
and: "the agent is added to the asset service"
agent = assetStorageService.merge(agent)
+ TestHTTPServerProtocol protocolInstance
+ def testAsset = new ThingAsset("Test Asset")
+ .setId("12345")
+ .addOrReplaceAttributes(
+ new Attribute<>("attribute1", TEXT, "Test")
+ )
+ .setLocation(new GeoJSONPoint(1d, 2d))
then: "the protocol should be deployed"
conditions.eventually {
assert agentService.getProtocolInstance(agent.id) != null
- assert ((TestHTTPServerProtocol)agentService.getProtocolInstance(agent.id)).deployment != null
+ protocolInstance = agentService.getProtocolInstance(agent.id) as TestHTTPServerProtocol
+ agent = assetStorageService.find(agent.id)
+ assert agent.getAttribute(Agent.STATUS).flatMap {it.value}.orElse(null) == ConnectionStatus.CONNECTED
+ assert Servlets.defaultContainer().getDeployment(AbstractHTTPServerProtocol.getDeploymentName(TestHTTPServerProtocol.class, agent.id)) != null
}
- when: "the authenticated test resource is used to post an asset"
- def testAsset = new ThingAsset("Test Asset")
- .setId("12345")
- .addOrReplaceAttributes(
- new Attribute<>("attribute1", TEXT, "Test")
- )
- .setLocation(new GeoJSONPoint(1d, 2d))
- authenticatedTestResource.postAsset(testAsset)
+ when: "the client proxy for the test resource (to be deployed by the protocol) is defined"
+ def authenticatedTestResource = getClientTarget(
+ serverUri(serverPort)
+ .path(protocolInstance.getDeploymentPath()),
+ accessToken).proxy(TestResource.class)
+ def testResource = getClientTarget(
+ serverUri(serverPort)
+ .path(protocolInstance.getDeploymentPath()),
+ null).proxy(TestResource.class)
+
+ then: "it should be possible to post an asset to this protocol's endpoint"
+ conditions.eventually {
+ tryPost(authenticatedTestResource, testAsset)
+ assert protocolInstance.resource1.postedAssets.size() == 1
+ }
then: "the asset should be stored in the test protocol"
conditions.eventually {
@@ -361,24 +367,24 @@ class HttpServerProtocolTest extends Specification implements ManagerContainerTr
when: "an additional instance of the Test HTTP Server protocol is deployed without security enabled"
def agent2 = new HTTPServerTestAgent("Test agent 2")
.setRealm(MASTER_REALM)
- .setDeploymentPath("test2")
.setRoleBasedSecurity(false)
-
+ TestHTTPServerProtocol protocolInstance2
agent2 = assetStorageService.merge(agent2)
- and: "an un-authenticated test resource proxy is created for the new deployment"
- def testResource2 = getClientTarget(
- serverUri(serverPort)
- .path(AbstractHTTPServerProtocol.DEFAULT_DEPLOYMENT_PATH_PREFIX)
- .path("test2"),
- null).proxy(TestResource.class)
-
then: "the protocol should be deployed"
conditions.eventually {
- assert agentService.getProtocolInstance(agent2.id) != null
+ protocolInstance2 = agentService.getProtocolInstance(agent2.id) as TestHTTPServerProtocol
+ assert protocolInstance2 != null
+ assert Servlets.defaultContainer().getDeployment(AbstractHTTPServerProtocol.getDeploymentName(TestHTTPServerProtocol.class, agent2.id)) != null
}
- when: "the new test resource is used to post an asset"
+ when: "an un-authenticated test resource proxy is created for the new deployment"
+ def testResource2 = getClientTarget(
+ serverUri(serverPort)
+ .path(protocolInstance2.getDeploymentPath()),
+ null).proxy(TestResource.class)
+
+ and: "the new test resource is used to post an asset"
testAsset = new ThingAsset("Test Asset 2")
testAsset.setId(UniqueIdentifierGenerator.generateId())
testAsset.addOrReplaceAttributes(
@@ -409,14 +415,12 @@ class HttpServerProtocolTest extends Specification implements ManagerContainerTr
assert asset.getLocation().map{it.coordinates.y}.orElse(-1d) == testAsset.getLocation().map{it.coordinates.y}.orElse(0d)
when: "an agent is deleted"
- def protocolInstance = agentService.getProtocolInstance(agent.id) as TestHTTPServerProtocol
- def deploymentManager = Servlets.defaultContainer().getDeployment(protocolInstance.deployment.deploymentInfo.getDeploymentName());
assetStorageService.delete([agent.id])
then: "the associated protocol instance should be un-deployed"
conditions.eventually {
assert agentService.getProtocolInstance(agent.id) == null
- assert deploymentManager.getState() == DeploymentManager.State.UNDEPLOYED
+ assert Servlets.defaultContainer().getDeployment(AbstractHTTPServerProtocol.getDeploymentName(TestHTTPServerProtocol.class, agent.id)) == null
}
then: "if an attempt is made to use the removed endpoint then no asset should be posted"
diff --git a/test/src/test/groovy/org/openremote/test/protocol/lorawan/chirpstack/ChirpStackTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/lorawan/chirpstack/ChirpStackTest.groovy
index 307c4516b..beb34993a 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/lorawan/chirpstack/ChirpStackTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/lorawan/chirpstack/ChirpStackTest.groovy
@@ -48,7 +48,7 @@ import java.util.concurrent.TimeUnit
import static org.openremote.container.security.IdentityProvider.OR_ADMIN_PASSWORD
import static org.openremote.container.security.IdentityProvider.OR_ADMIN_PASSWORD_DEFAULT
-import static org.openremote.container.util.MapAccess.getString
+import static org.openremote.model.util.MapAccess.getString
import static org.openremote.model.Constants.*
import static org.openremote.setup.integration.model.asset.ChirpStackTestAsset.*
diff --git a/test/src/test/groovy/org/openremote/test/protocol/lorawan/tts/TheThingsStackTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/lorawan/tts/TheThingsStackTest.groovy
index f560d5b66..9efe25f90 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/lorawan/tts/TheThingsStackTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/lorawan/tts/TheThingsStackTest.groovy
@@ -53,7 +53,7 @@ import java.util.concurrent.TimeUnit
import static org.openremote.agent.protocol.lorawan.tts.TheThingsStackProtocol.THE_THINGS_STACK_TEST
import static org.openremote.container.security.IdentityProvider.OR_ADMIN_PASSWORD
import static org.openremote.container.security.IdentityProvider.OR_ADMIN_PASSWORD_DEFAULT
-import static org.openremote.container.util.MapAccess.getString
+import static org.openremote.model.util.MapAccess.getString
import static org.openremote.model.Constants.*
import static org.openremote.setup.integration.model.asset.TheThingsStackTestAsset.*
diff --git a/test/src/test/groovy/org/openremote/test/protocol/velbus/VelbusProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/velbus/VelbusProtocolTest.groovy
index 6d9843e8c..55466e756 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/velbus/VelbusProtocolTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/velbus/VelbusProtocolTest.groovy
@@ -5,6 +5,7 @@ import org.openremote.agent.protocol.velbus.VelbusAgentLink
import org.openremote.manager.agent.AgentService
import org.openremote.manager.asset.AssetProcessingService
import org.openremote.manager.asset.AssetStorageService
+import org.openremote.model.asset.AssetTreeNode
import org.openremote.model.asset.agent.AgentResource
import org.openremote.model.asset.impl.ThingAsset
import org.openremote.model.attribute.Attribute
@@ -21,7 +22,7 @@ import org.openremote.setup.integration.protocol.velbus.MockVelbusProtocol
import java.util.stream.Collectors
-import static org.openremote.container.util.MapAccess.getString
+import static org.openremote.model.util.MapAccess.getString
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD_DEFAULT
import static org.openremote.model.Constants.*
@@ -154,7 +155,7 @@ class VelbusProtocolTest extends Specification implements ManagerContainerTrait
when: "discovery is requested with a VELBUS project file"
def fileInfo = new FileInfo("VelbusProject.vlp", velbusProjectFile, false)
- def assets = agentResource.doProtocolAssetImport(null, agent.getId(), MASTER_REALM, fileInfo)
+ AssetTreeNode[] assets = agentResource.doProtocolAssetImport(null, agent.getId(), MASTER_REALM, fileInfo)
then: "the correct number of assets should be returned and all should have IDs"
assert assets != null
@@ -197,7 +198,7 @@ class VelbusProtocolTest extends Specification implements ManagerContainerTrait
}
cleanup: "remove agent and imported assets"
- if (agent != null) {
+ if (agent != null && assets != null) {
ids = []
ids.addAll(Arrays.stream(assets).map{it.asset.id}.collect(Collectors.toList()))
ids.add(agent.id)
diff --git a/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientProtocolTest.groovy
index ef7887243..14cc35a67 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientProtocolTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientProtocolTest.groovy
@@ -56,7 +56,7 @@ import jakarta.ws.rs.core.HttpHeaders
import jakarta.ws.rs.core.MediaType
import jakarta.ws.rs.core.Response
-import static org.openremote.container.util.MapAccess.getString
+import static org.openremote.model.util.MapAccess.getString
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD_DEFAULT
import static org.openremote.model.Constants.KEYCLOAK_CLIENT_ID
diff --git a/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientTest.groovy
index 623abfb7d..8f1d88e2a 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientTest.groovy
@@ -49,7 +49,7 @@ import spock.util.concurrent.PollingConditions
import java.util.concurrent.CopyOnWriteArrayList
-import static org.openremote.container.util.MapAccess.getString
+import static org.openremote.model.util.MapAccess.getString
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD_DEFAULT
import static org.openremote.model.Constants.KEYCLOAK_CLIENT_ID
diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovy
index 7cda78845..ad0be214e 100644
--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovy
@@ -14,7 +14,7 @@ import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
-import static org.openremote.container.util.MapAccess.getString
+import static org.openremote.model.util.MapAccess.getString
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD_DEFAULT
import static org.openremote.model.Constants.*
diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovy
index 3ca732748..238d2fabe 100644
--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovy
@@ -11,7 +11,7 @@ import spock.lang.Specification
import spock.util.concurrent.PollingConditions
import jakarta.ws.rs.WebApplicationException
-import static org.openremote.container.util.MapAccess.getString
+import static org.openremote.model.util.MapAccess.getString
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD_DEFAULT
import static org.openremote.model.Constants.*
diff --git a/test/src/test/groovy/org/openremote/test/users/UserResourceTest.groovy b/test/src/test/groovy/org/openremote/test/users/UserResourceTest.groovy
index 0f1d3773d..985eb6243 100644
--- a/test/src/test/groovy/org/openremote/test/users/UserResourceTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/users/UserResourceTest.groovy
@@ -42,7 +42,7 @@ import jakarta.ws.rs.ForbiddenException
import static org.openremote.container.security.IdentityProvider.OR_ADMIN_PASSWORD
import static org.openremote.container.security.IdentityProvider.OR_ADMIN_PASSWORD_DEFAULT
-import static org.openremote.container.util.MapAccess.getString
+import static org.openremote.model.util.MapAccess.getString
import static org.openremote.model.Constants.KEYCLOAK_CLIENT_ID
import static org.openremote.model.Constants.MASTER_REALM
import static org.openremote.model.Constants.MASTER_REALM_ADMIN_USER