Skip to content

armgit / core

Public Imported from GitHub
0

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

Added message broker, improved container bootstrap

Christian Bauerfdf052d3e16b
diff --git a/container/build.gradle b/container/build.gradle
index 2a7e8b487..dcf264cd8 100644
--- a/container/build.gradle
+++ b/container/build.gradle
@@ -31,4 +31,11 @@ dependencies {
compile "org.hibernate:hibernate-entitymanager:$hibernateVersion"
compile "org.hibernate:hibernate-java8:$hibernateVersion"
compile "org.hibernate:hibernate-validator:$hibernateValidatorVersion"
+
+ compile "org.apache.camel:camel-core:$camelVersion"
+ compile "org.apache.camel:camel-servlet:$camelVersion"
+ compile "org.apache.camel:camel-ahc-ws:$camelVersion"
+ compile "org.apache.camel:camel-jackson:$camelVersion"
+ compile "org.apache.camel:camel-script:$camelVersion"
+ compile "org.apache.camel:camel-groovy:$camelVersion"
}
diff --git a/container/src/main/java/org/openremote/container/Container.java b/container/src/main/java/org/openremote/container/Container.java
index e63eb0468..fd5e1db25 100644
--- a/container/src/main/java/org/openremote/container/Container.java
+++ b/container/src/main/java/org/openremote/container/Container.java
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ObjectNode;
@@ -23,7 +24,6 @@ import java.util.stream.StreamSupport;
public class Container {
public static final Logger LOG;
- public static final ObjectMapper JSON;
static {
if (System.getProperty("java.util.logging.config.file") == null) {
@@ -37,22 +37,13 @@ public class Container {
}
LOG = Logger.getLogger(Container.class.getName());
-
- JSON = new ObjectMapper();
- JSON.setSerializationInclusion(JsonInclude.Include.NON_NULL)
- .configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)
- .configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false)
- .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
- .setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)
- .setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE)
- .setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE)
- .setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE)
- .setVisibility(PropertyAccessor.CREATOR, JsonAutoDetect.Visibility.NONE);
}
public static final String DEV_MODE = "DEV_MODE";
public static final boolean DEV_MODE_DEFAULT = true;
+ public final ObjectMapper JSON;
+
protected final ObjectNode config;
protected final boolean devMode;
@@ -84,6 +75,17 @@ public class Container {
@SafeVarargs
public Container(Map<String, String> config, Stream<ContainerService>... serviceStreams) {
+ JSON = new ObjectMapper();
+ JSON.setSerializationInclusion(JsonInclude.Include.NON_NULL)
+ .configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)
+ .configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false)
+ .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
+ .setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)
+ .setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE)
+ .setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE)
+ .setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE)
+ .setVisibility(PropertyAccessor.CREATOR, JsonAutoDetect.Visibility.NONE);
+
this.config = JSON.createObjectNode();
for (Map.Entry<String, String> entry : config.entrySet()) {
this.config.put(entry.getKey(), entry.getValue());
@@ -123,13 +125,22 @@ public class Container {
synchronized public CompletableFuture start() {
return CompletableFuture.runAsync(() -> {
LOG.info(">>> Starting runtime container...");
- for (ContainerService service : getServices()) {
- LOG.fine("Preparing service: " + service);
- service.prepare(Container.this);
- }
- for (ContainerService service : getServices()) {
- LOG.fine("Starting service: " + service);
- service.start(Container.this);
+ try {
+ for (ContainerService service : getServices()) {
+ LOG.fine("Initializing service: " + service);
+ service.init(Container.this);
+ }
+ for (int counter = getServices().length - 1; counter >= 0; counter--) {
+ ContainerService service = getServices()[counter];
+ LOG.fine("Configuring service: " + service);
+ service.configure(Container.this);
+ }
+ for (ContainerService service : getServices()) {
+ LOG.fine("Starting service: " + service);
+ service.start(Container.this);
+ }
+ } catch (Exception ex) {
+ throw new RuntimeException(ex);
}
LOG.info(">>> Runtime container startup complete");
});
@@ -139,7 +150,11 @@ public class Container {
LOG.info("<<< Stopping runtime container...");
for (ContainerService service : getServices()) {
LOG.fine("Stopping service: " + service);
- service.stop(this);
+ try {
+ service.stop(this);
+ } catch (Exception ex) {
+ throw new RuntimeException(ex);
+ }
}
LOG.info("<<< Runtime container stopped");
}
@@ -147,7 +162,7 @@ public class Container {
/**
* Starts the container and a non-daemon thread that waits forever.
*/
- public void startBackground() throws Exception{
+ public void startBackground() throws Exception {
// We block here so we die fast if startup fails
start().get();
Thread containerThread = new Thread("container") {
@@ -172,9 +187,22 @@ public class Container {
return services.values().toArray(new ContainerService[services.size()]);
}
+ /**
+ * Get a service instance matching the specified type exactly, or if that yields
+ * no result, try to get the first service instance that has a matching interface.
+ */
synchronized public <T extends ContainerService> T getService(Class<T> type) {
//noinspection unchecked
T service = (T) services.get(type);
+ if (service == null) {
+ for (ContainerService containerService : services.values()) {
+ if (type.isAssignableFrom(containerService.getClass())) {
+ //noinspection unchecked
+ service = (T) containerService;
+ break;
+ }
+ }
+ }
if (service == null)
throw new IllegalStateException("Missing required service: " + type);
return service;
diff --git a/container/src/main/java/org/openremote/container/ContainerService.java b/container/src/main/java/org/openremote/container/ContainerService.java
index b57e48102..c06aa478d 100644
--- a/container/src/main/java/org/openremote/container/ContainerService.java
+++ b/container/src/main/java/org/openremote/container/ContainerService.java
@@ -2,10 +2,24 @@ package org.openremote.container;
public interface ContainerService {
- void prepare(Container container);
+ /**
+ * All services are initialized in the order they have been added to container.
+ */
+ void init(Container container) throws Exception;
- void start(Container container);
+ /**
+ * After initialization, services are configured in reverse order.
+ */
+ void configure(Container container) throws Exception;
- void stop(Container container);
+ /**
+ * After configuration, services are started in the order they have been added to container.
+ */
+ void start(Container container) throws Exception;
+
+ /**
+ * When the container is shutting down, it stops all services in the order they have been added to container.
+ */
+ void stop(Container container) throws Exception;
}
diff --git a/container/src/main/java/org/openremote/container/json/JacksonConfig.java b/container/src/main/java/org/openremote/container/json/JacksonConfig.java
index ab877a31a..801c93893 100644
--- a/container/src/main/java/org/openremote/container/json/JacksonConfig.java
+++ b/container/src/main/java/org/openremote/container/json/JacksonConfig.java
@@ -12,8 +12,14 @@ import javax.ws.rs.ext.Provider;
@Produces(MediaType.APPLICATION_JSON)
public class JacksonConfig implements ContextResolver<ObjectMapper> {
+ final protected Container container;
+
+ public JacksonConfig(Container container) {
+ this.container = container;
+ }
+
@Override
public ObjectMapper getContext(Class<?> type) {
- return Container.JSON;
+ return container.JSON;
}
}
\ No newline at end of file
diff --git a/container/src/main/java/org/openremote/container/message/MessageBrokerContext.java b/container/src/main/java/org/openremote/container/message/MessageBrokerContext.java
new file mode 100644
index 000000000..69fef4705
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/message/MessageBrokerContext.java
@@ -0,0 +1,19 @@
+package org.openremote.container.message;
+
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.impl.PropertyPlaceholderDelegateRegistry;
+import org.apache.camel.impl.SimpleRegistry;
+import org.apache.camel.spi.Registry;
+
+public class MessageBrokerContext extends DefaultCamelContext {
+
+ @Override
+ protected Registry createRegistry() {
+ return new SimpleRegistry();
+ }
+
+ @Override
+ public SimpleRegistry getRegistry() {
+ return (SimpleRegistry) ((PropertyPlaceholderDelegateRegistry) super.getRegistry()).getRegistry();
+ }
+}
diff --git a/container/src/main/java/org/openremote/container/message/MessageBrokerService.java b/container/src/main/java/org/openremote/container/message/MessageBrokerService.java
new file mode 100644
index 000000000..e149dd385
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/message/MessageBrokerService.java
@@ -0,0 +1,89 @@
+package org.openremote.container.message;
+
+import org.apache.camel.Processor;
+import org.apache.camel.builder.LoggingErrorHandlerBuilder;
+import org.apache.camel.impl.DefaultStreamCachingStrategy;
+import org.apache.camel.spi.RouteContext;
+import org.apache.camel.spi.StreamCachingStrategy;
+import org.openremote.container.Container;
+import org.openremote.container.ContainerService;
+import org.openremote.container.web.DefaultWebsocketComponent;
+import org.openremote.container.web.WebService;
+import org.openremote.container.web.socket.WebsocketComponent;
+
+import java.util.logging.Logger;
+
+public class MessageBrokerService implements ContainerService {
+
+ private static final Logger LOG = Logger.getLogger(MessageBrokerService.class.getName());
+
+ public static final String WEBSOCKET_PATH = "/websocket";
+
+ public static final String MESSAGE_SESSION_ALLOWED_ORIGIN = "MESSAGE_SESSION_ALLOWED_ORIGIN";
+ public static final String MESSAGE_SESSION_ALLOWED_ORIGIN_DEFAULT = null;
+
+ protected MessageBrokerContext context;
+
+ @Override
+ public void init(Container container) throws Exception {
+ context = new MessageBrokerContext();
+
+ // TODO make configurable in environment
+ context.disableJMX();
+
+ // TODO might need this for errorhandler?
+ context.setAllowUseOriginalMessage(false);
+
+ // Don't use JMS, we do our own correlation
+ context.setUseBreadcrumb(false);
+
+ // TODO: Wait 5 seconds before forcing a route to stop?
+ context.getShutdownStrategy().setTimeout(5);
+
+ context.setStreamCaching(true);
+ StreamCachingStrategy streamCachingStrategy = new DefaultStreamCachingStrategy();
+ streamCachingStrategy.setSpoolThreshold(524288); // Half megabyte
+ context.setStreamCachingStrategy(streamCachingStrategy);
+
+ context.setErrorHandlerBuilder(new LoggingErrorHandlerBuilder() {
+ @Override
+ public Processor createErrorHandler(RouteContext routeContext, Processor processor) {
+ // TODO: Custom error handler?
+ return super.createErrorHandler(routeContext, processor);
+ }
+ });
+
+ context.getRegistry().put(Container.class.getName(), container);
+
+ String allowedOrigin = container.getConfig(MESSAGE_SESSION_ALLOWED_ORIGIN, MESSAGE_SESSION_ALLOWED_ORIGIN_DEFAULT);
+ WebsocketComponent websocketComponent = new DefaultWebsocketComponent(
+ container.getService(WebService.class),
+ allowedOrigin
+ );
+
+ context.addComponent(WebsocketComponent.NAME, websocketComponent);
+ }
+
+ @Override
+ public void configure(Container container) throws Exception {
+ // Start now so route endpoints are added before WebService is configured
+ LOG.info("Starting Camel message broker");
+ context.start();
+ }
+
+ @Override
+ public void start(Container container) throws Exception {
+ }
+
+ @Override
+ public void stop(Container container) throws Exception {
+ if (context != null) {
+ context.stop();
+ }
+ }
+
+ public MessageBrokerContext getContext() {
+ return context;
+ }
+
+}
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 27e519683..e214dee58 100644
--- a/container/src/main/java/org/openremote/container/persistence/PersistenceService.java
+++ b/container/src/main/java/org/openremote/container/persistence/PersistenceService.java
@@ -34,13 +34,14 @@ public class PersistenceService implements ContainerService {
protected EntityManagerFactory entityManagerFactory;
@Override
- public void prepare(Container container) {
+ public void init(Container container) throws Exception {
String databaseProduct = container.getConfig(DATABASE_PRODUCT, DATABASE_PRODUCT_DEFAULT);
-
LOG.info("Preparing persistence service for database: " + databaseProduct);
-
database = Database.Product.valueOf(databaseProduct);
+ }
+ @Override
+ public void configure(Container container) throws Exception {
String connectionUrl = container.getConfig(DATABASE_CONNECTION_URL, DATABASE_CONNECTION_URL_DEFAULT);
LOG.info("Using database connection URL: " + connectionUrl);
@@ -55,13 +56,13 @@ public class PersistenceService implements ContainerService {
}
@Override
- public void start(Container container) {
+ public void start(Container container) throws Exception {
this.entityManagerFactory =
Persistence.createEntityManagerFactory(persistenceUnitName, persistenceUnitProperties);
}
@Override
- public void stop(Container container) {
+ public void stop(Container container) throws Exception {
LOG.info("Stopping persistence service...");
if (entityManagerFactory != null) {
entityManagerFactory.close();
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 8d373c12e..490239985 100644
--- a/container/src/main/java/org/openremote/container/security/IdentityService.java
+++ b/container/src/main/java/org/openremote/container/security/IdentityService.java
@@ -35,7 +35,7 @@ import static javax.ws.rs.core.Response.Status.Family.REDIRECTION;
import static javax.ws.rs.core.Response.Status.Family.SUCCESSFUL;
import static org.openremote.container.web.WebClient.getTarget;
-public abstract class IdentityService implements ContainerService {
+public class IdentityService implements ContainerService {
private static final Logger LOG = Logger.getLogger(IdentityService.class.getName());
@@ -64,13 +64,13 @@ public abstract class IdentityService implements ContainerService {
protected UriBuilder externalAuthServerUrl;
protected UriBuilder keycloakHostUri;
protected UriBuilder keycloakServiceUri;
- protected Client client;
+ protected Client httpClient;
protected LoadingCache<ClientRealm.Key, ClientRealm> clientApplicationCache;
+ protected boolean keycloakReverseProxy;
+ protected String clientId;
@Override
- public void prepare(Container container) {
-
- boolean disableAPISecurity = container.getConfigBoolean(DISABLE_API_SECURITY, DISABLE_API_SECURITY_DEFAULT);
+ public void init(Container container) throws Exception {
boolean identityNetworkSecure = container.getConfigBoolean(IDENTITY_NETWORK_SECURE, IDENTITY_NETWORK_SECURE_DEFAULT);
String identityNetworkHost = container.getConfig(IDENTITY_NETWORK_HOST, IDENTITY_NETWORK_HOST_DEFAULT);
int identityNetworkPort = container.getConfigInteger(IDENTITY_NETWORK_WEBSERVER_PORT, IDENTITY_NETWORK_WEBSERVER_PORT_DEFAULT);
@@ -112,28 +112,33 @@ public abstract class IdentityService implements ContainerService {
container.getConfigInteger(KEYCLOAK_CLIENT_POOL_SIZE, KEYCLOAK_CLIENT_POOL_SIZE_DEFAULT)
);
- this.client = WebClient.registerDefaults(clientBuilder).build();
+ this.httpClient = WebClient.registerDefaults(container, clientBuilder).build();
clientApplicationCache = createClientApplicationCache();
+ }
- container.getService(getWebServiceClass()).getApiSingletons().add(
+ @Override
+ public void configure(Container container) throws Exception {
+ container.getService(WebService.class).getApiSingletons().add(
new IdentityResource(this)
);
- if (enableKeycloakReverseProxy()) {
+ if (isKeycloakReverseProxy()) {
SimpleProxyClientProvider proxyClient = new SimpleProxyClientProvider(keycloakHostUri.build());
ProxyHandler proxyHandler = new ProxyHandler(
proxyClient,
container.getConfigInteger(KEYCLOAK_REQUEST_TIMEOUT, KEYCLOAK_REQUEST_TIMEOUT_DEFAULT),
ResponseCodeHandler.HANDLE_404
);
- container.getService(getWebServiceClass()).getPrefixRoutes().put(AUTH_PATH, proxyHandler);
+ container.getService(WebService.class).getPrefixRoutes().put(AUTH_PATH, proxyHandler);
}
- if (disableAPISecurity) {
+ if (container.getConfigBoolean(DISABLE_API_SECURITY, DISABLE_API_SECURITY_DEFAULT)) {
LOG.warning("###################### API SECURITY DISABLED! ######################");
} else {
- container.getService(getWebServiceClass()).setKeycloakConfigResolver(request -> {
+ if (getClientId() == null)
+ throw new IllegalStateException("Client ID must be set to enable API security");
+ container.getService(WebService.class).setKeycloakConfigResolver(request -> {
KeycloakDeployment passthroughKeycloakDeployment = new KeycloakDeployment();
String realm = request.getQueryParamValue("realm");
@@ -148,28 +153,28 @@ public abstract class IdentityService implements ContainerService {
}
@Override
- public void start(Container container) {
+ public void start(Container container) throws Exception {
// TODO Not a great way to block startup while we wait for other services (Hystrix?)
pingKeycloak();
LOG.info("Keycloak identity provider available: " + keycloakServiceUri.build());
}
@Override
- public void stop(Container container) {
- if (client != null)
- client.close();
+ public void stop(Container container) throws Exception {
+ if (httpClient != null)
+ httpClient.close();
}
- public Client getClient() {
- return client;
+ public Client getHttpClient() {
+ return httpClient;
}
public KeycloakResource getKeycloak() {
- return getKeycloak(getTarget(client, keycloakServiceUri.build(), null));
+ return getKeycloak(getTarget(httpClient, keycloakServiceUri.build(), null));
}
public KeycloakResource getKeycloak(String accessToken) {
- return getKeycloak(getTarget(client, keycloakServiceUri.build(), accessToken));
+ return getKeycloak(getTarget(httpClient, keycloakServiceUri.build(), accessToken));
}
public KeycloakResource getKeycloak(ResteasyWebTarget target) {
@@ -269,9 +274,19 @@ public abstract class IdentityService implements ContainerService {
.build(loader);
}
- protected abstract boolean enableKeycloakReverseProxy();
+ public boolean isKeycloakReverseProxy() {
+ return keycloakReverseProxy;
+ }
+
+ public void setKeycloakReverseProxy(boolean keycloakReverseProxy) {
+ this.keycloakReverseProxy = keycloakReverseProxy;
+ }
- protected abstract Class<? extends WebService> getWebServiceClass();
+ public String getClientId() {
+ return clientId;
+ }
- protected abstract String getClientId();
+ public void setClientId(String clientId) {
+ this.clientId = clientId;
+ }
}
\ No newline at end of file
diff --git a/container/src/main/java/org/openremote/container/web/DefaultWebsocketComponent.java b/container/src/main/java/org/openremote/container/web/DefaultWebsocketComponent.java
new file mode 100644
index 000000000..6bdcf28b1
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/web/DefaultWebsocketComponent.java
@@ -0,0 +1,115 @@
+/*
+ * Copyright 2015, 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.HttpHandler;
+import io.undertow.servlet.api.DeploymentInfo;
+import io.undertow.servlet.api.FilterInfo;
+import io.undertow.servlet.api.InstanceHandle;
+import io.undertow.websockets.jsr.DefaultContainerConfigurator;
+import io.undertow.websockets.jsr.WebSocketDeploymentInfo;
+import org.openremote.container.message.MessageBrokerService;
+import org.openremote.container.web.socket.WebsocketAdapter;
+import org.openremote.container.web.socket.WebsocketCORSFilter;
+import org.openremote.container.web.socket.WebsocketComponent;
+import org.openremote.container.web.socket.WebsocketConsumer;
+
+import javax.servlet.DispatcherType;
+import javax.servlet.Filter;
+import javax.websocket.server.ServerEndpointConfig;
+import java.util.Map;
+import java.util.logging.Logger;
+
+public class DefaultWebsocketComponent extends WebsocketComponent {
+
+ private static final Logger LOG = Logger.getLogger(DefaultWebsocketComponent.class.getName());
+
+ final protected WebService webService;
+ final protected String allowedOrigin;
+ protected DeploymentInfo deploymentInfo;
+
+ public DefaultWebsocketComponent(WebService webService, String allowedOrigin) {
+ this.webService = webService;
+ this.allowedOrigin = allowedOrigin;
+ }
+
+ @Override
+ protected void deploy() throws Exception {
+
+ WebSocketDeploymentInfo webSocketDeploymentInfo = new WebSocketDeploymentInfo();
+
+ getConsumers().entrySet().stream().forEach(consumerEntry -> {
+ String endpointPath = MessageBrokerService.WEBSOCKET_PATH + "/" + consumerEntry.getKey();
+ 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(consumerEntry.getValue());
+ }
+ })
+ .build()
+ );
+ });
+
+ deploymentInfo = new DeploymentInfo()
+ .setDeploymentName("WebSocket Deployment")
+ .setContextPath(MessageBrokerService.WEBSOCKET_PATH)
+ .addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, webSocketDeploymentInfo)
+ .setClassLoader(WebsocketComponent.class.getClassLoader());
+
+ HttpHandler handler = webService.addServletDeployment(deploymentInfo);
+
+ webService.getPrefixRoutes().put(
+ MessageBrokerService.WEBSOCKET_PATH, handler
+ );
+ }
+
+ @Override
+ protected void undeploy() throws Exception {
+ if (deploymentInfo != null) {
+ webService.removeServletDeployment(deploymentInfo);
+ deploymentInfo = null;
+ }
+ webService.getPrefixRoutes().remove(MessageBrokerService.WEBSOCKET_PATH);
+ }
+
+ protected void addCORSFilter() {
+ if (allowedOrigin == null)
+ return;
+ WebsocketCORSFilter websocketCORSFilter = new WebsocketCORSFilter();
+ FilterInfo filterInfo = new FilterInfo("WebSocket CORS Filter", WebsocketCORSFilter.class, () -> new InstanceHandle<Filter>() {
+ @Override
+ public Filter getInstance() {
+ return websocketCORSFilter;
+ }
+
+ @Override
+ public void release() {
+ }
+ }).addInitParam(WebsocketCORSFilter.ALLOWED_ORIGIN, allowedOrigin);
+ deploymentInfo.addFilter(filterInfo);
+ deploymentInfo.addFilterUrlMapping(filterInfo.getName(), "/*", DispatcherType.REQUEST);
+ }
+
+}
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 752a3ba64..edb528e00 100644
--- a/container/src/main/java/org/openremote/container/web/WebClient.java
+++ b/container/src/main/java/org/openremote/container/web/WebClient.java
@@ -2,6 +2,7 @@ package org.openremote.container.web;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
+import org.openremote.container.Container;
import org.openremote.container.json.ElementalMessageBodyConverter;
import org.openremote.container.json.JacksonConfig;
import org.openremote.container.security.BearerAuthClientRequestFilter;
@@ -12,9 +13,9 @@ import java.net.URI;
public interface WebClient {
- static ResteasyClientBuilder registerDefaults(ResteasyClientBuilder builder) {
+ static ResteasyClientBuilder registerDefaults(Container container, ResteasyClientBuilder builder) {
return builder
- .register(JacksonConfig.class)
+ .register(new JacksonConfig(container))
.register(ElementalMessageBodyConverter.class)
.register(new BearerAuthClientRequestFilter())
.register(new ClientSecretRequestFilter());
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 aad447717..a82bb8501 100644
--- a/container/src/main/java/org/openremote/container/web/WebService.java
+++ b/container/src/main/java/org/openremote/container/web/WebService.java
@@ -30,6 +30,7 @@ import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
+import java.util.concurrent.RejectedExecutionException;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -56,44 +57,51 @@ public abstract class WebService implements ContainerService {
protected String host;
protected int port;
protected Undertow undertow;
+
+ protected String defaultRealm;
protected Map<String, HttpHandler> prefixRoutes = new LinkedHashMap<>();
+ protected Path staticResourceDocRoot;
protected Collection<Class<?>> apiClasses = new HashSet<>();
protected Collection<Object> apiSingletons = new HashSet<>();
protected KeycloakConfigResolver keycloakConfigResolver;
@Override
- public void prepare(Container container) {
+ public void init(Container container) throws Exception {
host = container.getConfig(WEBSERVER_LISTEN_HOST, WEBSERVER_LISTEN_HOST_DEFAULT);
port = container.getConfigInteger(WEBSERVER_LISTEN_PORT, WEBSERVER_LISTEN_PORT_DEFAULT);
}
@Override
- public void start(Container container) {
- if (undertow == null) {
-
- undertow = build(
- container,
- Undertow.builder()
- .addHttpListener(port, host)
- ).build();
+ public void configure(Container container) throws Exception {
+ undertow = build(
+ container,
+ Undertow.builder()
+ .addHttpListener(port, host)
+ ).build();
+ }
+ @Override
+ public void start(Container container) throws Exception {
+ if (undertow != null) {
LOG.info("Starting webserver on http://" + host + ":" + port);
undertow.start();
}
}
@Override
- public void stop(Container container) {
+ public void stop(Container container) throws Exception {
if (undertow != null) {
LOG.info("Stopping webserver...");
+ undertow.stop();
undertow = null;
}
}
protected Undertow.Builder build(Container container, Undertow.Builder builder) {
- Path docRoot = getStaticResourceDocRoot(container);
- HttpHandler staticResourceHandler = docRoot != null ? createStaticResourceHandler(container, docRoot) : null;
+ HttpHandler staticResourceHandler = getStaticResourceDocRoot() != null
+ ? createStaticResourceHandler(container, getStaticResourceDocRoot())
+ : null;
ResteasyDeployment resteasyDeployment = createResteasyDeployment(container);
HttpHandler apiHandler = createApiHandler(resteasyDeployment);
@@ -253,13 +261,13 @@ public abstract class WebService implements ContainerService {
deploymentInfo.addServletContextAttribute(
ResteasyContextParameters.RESTEASY_DEPLOYMENTS,
new HashMap<String, ResteasyDeployment>() {{
- put("", resteasyDeployment);
- }}
+ put("", resteasyDeployment);
+ }}
);
return addServletDeployment(deploymentInfo);
}
- protected HttpHandler addServletDeployment(DeploymentInfo deploymentInfo) {
+ public HttpHandler addServletDeployment(DeploymentInfo deploymentInfo) {
try {
DeploymentManager manager = Servlets.defaultContainer().addDeployment(deploymentInfo);
manager.deploy();
@@ -269,6 +277,17 @@ public abstract class WebService implements ContainerService {
}
}
+ 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);
+ }
+ }
+
protected ResteasyDeployment createResteasyDeployment(Container container) {
if (getApiClasses() == null && getApiSingletons() == null)
return null;
@@ -277,7 +296,7 @@ public abstract class WebService implements ContainerService {
resteasyDeployment.setApplication(webApplication);
// Custom providers (these only apply to server applications, not client calls)
- resteasyDeployment.getActualProviderClasses().add(JacksonConfig.class);
+ resteasyDeployment.getProviders().add(new JacksonConfig(container));
resteasyDeployment.getActualProviderClasses().add(ElementalMessageBodyConverter.class);
resteasyDeployment.getActualProviderClasses().add(AlreadyGzippedWriterInterceptor.class);
resteasyDeployment.getActualProviderClasses().add(ClientErrorExceptionHandler.class);
@@ -286,21 +305,14 @@ public abstract class WebService implements ContainerService {
}
/**
- * Override this method to serve static resources from file system on the /static/* path.
- */
- protected Path getStaticResourceDocRoot(Container container) {
- return null;
- }
-
- /**
- * Simple path prefix routing.
+ * Add handlers with a path prefix.
*/
public Map<String, HttpHandler> getPrefixRoutes() {
return prefixRoutes;
}
/**
- * Add resource/provider/etc. classes to enable REST API.
+ * Add resource/provider/etc. classes to enable REST API
*/
public Collection<Class<?>> getApiClasses() {
return apiClasses;
@@ -326,6 +338,30 @@ public abstract class WebService implements ContainerService {
this.keycloakConfigResolver = keycloakConfigResolver;
}
- protected abstract String getDefaultRealm();
+ /**
+ * Default realm path the browser will be redirected to when a / root request is made.
+ */
+ public String getDefaultRealm() {
+ return defaultRealm;
+ }
+
+ public void setDefaultRealm(String defaultRealm) {
+ if (this.defaultRealm != null)
+ throw new IllegalStateException("Default realm already set: " + this.defaultRealm);
+ this.defaultRealm = defaultRealm;
+ }
+
+ /**
+ * Set to serve static resources from file system on the /static/* path.
+ */
+ public Path getStaticResourceDocRoot() {
+ return staticResourceDocRoot;
+ }
+
+ public void setStaticResourceDocRoot(Path staticResourceDocRoot) {
+ if (this.staticResourceDocRoot != null)
+ throw new IllegalStateException("Static resource path already set: " + this.staticResourceDocRoot);
+ this.staticResourceDocRoot = staticResourceDocRoot;
+ }
}
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
new file mode 100644
index 000000000..08e2efc57
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/web/socket/MemoryWebsocketSessions.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright 2015, 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 javax.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() throws Exception {
+ // noop
+ }
+
+ @Override
+ public void stop() throws Exception {
+ 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
new file mode 100644
index 000000000..2a0dd800a
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/web/socket/WebsocketAdapter.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright 2015, 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 javax.websocket.CloseReason;
+import javax.websocket.Endpoint;
+import javax.websocket.EndpointConfig;
+import javax.websocket.Session;
+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) {
+ if (LOG.isLoggable(Level.FINE))
+ LOG.fine("Websocket session open: " + session.getId());
+ consumer.getEndpoint().getWebsocketSessions().add(session);
+
+ session.addMessageHandler(String.class, message -> {
+ if (LOG.isLoggable(Level.FINE))
+ LOG.fine("Websocket session " + session.getId() + " message received: " + message);
+ this.consumer.sendMessage(session.getId(), message);
+ });
+ }
+
+ @Override
+ public void onClose(Session session, CloseReason closeReason) {
+ if (LOG.isLoggable(Level.FINE))
+ LOG.fine("Websocket session close: " + session.getId() + " " + closeReason);
+ consumer.getEndpoint().getWebsocketSessions().remove(session);
+ }
+
+ @Override
+ public void onError(Session session, Throwable thr) {
+ super.onError(session, thr);
+ if (LOG.isLoggable(Level.INFO))
+ LOG.log(Level.INFO, "Websocket session error: " + session.getId(), thr);
+ consumer.getEndpoint().getWebsocketSessions().remove(session);
+ }
+}
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
new file mode 100644
index 000000000..0790e29c5
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/web/socket/WebsocketCORSFilter.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright 2015, 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 javax.servlet.*;
+import javax.servlet.http.HttpServletRequest;
+import javax.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() {
+ }
+
+}
\ No newline at end of file
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
new file mode 100644
index 000000000..b44a4b3d7
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/web/socket/WebsocketComponent.java
@@ -0,0 +1,109 @@
+/*
+ * Copyright 2015, 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.impl.UriEndpointComponent;
+import org.apache.camel.util.ServiceHelper;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.logging.Logger;
+
+public abstract class WebsocketComponent extends UriEndpointComponent {
+
+ 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() {
+ super(WebsocketEndpoint.class);
+ 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();
+ } catch (Exception ex) {
+ throw new RuntimeException(ex);
+ }
+ }
+
+ protected void redeploy() throws Exception {
+ // TODO what happens to inflight sessions?
+ undeploy();
+ 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/WebsocketConstants.java b/container/src/main/java/org/openremote/container/web/socket/WebsocketConstants.java
new file mode 100644
index 000000000..8db74e4b8
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/web/socket/WebsocketConstants.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2015, 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;
+
+public interface WebsocketConstants {
+
+ String SESSION_KEY = "websocket.sessionKey";
+ String SEND_TO_ALL = "websocket.sendToAll";
+
+}
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
new file mode 100644
index 000000000..a6d2aae68
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/web/socket/WebsocketConsumer.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright 2015, 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.impl.DefaultConsumer;
+
+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 sessionKey, final String message) {
+ sendMessage(sessionKey, (Object)message);
+ }
+
+ public void sendMessage(final String sessionKey, final Object message) {
+ final Exchange exchange = getEndpoint().createExchange();
+ exchange.getIn().setHeader(WebsocketConstants.SESSION_KEY, sessionKey);
+ exchange.getIn().setBody(message);
+
+ 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
new file mode 100644
index 000000000..3f5bf5f15
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/web/socket/WebsocketEndpoint.java
@@ -0,0 +1,104 @@
+/*
+ * Copyright 2015, 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.impl.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
new file mode 100644
index 000000000..40fa1f254
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/web/socket/WebsocketProducer.java
@@ -0,0 +1,105 @@
+/*
+ * Copyright 2015, 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.impl.DefaultProducer;
+
+import javax.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(WebsocketConstants.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(WebsocketConstants.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 (LOG.isLoggable(Level.FINE))
+ LOG.fine("Sending to session " + session.getId() + ": " + message);
+ if (message instanceof String) {
+ 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
new file mode 100644
index 000000000..cceba9a15
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/web/socket/WebsocketSessions.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright 2015, 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 javax.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/gradle.properties b/gradle.properties
index a471592f5..3c4a3d027 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -25,4 +25,5 @@ h2Version = 1.4.190
hikaricpVersion = 2.4.3
junitVersion = 4.12
spockVersion = 1.0-groovy-2.4
-objenesisVersion = 2.2
\ No newline at end of file
+objenesisVersion = 2.2
+camelVersion = 2.16.2
\ No newline at end of file
diff --git a/manager/src/main/java/org/openremote/manager/server/SampleDataService.java b/manager/src/main/java/org/openremote/manager/server/SampleDataService.java
index 9c2f59725..eae5d8b30 100644
--- a/manager/src/main/java/org/openremote/manager/server/SampleDataService.java
+++ b/manager/src/main/java/org/openremote/manager/server/SampleDataService.java
@@ -43,11 +43,16 @@ public class SampleDataService implements ContainerService {
*/
@Override
- public void prepare(Container container) {
+ public void init(Container container) throws Exception {
identityService = container.getService(ManagerIdentityService.class);
assetsService = container.getService(AssetsService.class);
}
+ @Override
+ public void configure(Container container) throws Exception {
+
+ }
+
@Override
public void start(Container container) {
if (!container.isDevMode() && !container.getConfigBoolean(IMPORT_SAMPLE_DATA, IMPORT_SAMPLE_DATA_DEFAULT)) {
@@ -185,7 +190,7 @@ public class SampleDataService implements ContainerService {
fromCallable(() -> keycloakResource.createRoleForClientApplication(
MASTER_REALM, clientObjectId, new RoleRepresentation("read", "Read all data", false)
)).map(response ->
- getTarget(identityService.getClient(), response.getLocation(), accessToken).request(APPLICATION_JSON).get(RoleRepresentation.class)
+ getTarget(identityService.getHttpClient(), response.getLocation(), accessToken).request(APPLICATION_JSON).get(RoleRepresentation.class)
).toBlocking().single();
LOG.info("Added role '" + readRole.getName() + "'");
@@ -193,14 +198,14 @@ public class SampleDataService implements ContainerService {
fromCallable(() -> keycloakResource.createRoleForClientApplication(
MASTER_REALM, clientObjectId, new RoleRepresentation("read:map", "View map", false)
)).map(response ->
- getTarget(identityService.getClient(), response.getLocation(), accessToken).request(APPLICATION_JSON).get(RoleRepresentation.class)
+ getTarget(identityService.getHttpClient(), response.getLocation(), accessToken).request(APPLICATION_JSON).get(RoleRepresentation.class)
).toBlocking().single();
RoleRepresentation readAssetsRole =
fromCallable(() -> keycloakResource.createRoleForClientApplication(
MASTER_REALM, clientObjectId, new RoleRepresentation("read:assets", "Read context broker assets", false)
)).map(response ->
- getTarget(identityService.getClient(), response.getLocation(), accessToken).request(APPLICATION_JSON).get(RoleRepresentation.class)
+ getTarget(identityService.getHttpClient(), response.getLocation(), accessToken).request(APPLICATION_JSON).get(RoleRepresentation.class)
).toBlocking().single();
LOG.info("Added role '" + readAssetsRole.getName() + "'");
@@ -212,7 +217,7 @@ public class SampleDataService implements ContainerService {
fromCallable(() -> keycloakResource.createRoleForClientApplication(
MASTER_REALM, clientObjectId, new RoleRepresentation("write", "Write all data", false)
)).map(response ->
- getTarget(identityService.getClient(), response.getLocation(), accessToken).request(APPLICATION_JSON).get(RoleRepresentation.class)
+ getTarget(identityService.getHttpClient(), response.getLocation(), accessToken).request(APPLICATION_JSON).get(RoleRepresentation.class)
).toBlocking().single();
LOG.info("Added role '" + writeRole.getName() + "'");
@@ -220,7 +225,7 @@ public class SampleDataService implements ContainerService {
fromCallable(() -> keycloakResource.createRoleForClientApplication(
MASTER_REALM, clientObjectId, new RoleRepresentation("write:assets", "Write context broker assets", false)
)).map(response ->
- getTarget(identityService.getClient(), response.getLocation(), accessToken).request(APPLICATION_JSON).get(RoleRepresentation.class)
+ getTarget(identityService.getHttpClient(), response.getLocation(), accessToken).request(APPLICATION_JSON).get(RoleRepresentation.class)
).toBlocking().single();
LOG.info("Added role '" + writeAssetsRole.getName() + "'");
@@ -254,7 +259,7 @@ public class SampleDataService implements ContainerService {
final UserRepresentation finalTestUser = testUser;
testUser = fromCallable(() -> keycloakResource.createUser(MASTER_REALM, finalTestUser))
.map(response ->
- getTarget(identityService.getClient(), response.getLocation(), accessToken).request(APPLICATION_JSON).get(UserRepresentation.class)
+ getTarget(identityService.getHttpClient(), response.getLocation(), accessToken).request(APPLICATION_JSON).get(UserRepresentation.class)
).toBlocking().single();
CredentialRepresentation testUserCredential = new CredentialRepresentation();
diff --git a/manager/src/main/java/org/openremote/manager/server/Server.java b/manager/src/main/java/org/openremote/manager/server/Server.java
index b4888de18..08086a15f 100644
--- a/manager/src/main/java/org/openremote/manager/server/Server.java
+++ b/manager/src/main/java/org/openremote/manager/server/Server.java
@@ -1,7 +1,9 @@
package org.openremote.manager.server;
import org.openremote.container.Container;
+import org.openremote.container.message.MessageBrokerService;
import org.openremote.manager.server.assets.AssetsService;
+import org.openremote.manager.server.event.EventService;
import org.openremote.manager.server.map.MapService;
import org.openremote.manager.server.security.ManagerIdentityService;
import org.openremote.manager.server.web.ManagerWebService;
@@ -16,6 +18,8 @@ public class Server {
new Container(
new ManagerWebService(),
new ManagerIdentityService(),
+ new MessageBrokerService(),
+ new EventService(),
new AssetsService(),
new MapService(),
new SampleDataService()
diff --git a/manager/src/main/java/org/openremote/manager/server/assets/AssetsResourceImpl.java b/manager/src/main/java/org/openremote/manager/server/assets/AssetsResourceImpl.java
index 8b1af8748..ca8ff9d97 100644
--- a/manager/src/main/java/org/openremote/manager/server/assets/AssetsResourceImpl.java
+++ b/manager/src/main/java/org/openremote/manager/server/assets/AssetsResourceImpl.java
@@ -11,8 +11,6 @@ import org.openremote.manager.shared.ngsi.Entity;
import org.openremote.manager.shared.ngsi.params.EntityListParams;
import org.openremote.manager.shared.ngsi.params.EntityParams;
-import javax.ws.rs.ClientErrorException;
-import javax.ws.rs.NotFoundException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import java.util.logging.Logger;
diff --git a/manager/src/main/java/org/openremote/manager/server/assets/AssetsService.java b/manager/src/main/java/org/openremote/manager/server/assets/AssetsService.java
index aa75583b3..62e607413 100644
--- a/manager/src/main/java/org/openremote/manager/server/assets/AssetsService.java
+++ b/manager/src/main/java/org/openremote/manager/server/assets/AssetsService.java
@@ -7,7 +7,7 @@ import org.openremote.container.Container;
import org.openremote.container.ContainerService;
import org.openremote.container.observable.RetryWithDelay;
import org.openremote.container.web.WebClient;
-import org.openremote.manager.server.web.ManagerWebService;
+import org.openremote.container.web.WebService;
import org.openremote.manager.shared.ngsi.EntryPoint;
import rx.Observable;
@@ -35,11 +35,10 @@ public class AssetsService implements ContainerService {
public static final int CONTEXTBROKER_CLIENT_POOL_SIZE_DEFAULT = 20;
protected UriBuilder contextBrokerHostUri;
- protected Client client;
+ protected Client httpClient;
@Override
- public void prepare(Container container) {
-
+ public void init(Container container) throws Exception {
contextBrokerHostUri =
UriBuilder.fromPath("/")
.scheme("http")
@@ -62,39 +61,41 @@ public class AssetsService implements ContainerService {
container.getConfigInteger(CONTEXTBROKER_CLIENT_POOL_SIZE, CONTEXTBROKER_CLIENT_POOL_SIZE_DEFAULT)
);
- this.client = WebClient
- .registerDefaults(clientBuilder)
+ this.httpClient = WebClient
+ .registerDefaults(container, clientBuilder)
.register(EntryPointMessageBodyConverter.class)
.register(EntityMessageBodyConverter.class)
.register(EntityArrayMessageBodyConverter.class)
.build();
+ }
- container.getService(ManagerWebService.class).getApiSingletons().add(new EntryPointMessageBodyConverter());
- container.getService(ManagerWebService.class).getApiSingletons().add(new EntityMessageBodyConverter());
- container.getService(ManagerWebService.class).getApiSingletons().add(new EntityArrayMessageBodyConverter());
-
- container.getService(ManagerWebService.class).getApiSingletons().add(new AssetsResourceImpl(this));
+ @Override
+ public void configure(Container container) throws Exception {
+ container.getService(WebService.class).getApiSingletons().add(new EntryPointMessageBodyConverter());
+ container.getService(WebService.class).getApiSingletons().add(new EntityMessageBodyConverter());
+ container.getService(WebService.class).getApiSingletons().add(new EntityArrayMessageBodyConverter());
+ container.getService(WebService.class).getApiSingletons().add(new AssetsResourceImpl(this));
}
@Override
- public void start(Container container) {
+ public void start(Container container) throws Exception {
// TODO Not a great way to block startup while we wait for other services (Hystrix?)
pingContextBroker();
LOG.info("Context broker provider available: " + contextBrokerHostUri.build());
}
@Override
- public void stop(Container container) {
- if (client != null)
- client.close();
+ public void stop(Container container) throws Exception {
+ if (httpClient != null)
+ httpClient.close();
}
- public Client getClient() {
- return client;
+ public Client getHttpClient() {
+ return httpClient;
}
public ContextBrokerResource getContextBroker() {
- return getContextBroker(getTarget(client, contextBrokerHostUri.build(), null));
+ return getContextBroker(getTarget(httpClient, contextBrokerHostUri.build(), null));
}
public ContextBrokerResource getContextBroker(ResteasyWebTarget target) {
diff --git a/manager/src/main/java/org/openremote/manager/server/event/EventService.java b/manager/src/main/java/org/openremote/manager/server/event/EventService.java
new file mode 100644
index 000000000..a0bbbfdce
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/server/event/EventService.java
@@ -0,0 +1,89 @@
+package org.openremote.manager.server.event;
+
+import org.apache.camel.ProducerTemplate;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.bean.AmbiguousMethodCallException;
+import org.openremote.container.Container;
+import org.openremote.container.ContainerService;
+import org.openremote.container.message.MessageBrokerContext;
+import org.openremote.container.message.MessageBrokerService;
+import org.openremote.manager.shared.event.Event;
+import org.openremote.manager.shared.event.Message;
+
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+public class EventService implements ContainerService {
+
+ private static final Logger LOG = Logger.getLogger(EventService.class.getName());
+ public static final String WEBSOCKET_EVENTS = "events";
+
+ public static final String INCOMING_EVENT_QUEUE = "seda://incomingEvent?multipleConsumers=true&waitForTaskToComplete=NEVER";
+ public static final String OUTGOING_EVENT_QUEUE = "seda://outgoingEvent?multipleConsumers=true&waitForTaskToComplete=NEVER";
+
+ protected ProducerTemplate producerTemplate;
+
+ @Override
+ public void init(Container container) throws Exception {
+
+ }
+
+ @Override
+ public void configure(Container container) throws Exception {
+ MessageBrokerService messageBrokerService = container.getService(MessageBrokerService.class);
+ MessageBrokerContext context = messageBrokerService.getContext();
+
+ context.getTypeConverterRegistry().addTypeConverters(new EventTypeConverters());
+
+ producerTemplate = context.createProducerTemplate();
+
+ context.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() throws Exception {
+
+ from("websocket://" + WEBSOCKET_EVENTS)
+ .routeId("Receive incoming events on WebSocket")
+ .convertBodyTo(Event.class)
+ .to(EventService.INCOMING_EVENT_QUEUE);
+
+ from(EventService.INCOMING_EVENT_QUEUE)
+ .routeId("Handle incoming events")
+ .doTry()
+ .bean(EventService.this, "onEvent")
+ .doCatch(AmbiguousMethodCallException.class) // No overloaded method for given event subtype
+ .log("log:org.openremote.event.unhandled?level=DEBUG&showCaughtException=false&showBodyType=false&showExchangePattern=false&showStackTrace=false")
+ .stop()
+ .endDoTry();
+
+ from(EventService.OUTGOING_EVENT_QUEUE)
+ .routeId("Send outgoing events to all WebSocket sessions")
+ .to("websocket://" + WEBSOCKET_EVENTS + "?sendToAll=true");
+ }
+ });
+ }
+
+ @Override
+ public void start(Container container) {
+
+ }
+
+ @Override
+ public void stop(Container container) {
+
+ }
+
+ public void sendEvent(Event event) {
+ if (LOG.isLoggable(Level.FINE))
+ LOG.fine("Sending: " + event);
+ producerTemplate.sendBody(OUTGOING_EVENT_QUEUE, event);
+ }
+
+ public void onEvent(Message message) {
+ if (LOG.isLoggable(Level.FINE))
+ LOG.fine("### On incoming message event: " + message);
+
+ // TODO echo!
+ sendEvent(message);
+ }
+
+}
diff --git a/manager/src/main/java/org/openremote/manager/server/event/EventTypeConverters.java b/manager/src/main/java/org/openremote/manager/server/event/EventTypeConverters.java
new file mode 100644
index 000000000..df4c338d7
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/server/event/EventTypeConverters.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright 2015, 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.server.event;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.camel.Converter;
+import org.apache.camel.Exchange;
+import org.apache.camel.TypeConverters;
+import org.openremote.container.Container;
+import org.openremote.manager.shared.event.Event;
+import org.slf4j.LoggerFactory;
+
+public class EventTypeConverters implements TypeConverters {
+
+ private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(EventTypeConverters.class);
+
+
+ @Converter
+ public String writeEvent(Event event, Exchange exchange) throws Exception {
+ LOG.trace("Writing event JSON: " + event);
+ return getObjectMapper(exchange).writeValueAsString(event);
+ }
+
+ @Converter
+ public Event readEvent(String string, Exchange exchange) throws Exception {
+ LOG.trace("Reading event JSON: " + string);
+ return getObjectMapper(exchange).readValue(string, Event.class);
+ }
+
+ protected static ObjectMapper getObjectMapper(Exchange exchange) {
+ Container container = (Container) exchange.getContext().getRegistry().lookupByName(Container.class.getName());
+ return container.JSON;
+ }}
\ No newline at end of file
diff --git a/manager/src/main/java/org/openremote/manager/server/map/MapService.java b/manager/src/main/java/org/openremote/manager/server/map/MapService.java
index 475c27a23..a0a9a5375 100644
--- a/manager/src/main/java/org/openremote/manager/server/map/MapService.java
+++ b/manager/src/main/java/org/openremote/manager/server/map/MapService.java
@@ -5,7 +5,7 @@ import elemental.json.JsonArray;
import elemental.json.JsonObject;
import org.openremote.container.Container;
import org.openremote.container.ContainerService;
-import org.openremote.manager.server.web.ManagerWebService;
+import org.openremote.container.web.WebService;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -35,7 +35,7 @@ public class MapService implements ContainerService {
protected JsonObject mapSettings;
@Override
- public void prepare(Container container) {
+ public void init(Container container) throws Exception {
this.devMode = container.isDevMode();
mapTilesPath = Paths.get(container.getConfig(MAP_TILES_PATH, MAP_TILES_PATH_DEFAULT));
@@ -51,34 +51,29 @@ public class MapService implements ContainerService {
"MapWidget settings file not found: " + mapSettingsPath.toAbsolutePath()
);
}
+ }
- container.getService(ManagerWebService.class).getApiSingletons().add(
+ @Override
+ public void configure(Container container) throws Exception {
+ container.getService(WebService.class).getApiSingletons().add(
new MapResourceImpl(this)
);
}
@Override
- public void start(Container container) {
+ public void start(Container container) throws Exception {
LOG.info("Starting map service with tile data: " + mapTilesPath.toAbsolutePath());
- try {
- Class.forName(org.sqlite.JDBC.class.getName());
- connection = DriverManager.getConnection("jdbc:sqlite:" + mapTilesPath.toAbsolutePath());
- } catch (Exception ex) {
- throw new IllegalStateException(ex);
- }
+ Class.forName(org.sqlite.JDBC.class.getName());
+ connection = DriverManager.getConnection("jdbc:sqlite:" + mapTilesPath.toAbsolutePath());
readMapSettings();
}
@Override
- public void stop(Container container) {
+ public void stop(Container container) throws Exception {
LOG.info("Stopping map service...");
if (connection != null) {
- try {
- connection.close();
- } catch (SQLException ex) {
- LOG.warning("Error closing connection: " + ex);
- }
+ connection.close();
}
}
diff --git a/manager/src/main/java/org/openremote/manager/server/security/ManagerIdentityService.java b/manager/src/main/java/org/openremote/manager/server/security/ManagerIdentityService.java
index 70a3cf6f4..98ea7eef5 100644
--- a/manager/src/main/java/org/openremote/manager/server/security/ManagerIdentityService.java
+++ b/manager/src/main/java/org/openremote/manager/server/security/ManagerIdentityService.java
@@ -1,24 +1,15 @@
package org.openremote.manager.server.security;
+import org.openremote.container.Container;
import org.openremote.container.security.IdentityService;
-import org.openremote.container.web.WebService;
import org.openremote.manager.server.Constants;
-import org.openremote.manager.server.web.ManagerWebService;
public class ManagerIdentityService extends IdentityService {
@Override
- protected boolean enableKeycloakReverseProxy() {
- return true;
- }
-
- @Override
- protected Class<? extends WebService> getWebServiceClass() {
- return ManagerWebService.class;
- }
-
- @Override
- protected String getClientId() {
- return Constants.MANAGER_CLIENT_ID;
+ public void init(Container container) throws Exception {
+ super.init(container);
+ setKeycloakReverseProxy(true);
+ setClientId(Constants.MANAGER_CLIENT_ID);
}
}
diff --git a/manager/src/main/java/org/openremote/manager/server/web/ManagerWebService.java b/manager/src/main/java/org/openremote/manager/server/web/ManagerWebService.java
index e97414f13..03273eb41 100644
--- a/manager/src/main/java/org/openremote/manager/server/web/ManagerWebService.java
+++ b/manager/src/main/java/org/openremote/manager/server/web/ManagerWebService.java
@@ -3,26 +3,19 @@ package org.openremote.manager.server.web;
import org.openremote.container.Container;
import org.openremote.container.web.WebService;
-import java.nio.file.Path;
import java.nio.file.Paths;
-import java.util.logging.Logger;
import static org.openremote.manager.server.Constants.MASTER_REALM;
public class ManagerWebService extends WebService {
- private static final Logger LOG = Logger.getLogger(ManagerWebService.class.getName());
-
public static final String WEBSERVER_DOCROOT = "WEBSERVER_DOCROOT";
public static final String WEBSERVER_DOCROOT_DEFAULT = "src/main/webapp";
@Override
- protected String getDefaultRealm() {
- return MASTER_REALM;
- }
-
- @Override
- protected Path getStaticResourceDocRoot(Container container) {
- return Paths.get(container.getConfig(WEBSERVER_DOCROOT, WEBSERVER_DOCROOT_DEFAULT));
+ public void init(Container container) throws Exception {
+ super.init(container);
+ setDefaultRealm(MASTER_REALM);
+ setStaticResourceDocRoot(Paths.get(container.getConfig(WEBSERVER_DOCROOT, WEBSERVER_DOCROOT_DEFAULT)));
}
}
diff --git a/manager/src/main/java/org/openremote/manager/shared/event/Event.java b/manager/src/main/java/org/openremote/manager/shared/event/Event.java
new file mode 100644
index 000000000..851c7f260
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/shared/event/Event.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright 2015, 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.shared.event;
+
+import com.fasterxml.jackson.annotation.JsonSubTypes;
+import com.fasterxml.jackson.annotation.JsonTypeInfo;
+import org.openremote.manager.shared.util.Util;
+
+@JsonSubTypes({
+ // Events used on client and server (serialized on client/server bus)
+ @JsonSubTypes.Type(value = Message.class, name = "MESSAGE"),
+ /*
+ @JsonSubTypes.Type(value = FlowDeployEvent.class, name = "FLOW_DEPLOY"),
+ @JsonSubTypes.Type(value = FlowDeploymentFailureEvent.class, name = "FLOW_DEPLOYMENT_FAILURE"),
+ @JsonSubTypes.Type(value = FlowRuntimeFailureEvent.class, name = "FLOW_RUNTIME_FAILURE"),
+ @JsonSubTypes.Type(value = FlowRequestStatusEvent.class, name = "FLOW_REQUEST_STATUS"),
+ @JsonSubTypes.Type(value = FlowStatusEvent.class, name = "FLOW_STATUS"),
+ @JsonSubTypes.Type(value = FlowStopEvent.class, name = "FLOW_STOP"),
+ @JsonSubTypes.Type(value = InventoryDevicesUpdatedEvent.class, name = "INVENTORY_DEVICES_UPDATED"),
+ // Events used only on client (serialized on console/native shell bus)
+ @JsonSubTypes.Type(value = ConsoleEditModeEvent.class, name = "CONSOLE_EDIT_MODE"),
+ @JsonSubTypes.Type(value = ConsoleLoopDetectedEvent.class, name = "CONSOLE_LOOP_DETECTED"),
+ @JsonSubTypes.Type(value = ConsoleRefreshedEvent.class, name = "CONSOLE_REFRESHED"),
+ @JsonSubTypes.Type(value = ConsoleRefreshEvent.class, name = "CONSOLE_REFRESH"),
+ @JsonSubTypes.Type(value = ConsoleWidgetModifiedEvent.class, name = "CONSOLE_WIDGET_MODIFIED"),
+ @JsonSubTypes.Type(value = ConsoleZoomEvent.class, name = "CONSOLE_ZOOM"),
+ @JsonSubTypes.Type(value = MessageReceivedEvent.class, name = "MESSAGE_RECEIVED"),
+ @JsonSubTypes.Type(value = MessageSendEvent.class, name = "MESSAGE_SEND"),
+ @JsonSubTypes.Type(value = NodeCreateEvent.class, name = "NODE_CREATE"),
+ @JsonSubTypes.Type(value = NodeSelectedEvent.class, name = "NODE_SELECTED"),
+ @JsonSubTypes.Type(value = ShellCloseEvent.class, name = "SHELL_CLOSE"),
+ @JsonSubTypes.Type(value = ShellOpenEvent.class, name = "SHELL_OPEN"),
+ @JsonSubTypes.Type(value = ShellReadyEvent.class, name = "SHELL_READY"),
+ @JsonSubTypes.Type(value = ShowFailureEvent.class, name = "SHOW_FAILURE"),
+ @JsonSubTypes.Type(value = ShowInfoEvent.class, name = "SHOW_INFO"),
+ @JsonSubTypes.Type(value = SubflowNodeCreateEvent.class, name = "SUBFLOW_NODE_CREATE")
+ */
+})
+@JsonTypeInfo(
+ use = JsonTypeInfo.Id.NAME,
+ include = JsonTypeInfo.As.PROPERTY,
+ property = "event"
+)
+public abstract class Event {
+
+ public static String getType(String simpleClassName) {
+ String type = Util.toLowerCaseDash(simpleClassName);
+
+ if (type.length() > 6 && type.substring(type.length() - 6).equals("-event"))
+ type = type.substring(0, type.length() - 6);
+
+ return type;
+ }
+
+ public static String getType(Class<? extends Event> actionClass) {
+ return getType(actionClass.getSimpleName());
+ }
+
+ public String getType() {
+ return getType(getClass());
+ }
+
+}
diff --git a/manager/src/main/java/org/openremote/manager/shared/event/Message.java b/manager/src/main/java/org/openremote/manager/shared/event/Message.java
new file mode 100644
index 000000000..57154f868
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/shared/event/Message.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright 2015, 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.shared.event;
+
+import jsinterop.annotations.JsIgnore;
+
+import java.util.Map;
+
+public class Message extends Event {
+
+ public Map<String, Object> headers;
+ public String body;
+
+ public Message() {
+ }
+
+ public Message(Map<String, Object> headers, String body) {
+ this.headers = headers;
+ this.body = body;
+ }
+
+ public Message(String body) {
+ this.body = body;
+ }
+
+
+ public Map<String, Object> getHeaders() {
+ return headers;
+ }
+
+ public void setHeaders(Map<String, Object> headers) {
+ this.headers = headers;
+ }
+
+ public boolean hasHeaders() {
+ return getHeaders() != null;
+ }
+
+ public String getBody() {
+ return body;
+ }
+
+ public void setBody(String body) {
+ this.body = body;
+ }
+
+ @Override
+ public String toString() {
+ return "Message{" +
+ "headers=" + headers +
+ ", body='" + body + '\'' +
+ '}';
+ }
+}
diff --git a/manager/src/main/java/org/openremote/manager/shared/util/Util.java b/manager/src/main/java/org/openremote/manager/shared/util/Util.java
new file mode 100644
index 000000000..1cd61be0d
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/shared/util/Util.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright 2015, 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.shared.util;
+
+import java.util.Locale;
+
+public class Util {
+
+ public static String toLowerCaseDash(String camelCase) {
+ // Transforms 'EXFooBar123' into 'ex-foo-bar-123 and "attributeX" into "attribute-x" without regex (GWT!)
+ if (camelCase == null)
+ return null;
+ if (camelCase.length() == 0)
+ return camelCase;
+ StringBuilder sb = new StringBuilder();
+ char[] chars = camelCase.toCharArray();
+ boolean inNonLowerCase = false;
+ for (int i = 0; i < chars.length; i++) {
+ char c = chars[i];
+ if (!Character.isLowerCase(c)) {
+ if (!inNonLowerCase) {
+ if (i > 0)
+ sb.append("-");
+ } else if (i < chars.length -1 && Character.isLowerCase(chars[i+1])) {
+ sb.append("-");
+ }
+ inNonLowerCase = true;
+ } else {
+ inNonLowerCase = false;
+ }
+ sb.append(c);
+ }
+ String name = sb.toString();
+ name = name.toLowerCase(Locale.ROOT);
+ return name;
+ }
+
+}
diff --git a/manager/src/main/resources/logging.properties b/manager/src/main/resources/logging.properties
index c3d06f921..2473d8ee9 100644
--- a/manager/src/main/resources/logging.properties
+++ b/manager/src/main/resources/logging.properties
@@ -6,6 +6,7 @@ java.util.logging.ConsoleHandler.level=FINEST
.level=INFO
org.openremote.level=FINEST
+org.openremote.container.message.MessageBrokerContext.level=INFO
# Low-level debugging
javax.management.level=WARNING
diff --git a/manager/src/test/groovy/org/openremote/test/ContainerTrait.groovy b/manager/src/test/groovy/org/openremote/test/ContainerTrait.groovy
index 68c8fb517..b9cc3ebb3 100644
--- a/manager/src/test/groovy/org/openremote/test/ContainerTrait.groovy
+++ b/manager/src/test/groovy/org/openremote/test/ContainerTrait.groovy
@@ -1,5 +1,9 @@
package org.openremote.test
+import com.fasterxml.jackson.databind.ObjectMapper
+import org.apache.camel.ProducerTemplate
+import org.apache.camel.builder.RouteBuilder
+import org.apache.camel.component.mock.MockEndpoint
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget
import org.junit.After
@@ -7,12 +11,15 @@ import org.junit.Before
import org.keycloak.representations.AccessTokenResponse
import org.openremote.container.Container
import org.openremote.container.ContainerService
+import org.openremote.container.message.MessageBrokerContext
+import org.openremote.container.message.MessageBrokerService
import org.openremote.container.security.AuthForm
import org.openremote.container.security.IdentityService
import org.openremote.container.web.WebClient
import org.openremote.container.web.WebService
import org.openremote.manager.server.SampleDataService
import org.openremote.manager.server.assets.AssetsService
+import org.openremote.manager.server.event.EventService
import org.openremote.manager.server.map.MapService
import org.openremote.manager.server.security.ManagerIdentityService
import org.openremote.manager.server.web.ManagerWebService
@@ -29,6 +36,28 @@ trait ContainerTrait {
int serverPort;
Client client;
UriBuilder serverApiUri;
+ MessageBrokerContext messageClientContext;
+ ProducerTemplate messageProducer;
+ MockEndpoint messageReceiver;
+
+ static class MockRouteBuilder extends RouteBuilder {
+
+ final String eventsUrl;
+
+ MockRouteBuilder(String eventsUrl) {
+ this.eventsUrl = eventsUrl
+ }
+
+ @Override
+ public void configure() throws Exception {
+ from("direct:sendEvent")
+ .to(eventsUrl);
+
+ from(eventsUrl)
+ .to('log:EVENT_RECEIVED: ${body}')
+ .to("mock:eventReceiver");
+ }
+ }
@Before
setupContainer() {
@@ -45,6 +74,8 @@ trait ContainerTrait {
Stream.of(
new ManagerWebService(),
new ManagerIdentityService(),
+ new MessageBrokerService(),
+ new EventService(),
new AssetsService(),
new MapService(),
new SampleDataService()
@@ -59,24 +90,47 @@ trait ContainerTrait {
.socketTimeout(10, SECONDS)
.connectionPoolSize(10);
- client = prepareClient(WebClient.registerDefaults(clientBuilder)).build();
+ client = prepareClient(WebClient.registerDefaults(container, clientBuilder)).build();
serverApiUri = UriBuilder.fromUri("")
.scheme("http").host("localhost").port(serverPort);
container.startBackground();
+
+ // Websocket/message broker test client using Camel
+ messageClientContext = new MessageBrokerContext();
+
+ messageProducer = messageClientContext.createProducerTemplate();
+ messageProducer.setDefaultEndpoint(messageClientContext.getEndpoint("direct:sendEvent"));
+
+ messageReceiver = messageClientContext.getEndpoint("mock:eventReceiver", MockEndpoint.class);
+ messageReceiver.setResultWaitTime(5000);
+
+ messageClientContext.addRoutes(new MockRouteBuilder(getWebsocketUrl(EventService.WEBSOCKET_EVENTS)));
+
+ messageClientContext.start()
}
@After
cleanupContainer() {
+ if (messageClientContext)
+ messageClientContext.stop();
if (container)
container.stop();
}
+ ObjectMapper getJSON() {
+ container.JSON;
+ }
+
def prepareClient(ResteasyClientBuilder clientBuilder) {
return clientBuilder;
}
+ def ResteasyWebTarget getClientTarget() {
+ WebClient.getTarget(client, serverApiUri.clone().build());
+ }
+
def ResteasyWebTarget getClientTarget(String realm) {
WebClient.getTarget(client, serverApiUri.clone().replacePath(realm).build());
}
@@ -89,6 +143,18 @@ trait ContainerTrait {
WebClient.getTarget(client, serverApiUri.clone().replacePath(realm).path(path).build(), accessToken);
}
+ def getWebSocketScheme() {
+ "ahc-ws";
+ }
+
+ def getWebsocketUrl(String endpoint) {
+ getClientTarget().getUriBuilder().clone()
+ .scheme(webSocketScheme)
+ .path(MessageBrokerService.WEBSOCKET_PATH)
+ .path(endpoint)
+ .build().toString();
+ }
+
def findEphemeralPort() {
ServerSocket socket = new ServerSocket(0, 0, Inet4Address.getLocalHost());
int port = socket.getLocalPort();
diff --git a/manager/src/test/groovy/org/openremote/test/event/EventEchoTest.groovy b/manager/src/test/groovy/org/openremote/test/event/EventEchoTest.groovy
new file mode 100644
index 000000000..0cd116ce0
--- /dev/null
+++ b/manager/src/test/groovy/org/openremote/test/event/EventEchoTest.groovy
@@ -0,0 +1,26 @@
+package org.openremote.test.event
+
+import org.openremote.manager.shared.event.Message
+import org.openremote.test.ContainerTrait
+import spock.lang.Specification
+
+class EventEchoTest extends Specification implements ContainerTrait {
+
+ def "Ping/pong event service"() {
+ given: "A sample message"
+ def sampleMessage = new Message("Hello World");
+ and: "the expected answer messages"
+ messageReceiver.reset();
+ messageReceiver.expectedBodiesReceived(
+ JSON.writeValueAsString(sampleMessage)
+ )
+
+ when: "sending the message"
+ messageProducer.sendBody(
+ JSON.writeValueAsString(sampleMessage)
+ );
+
+ then: "the expected messages should eventually arrive"
+ messageReceiver.assertIsSatisfied();
+ }
+}