Skip to content

armgit / core

Public Imported from GitHub
0

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

Migrated to camel undertow component for websockets (#1082)

Rich Turnerc9b5ef31f1e7
diff --git a/container/src/main/java/org/openremote/container/message/MessageBrokerService.java b/container/src/main/java/org/openremote/container/message/MessageBrokerService.java
index 1d8dab657..ca304ce61 100644
--- a/container/src/main/java/org/openremote/container/message/MessageBrokerService.java
+++ b/container/src/main/java/org/openremote/container/message/MessageBrokerService.java
@@ -40,8 +40,6 @@ import org.apache.camel.util.StringHelper;
import org.apache.camel.util.concurrent.CamelThreadFactory;
import org.openremote.container.concurrent.ContainerExecutor;
import org.openremote.container.concurrent.ContainerScheduledExecutor;
-import org.openremote.container.web.DefaultWebsocketComponent;
-import org.openremote.container.web.socket.WebsocketComponent;
import org.openremote.model.Container;
import org.openremote.model.ContainerService;
@@ -51,12 +49,8 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.logging.Logger;
-import static org.openremote.container.util.MapAccess.getString;
-
public class MessageBrokerService implements ContainerService {
- public static final String MESSAGE_SESSION_ALLOWED_ORIGIN = "MESSAGE_SESSION_ALLOWED_ORIGIN";
- public static final String MESSAGE_SESSION_ALLOWED_ORIGIN_DEFAULT = null;
private static final Logger LOG = Logger.getLogger(MessageBrokerService.class.getName());
public static final int PRIORITY = ContainerService.LOW_PRIORITY;
@@ -142,13 +136,6 @@ public class MessageBrokerService implements ContainerService {
((SimpleRegistry)((DefaultRegistry)context.getRegistry()).getFallbackRegistry()).put("OpenRemote", Map.of(Container.class, container));
- String allowedOrigin = getString(container.getConfig(), MESSAGE_SESSION_ALLOWED_ORIGIN, MESSAGE_SESSION_ALLOWED_ORIGIN_DEFAULT);
- WebsocketComponent websocketComponent = new DefaultWebsocketComponent(
- container,
- allowedOrigin
- );
-
- context.addComponent(WebsocketComponent.NAME, websocketComponent);
context.addComponent("snmp", new SnmpComponent());
}
diff --git a/container/src/main/java/org/openremote/container/web/ConnectionConstants.java b/container/src/main/java/org/openremote/container/web/ConnectionConstants.java
deleted file mode 100644
index 6c3e2ea74..000000000
--- a/container/src/main/java/org/openremote/container/web/ConnectionConstants.java
+++ /dev/null
@@ -1,33 +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;
-
-public interface ConnectionConstants {
-
- String SESSION_TERMINATOR = "connection.sessionTerminator";
- String SESSION_KEY = "connection.sessionKey";
- String SEND_TO_ALL = "connection.sendToAll";
- String HANDSHAKE_REALM = "connection.realm";
- String HANDSHAKE_AUTH = "connection.auth";
- String SESSION_OPEN = "connection.sessionOpen";
- String SESSION_CLOSE = "connection.sessionClose";
- String SESSION_CLOSE_ERROR = "connection.sessionCloseError";
-
-}
diff --git a/container/src/main/java/org/openremote/container/web/DefaultWebsocketComponent.java b/container/src/main/java/org/openremote/container/web/DefaultWebsocketComponent.java
deleted file mode 100644
index 277d4b699..000000000
--- a/container/src/main/java/org/openremote/container/web/DefaultWebsocketComponent.java
+++ /dev/null
@@ -1,169 +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 io.undertow.server.DefaultByteBufferPool;
-import io.undertow.server.HttpHandler;
-import io.undertow.servlet.api.DeploymentInfo;
-import io.undertow.servlet.api.SecurityConstraint;
-import io.undertow.servlet.api.SecurityInfo;
-import io.undertow.servlet.api.WebResourceCollection;
-import io.undertow.websockets.jsr.DefaultContainerConfigurator;
-import io.undertow.websockets.jsr.UndertowContainerProvider;
-import io.undertow.websockets.jsr.WebSocketDeploymentInfo;
-import org.keycloak.KeycloakPrincipal;
-import org.openremote.container.security.AuthContext;
-import org.openremote.container.security.basic.BasicAuthContext;
-import org.openremote.container.security.keycloak.AccessTokenAuthContext;
-import org.openremote.container.web.socket.WebsocketAdapter;
-import org.openremote.container.web.socket.WebsocketComponent;
-import org.openremote.model.Constants;
-import org.openremote.model.Container;
-import org.xnio.OptionMap;
-import org.xnio.Options;
-import org.xnio.Xnio;
-
-import jakarta.websocket.HandshakeResponse;
-import jakarta.websocket.server.HandshakeRequest;
-import jakarta.websocket.server.ServerEndpointConfig;
-import java.security.Principal;
-import java.util.Optional;
-import java.util.logging.Logger;
-
-import static org.openremote.container.web.WebService.pathStartsWithHandler;
-
-public class DefaultWebsocketComponent extends WebsocketComponent {
-
- public static final String WEBSOCKET_PATH = "/websocket";
- private static final Logger LOG = Logger.getLogger(DefaultWebsocketComponent.class.getName());
-
- static {
- UndertowContainerProvider.disableDefaultContainer();
- }
-
- final protected Container container;
- final protected WebService webService;
- final protected String allowedOrigin;
- protected DeploymentInfo deploymentInfo;
- protected WebService.RequestHandler websocketHttpHandler;
-
- public DefaultWebsocketComponent(Container container, String allowedOrigin) {
- this.container = container;
- this.webService = container.getService(WebService.class);
- this.allowedOrigin = allowedOrigin;
- }
-
- @Override
- protected void deploy() throws Exception {
-
- WebSocketDeploymentInfo webSocketDeploymentInfo = new WebSocketDeploymentInfo();
-
- getConsumers().forEach((key, value) -> {
- String endpointPath = WEBSOCKET_PATH + "/" + key;
- LOG.info("Deploying websocket endpoint: " + endpointPath);
- webSocketDeploymentInfo.addEndpoint(
- ServerEndpointConfig.Builder.create(WebsocketAdapter.class, endpointPath)
- .configurator(new DefaultContainerConfigurator() {
- @SuppressWarnings("unchecked")
- @Override
- public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException {
- return (T) new WebsocketAdapter(value);
- }
-
- @Override
- public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {
- String realm = Optional.ofNullable(request.getHeaders().get(Constants.REALM_PARAM_NAME))
- .map(realms -> realms.isEmpty() ? null : realms.get(0)).orElse(null);
-
- Principal principal = request.getUserPrincipal();
- AuthContext authContext = null;
-
- if (principal instanceof KeycloakPrincipal) {
- KeycloakPrincipal<?> keycloakPrincipal = (KeycloakPrincipal<?>) principal;
- authContext = new AccessTokenAuthContext(
- keycloakPrincipal.getKeycloakSecurityContext().getRealm(),
- keycloakPrincipal.getKeycloakSecurityContext().getToken()
- );
- } else if (principal instanceof BasicAuthContext) {
- authContext = (BasicAuthContext) principal;
- } else if (principal != null) {
- LOG.info("Unsupported user principal type: " + principal);
- }
-
- config.getUserProperties().put(ConnectionConstants.HANDSHAKE_AUTH, authContext);
- config.getUserProperties().put(ConnectionConstants.HANDSHAKE_REALM, realm);
-
- super.modifyHandshake(config, request, response);
- }
- })
- .build()
- );
- });
-
- // We use the I/O thread to handle received websocket frames, as we expect to quickly hand them over to
- // an internal asynchronous message queue for processing, so we don't need a separate worker thread
- // pool for websocket frame processing
- webSocketDeploymentInfo.setDispatchToWorkerThread(false);
-
- // Make the shit Undertow/Websocket JSR client bootstrap happy - this is the pool that would be used
- // when Undertow acts as a WebSocket client, which we don't do... and I'm not even sure it can do that...
- webSocketDeploymentInfo.setWorker(Xnio.getInstance().createWorker(
- OptionMap.builder()
- .set(Options.WORKER_TASK_MAX_THREADS, 1)
- .set(Options.WORKER_NAME, "WebsocketInternalClient")
- .set(Options.THREAD_DAEMON, true)
- .getMap()
- ));
- boolean directBuffers = Boolean.getBoolean("io.undertow.websockets.direct-buffers");
- webSocketDeploymentInfo.setBuffers(new DefaultByteBufferPool(directBuffers, 1024, 100, 12));
-
- String deploymentName = "WebSocket Deployment";
- deploymentInfo = new DeploymentInfo()
- .setDeploymentName(deploymentName)
- .setContextPath(WEBSOCKET_PATH)
- .addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, webSocketDeploymentInfo)
- .setClassLoader(WebsocketComponent.class.getClassLoader());
-
- // Require authentication, but authorize specific roles later in Camel
- WebResourceCollection resourceCollection = new WebResourceCollection();
- resourceCollection.addUrlPattern("/*");
- SecurityConstraint constraint = new SecurityConstraint();
- constraint.setEmptyRoleSemantic(SecurityInfo.EmptyRoleSemantic.PERMIT);
- constraint.addWebResourceCollection(resourceCollection);
- deploymentInfo.addSecurityConstraints(constraint);
-
- HttpHandler handler = WebService.addServletDeployment(container, deploymentInfo, true);
-
- websocketHttpHandler = pathStartsWithHandler(deploymentName, WEBSOCKET_PATH, handler);
-
- // Give web socket handler higher priority than any other handlers already added
- webService.getRequestHandlers().add(0, websocketHttpHandler);
- }
-
- @Override
- protected void undeploy() throws Exception {
- if (deploymentInfo != null) {
- webService.removeServletDeployment(deploymentInfo);
- deploymentInfo = null;
- }
- webService.getRequestHandlers().remove(websocketHttpHandler);
- websocketHttpHandler = null;
- }
-}
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 f8ee3dcf9..0654e73bf 100644
--- a/container/src/main/java/org/openremote/container/web/WebService.java
+++ b/container/src/main/java/org/openremote/container/web/WebService.java
@@ -301,6 +301,10 @@ public abstract class WebService implements ContainerService {
return resteasyDeployment;
}
+ public Undertow getUndertow() {
+ return undertow;
+ }
+
public static synchronized FilterInfo getCorsFilterInfo(Container container) {
if (corsFilterRef == null) {
diff --git a/container/src/main/java/org/openremote/container/web/socket/MemoryWebsocketSessions.java b/container/src/main/java/org/openremote/container/web/socket/MemoryWebsocketSessions.java
deleted file mode 100644
index 4f10b9c5d..000000000
--- a/container/src/main/java/org/openremote/container/web/socket/MemoryWebsocketSessions.java
+++ /dev/null
@@ -1,57 +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.socket;
-
-import jakarta.websocket.Session;
-import java.util.Collection;
-import java.util.concurrent.ConcurrentHashMap;
-
-public class MemoryWebsocketSessions extends ConcurrentHashMap<String, Session> implements WebsocketSessions {
-
- @Override
- public void add(Session websocketSession) {
- super.put(websocketSession.getId(), websocketSession);
- }
-
- @Override
- public void remove(Session websocketSession) {
- super.remove(websocketSession.getId());
- }
-
- @Override
- public Session get(String sessionId) {
- return super.get(sessionId);
- }
-
- @Override
- public Collection<Session> getAll() {
- return super.values();
- }
-
- @Override
- public void start() {
- // noop
- }
-
- @Override
- public void stop() {
- clear();
- }
-}
diff --git a/container/src/main/java/org/openremote/container/web/socket/WebsocketAdapter.java b/container/src/main/java/org/openremote/container/web/socket/WebsocketAdapter.java
deleted file mode 100644
index 13937a56b..000000000
--- a/container/src/main/java/org/openremote/container/web/socket/WebsocketAdapter.java
+++ /dev/null
@@ -1,121 +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.socket;
-
-import io.undertow.websockets.jsr.UndertowSession;
-import org.apache.camel.Exchange;
-import org.openremote.container.security.AuthContext;
-import org.openremote.container.security.keycloak.KeycloakIdentityProvider;
-import org.openremote.container.web.ConnectionConstants;
-import org.openremote.model.Constants;
-
-import jakarta.websocket.CloseReason;
-import jakarta.websocket.Endpoint;
-import jakarta.websocket.EndpointConfig;
-import jakarta.websocket.Session;
-import java.io.IOException;
-import java.util.concurrent.RejectedExecutionException;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-public class WebsocketAdapter extends Endpoint {
-
- private static final Logger LOG = Logger.getLogger(WebsocketAdapter.class.getName());
-
- final protected WebsocketConsumer consumer;
-
- public WebsocketAdapter(WebsocketConsumer consumer) {
- this.consumer = consumer;
- }
-
- @Override
- public void onOpen(Session session, EndpointConfig config) {
- LOG.fine("Client connection created: " + sessionToString(session));
- session.setMaxIdleTimeout(0);
- consumer.getEndpoint().getWebsocketSessions().add(session);
- this.consumer.sendMessage(null, exchange -> {
- this.prepareExchange(exchange, session);
- exchange.getIn().setHeader(ConnectionConstants.SESSION_OPEN, true);
- });
- session.addMessageHandler(String.class, message -> {
- if (LOG.isLoggable(Level.FINEST)) {
- LOG.finest("Websocket session '" + sessionToString(session) + "' message received: " + message);
- }
- this.consumer.sendMessage(message, exchange -> this.prepareExchange(exchange, session));
- });
- }
-
- @Override
- public void onClose(Session session, CloseReason closeReason) {
- LOG.fine("Client connection closed: " + sessionToString(session));
- this.consumer.sendMessage(closeReason, exchange -> {
- this.prepareExchange(exchange, session);
- exchange.getIn().setHeader(ConnectionConstants.SESSION_CLOSE, true);
- });
- consumer.getEndpoint().getWebsocketSessions().remove(session);
- }
-
- @Override
- public void onError(Session session, Throwable thr) {
- super.onError(session, thr);
- // Ignore connection reset
- if (!(thr instanceof IOException && thr.getMessage().equals("Connection reset by peer"))) {
- LOG.info("Client connection error: " + sessionToString(session));
- }
- this.consumer.sendMessage(thr, exchange -> {
- this.prepareExchange(exchange, session);
- exchange.getIn().setHeader(ConnectionConstants.SESSION_CLOSE_ERROR, true);
- });
- consumer.getEndpoint().getWebsocketSessions().remove(session);
- }
-
- protected String sessionToString(Session session) {
- UndertowSession undertowSession = ((UndertowSession) session);
- String sourceAddress = undertowSession.getWebSocketChannel().getSourceAddress().toString();
- String usernameAndRealm = KeycloakIdentityProvider.getSubjectNameAndRealm(undertowSession.getUserPrincipal());
- return "connection=" + sourceAddress + ", sessionID=" + session.getId() + ", subject=" + usernameAndRealm;
- }
-
- protected void prepareExchange(Exchange exchange, Session session) {
- exchange.getIn().setHeader(ConnectionConstants.SESSION_KEY, session.getId());
- exchange.getIn().setHeader(Constants.AUTH_CONTEXT, getHandshakeAuth(session));
- exchange.getIn().setHeader(Constants.REALM_PARAM_NAME, getHandshakeRealm(session));
- exchange.getIn().setHeader(ConnectionConstants.SESSION_TERMINATOR, getSessionTerminator(session));
- }
-
- protected AuthContext getHandshakeAuth(Session session) {
- return (AuthContext) session.getUserProperties().get(ConnectionConstants.HANDSHAKE_AUTH);
- }
-
- protected String getHandshakeRealm(Session session) {
- return (String) session.getUserProperties().get(ConnectionConstants.HANDSHAKE_REALM);
- }
-
- protected Runnable getSessionTerminator(Session session) {
- return () -> {
- try {
- session.close();
- } catch (RejectedExecutionException ignored) {
- } catch (IOException ignored) {
- LOG.log(Level.INFO, "Failed to close client session: " + session.getId());
- }
- };
- }
-}
diff --git a/container/src/main/java/org/openremote/container/web/socket/WebsocketCORSFilter.java b/container/src/main/java/org/openremote/container/web/socket/WebsocketCORSFilter.java
deleted file mode 100644
index 7021d12f5..000000000
--- a/container/src/main/java/org/openremote/container/web/socket/WebsocketCORSFilter.java
+++ /dev/null
@@ -1,73 +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.socket;
-
-import jakarta.servlet.*;
-import jakarta.servlet.http.HttpServletRequest;
-import jakarta.servlet.http.HttpServletResponse;
-import java.io.IOException;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-public class WebsocketCORSFilter implements Filter {
-
- private static final Logger LOG = Logger.getLogger(WebsocketCORSFilter.class.getName());
-
- public static final String ALLOWED_ORIGIN = "ALLOWED_ORIGIN";
-
- protected String allowedOrigin;
-
- @Override
- public void init(FilterConfig filterConfig) throws ServletException {
- allowedOrigin = filterConfig.getInitParameter(ALLOWED_ORIGIN);
- }
-
- @Override
- public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
- throws IOException, ServletException {
-
- if (allowedOrigin == null) {
- if (LOG.isLoggable(Level.FINE))
- LOG.fine("No origin restriction, allowing Websocket upgrade request");
- chain.doFilter(request, response);
- return;
- }
-
- HttpServletRequest req = (HttpServletRequest) request;
- HttpServletResponse resp = (HttpServletResponse) response;
- if (req.getHeader("Upgrade") != null) {
- String origin = req.getHeader("Origin");
- if (origin != null && origin.equals(allowedOrigin)) {
- if (LOG.isLoggable(Level.FINE))
- LOG.fine("Received origin is allowed origin, allowing Websocket upgrade request: " + origin);
- chain.doFilter(request, response);
- return;
- }
- }
-
- LOG.info("Illegal origin, dropping Websocket upgrade request");
- resp.sendError(400, "Origin is not allowed");
- }
-
- @Override
- public void destroy() {
- }
-
-}
diff --git a/container/src/main/java/org/openremote/container/web/socket/WebsocketComponent.java b/container/src/main/java/org/openremote/container/web/socket/WebsocketComponent.java
deleted file mode 100644
index 595aae21d..000000000
--- a/container/src/main/java/org/openremote/container/web/socket/WebsocketComponent.java
+++ /dev/null
@@ -1,112 +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.socket;
-
-import org.apache.camel.Endpoint;
-import org.apache.camel.support.DefaultComponent;
-import org.apache.camel.support.service.ServiceHelper;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.logging.Logger;
-
-public abstract class WebsocketComponent extends DefaultComponent {
-
- private static final Logger LOG = Logger.getLogger(WebsocketComponent.class.getName());
-
- public static final String NAME = "websocket";
-
- final protected Map<String, WebsocketConsumer> consumers = new HashMap<>();
- final protected WebsocketSessions websocketSessions;
-
- public WebsocketComponent() {
- this.websocketSessions = new MemoryWebsocketSessions();
- }
-
- @Override
- protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
- WebsocketEndpoint endpoint = new WebsocketEndpoint(this, uri, remaining, parameters);
- setProperties(endpoint, parameters);
- return endpoint;
- }
-
- @Override
- protected void doStart() throws Exception {
- super.doStart();
- ServiceHelper.startService(getWebsocketSessions());
- }
-
- @Override
- protected void doStop() throws Exception {
- super.doStop();
- ServiceHelper.stopService(getWebsocketSessions());
- undeploy();
- }
-
- public WebsocketSessions getWebsocketSessions() {
- return websocketSessions;
- }
-
- public Map<String, WebsocketConsumer> getConsumers() {
- return consumers;
- }
-
- synchronized public void connect(WebsocketConsumer consumer) {
- String resourceUri = consumer.getEndpoint().getResourceUri();
- if (consumers.containsKey(resourceUri)) {
- LOG.fine("Websocket server endpoint already connected: " + resourceUri);
- return;
- }
- consumers.put(resourceUri, consumer);
- try {
- redeploy();
- } catch (Exception ex) {
- throw new RuntimeException(ex);
- }
- }
-
- synchronized public void disconnect(WebsocketConsumer consumer) {
- String resourceUri = consumer.getEndpoint().getResourceUri();
- if (!consumers.containsKey(resourceUri)) {
- return;
- }
- consumers.remove(resourceUri);
- try {
- redeploy(consumers.size() == 0);
- } catch (Exception ex) {
- throw new RuntimeException(ex);
- }
- }
-
- protected void redeploy() throws Exception {
- redeploy(false);
- }
-
- protected void redeploy(boolean doUndeployOnly) throws Exception {
- // TODO what happens to inflight sessions?
- undeploy();
- if (!doUndeployOnly)
- deploy();
- }
-
- protected abstract void deploy() throws Exception;
- protected abstract void undeploy() throws Exception;
-}
-
diff --git a/container/src/main/java/org/openremote/container/web/socket/WebsocketConsumer.java b/container/src/main/java/org/openremote/container/web/socket/WebsocketConsumer.java
deleted file mode 100644
index 6d31d06cf..000000000
--- a/container/src/main/java/org/openremote/container/web/socket/WebsocketConsumer.java
+++ /dev/null
@@ -1,75 +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.socket;
-
-import org.apache.camel.Exchange;
-import org.apache.camel.Processor;
-import org.apache.camel.support.DefaultConsumer;
-
-import java.util.function.Consumer;
-
-public class WebsocketConsumer extends DefaultConsumer {
-
- private final WebsocketEndpoint endpoint;
-
- public WebsocketConsumer(WebsocketEndpoint endpoint, Processor processor) {
- super(endpoint, processor);
- this.endpoint = endpoint;
- }
-
- @Override
- public void doStart() throws Exception {
- super.doStart();
- endpoint.connect(this);
- }
-
- @Override
- public void doStop() throws Exception {
- endpoint.disconnect(this);
- super.doStop();
- }
-
- public WebsocketEndpoint getEndpoint() {
- return endpoint;
- }
-
- public void sendMessage(final String message) {
- sendMessage((Object) message);
- }
-
- public void sendMessage(final Object message) {
- sendMessage(message, null);
- }
-
- public void sendMessage(final Object message, Consumer<Exchange> exchangePreparer) {
- final Exchange exchange = getEndpoint().createExchange();
- exchange.getIn().setBody(message);
-
- if (exchangePreparer != null) {
- exchangePreparer.accept(exchange);
- }
-
- getAsyncProcessor().process(exchange, doneSync -> {
- if (exchange.getException() != null) {
- getExceptionHandler().handleException("Error processing exchange", exchange, exchange.getException());
- }
- });
- }
-}
diff --git a/container/src/main/java/org/openremote/container/web/socket/WebsocketEndpoint.java b/container/src/main/java/org/openremote/container/web/socket/WebsocketEndpoint.java
deleted file mode 100644
index 221ff0dcc..000000000
--- a/container/src/main/java/org/openremote/container/web/socket/WebsocketEndpoint.java
+++ /dev/null
@@ -1,103 +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.socket;
-
-import org.apache.camel.Consumer;
-import org.apache.camel.Processor;
-import org.apache.camel.Producer;
-import org.apache.camel.support.DefaultEndpoint;
-import org.apache.camel.spi.Metadata;
-import org.apache.camel.spi.UriEndpoint;
-import org.apache.camel.spi.UriParam;
-import org.apache.camel.spi.UriPath;
-import org.apache.camel.util.ObjectHelper;
-
-import java.util.Map;
-
-@UriEndpoint(scheme = "ws", title = "Undertow Websocket", syntax = "ws:resourceUri", consumerClass = WebsocketConsumer.class, label = "http,websocket")
-public class WebsocketEndpoint extends DefaultEndpoint {
-
- private WebsocketComponent component;
-
- @UriPath
- @Metadata(required = true)
- private String resourceUri;
-
- @UriParam
- private Boolean sendToAll;
-
- public WebsocketEndpoint(WebsocketComponent component, String uri, String resourceUri, Map<String, Object> parameters) {
- super(uri, component);
- this.resourceUri = resourceUri;
- this.component = component;
- }
-
- @Override
- public WebsocketComponent getComponent() {
- ObjectHelper.notNull(component, "component");
- return (WebsocketComponent) super.getComponent();
- }
-
- @Override
- public Consumer createConsumer(Processor processor) throws Exception {
- ObjectHelper.notNull(component, "component");
- WebsocketConsumer consumer = new WebsocketConsumer(this, processor);
- configureConsumer(consumer);
- return consumer;
- }
-
- @Override
- public Producer createProducer() throws Exception {
- return new WebsocketProducer(this);
- }
-
- @Override
- public boolean isSingleton() {
- return true;
- }
-
- public WebsocketSessions getWebsocketSessions() {
- return getComponent().getWebsocketSessions();
- }
-
- public void connect(WebsocketConsumer consumer) throws Exception {
- component.connect(consumer);
- }
-
- public void disconnect(WebsocketConsumer consumer) throws Exception {
- component.disconnect(consumer);
- }
-
- public Boolean getSendToAll() {
- return sendToAll;
- }
-
- public void setSendToAll(Boolean sendToAll) {
- this.sendToAll = sendToAll;
- }
-
- public String getResourceUri() {
- return resourceUri;
- }
-
- public void setResourceUri(String resourceUri) {
- this.resourceUri = resourceUri;
- }
-}
diff --git a/container/src/main/java/org/openremote/container/web/socket/WebsocketProducer.java b/container/src/main/java/org/openremote/container/web/socket/WebsocketProducer.java
deleted file mode 100644
index e1e3942d9..000000000
--- a/container/src/main/java/org/openremote/container/web/socket/WebsocketProducer.java
+++ /dev/null
@@ -1,105 +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.socket;
-
-import org.apache.camel.CamelExchangeException;
-import org.apache.camel.Exchange;
-import org.apache.camel.Message;
-import org.apache.camel.support.DefaultProducer;
-import org.openremote.container.web.ConnectionConstants;
-
-import jakarta.websocket.Session;
-import java.io.IOException;
-import java.util.Collection;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-public class WebsocketProducer extends DefaultProducer {
-
- private static final Logger LOG = Logger.getLogger(WebsocketProducer.class.getName());
-
- private final Boolean sendToAll;
- private final WebsocketEndpoint endpoint;
-
- public WebsocketProducer(WebsocketEndpoint endpoint) {
- super(endpoint);
- this.sendToAll = endpoint.getSendToAll();
- this.endpoint = endpoint;
- }
-
- @Override
- public void process(Exchange exchange) throws Exception {
- Message in = exchange.getIn();
- Object message = in.getMandatoryBody();
- if (!(message == null || message instanceof String || message instanceof byte[])) {
- message = in.getMandatoryBody(String.class);
- }
- if (isSendToAllSet(in)) {
- sendToAll(message, exchange);
- } else {
- String sessionKey = in.getHeader(ConnectionConstants.SESSION_KEY, String.class);
- if (sessionKey != null) {
- Session websocket = getEndpoint().getComponent().getWebsocketSessions().get(sessionKey);
- sendMessage(websocket, message);
- } else {
- throw new IllegalArgumentException("Failed to send message to Websocket session; session key not set.");
- }
- }
- }
-
- public WebsocketEndpoint getEndpoint() {
- return endpoint;
- }
-
- protected boolean isSendToAllSet(Message in) {
- Boolean value = in.getHeader(ConnectionConstants.SEND_TO_ALL, sendToAll, Boolean.class);
- return value == null ? false : value;
- }
-
- protected void sendToAll(Object message, Exchange exchange) throws Exception {
- Collection<Session> sessions = getEndpoint().getComponent().getWebsocketSessions().getAll();
- if (LOG.isLoggable(Level.FINE))
- LOG.fine("Sending to all sessions (" + sessions.size() + "): " + message);
-
- Exception exception = null;
- for (Session session : sessions) {
- try {
- sendMessage(session, message);
- } catch (Exception e) {
- if (exception == null) {
- exception = new CamelExchangeException("Failed to deliver message to one or more recipients.", exchange, e);
- }
- }
- }
- if (exception != null) {
- throw exception;
- }
- }
-
- protected void sendMessage(Session session, Object message) throws IOException {
- if (session != null && session.isOpen()) {
- if (message instanceof String) {
- if (LOG.isLoggable(Level.FINE))
- LOG.finest("Sending to session " + session.getId() + ": " + message);
- session.getBasicRemote().sendText((String) message);
- }
- }
- }
-}
diff --git a/container/src/main/java/org/openremote/container/web/socket/WebsocketSessions.java b/container/src/main/java/org/openremote/container/web/socket/WebsocketSessions.java
deleted file mode 100644
index 47bb1ac15..000000000
--- a/container/src/main/java/org/openremote/container/web/socket/WebsocketSessions.java
+++ /dev/null
@@ -1,36 +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.socket;
-
-import org.apache.camel.Service;
-
-import jakarta.websocket.Session;
-import java.util.Collection;
-
-public interface WebsocketSessions extends Service {
-
- void add(Session websocketSession);
-
- void remove(Session websocketSession);
-
- Session get(String sessionId);
-
- Collection<Session> getAll();
-}
diff --git a/manager/build.gradle b/manager/build.gradle
index ae0c898a6..7e75d9269 100644
--- a/manager/build.gradle
+++ b/manager/build.gradle
@@ -23,6 +23,7 @@ dependencies {
implementation "org.eclipse.angus:angus-mail:$jakartaMailVersion"
implementation "io.swagger.core.v3:swagger-jaxrs2-jakarta:$swaggerVersion"
implementation "org.openjdk.nashorn:nashorn-core:$nashornVersion"
+ implementation "org.apache.camel:camel-undertow:$camelVersion"
implementation ("io.netty:netty-codec-http:$nettyVersion") {
force = true
diff --git a/manager/src/main/java/org/openremote/manager/event/ClientEventService.java b/manager/src/main/java/org/openremote/manager/event/ClientEventService.java
index f5bf54783..1752a62c5 100644
--- a/manager/src/main/java/org/openremote/manager/event/ClientEventService.java
+++ b/manager/src/main/java/org/openremote/manager/event/ClientEventService.java
@@ -19,12 +19,19 @@
*/
package org.openremote.manager.event;
+import io.undertow.websockets.core.WebSocketChannel;
+import io.undertow.websockets.spi.WebSocketHttpExchange;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.undertow.UndertowComponent;
+import org.apache.camel.component.undertow.UndertowConstants;
+import org.apache.camel.component.undertow.UndertowHostKey;
+import org.keycloak.KeycloakPrincipal;
import org.openremote.container.message.MessageBrokerService;
import org.openremote.container.security.AuthContext;
+import org.openremote.container.security.basic.BasicAuthContext;
+import org.openremote.container.security.keycloak.AccessTokenAuthContext;
import org.openremote.container.timer.TimerService;
-import org.openremote.container.web.ConnectionConstants;
import org.openremote.manager.gateway.GatewayService;
import org.openremote.manager.mqtt.DefaultMQTTHandler;
import org.openremote.manager.security.ManagerIdentityService;
@@ -35,6 +42,8 @@ import org.openremote.model.ContainerService;
import org.openremote.model.event.shared.*;
import org.openremote.model.syslog.SyslogEvent;
+import java.io.IOException;
+import java.security.Principal;
import java.util.Collection;
import java.util.HashSet;
import java.util.Objects;
@@ -44,11 +53,11 @@ import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ExecutorService;
import java.util.function.Consumer;
-import java.util.logging.Level;
-import java.util.logging.Logger;
+import static java.lang.System.Logger.Level.DEBUG;
+import static java.lang.System.Logger.Level.TRACE;
import static org.apache.camel.builder.PredicateBuilder.or;
-import static org.openremote.container.web.ConnectionConstants.SESSION_TERMINATOR;
+import static org.openremote.model.Constants.*;
/**
* Receives and publishes messages, handles the client/server event bus.
@@ -107,11 +116,11 @@ public class ClientEventService extends RouteBuilder implements ContainerService
public static final int PRIORITY = ManagerWebService.PRIORITY - 200;
public static final String HEADER_CONNECTION_TYPE = ClientEventService.class.getName() + ".HEADER_CONNECTION_TYPE";
- public static final String HEADER_CONNECTION_TYPE_WEBSOCKET = ClientEventService.class.getName() + ".HEADER_CONNECTION_TYPE_WEBSOCKET";
- public static final String HEADER_CONNECTION_TYPE_MQTT = ClientEventService.class.getName() + ".HEADER_CONNECTION_TYPE_MQTT";
+ public static final String HEADER_CONNECTION_TYPE_WEBSOCKET = "websocket";
+ public static final String HEADER_CONNECTION_TYPE_MQTT = "mqtt";
public static final String HEADER_REQUEST_RESPONSE_MESSAGE_ID = ClientEventService.class.getName() + ".HEADER_REQUEST_RESPONSE_MESSAGE_ID";
- private static final Logger LOG = Logger.getLogger(ClientEventService.class.getName());
- public static final String WEBSOCKET_EVENTS = "events";
+ private static final System.Logger LOG = System.getLogger(ClientEventService.class.getName());
+ public static final String WEBSOCKET_URI = "undertow://ws://0.0.0.0/websocket/events?fireWebSocketChannelEvents=true&sendTimeout=15000"; // Host is not used as existing undertow instance is utilised
protected static final String INTERNAL_SESSION_KEY = "ClientEventServiceInternal";
// TODO: Some of these options should be configurable depending on expected load etc.
@@ -146,11 +155,11 @@ public class ClientEventService extends RouteBuilder implements ContainerService
}
public static String getSessionKey(Exchange exchange) {
- return exchange.getIn().getHeader(ConnectionConstants.SESSION_KEY, String.class);
+ return exchange.getIn().getHeader(SESSION_KEY, String.class);
}
public static String getClientId(Exchange exchange) {
- AuthContext authContext = exchange.getIn().getHeader(Constants.AUTH_CONTEXT, AuthContext.class);
+ AuthContext authContext = exchange.getIn().getHeader(AUTH_CONTEXT, AuthContext.class);
if(authContext != null) {
return authContext.getClientId();
}
@@ -170,10 +179,27 @@ public class ClientEventService extends RouteBuilder implements ContainerService
gatewayService = container.getService(GatewayService.class);
executorService = container.getExecutorService();
+ ManagerWebService webService = container.getService(ManagerWebService.class);
+
eventSubscriptions = new EventSubscriptions(
container.getService(TimerService.class)
);
+// // TODO: Replace this custom websocket component with camel undertow component once it is migrated to jakarta packages
+// WebsocketComponent websocketComponent = new DefaultWebsocketComponent(
+// container
+// );
+// messageBrokerService.getContext().addComponent(WebsocketComponent.NAME, websocketComponent);
+
+ UndertowComponent undertowWebsocketComponent = new UndertowComponent(messageBrokerService.getContext()) {
+ @Override
+ protected org.apache.camel.component.undertow.UndertowHost createUndertowHost(UndertowHostKey key) {
+ return new UndertowHost(container, key, getHostOptions());
+ }
+ };
+ messageBrokerService.getContext().addComponent("undertow", undertowWebsocketComponent);
+
+
messageBrokerService.getContext().getTypeConverterRegistry().addTypeConverters(
new EventTypeConverters()
);
@@ -192,10 +218,97 @@ public class ClientEventService extends RouteBuilder implements ContainerService
// TODO: Remove prefix and just use event type then use a subscription wrapper to pass subscription ID around
@Override
public void configure() throws Exception {
- from("websocket://" + WEBSOCKET_EVENTS)
- .routeId("FromClientWebsocketEvents")
+ from(WEBSOCKET_URI)
+ .routeId("FromWebsocket")
.process(exchange -> {
+ String connectionKey = exchange.getIn().getHeader(UndertowConstants.CONNECTION_KEY, String.class);
exchange.getIn().setHeader(HEADER_CONNECTION_TYPE, HEADER_CONNECTION_TYPE_WEBSOCKET);
+ exchange.getIn().setHeader(SESSION_KEY, connectionKey);
+ })
+ .choice()
+ .when(header(UndertowConstants.EVENT_TYPE))
+ .process(exchange -> {
+ UndertowConstants.EventType eventType = exchange.getIn().getHeader(UndertowConstants.EVENT_TYPE_ENUM, UndertowConstants.EventType.class);
+ WebSocketChannel webSocketChannel = exchange.getIn().getHeader(UndertowConstants.CHANNEL, WebSocketChannel.class);
+
+ switch (eventType) {
+ case ONOPEN -> {
+ WebSocketHttpExchange httpExchange = exchange.getIn().getHeader(UndertowConstants.EXCHANGE, WebSocketHttpExchange.class);
+ String realm = httpExchange.getRequestHeader(Constants.REALM_PARAM_NAME);
+ Principal principal = httpExchange.getUserPrincipal();
+ AuthContext authContext = null;
+
+ if (principal instanceof KeycloakPrincipal<?> keycloakPrincipal) {
+ authContext = new AccessTokenAuthContext(
+ keycloakPrincipal.getKeycloakSecurityContext().getRealm(),
+ keycloakPrincipal.getKeycloakSecurityContext().getToken()
+ );
+ } else if (principal instanceof BasicAuthContext) {
+ authContext = (BasicAuthContext) principal;
+ } else if (principal != null) {
+ LOG.log(System.Logger.Level.INFO, "Unsupported user principal type: " + principal);
+ }
+
+ // Push auth and realm into channel for future use
+ webSocketChannel.setAttribute(Constants.AUTH_CONTEXT, authContext);
+ webSocketChannel.setAttribute(Constants.REALM_PARAM_NAME, realm);
+
+ exchange.getIn().setHeader(Constants.AUTH_CONTEXT, authContext);
+ exchange.getIn().setHeader(Constants.REALM_PARAM_NAME, realm);
+ exchange.getIn().setHeader(SESSION_TERMINATOR, getWebsocketSessionTerminator(webSocketChannel));
+ exchange.getIn().setHeader(SESSION_OPEN, true);
+ LOG.log(DEBUG, "Client connection created: " + webSocketChannel.getSourceAddress());
+ }
+ case ONCLOSE -> {
+ AuthContext authContext = (AuthContext)webSocketChannel.getAttribute(Constants.AUTH_CONTEXT);
+ String realm = (String)webSocketChannel.getAttribute(Constants.REALM_PARAM_NAME);
+
+ exchange.getIn().setHeader(Constants.AUTH_CONTEXT, authContext);
+ exchange.getIn().setHeader(Constants.REALM_PARAM_NAME, realm);
+
+ // Use protocol agnostic session open header
+ exchange.getIn().setHeader(SESSION_CLOSE, true);
+ LOG.log(DEBUG, "Client connection closed: " + webSocketChannel.getSourceAddress());
+ }
+ case ONERROR -> {
+ AuthContext authContext = (AuthContext)webSocketChannel.getAttribute(Constants.AUTH_CONTEXT);
+ String realm = (String)webSocketChannel.getAttribute(Constants.REALM_PARAM_NAME);
+
+ exchange.getIn().setHeader(Constants.AUTH_CONTEXT, authContext);
+ exchange.getIn().setHeader(Constants.REALM_PARAM_NAME, realm);
+
+ // Use protocol agnostic session open header
+ exchange.getIn().setHeader(SESSION_CLOSE_ERROR, true);
+ LOG.log(DEBUG, "Client connection error: " + webSocketChannel.getSourceAddress());
+ try {
+ webSocketChannel.close();
+ } catch (Exception ignored) {}
+ }
+ }
+ })
+ .to(CLIENT_EVENT_QUEUE)
+ .stop()
+ .when(body().isInstanceOf(SharedEvent.class))
+ .process(exchange -> {
+ // Set timestamp if not set
+ if (exchange.getIn().getBody() instanceof SharedEvent) {
+ SharedEvent event = exchange.getIn().getBody(SharedEvent.class);
+ // If there is no timestamp in event, set to system time
+ if (event.getTimestamp() <= 0) {
+ event.setTimestamp(timerService.getCurrentTimeMillis());
+ }
+ }
+ })
+ .endChoice()
+ .end()
+ .process(exchange -> {
+
+ WebSocketChannel webSocketChannel = exchange.getIn().getHeader(UndertowConstants.CHANNEL, WebSocketChannel.class);
+ AuthContext authContext = (AuthContext)webSocketChannel.getAttribute(Constants.AUTH_CONTEXT);
+ String realm = (String)webSocketChannel.getAttribute(Constants.REALM_PARAM_NAME);
+
+ exchange.getIn().setHeader(Constants.AUTH_CONTEXT, authContext);
+ exchange.getIn().setHeader(Constants.REALM_PARAM_NAME, realm);
// Do basic formatting of exchange
EventRequestResponseWrapper<?> requestResponse = null;
@@ -224,16 +337,12 @@ public class ClientEventService extends RouteBuilder implements ContainerService
// Perform authorisation
if (exchange.getIn().getBody() instanceof SharedEvent) {
SharedEvent event = exchange.getIn().getBody(SharedEvent.class);
- AuthContext authContext = exchange.getIn().getHeader(Constants.AUTH_CONTEXT, AuthContext.class);
- String realm = exchange.getIn().getHeader(Constants.REALM_PARAM_NAME, String.class);
if (!authorizeEventWrite(realm, authContext, event)) {
stopMessage(exchange);
}
} else if (exchange.getIn().getBody() instanceof EventSubscription<?>) {
EventSubscription<?> subscription = exchange.getIn().getBody(EventSubscription.class);
- AuthContext authContext = exchange.getIn().getHeader(Constants.AUTH_CONTEXT, AuthContext.class);
- String realm = exchange.getIn().getHeader(Constants.REALM_PARAM_NAME, String.class);
String sessionKey = getSessionKey(exchange);
if (!authorizeEventSubscription(realm, authContext, subscription)) {
@@ -242,50 +351,40 @@ public class ClientEventService extends RouteBuilder implements ContainerService
}
}
})
- .to(ClientEventService.CLIENT_EVENT_QUEUE)
+ .to(CLIENT_EVENT_QUEUE)
.end();
- from(ClientEventService.CLIENT_EVENT_QUEUE)
+ from(CLIENT_EVENT_QUEUE)
.routeId("ClientEvents")
.threads().executorService(executorService)
.choice()
- .when(header(ConnectionConstants.SESSION_OPEN))
+ .when(header(SESSION_OPEN))
.process(exchange -> {
String sessionKey = getSessionKey(exchange);
- LOG.finest("Adding session: " + sessionKey);
sessionKeyInfoMap.put(sessionKey, createSessionInfo(sessionKey, exchange));
passToInterceptors(exchange);
})
.stop()
.when(or(
- header(ConnectionConstants.SESSION_CLOSE),
- header(ConnectionConstants.SESSION_CLOSE_ERROR)
+ header(SESSION_CLOSE),
+ header(SESSION_CLOSE_ERROR)
))
.process(exchange -> {
String sessionKey = getSessionKey(exchange);
- LOG.finest("Removing session: " + sessionKey);
+ LOG.log(TRACE, "Removing session: " + sessionKey);
sessionKeyInfoMap.remove(sessionKey);
eventSubscriptions.cancelAll(sessionKey);
passToInterceptors(exchange);
})
.stop()
.end()
- .process(exchange -> {
- // Set timestamp if not set
- if (exchange.getIn().getBody() instanceof SharedEvent) {
- SharedEvent event = exchange.getIn().getBody(SharedEvent.class);
- // If there is no timestamp in event, set to system time
- if (event.getTimestamp() <= 0) {
- event.setTimestamp(timerService.getCurrentTimeMillis());
- }
- }
- })
.process(this::passToInterceptors)
.choice()
.when(body().isInstanceOf(EventSubscription.class))
.process(exchange -> {
String sessionKey = getSessionKey(exchange);
EventSubscription<?> subscription = exchange.getIn().getBody(EventSubscription.class);
+ LOG.log(System.Logger.Level.TRACE, () -> "Adding subscription for session '" + sessionKey + "': " + subscription);
eventSubscriptions.createOrUpdate(sessionKey, subscription);
subscription.setSubscribed(true);
sendToSession(sessionKey, subscription);
@@ -294,7 +393,9 @@ public class ClientEventService extends RouteBuilder implements ContainerService
.when(body().isInstanceOf(CancelEventSubscription.class))
.process(exchange -> {
String sessionKey = getSessionKey(exchange);
- eventSubscriptions.cancel(sessionKey, exchange.getIn().getBody(CancelEventSubscription.class));
+ CancelEventSubscription cancelEventSubscription = exchange.getIn().getBody(CancelEventSubscription.class);
+ eventSubscriptions.cancel(sessionKey, cancelEventSubscription);
+ LOG.log(System.Logger.Level.TRACE, () -> "Cancelling subscription for session '" + sessionKey + "': " + cancelEventSubscription);
})
.stop()
.when(body().isInstanceOf(SharedEvent.class))
@@ -311,7 +412,7 @@ public class ClientEventService extends RouteBuilder implements ContainerService
.stop()
.endChoice()
.otherwise()
- .process(exchange -> LOG.fine("Unsupported message body: " + exchange.getIn().getBody()))
+ .process(exchange -> LOG.log(System.Logger.Level.TRACE, () -> "Unsupported message body: " + exchange.getIn().getBody()))
.end();
}
@@ -379,9 +480,9 @@ public class ClientEventService extends RouteBuilder implements ContainerService
if (!authorized) {
if (authContext != null) {
- LOG.fine("Client not authorised to subscribe: subscription=" + subscription + ", requestRealm=" + realm + ", username=" + authContext.getUsername() + ", userRealm=" + authContext.getAuthenticatedRealmName());
+ LOG.log(DEBUG, "Client not authorised to subscribe: subscription=" + subscription + ", requestRealm=" + realm + ", username=" + authContext.getUsername() + ", userRealm=" + authContext.getAuthenticatedRealmName());
} else {
- LOG.fine("Client not authorised to subscribe: subscription=" + subscription + ", requestRealm=" + realm + ", user=null");
+ LOG.log(DEBUG, "Client not authorised to subscribe: subscription=" + subscription + ", requestRealm=" + realm + ", user=null");
}
}
@@ -397,9 +498,9 @@ public class ClientEventService extends RouteBuilder implements ContainerService
if (!authorized) {
if (authContext != null) {
- LOG.fine("Client not authorised to send event: type=" + event.getEventType() + ", requestRealm=" + realm + ", username=" + authContext.getUsername() + ", userRealm=" + authContext.getAuthenticatedRealmName());
+ LOG.log(DEBUG, "Client not authorised to send event: type=" + event.getEventType() + ", requestRealm=" + realm + ", username=" + authContext.getUsername() + ", userRealm=" + authContext.getAuthenticatedRealmName());
} else {
- LOG.fine("Client not authorised to send event: type=" + event.getEventType() + ", requestRealm=" + realm + ", user=null");
+ LOG.log(DEBUG,"Client not authorised to send event: type=" + event.getEventType() + ", requestRealm=" + realm + ", user=null");
}
}
@@ -415,9 +516,7 @@ public class ClientEventService extends RouteBuilder implements ContainerService
if (messageBrokerService != null && messageBrokerService.getFluentProducerTemplate() != null) {
// Don't log that we are publishing a syslog event,
if (!(event instanceof SyslogEvent)) {
- if (LOG.isLoggable(Level.FINEST)) {
- LOG.finest("Publishing: " + event);
- }
+ LOG.log(System.Logger.Level.TRACE, () -> "Publishing to clients: " + event);
}
messageBrokerService.getFluentProducerTemplate()
.withBody(event)
@@ -428,24 +527,21 @@ public class ClientEventService extends RouteBuilder implements ContainerService
public void sendToSession(String sessionKey, Object data) {
if (messageBrokerService != null && messageBrokerService.getFluentProducerTemplate() != null) {
- if (LOG.isLoggable(Level.FINEST)) {
- LOG.finest("Sending to session '" + sessionKey + "': " + data);
- }
SessionInfo sessionInfo = sessionKeyInfoMap.get(sessionKey);
if (sessionInfo == null) {
- LOG.info("Cannot send to requested session it doesn't exist or is disconnected:" + sessionKey);
+ LOG.log(System.Logger.Level.INFO, "Cannot send to requested session it doesn't exist or is disconnected:" + sessionKey);
return;
}
if (sessionInfo.connectionType.equals(HEADER_CONNECTION_TYPE_WEBSOCKET)) {
messageBrokerService.getFluentProducerTemplate()
.withBody(data)
- .withHeader(ConnectionConstants.SESSION_KEY, sessionKey)
- .to("websocket://" + WEBSOCKET_EVENTS)
+ .withHeader(UndertowConstants.CONNECTION_KEY, sessionKey)
+ .to(WEBSOCKET_URI)
.asyncSend();
} else if (sessionInfo.connectionType.equals(HEADER_CONNECTION_TYPE_MQTT)) {
messageBrokerService.getFluentProducerTemplate()
.withBody(data)
- .withHeader(ConnectionConstants.SESSION_KEY, sessionKey)
+ .withHeader(SESSION_KEY, sessionKey)
.to(DefaultMQTTHandler.CLIENT_QUEUE)
.asyncSend();
}
@@ -459,7 +555,7 @@ public class ClientEventService extends RouteBuilder implements ContainerService
return;
}
- LOG.fine("Closing session: " + sessionKey);
+ LOG.log(DEBUG, "Closing session: " + sessionKey);
sessionInfo.closeRunnable.run();
}
@@ -469,7 +565,7 @@ public class ClientEventService extends RouteBuilder implements ContainerService
interceptor.accept(exchange);
boolean stop = exchange.isRouteStop();
if (stop) {
- LOG.finest("Client event interceptor marked exchange as `stop routing`");
+ LOG.log(TRACE, "Client event interceptor marked exchange as `stop routing`: " + interceptor);
}
return stop;
}));
@@ -486,4 +582,12 @@ public class ClientEventService extends RouteBuilder implements ContainerService
Runnable closeRunnable = exchange.getIn().getHeader(SESSION_TERMINATOR, Runnable.class);
return new SessionInfo(connectionType, closeRunnable);
}
+
+ protected Runnable getWebsocketSessionTerminator(WebSocketChannel webSocketChannel) {
+ return () -> {
+ try {
+ webSocketChannel.close();
+ } catch (IOException ignored) {}
+ };
+ }
}
diff --git a/manager/src/main/java/org/openremote/manager/event/EventSubscriptions.java b/manager/src/main/java/org/openremote/manager/event/EventSubscriptions.java
index 6884f03ee..c817b7c7c 100644
--- a/manager/src/main/java/org/openremote/manager/event/EventSubscriptions.java
+++ b/manager/src/main/java/org/openremote/manager/event/EventSubscriptions.java
@@ -24,7 +24,6 @@ import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.support.DefaultMessage;
import org.openremote.container.timer.TimerService;
-import org.openremote.container.web.ConnectionConstants;
import org.openremote.model.event.TriggeredEventSubscription;
import org.openremote.model.event.shared.CancelEventSubscription;
import org.openremote.model.event.shared.EventSubscription;
@@ -36,6 +35,8 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.logging.Logger;
+import static org.openremote.model.Constants.SESSION_KEY;
+
/**
* Manages subscriptions to events for WebSocket sessions.
*/
@@ -149,7 +150,7 @@ public class EventSubscriptions {
Message msg = new DefaultMessage(exchange.getContext());
msg.setBody(triggeredEventSubscription); // Don't copy the event, use same reference
msg.setHeaders(new HashMap<>(exchange.getIn().getHeaders())); // Copy headers
- msg.setHeader(ConnectionConstants.SESSION_KEY, sessionKey);
+ msg.setHeader(SESSION_KEY, sessionKey);
messageList.add(msg);
} else {
if (triggeredEventSubscription.getEvents() != null) {
diff --git a/manager/src/main/java/org/openremote/manager/event/UndertowHost.java b/manager/src/main/java/org/openremote/manager/event/UndertowHost.java
new file mode 100644
index 000000000..8f15d09d0
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/event/UndertowHost.java
@@ -0,0 +1,114 @@
+/*
+ * Copyright 2023, 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.event;
+
+import com.google.api.Http;
+import io.undertow.Undertow;
+import io.undertow.server.HttpHandler;
+import io.undertow.servlet.Servlets;
+import io.undertow.servlet.api.DeploymentInfo;
+import io.undertow.servlet.api.SecurityConstraint;
+import io.undertow.servlet.api.SecurityInfo;
+import io.undertow.servlet.api.WebResourceCollection;
+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.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
+ */
+public class UndertowHost implements org.apache.camel.component.undertow.UndertowHost {
+
+ 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) {
+ this.container = container;
+ this.undertow = container.getService(WebService.class).getUndertow();
+ this.key = key;
+ this.options = options;
+ }
+
+ @Override
+ public void validateEndpointURI(URI httpURI) {
+ // all URIs are good
+ }
+
+ @Override
+ public HttpHandler registerHandler(UndertowConsumer consumer, HttpHandlerRegistrationInfo registrationInfo, HttpHandler handler) {
+
+ if (camelHandler != null) {
+ return camelHandler;
+ }
+
+ String path = registrationInfo.getUri().getPath();
+ String deploymentName = "Camel WebSocket Deployment";
+ deployment = Servlets.deployment()
+ .setDeploymentName(deploymentName)
+ .setContextPath(path)
+ .setClassLoader(getClass().getClassLoader())
+ //httpHandler for servlet is ignored, camel handler is used instead of it
+ .addInnerHandlerChainWrapper(h -> handler);
+
+ // Require authentication, but authorize specific roles later in Camel
+ WebResourceCollection resourceCollection = new WebResourceCollection();
+ resourceCollection.addUrlPattern("/*");
+ SecurityConstraint constraint = new SecurityConstraint();
+ 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().add(0, websocketHttpHandler);
+
+ // Caller expects a CamelWebSocketHandler instance
+ camelHandler = handler;
+ return handler;
+ }
+
+ @Override
+ public void unregisterHandler(UndertowConsumer consumer, HttpHandlerRegistrationInfo registrationInfo) {
+ WebService webService = container.getService(WebService.class);
+
+ if (deployment != null) {
+ webService.removeServletDeployment(deployment);
+ deployment = null;
+ }
+
+ webService.getRequestHandlers().remove(websocketHttpHandler);
+ websocketHttpHandler = null;
+ }
+}
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 3c5462712..d1a02c2e7 100644
--- a/manager/src/main/java/org/openremote/manager/gateway/GatewayService.java
+++ b/manager/src/main/java/org/openremote/manager/gateway/GatewayService.java
@@ -19,11 +19,11 @@
*/
package org.openremote.manager.gateway;
+import jakarta.persistence.EntityManager;
import org.apache.camel.Exchange;
import org.apache.camel.Predicate;
import org.apache.camel.builder.RouteBuilder;
import org.openremote.container.message.MessageBrokerService;
-import org.openremote.container.web.ConnectionConstants;
import org.openremote.manager.asset.AssetProcessingException;
import org.openremote.manager.asset.AssetProcessingService;
import org.openremote.manager.asset.AssetStorageService;
@@ -53,7 +53,6 @@ import org.openremote.model.security.User;
import org.openremote.model.syslog.SyslogCategory;
import org.openremote.model.util.TextUtil;
-import jakarta.persistence.EntityManager;
import java.util.*;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -67,6 +66,7 @@ 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.manager.gateway.GatewayConnector.mapAssetId;
+import static org.openremote.model.Constants.*;
import static org.openremote.model.syslog.SyslogCategory.GATEWAY;
/**
@@ -295,13 +295,13 @@ public class GatewayService extends RouteBuilder implements ContainerService, As
return;
}
- if (header(ConnectionConstants.SESSION_OPEN).matches(exchange)) {
+ if (header(SESSION_OPEN).matches(exchange)) {
String sessionKey = ClientEventService.getSessionKey(exchange);
processGatewayConnected(clientId, sessionKey);
return;
}
- if (or(header(ConnectionConstants.SESSION_CLOSE), header(ConnectionConstants.SESSION_CLOSE_ERROR)).matches(exchange)) {
+ if (or(header(SESSION_CLOSE), header(SESSION_CLOSE_ERROR)).matches(exchange)) {
processGatewayDisconnected(clientId);
return;
}
diff --git a/manager/src/main/java/org/openremote/manager/mqtt/DefaultMQTTHandler.java b/manager/src/main/java/org/openremote/manager/mqtt/DefaultMQTTHandler.java
index 0a49856ed..4da9b434c 100644
--- a/manager/src/main/java/org/openremote/manager/mqtt/DefaultMQTTHandler.java
+++ b/manager/src/main/java/org/openremote/manager/mqtt/DefaultMQTTHandler.java
@@ -25,7 +25,6 @@ import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection;
import org.apache.camel.builder.RouteBuilder;
import org.keycloak.KeycloakSecurityContext;
import org.openremote.container.security.AuthContext;
-import org.openremote.container.web.ConnectionConstants;
import org.openremote.manager.asset.AssetStorageService;
import org.openremote.manager.event.ClientEventService;
import org.openremote.model.Constants;
@@ -51,7 +50,7 @@ import java.util.regex.Pattern;
import static org.openremote.manager.event.ClientEventService.CLIENT_EVENT_QUEUE;
import static org.openremote.manager.mqtt.MQTTBrokerService.getConnectionIDString;
-import static org.openremote.model.Constants.ASSET_ID_REGEXP;
+import static org.openremote.model.Constants.*;
import static org.openremote.model.syslog.SyslogCategory.API;
/**
@@ -106,7 +105,7 @@ public class DefaultMQTTHandler extends MQTTHandler {
.when(body().isInstanceOf(TriggeredEventSubscription.class))
.process(exchange -> {
// Get the subscriber consumer
- String connectionID = exchange.getIn().getHeader(ConnectionConstants.SESSION_KEY, String.class);
+ String connectionID = exchange.getIn().getHeader(SESSION_KEY, String.class);
if (connectionID == null) {
LOG.warning("No connection ID for triggered subscription so cannot deliver");
} else {
@@ -138,7 +137,7 @@ public class DefaultMQTTHandler extends MQTTHandler {
public void onConnect(RemotingConnection connection) {
super.onConnect(connection);
Map<String, Object> headers = prepareHeaders(null, connection);
- headers.put(ConnectionConstants.SESSION_OPEN, true);
+ headers.put(SESSION_OPEN, true);
// Put a close connection runnable into the headers for the client event service
Runnable closeRunnable = () -> {
@@ -147,7 +146,7 @@ public class DefaultMQTTHandler extends MQTTHandler {
mqttBrokerService.doForceDisconnect(connection);
}
};
- headers.put(ConnectionConstants.SESSION_TERMINATOR, closeRunnable);
+ headers.put(SESSION_TERMINATOR, closeRunnable);
messageBrokerService.getFluentProducerTemplate()
.withHeaders(headers)
.to(CLIENT_EVENT_QUEUE)
@@ -159,7 +158,7 @@ public class DefaultMQTTHandler extends MQTTHandler {
super.onDisconnect(connection);
Map<String, Object> headers = prepareHeaders(null, connection);
- headers.put(ConnectionConstants.SESSION_CLOSE, true);
+ headers.put(SESSION_CLOSE, true);
messageBrokerService.getFluentProducerTemplate()
.withHeaders(headers)
.to(CLIENT_EVENT_QUEUE)
@@ -171,7 +170,7 @@ public class DefaultMQTTHandler extends MQTTHandler {
public void onConnectionLost(RemotingConnection connection) {
super.onConnectionLost(connection);
Map<String, Object> headers = prepareHeaders(null, connection);
- headers.put(ConnectionConstants.SESSION_CLOSE_ERROR, true);
+ headers.put(SESSION_CLOSE_ERROR, true);
messageBrokerService.getFluentProducerTemplate()
.withHeaders(headers)
.to(CLIENT_EVENT_QUEUE)
@@ -572,7 +571,7 @@ public class DefaultMQTTHandler extends MQTTHandler {
protected static Map<String, Object> prepareHeaders(String requestRealm, RemotingConnection connection) {
Map<String, Object> headers = new HashMap<>();
- headers.put(ConnectionConstants.SESSION_KEY, getConnectionIDString(connection));
+ headers.put(SESSION_KEY, getConnectionIDString(connection));
headers.put(ClientEventService.HEADER_CONNECTION_TYPE, ClientEventService.HEADER_CONNECTION_TYPE_MQTT);
headers.put(Constants.REALM_PARAM_NAME, requestRealm);
return headers;
diff --git a/model/src/main/java/org/openremote/model/Constants.java b/model/src/main/java/org/openremote/model/Constants.java
index b57400ea7..a57571afd 100644
--- a/model/src/main/java/org/openremote/model/Constants.java
+++ b/model/src/main/java/org/openremote/model/Constants.java
@@ -45,6 +45,11 @@ public interface Constants {
String WRITE_INSIGHTS_ROLE = "write:insights";
String RESTRICTED_USER_REALM_ROLE = "restricted_user";
String AUTH_CONTEXT = "AUTH_CONTEXT";
+ String SESSION_TERMINATOR = "connection.sessionTerminator";
+ String SESSION_KEY = "connection.sessionKey";
+ String SESSION_OPEN = "connection.sessionOpen";
+ String SESSION_CLOSE = "connection.sessionClose";
+ String SESSION_CLOSE_ERROR = "connection.sessionCloseError";
int ACCESS_TOKEN_LIFESPAN_SECONDS = 60; // 1 minute
String PERSISTENCE_SEQUENCE_ID_GENERATOR = "OPENREMOTE_SEQUENCE";
String PERSISTENCE_UNIQUE_ID_GENERATOR = "UNIQUE_ID_GENERATOR";
diff --git a/test/src/testFixtures/groovy/org/openremote/test/ContainerTrait.groovy b/test/src/testFixtures/groovy/org/openremote/test/ContainerTrait.groovy
index cc6d592c4..eacf4c13d 100644
--- a/test/src/testFixtures/groovy/org/openremote/test/ContainerTrait.groovy
+++ b/test/src/testFixtures/groovy/org/openremote/test/ContainerTrait.groovy
@@ -35,7 +35,6 @@ 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.container.web.DefaultWebsocketComponent
import org.openremote.container.web.WebClient
import org.openremote.manager.agent.AgentService
import org.openremote.manager.asset.AssetProcessingService
@@ -518,27 +517,4 @@ trait ContainerTrait {
ProducerTemplate getMessageProducerTemplate(Container container) {
return container.getService(MessageBrokerService.class).getContext().createProducerTemplate()
}
-
- void addRoutes(RouteBuilder routeBuilder) {
- container.getService(MessageBrokerService.class).getContext().addRoutes(routeBuilder)
- }
-
- WebSocketContainer createWebsocketClient() {
- return ClientManager.createClient()
- }
-
- UriBuilder getWebsocketServerUrl(UriBuilder uriBuilder, String endpointPath, String realm, String accessToken) {
- uriBuilder.clone()
- .scheme("ws")
- .replacePath(DefaultWebsocketComponent.WEBSOCKET_PATH)
- .path(endpointPath)
- .queryParam(Constants.REALM_PARAM_NAME, realm)
- .queryParam("Authorization", "Bearer " + accessToken)
- }
-
- Session connect(WebSocketContainer websocketContainer, Endpoint endpoint, UriBuilder serverUri, String endpointPath, String realm, String accessToken) {
- def websocketUrl = getWebsocketServerUrl(serverUri, endpointPath, realm, accessToken)
- def config = ClientEndpointConfig.Builder.create().build()
- websocketContainer.connectToServer(endpoint, config, websocketUrl.build())
- }
}