100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Added HTTP Server Protocol with tests
Rich Turnerad4a2e0f2a8c
diff --git a/agent/src/main/java/org/openremote/agent/protocol/http/AbstractHttpServerProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/http/AbstractHttpServerProtocol.javanew file mode 100644index 000000000..4b9dbb7e5--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/http/AbstractHttpServerProtocol.java@@ -0,0 +1,377 @@+/*+ * Copyright 2017, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.agent.protocol.http;++import com.google.common.collect.Lists;+import io.undertow.server.HttpHandler;+import io.undertow.servlet.Servlets;+import io.undertow.servlet.api.DeploymentInfo;+import io.undertow.servlet.api.DeploymentManager;+import io.undertow.servlet.api.ServletInfo;+import org.jboss.resteasy.plugins.interceptors.CorsFilter;+import org.jboss.resteasy.plugins.interceptors.RoleBasedSecurityFeature;+import org.jboss.resteasy.plugins.server.servlet.HttpServlet30Dispatcher;+import org.jboss.resteasy.spi.ResteasyDeployment;+import org.openremote.agent.protocol.AbstractProtocol;+import org.openremote.container.Container;+import org.openremote.container.json.JacksonConfig;+import org.openremote.container.json.ModelValueMessageBodyConverter;+import org.openremote.container.security.IdentityService;+import org.openremote.container.web.*;+import org.openremote.model.AbstractValueHolder;+import org.openremote.model.ValueHolder;+import org.openremote.model.asset.AssetAttribute;+import org.openremote.model.asset.agent.ProtocolConfiguration;+import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.attribute.MetaItem;+import org.openremote.model.util.Pair;+import org.openremote.model.util.TextUtil;+import org.openremote.model.value.ArrayValue;+import org.openremote.model.value.StringValue;+import org.openremote.model.value.Values;++import javax.servlet.ServletException;+import javax.ws.rs.HttpMethod;+import javax.ws.rs.core.Application;+import java.util.*;+import java.util.logging.Level;+import java.util.logging.Logger;+import java.util.regex.Pattern;++import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;++/**+ * This is an abstract protocol for creating JAX-RS deployments; a concrete implementation should be created for each+ * required JAX-RS deployment. Multiple instances of the same deployment can be created using multiple {@link+ * ProtocolConfiguration}s for the desired concrete implementation.+ * <p>+ * The deployment is deployed by creating a {@link ProtocolConfiguration} with the following {@link MetaItem}s:+ * <ul>+ * <li>{@link #META_PROTOCOL_DEPLOYMENT_PATH} <b>(required)</b></li>+ * <li>{@link #META_PROTOCOL_ALLOWED_ORIGINS}</li>+ * <li>{@link #META_PROTOCOL_ALLOWED_METHODS}</li>+ * </ul>+ * The path used for the deployment is determined by {@link #getDeploymentPath}+ */+public abstract class AbstractHttpServerProtocol extends AbstractProtocol {++ public static final String PROTOCOL_NAME = PROTOCOL_NAMESPACE + ":httpServer";++ /**+ * This is the default path prefix for all deployments. Should not be overridden unless you know what you are doing+ * and there is a good reason to override.+ */+ public static final String DEFAULT_DEPLOYMENT_PATH_PREFIX = "/rest";++ /**+ * Sets the instance part of the path used for this deployment see {@link #getDeploymentPath}. Note the final full+ * path to a deployment must match the {@link #PATH_REGEX} filter.+ */+ public static final String META_PROTOCOL_DEPLOYMENT_PATH = PROTOCOL_NAME + ":deploymentPath";++ /**+ * Sets the allowed origins for CORS (incoming requests should include an origin header for CORS support). Note if+ * the container is started in development mode (i.e. {@link Container#DEV_MODE}=true) then all origins are allowed+ * to facilitate local development. Should be {@link StringValue} or an {@link ArrayValue} of {@link StringValue}s+ * containing the allowed origins.+ */+ public static final String META_PROTOCOL_ALLOWED_ORIGINS = PROTOCOL_NAME + ":allowedOrigins";++ /**+ * Sets the allowed methods for CORS (incoming requests should include an origin header for CORS support). Should be+ * a comma separated string of allowed {@link HttpMethod}s (e.g. "OPTIONS, GET, POST") (default:+ * {@value #DEFAULT_ALLOWED_METHODS}).+ */+ public static final String META_PROTOCOL_ALLOWED_METHODS = PROTOCOL_NAME + ":allowedMethods";++ /**+ * Flag to enable role based security using the {@link RoleBasedSecurityFeature}; also requires that the+ * {@link Container} is started with an {@link IdentityService}.+ */+ public static final String META_PROTOCOL_ROLE_BASED_SECURITY_ENABLED = PROTOCOL_NAME + ":roleBasedSecurity";++ /**+ * The regex used to validate the deployment path.+ */+ public static final Pattern PATH_REGEX = Pattern.compile("^[\\w/_]+$", Pattern.CASE_INSENSITIVE);+++ public static final String DEFAULT_ALLOWED_METHODS = "OPTIONS, GET, POST, DELETE, PUT, PATCH";+ public static final String DEFAULT_DEPLOYMENT_NAME_FORMAT = "HttpServer %1$s Deployment %2$d";+ private static final Logger LOG = Logger.getLogger(AbstractHttpServerProtocol.class.getName());+ protected static WebServiceExceptions.DefaultResteasyExceptionMapper defaultResteasyExceptionMapper;+ protected static WebServiceExceptions.ForbiddenResteasyExceptionMapper forbiddenResteasyExceptionMapper;+ protected static JacksonConfig jacksonConfig;+ protected static ModelValueMessageBodyConverter modelValueMessageBodyConverter;+ protected static AlreadyGzippedWriterInterceptor alreadtGzippedWriterInterceptor;+ protected static ClientErrorExceptionHandler clientErrorExceptionHandler;+ protected static WebServiceExceptions.ServletUndertowExceptionHandler undertowExceptionHandler;+ protected static final Map<AttributeRef, Pair<DeploymentInfo, HttpHandler>> deployments = new HashMap<>();+ protected int deploymentCounter = 0;+ protected Container container;+ protected boolean devMode;+ protected IdentityService identityService;+ protected WebService webService;++ @Override+ public void init(Container container) throws Exception {+ super.init(container);+ this.container = container;+ this.devMode = container.isDevMode();++ identityService = container.hasService(IdentityService.class)+ ? container.getService(IdentityService.class)+ : null;++ webService = container.getService(WebService.class);++ if (defaultResteasyExceptionMapper == null) {+ defaultResteasyExceptionMapper = new WebServiceExceptions.DefaultResteasyExceptionMapper(devMode);+ forbiddenResteasyExceptionMapper = new WebServiceExceptions.ForbiddenResteasyExceptionMapper(devMode);+ undertowExceptionHandler = new WebServiceExceptions.ServletUndertowExceptionHandler(devMode);+ jacksonConfig = new JacksonConfig();+ modelValueMessageBodyConverter = new ModelValueMessageBodyConverter();+ alreadtGzippedWriterInterceptor = new AlreadyGzippedWriterInterceptor();+ clientErrorExceptionHandler = new ClientErrorExceptionHandler();+ }+ }++ @Override+ protected void doLinkProtocolConfiguration(AssetAttribute protocolConfiguration) {+ Application application = createApplication(protocolConfiguration);+ ResteasyDeployment deployment = createDeployment(application, protocolConfiguration);+ DeploymentInfo deploymentInfo = createDeploymentInfo(deployment, protocolConfiguration);+ configureDeploymentInfo(deploymentInfo);+ deploy(deploymentInfo, protocolConfiguration);+ }++ @Override+ protected void doUnlinkProtocolConfiguration(AssetAttribute protocolConfiguration) {+ undeploy(protocolConfiguration);+ }++ protected Application createApplication(AssetAttribute protocolConfiguration) {+ List<Object> providers = getStandardProviders(protocolConfiguration);+ providers = providers == null ? new ArrayList<>() : providers;+ providers.addAll(getApiSingletons(protocolConfiguration));+ return new WebApplication(container, null, providers);+ }++ protected ResteasyDeployment createDeployment(Application application, AssetAttribute protocolConfiguration) {+ ResteasyDeployment resteasyDeployment = new ResteasyDeployment();+ resteasyDeployment.setApplication(application);++ List<String> allowedOrigins;++ if (devMode) {+ allowedOrigins = Collections.singletonList("*");+ } else {+ Optional<MetaItem> allowedOriginsMeta = protocolConfiguration+ .getMetaItem(META_PROTOCOL_ALLOWED_ORIGINS);++ allowedOrigins = allowedOriginsMeta+ .flatMap(AbstractValueHolder::getValueAsString)+ .map(Collections::singletonList)+ .orElseGet(() ->+ allowedOriginsMeta.flatMap(AbstractValueHolder::getValueAsArray)+ .flatMap(arrayValue ->+ Values.getArrayElements(+ arrayValue,+ StringValue.class,+ true,+ false,+ StringValue::getString))+ .orElse(null));+ }++ if (allowedOrigins != null) {+ String allowedMethods = protocolConfiguration+ .getMetaItem(META_PROTOCOL_ALLOWED_METHODS)+ .flatMap(AbstractValueHolder::getValueAsString)+ .orElse(DEFAULT_ALLOWED_METHODS);++ if (TextUtil.isNullOrEmpty(allowedMethods)) {+ throw new IllegalArgumentException("Allowed methods meta item must be a non empty string: "+ + META_PROTOCOL_ALLOWED_METHODS);+ }++ CorsFilter corsFilter = new CorsFilter();+ corsFilter.getAllowedOrigins().addAll(allowedOrigins);+ corsFilter.setAllowedMethods(allowedMethods);+ resteasyDeployment.getProviders().add(corsFilter);+ }++ return resteasyDeployment;+ }++ protected DeploymentInfo createDeploymentInfo(ResteasyDeployment resteasyDeployment, AssetAttribute protocolConfiguration) {+ String deploymentPath = getDeploymentPath(protocolConfiguration);+ String deploymentName = getDeploymentName(protocolConfiguration);++ boolean enableSecurity = protocolConfiguration.getMetaItem(META_PROTOCOL_ROLE_BASED_SECURITY_ENABLED)+ .flatMap(AbstractValueHolder::getValueAsBoolean)+ .orElse(false);++ if (enableSecurity) {+ if (identityService == null) {+ throw new RuntimeException("Role based security can only be enabled when an identity service is available");+ }+ }++ resteasyDeployment.setSecurityEnabled(enableSecurity);++ ServletInfo resteasyServlet = Servlets.servlet("ResteasyServlet", HttpServlet30Dispatcher.class)+ .setAsyncSupported(true)+ .setLoadOnStartup(1)+ .addMapping("/*");++ DeploymentInfo deploymentInfo = new DeploymentInfo()+ .setDeploymentName(deploymentName)+ .setContextPath(deploymentPath)+ .addServletContextAttribute(ResteasyDeployment.class.getName(), resteasyDeployment)+ .addServlet(resteasyServlet)+ .setClassLoader(Container.class.getClassLoader());++ if (enableSecurity) {+ identityService.secureDeployment(deploymentInfo);+ }++ return deploymentInfo;+ }++ /**+ * Should return instances of all JAX-RS interface implementations that make up this protocol's deployment.+ */+ abstract protected Set<Object> getApiSingletons(AssetAttribute protocolConfiguration);++ /**+ * Get the path prefix to use for this protocol instance; should use {@value #DEFAULT_DEPLOYMENT_PATH_PREFIX} unless there+ * is a good reason to override this.+ */+ protected String getDeploymentPathPrefix() {+ return DEFAULT_DEPLOYMENT_PATH_PREFIX;+ }++ /**+ * Deployment path will always be prefixed with {@link #getDeploymentPathPrefix()}; default implementation combines+ * the prefix with the value of {@link #META_PROTOCOL_DEPLOYMENT_PATH}, for example:+ * <ul>+ * <li>getDeploymentPathPrefix() = {@value #DEFAULT_DEPLOYMENT_PATH_PREFIX}</li>+ * <li>{@link #META_PROTOCOL_DEPLOYMENT_PATH} = "complaints"</li>+ * </ul>+ * <p>+ * Full path to deployment = "/rest/complaints"+ * <p>+ * If the {@link #META_PROTOCOL_DEPLOYMENT_PATH} is missing or not a {@link StringValue} or the generated path does+ * not match the {@link #PATH_REGEX} regex then an {@link IllegalArgumentException} will is thrown.+ */+ protected String getDeploymentPath(AssetAttribute protocolConfiguration) throws IllegalArgumentException {+ String path = protocolConfiguration.getMetaItem(META_PROTOCOL_DEPLOYMENT_PATH)+ .flatMap(ValueHolder::getValueAsString)+ .map(String::toLowerCase)+ .orElseThrow(() ->+ new IllegalArgumentException(+ "Required deployment path meta item is missing or invalid: " + META_PROTOCOL_DEPLOYMENT_PATH));++ String deploymentPath = getDeploymentPathPrefix() + "/" + path;++ if (!PATH_REGEX.matcher(deploymentPath).find()) {+ throw new IllegalArgumentException(+ "Required deployment path meta item is missing or invalid: " + META_PROTOCOL_DEPLOYMENT_PATH);+ }++ return deploymentPath;+ }++ /**+ * Get standard JAX-RS providers that are used in all deployments.+ */+ protected List<Object> getStandardProviders(AssetAttribute protocolConfiguration) {+ return Lists.newArrayList(+ defaultResteasyExceptionMapper,+ forbiddenResteasyExceptionMapper,+ jacksonConfig,+ modelValueMessageBodyConverter,+ alreadtGzippedWriterInterceptor,+ clientErrorExceptionHandler+ );+ }++ protected void configureDeploymentInfo(DeploymentInfo deploymentInfo) {+ // This will catch anything not handled by Resteasy/Servlets, such as IOExceptions "at the wrong time"+ deploymentInfo.setExceptionHandler(undertowExceptionHandler);+ }++ /**+ * Get a unique deployment name for the supplied {@link ProtocolConfiguration}.+ */+ protected String getDeploymentName(AssetAttribute protocolConfiguration) {+ deploymentCounter++;+ return String.format(DEFAULT_DEPLOYMENT_NAME_FORMAT, getProtocolDisplayName(), deploymentCounter);+ }++ protected void deploy(DeploymentInfo deploymentInfo, AssetAttribute protocolConfiguration) {+ LOG.info("Deploying JAX-RS deployment for: " + protocolConfiguration.getReferenceOrThrow());+ DeploymentManager manager = Servlets.defaultContainer().addDeployment(deploymentInfo);+ manager.deploy();+ HttpHandler httpHandler;++ try {+ httpHandler = manager.start();+ deployments.put(protocolConfiguration.getReferenceOrThrow(), new Pair<>(deploymentInfo, httpHandler));+ LOG.info("Registering HTTP Server Protocol request handler '"+ + this.getClass().getSimpleName()+ + "' for request path: "+ + deploymentInfo.getContextPath());+ webService.getRequestPathHandler().addPrefixPath(deploymentInfo.getContextPath(), httpHandler);+ } catch (ServletException e) {+ LOG.severe("Failed to deploy deployment: " + deploymentInfo.getDeploymentName());+ }+ }++ protected void undeploy(AssetAttribute protocolConfiguration) {+ Pair<DeploymentInfo, HttpHandler> deploymentInfoHttpHandlerPair = deployments.get(protocolConfiguration.getReferenceOrThrow());++ if (deploymentInfoHttpHandlerPair == null) {+ LOG.info("Deployment doesn't exist for protocol configuration: " + protocolConfiguration);+ return;+ }++ DeploymentInfo deploymentInfo = deploymentInfoHttpHandlerPair.key;++ try {+ LOG.info("Un-registering HTTP Server Protocol request handler '"+ + this.getClass().getSimpleName()+ + "' for request path: "+ + deploymentInfo.getContextPath());+ webService.getRequestPathHandler().removePrefixPath(deploymentInfo.getContextPath());+ DeploymentManager manager = Servlets.defaultContainer().getDeployment(deploymentInfo.getDeploymentName());+ manager.stop();+ manager.undeploy();+ Servlets.defaultContainer().removeDeployment(deploymentInfo);+ deployments.remove(protocolConfiguration.getReferenceOrThrow());+ } catch (Exception ex) {+ LOG.log(Level.WARNING,+ "An exception occurred whilst un-deploying protocolConfiguration: " + protocolConfiguration.getReferenceOrThrow(),+ ex);+ throw new RuntimeException(ex);+ }+ }+}\ No newline at end of filediff --git a/container/src/main/java/org/openremote/container/web/WebService.java b/container/src/main/java/org/openremote/container/web/WebService.javaindex 0a4b33f4d..cb0798830 100644--- a/container/src/main/java/org/openremote/container/web/WebService.java+++ b/container/src/main/java/org/openremote/container/web/WebService.java@@ -21,6 +21,7 @@ package org.openremote.container.web;import io.undertow.Undertow;import io.undertow.server.HttpHandler;+import io.undertow.server.handlers.PathHandler;import io.undertow.server.handlers.RedirectHandler;import io.undertow.server.handlers.RequestDumpingHandler;import io.undertow.servlet.Servlets;@@ -75,9 +76,10 @@ public abstract class WebService implements ContainerService {public static final String API_PATH = "/api";public static final String JSAPI_PATH = "/jsapi";- protected final Pattern PATTERN_REALM_ROOT = Pattern.compile("/([a-zA-Z0-9\\-_]+)/?");- protected final Pattern PATTERN_REALM_SUB = Pattern.compile("/([a-zA-Z0-9\\-_]+)/(.*)");+ protected static final Pattern PATTERN_REALM_ROOT = Pattern.compile("/([a-zA-Z0-9\\-_]+)/?");+ protected static final Pattern PATTERN_REALM_SUB = Pattern.compile("/([a-zA-Z0-9\\-_]+)/(.*)");+ protected PathHandler requestPathHandler;protected boolean devMode;protected String host;protected int port;@@ -135,6 +137,10 @@ public abstract class WebService implements ContainerService {}}+ public PathHandler getRequestPathHandler() {+ return requestPathHandler;+ }+protected Undertow.Builder build(Container container, Undertow.Builder builder) {LOG.info("Building web routing with custom routes: " + getPrefixRoutes().keySet());@@ -144,8 +150,10 @@ public abstract class WebService implements ContainerService {: null;ResteasyDeployment resteasyDeployment = createResteasyDeployment(container);+HttpHandler apiHandler = createApiHandler(identityService, resteasyDeployment);HttpHandler jsApiHandler = createJsApiHandler(identityService, resteasyDeployment);+ requestPathHandler = new PathHandler(apiHandler);HttpHandler handler = exchange -> {String requestPath = exchange.getRequestPath();@@ -189,29 +197,30 @@ public abstract class WebService implements ContainerService {return;}- // Serve API with path /<realm>/*Matcher realmSubMatcher = PATTERN_REALM_SUB.matcher(requestPath);- if (apiHandler != null && realmSubMatcher.matches()) {- LOG.fine("Serving API call: " + requestPath);- String realm = realmSubMatcher.group(1);-- // Move the realm from path segment to header- exchange.getRequestHeaders().put(HttpString.tryFromString(REQUEST_HEADER_REALM), realm);-- // Rewrite path, remove realm segment- URI apiUrl = fromUri(exchange.getRequestURL())- .replacePath(API_PATH).path(realmSubMatcher.group(2))- .build();- exchange.setRequestURI(apiUrl.toString(), true);- exchange.setRequestPath(apiUrl.getPath());- exchange.setRelativePath(apiUrl.getPath());-- apiHandler.handleRequest(exchange);- return;++ if (!realmSubMatcher.matches()) {+ exchange.setStatusCode(NOT_FOUND.getStatusCode());+ throw new WebApplicationException(NOT_FOUND);}- exchange.setStatusCode(NOT_FOUND.getStatusCode());- throw new WebApplicationException(NOT_FOUND);+ // Extract realm from path and push it into REQUEST_HEADER_REALM header+ String realm = realmSubMatcher.group(1);++ // Move the realm from path segment to header+ exchange.getRequestHeaders().put(HttpString.tryFromString(REQUEST_HEADER_REALM), realm);++ // Rewrite path, remove realm segment+ URI url = fromUri(exchange.getRequestURL())+ .replacePath(realmSubMatcher.group(2))+ .build();+ exchange.setRequestURI(url.toString(), true);+ exchange.setRequestPath(url.getPath());+ exchange.setRelativePath(url.getPath());++ // Look for registered path handlers and fallback to API handler+ LOG.fine("Serving HTTP call: " + url.getPath());+ requestPathHandler.handleRequest(exchange);};handler = new WebServiceExceptions.RootUndertowExceptionHandler(devMode, handler);@@ -359,8 +368,6 @@ public abstract class WebService implements ContainerService {* Provides the LAN IPv4 address the container is bound to so it can be* used in the context provider callbacks; if CB is on the other side of some sort* of NAT then this won't work also assumes HTTP- *- * @return*/public URI getHostUri() {return containerHostUri;diff --git a/test/src/main/groovy/org/openremote/test/ContainerTrait.groovy b/test/src/main/groovy/org/openremote/test/ContainerTrait.groovyindex 346f553cc..3bb6f3952 100644--- a/test/src/main/groovy/org/openremote/test/ContainerTrait.groovy+++ b/test/src/main/groovy/org/openremote/test/ContainerTrait.groovy@@ -90,6 +90,10 @@ trait ContainerTrait {WebClient.getTarget(createClient().build(), serverUri.clone().replacePath(realm).build(), accessToken, null, null)}+ static ResteasyWebTarget getClientTarget(UriBuilder serverUri, String realm, String path, String accessToken) {+ WebClient.getTarget(createClient().build(), serverUri.clone().replacePath(realm).path(path).build(), accessToken, null, null)+ }+static ResteasyWebTarget getClientTarget(ResteasyClient client, UriBuilder serverUri, String realm, String accessToken) {WebClient.getTarget(client, serverUri.clone().replacePath(realm).build(), accessToken, null, null)}diff --git a/test/src/main/groovy/org/openremote/test/protocol/http/TestHttpServerProtocol.java b/test/src/main/groovy/org/openremote/test/protocol/http/TestHttpServerProtocol.javanew file mode 100644index 000000000..664717c56--- /dev/null+++ b/test/src/main/groovy/org/openremote/test/protocol/http/TestHttpServerProtocol.java@@ -0,0 +1,66 @@+/*+ * Copyright 2017, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.test.protocol.http;++import org.openremote.agent.protocol.http.AbstractHttpServerProtocol;+import org.openremote.model.asset.AssetAttribute;+import org.openremote.model.attribute.AttributeEvent;++import java.util.Collections;+import java.util.HashSet;+import java.util.Set;++public class TestHttpServerProtocol extends AbstractHttpServerProtocol {++ public static final String PROTOCOL_NAME = AbstractHttpServerProtocol.PROTOCOL_NAME + ":test";+ public TestResourceImpl resource1 = new TestResourceImpl();++ @Override+ protected Set<Object> getApiSingletons(AssetAttribute protocolConfiguration) {+ return new HashSet<>(Collections.singletonList(resource1));+ }++ @Override+ protected void doLinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration) {+ }++ @Override+ protected void doUnlinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration) {+ }++ @Override+ protected void processLinkedAttributeWrite(AttributeEvent event, AssetAttribute protocolConfiguration) {+ }++ @Override+ public String getProtocolName() {+ return PROTOCOL_NAME;+ }++ @Override+ public String getProtocolDisplayName() {+ return "HTTP Server Test Protocol";+ }++ @Override+ public String getVersion() {+ return "1.0";+ }+}diff --git a/test/src/main/groovy/org/openremote/test/protocol/http/TestResource.java b/test/src/main/groovy/org/openremote/test/protocol/http/TestResource.javanew file mode 100644index 000000000..98d0317d5--- /dev/null+++ b/test/src/main/groovy/org/openremote/test/protocol/http/TestResource.java@@ -0,0 +1,40 @@+/*+ * Copyright 2017, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.test.protocol.http;++import org.openremote.model.asset.Asset;++import javax.annotation.security.RolesAllowed;+import javax.ws.rs.*;++import static javax.ws.rs.core.MediaType.APPLICATION_JSON;++@Path("resource1")+public interface TestResource {++ @POST+ @Consumes(APPLICATION_JSON)+ @RolesAllowed({"write:assets"})+ void postAsset(Asset asset);++ @GET+ @Produces(APPLICATION_JSON)+ Asset getAsset(@QueryParam("assetId") String assetId);+}diff --git a/test/src/main/groovy/org/openremote/test/protocol/http/TestResourceImpl.java b/test/src/main/groovy/org/openremote/test/protocol/http/TestResourceImpl.javanew file mode 100644index 000000000..103a9cace--- /dev/null+++ b/test/src/main/groovy/org/openremote/test/protocol/http/TestResourceImpl.java@@ -0,0 +1,40 @@+/*+ * Copyright 2017, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.test.protocol.http;++import org.openremote.model.asset.Asset;++import java.util.ArrayList;+import java.util.List;++public class TestResourceImpl implements TestResource {++ public List<Asset> postedAssets = new ArrayList<>();++ @Override+ public void postAsset(Asset asset) {+ postedAssets.add(asset);+ }++ @Override+ public Asset getAsset(String assetId) {+ return postedAssets.stream().filter(asset -> asset.getId().equals(assetId)).findFirst().orElse(null);+ }+}diff --git a/test/src/test/groovy/org/openremote/test/protocol/http/HttpClientProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/http/HttpClientProtocolTest.groovyindex 1d9bd42f1..ab2942af7 100644--- a/test/src/test/groovy/org/openremote/test/protocol/http/HttpClientProtocolTest.groovy+++ b/test/src/test/groovy/org/openremote/test/protocol/http/HttpClientProtocolTest.groovy@@ -272,7 +272,7 @@ class HttpClientProtocolTest extends Specification implements ManagerContainerTrdef "Check HTTP client protocol configuration and linked attribute deployment"() {given: "expected conditions"- def conditions = new PollingConditions(timeout: 15, initialDelay: 1, delay: 1)+ def conditions = new PollingConditions(timeout: 10, initialDelay: 1)and: "the HTTP client protocol polling time units are set to milliseconds"HttpClientProtocol.POLLING_TIME_UNIT = TimeUnit.MILLISECONDSdiff --git a/test/src/test/groovy/org/openremote/test/protocol/http/HttpServerProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/http/HttpServerProtocolTest.groovynew file mode 100644index 000000000..160f5b1f2--- /dev/null+++ b/test/src/test/groovy/org/openremote/test/protocol/http/HttpServerProtocolTest.groovy@@ -0,0 +1,436 @@+/*+ * Copyright 2017, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.test.protocol.http++import com.vividsolutions.jts.geom.Coordinate+import com.vividsolutions.jts.geom.GeometryFactory+import org.jboss.resteasy.spi.ResteasyUriInfo+import org.jboss.resteasy.util.BasicAuthHelper+import org.openremote.agent.protocol.http.*+import org.openremote.manager.agent.AgentService+import org.openremote.manager.asset.AssetProcessingService+import org.openremote.manager.asset.AssetStorageService+import org.openremote.manager.asset.ServerAsset+import org.openremote.model.asset.AssetAttribute+import org.openremote.model.asset.AssetType+import org.openremote.model.attribute.AttributeType+import org.openremote.model.attribute.MetaItem+import org.openremote.model.value.ObjectValue+import org.openremote.model.value.Values+import org.openremote.test.ManagerContainerTrait+import spock.lang.Shared+import spock.lang.Specification+import spock.util.concurrent.PollingConditions++import javax.ws.rs.ForbiddenException+import javax.ws.rs.HttpMethod+import javax.ws.rs.NotFoundException+import javax.ws.rs.client.ClientRequestContext+import javax.ws.rs.client.ClientRequestFilter+import javax.ws.rs.core.*++import static org.openremote.container.util.MapAccess.getString+import static org.openremote.manager.setup.AbstractKeycloakSetup.SETUP_ADMIN_PASSWORD+import static org.openremote.manager.setup.AbstractKeycloakSetup.SETUP_ADMIN_PASSWORD_DEFAULT+import static org.openremote.model.Constants.*+import static org.openremote.model.asset.agent.ProtocolConfiguration.initProtocolConfiguration++class HttpServerProtocolTest extends Specification implements ManagerContainerTrait {++ @Shared+ def mockServer = new ClientRequestFilter() {++ private boolean supportsRefresh+ private int accessTokenCount+ private int refreshTokenCount+ private String accessToken = null+ private String refreshToken = null+ private int pingCount = 0+ private int pollCountFast = 0+ private int pollCountSlow = 0+ private boolean putRequestWithHeadersCalled = false+ private int successFailureCount = 0++ @Override+ void filter(ClientRequestContext requestContext) throws IOException {+ def requestUri = requestContext.uri+ def requestPath = requestUri.scheme + "://" + requestUri.host + requestUri.path++ switch (requestPath) {+ case "https://mockapi/basicauth":+ def authHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION)+ if (authHeader != null) {+ def usernameAndPassword = BasicAuthHelper.parseHeader(authHeader)+ if (usernameAndPassword != null+ && usernameAndPassword[0] == "testuser"+ && usernameAndPassword[1] == "password1") {+ requestContext.abortWith(Response.ok().build())+ return+ }+ }+ break+ case "https://mockapi/token":+ // OAuth token request extract the grant info+ def grant = ((Form) requestContext.getEntity()).asMap()+ if (grant.getFirst(OAuthGrant.VALUE_KEY_GRANT_TYPE) == "password"+ && grant.getFirst(OAuthGrant.VALUE_KEY_CLIENT_ID) == "TestClient"+ && grant.getFirst(OAuthGrant.VALUE_KEY_CLIENT_SECRET) == "TestSecret"+ && grant.getFirst(OAuthGrant.VALUE_KEY_SCOPE) == "scope1 scope2"+ && grant.getFirst(OAuthPasswordGrant.VALUE_KEY_USERNAME) == "testuser"+ && grant.getFirst(OAuthPasswordGrant.VALUE_KEY_PASSWORD) == "password") {+ accessToken = "accesstoken" + accessTokenCount+++ def response = new OAuthServerResponse()+ response.accessToken = accessToken+ response.expiresIn = 100+ response.tokenType = "Bearer"++ // Include refresh token if configured to support it+ if (supportsRefresh) {+ refreshToken = "refreshtoken" + accessTokenCount+ response.refreshToken = refreshToken+ }++ requestContext.abortWith(+ Response.ok(response, MediaType.APPLICATION_JSON_TYPE).build()+ )+ return+ } else if (grant.getFirst(OAuthGrant.VALUE_KEY_GRANT_TYPE) == "refresh_token"+ && grant.getFirst(OAuthGrant.VALUE_KEY_CLIENT_ID) == "TestClient"+ && grant.getFirst(OAuthGrant.VALUE_KEY_CLIENT_SECRET) == "TestSecret"+ && grant.getFirst(OAuthGrant.VALUE_KEY_SCOPE) == "scope1 scope2"+ && grant.getFirst(OAuthRefreshTokenGrant.VALUE_KEY_REFRESH_TOKEN) == refreshToken) {+ refreshTokenCount+++ accessToken = "accesstoken" + accessTokenCount+++ refreshToken = "refreshtoken" + accessTokenCount+ def response = new OAuthServerResponse()+ response.accessToken = accessToken+ response.refreshToken = refreshToken+ response.expiresIn = 100+ response.tokenType = "Bearer"++ requestContext.abortWith(+ Response.ok(response, MediaType.APPLICATION_JSON_TYPE).build()+ )+ return+ }+ break+ default:+ // Check access token is valid+ def authHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION)+ def accessToken = authHeader == null ? null : authHeader.substring(7)+ if (accessToken == null || this.accessToken == null || accessToken != this.accessToken) {+ requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build())+ return+ }+ break+ }++ switch (requestPath) {+ case "https://mockapi/pingGet":+ UriInfo uriInfo = new ResteasyUriInfo(requestContext.uri)+ def queryParams = uriInfo.getQueryParameters(true)+ if (queryParams.get("param1").size() == 1+ && queryParams.getFirst("param1") == "param1Value1"+ && queryParams.get("param2").size() == 2+ && queryParams.get("param2").get(0) == "param2Value1"+ && queryParams.get("param2").get(1) == "param2Value2"+ && requestContext.getHeaderString("header1") == "header1Value1"+ && requestContext.getHeaderString("header2") == "header2Value1,header2Value2") {+ pingCount+++ requestContext.abortWith(+ Response.ok().build()+ )+ return+ }+ break+ case "https://mockapi/pingPost":+ UriInfo uriInfo = new ResteasyUriInfo(requestContext.uri)+ def queryParams = uriInfo.getQueryParameters(true)+ if (queryParams.get("param1").size() == 2+ && queryParams.getFirst("param1") == "param1Value1"+ && queryParams.get("param1").get(1) == "param1Value2"+ && queryParams.get("param2").size() == 2+ && queryParams.get("param2").get(0) == "param2Value1"+ && queryParams.get("param2").get(1) == "param2Value2"+ && queryParams.get("param3").size() == 1+ && queryParams.getFirst("param3") == "param3Value1"+ && requestContext.method == HttpMethod.POST+ && requestContext.getHeaderString("header1") == "header1Value1"+ && requestContext.getHeaderString("header2") == "header2Value1,header2Value2"+ && (requestContext.getHeaderString("Content-type") == MediaType.APPLICATION_JSON+ || requestContext.getHeaderString("Content-type") == MediaType.APPLICATION_XML)) {++ String bodyStr = (String)requestContext.getEntity()+ ObjectValue body = Values.<ObjectValue>parse(bodyStr).orElse(null)+ if (body.get("prop1").isPresent() && body.get("prop2").isPresent()) {+ pingCount+++ requestContext.abortWith(Response.ok().build())+ return+ }+ }+ break+ case "https://mockapi/put_request_with_headers":+ UriInfo uriInfo = new ResteasyUriInfo(requestContext.uri)+ def queryParams = uriInfo.getQueryParameters(true)+ if (queryParams.get("param1").size() == 1+ && queryParams.getFirst("param1") == "param1Value1"+ && queryParams.get("param2").size() == 3+ && queryParams.get("param2").get(0) == "param2Value1"+ && queryParams.get("param2").get(1) == "param2Value2"+ && queryParams.get("param2").get(2) == "param2Value3"+ && queryParams.get("param3").size() == 1+ && queryParams.getFirst("param3") == "param3Value1"+ && requestContext.method == HttpMethod.PUT+ && requestContext.getHeaderString("header1") == null+ && requestContext.getHeaderString("header2") == "header2Value1,header2Value2"+ && requestContext.getHeaderString("Content-type") == MediaType.APPLICATION_JSON) {++ String bodyStr = (String)requestContext.getEntity()+ ObjectValue body = Values.<ObjectValue>parse(bodyStr).orElse(null)+ if (body.get("prop1").isPresent()+ && body.get("prop1").get().toString() == /{"myProp1":123,"myProp2":true}/+ && body.get("prop2").isPresent() && body.get("prop2").get().toString() == "prop2Value") {+ putRequestWithHeadersCalled = true+ requestContext.abortWith(Response.ok().build())+ return+ }+ }+ break+ case "https://mockapi/value/50/set":+ requestContext.abortWith(Response.ok().build())+ return+ case "https://mockapi/get_poll_slow":+ pollCountSlow+++ requestContext.abortWith(+ Response+ .ok("This is an example response where the value of 100% is in the body of the message.", MediaType.TEXT_PLAIN)+ .build()+ )+ return+ case "https://mockapi/get_poll_fast":+ pollCountFast+++ requestContext.abortWith(+ Response+ .ok("This is an example response where there are multiple values of 100% 60% in the body of the message.", MediaType.TEXT_PLAIN)+ .build()+ )+ return+ case "https://mockapi/get_success_200":+ case "https://redirected.mockapi/get_success_200":+ successFailureCount+++ requestContext.abortWith(Response.ok().build())+ return+ case "https://mockapi/get_failure_401":+ successFailureCount+++ requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build())+ return+ case "https://mockapi/redirect":+ requestContext.abortWith(Response.temporaryRedirect(new URI("https://redirected.mockapi/get_success_200")).build())+ return+ }++ requestContext.abortWith(Response.serverError().build())+ }+ }++ def cleanupSpec() {+ WebTargetBuilder.close()+ }++ def cleanup() {+ mockServer.supportsRefresh = false+ mockServer.accessToken = null+ mockServer.refreshToken = null+ mockServer.accessTokenCount = 0+ mockServer.refreshTokenCount = 0+ mockServer.pingCount = 0+ mockServer.pollCountSlow = 0+ mockServer.pollCountFast = 0+ mockServer.successFailureCount = 0+ mockServer.putRequestWithHeadersCalled = false+ }++ def "Check HTTP server protocol configuration and JAX-RS deployment"() {++ given: "expected conditions"+ def conditions = new PollingConditions(timeout: 10, initialDelay: 1)++ and: "the container starts with the test http server protocol"+ def serverPort = findEphemeralPort()+ def testServerProtocol = new TestHttpServerProtocol()+ def container = startContainerNoDemoImport(defaultConfig(serverPort), defaultServices(testServerProtocol))+ def httpClientProtocol = container.getService(HttpClientProtocol.class)+ def assetStorageService = container.getService(AssetStorageService.class)+ def assetProcessingService = container.getService(AssetProcessingService.class)+ def agentService = container.getService(AgentService.class)++ and: "an authenticated admin user"+ def accessToken = authenticate(+ container,+ MASTER_REALM,+ KEYCLOAK_CLIENT_ID,+ MASTER_REALM_ADMIN_USER,+ getString(container.getConfig(), SETUP_ADMIN_PASSWORD, SETUP_ADMIN_PASSWORD_DEFAULT)+ ).token++ and: "the test resource (to be deployed by the protocol)"+ def authenticatedTestResource = getClientTarget(+ serverUri(serverPort),+ MASTER_REALM,+ AbstractHttpServerProtocol.DEFAULT_DEPLOYMENT_PATH_PREFIX + "/test",+ accessToken).proxy(TestResource.class)+ def testResource = getClientTarget(+ serverUri(serverPort),+ MASTER_REALM,+ AbstractHttpServerProtocol.DEFAULT_DEPLOYMENT_PATH_PREFIX + "/test",+ null).proxy(TestResource.class)++ when: "an agent with a test HTTP server protocol configuration is created"+ def agent = new ServerAsset()+ agent.setRealmId(MASTER_REALM)+ agent.setName("Test Agent")+ agent.setType(AssetType.AGENT)+ agent.setAttributes(+ initProtocolConfiguration(new AssetAttribute("protocolConfig"), TestHttpServerProtocol.PROTOCOL_NAME)+ .addMeta(+ new MetaItem(+ AbstractHttpServerProtocol.META_PROTOCOL_DEPLOYMENT_PATH,+ Values.create("test")+ ),+ new MetaItem(+ AbstractHttpServerProtocol.META_PROTOCOL_ROLE_BASED_SECURITY_ENABLED,+ Values.create(true)+ )+ )+ )++ and: "the agent is added to the asset service"+ agent = assetStorageService.merge(agent)++ then: "the protocol should be deployed"+ conditions.eventually {+ assert AbstractHttpServerProtocol.deployments.size() == 1+ }++ when: "the authenticated test resource is used to post an asset"+ def testAsset = new ServerAsset("Test Asset", AssetType.THING)+ testAsset.setId("12345")+ testAsset.setAttributes(+ new AssetAttribute("attribute1", AttributeType.STRING, Values.create("Test"))+ )+ testAsset.setLocation(new GeometryFactory().createPoint(new Coordinate(1d, 2d)))+ authenticatedTestResource.postAsset(testAsset)++ then: "the asset should be stored in the test protocol"+ conditions.eventually {+ assert testServerProtocol.resource1.postedAssets.size() == 1+ assert testServerProtocol.resource1.postedAssets.get(0).name == "Test Asset"+ assert testServerProtocol.resource1.postedAssets.get(0).hasTypeWellKnown()+ assert testServerProtocol.resource1.postedAssets.get(0).wellKnownType == AssetType.THING+ assert testServerProtocol.resource1.postedAssets.get(0).coordinates[0] == 1d+ assert testServerProtocol.resource1.postedAssets.get(0).coordinates[1] == 2d+ }++ when: "the authenticated test resource is used to get an asset"+ def asset = authenticatedTestResource.getAsset("12345")++ then: "the asset should match the posted asset"+ assert asset.name == testAsset.name+ assert asset.wellKnownType == testAsset.wellKnownType+ assert asset.coordinates[0] == testAsset.coordinates[0]+ assert asset.coordinates[1] == testAsset.coordinates[1]++ when: "the un-authenticated test resource is used to post an asset"+ testResource.postAsset(testAsset)++ then: "an exception should be thrown"+ thrown ForbiddenException++ when: "an additional instance of the Test HTTP Server protocol is deployed without security enabled"+ agent.addAttributes(+ initProtocolConfiguration(new AssetAttribute("protocolConfig2"), TestHttpServerProtocol.PROTOCOL_NAME)+ .addMeta(+ new MetaItem(+ AbstractHttpServerProtocol.META_PROTOCOL_DEPLOYMENT_PATH,+ Values.create("test2")+ )+ )+ )+ agent = assetStorageService.merge(agent)++ and: "an un-authenticated test resource proxy is created for the new deployment"+ def testResource2 = getClientTarget(+ serverUri(serverPort),+ MASTER_REALM,+ AbstractHttpServerProtocol.DEFAULT_DEPLOYMENT_PATH_PREFIX + "/test2",+ null).proxy(TestResource.class)++ then: "the protocol should be deployed"+ conditions.eventually {+ assert AbstractHttpServerProtocol.deployments.size() == 2+ }++ when: "the new test resource is used to post an asset"+ testAsset = new ServerAsset("Test Asset 2", AssetType.THING)+ testAsset.setId("67890")+ testAsset.setAttributes(+ new AssetAttribute("attribute2", AttributeType.STRING, Values.create("Test"))+ )+ testAsset.setLocation(new GeometryFactory().createPoint(new Coordinate(3d, 4d)))+ authenticatedTestResource.postAsset(testAsset)++ then: "the asset should be stored in the test protocol"+ conditions.eventually {+ assert testServerProtocol.resource1.postedAssets.size() == 2+ assert testServerProtocol.resource1.postedAssets.get(1).name == "Test Asset 2"+ assert testServerProtocol.resource1.postedAssets.get(1).hasTypeWellKnown()+ assert testServerProtocol.resource1.postedAssets.get(1).wellKnownType == AssetType.THING+ assert testServerProtocol.resource1.postedAssets.get(1).coordinates[0] == 3d+ assert testServerProtocol.resource1.postedAssets.get(1).coordinates[1] == 4d+ }++ when: "the new test resource is used to get an asset"+ asset = authenticatedTestResource.getAsset("67890")++ then: "the asset should match the posted asset"+ assert asset.name == testAsset.name+ assert asset.wellKnownType == testAsset.wellKnownType+ assert asset.coordinates[0] == testAsset.coordinates[0]+ assert asset.coordinates[1] == testAsset.coordinates[1]++ when: "a protocol configuration is deleted"+ agent.removeAttribute("protocolConfig")+ agent = assetStorageService.merge(agent)++ then: "the associated protocol instance should be un-deployed"+ conditions.eventually {+ assert AbstractHttpServerProtocol.deployments.size() == 1+ }++ when: "an attempt is made to use the removed endpoint"+ authenticatedTestResource.postAsset(testAsset)++ then: "a not found exception should be thrown"+ thrown NotFoundException++ cleanup: "the server should be stopped"+ stopContainer(container)+ }+}\ No newline at end of file