Skip to content

armgit / core

Public Imported from GitHub
0

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

Added HttpClientProtocol

Rich Turner6a428096222d
diff --git a/agent/src/main/java/org/openremote/agent/protocol/http/FollowRedirectFilter.java b/agent/src/main/java/org/openremote/agent/protocol/http/FollowRedirectFilter.java
new file mode 100644
index 000000000..4dc9abf2d
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/http/FollowRedirectFilter.java
@@ -0,0 +1,49 @@
+/*
+ * 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 javax.ws.rs.client.ClientRequestContext;
+import javax.ws.rs.client.ClientResponseContext;
+import javax.ws.rs.client.ClientResponseFilter;
+import javax.ws.rs.core.Response;
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * A filter for following 300 range response re-directions.
+ */
+public class FollowRedirectFilter implements ClientResponseFilter {
+ @Override
+ public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException
+ {
+ if (responseContext.getStatusInfo().getFamily() != Response.Status.Family.REDIRECTION)
+ return;
+
+ Response resp = requestContext.getClient()
+ .target(responseContext.getLocation())
+ .request()
+ .headers(requestContext.getHeaders())
+ .method(requestContext.getMethod());
+
+ responseContext.setEntityStream((InputStream) resp.getEntity());
+ responseContext.setStatusInfo(resp.getStatusInfo());
+ responseContext.setStatus(resp.getStatus());
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/http/HeaderInjectorFilter.java b/agent/src/main/java/org/openremote/agent/protocol/http/HeaderInjectorFilter.java
new file mode 100644
index 000000000..035c71500
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/http/HeaderInjectorFilter.java
@@ -0,0 +1,54 @@
+/*
+ * 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 javax.ws.rs.client.ClientRequestContext;
+import javax.ws.rs.client.ClientRequestFilter;
+import javax.ws.rs.core.MultivaluedMap;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * A filter for injecting headers into the request.
+ */
+public class HeaderInjectorFilter implements ClientRequestFilter {
+
+ protected Set<Map.Entry<String, List<String>>> headers;
+
+ public HeaderInjectorFilter(MultivaluedMap<String, String> headers) {
+ this.headers = headers.entrySet();
+ }
+
+ @Override
+ public void filter(ClientRequestContext requestContext) throws IOException {
+ headers.forEach(headerAndValues -> {
+ if (headerAndValues.getValue().isEmpty()) {
+ requestContext.getHeaders().remove(headerAndValues.getKey());
+ } else {
+ requestContext
+ .getHeaders()
+ .addAll(headerAndValues.getKey(), headerAndValues.getValue().toArray());
+ }
+ }
+ );
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/http/HttpClientProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/http/HttpClientProtocol.java
new file mode 100644
index 000000000..7472a1eff
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/http/HttpClientProtocol.java
@@ -0,0 +1,983 @@
+/*
+ * 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 org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
+import org.openremote.agent.protocol.AbstractProtocol;
+import org.openremote.container.Container;
+import org.openremote.model.AbstractValueHolder;
+import org.openremote.model.asset.AssetAttribute;
+import org.openremote.model.asset.AssetMeta;
+import org.openremote.model.asset.agent.ConnectionStatus;
+import org.openremote.model.asset.agent.ProtocolConfiguration;
+import org.openremote.model.attribute.*;
+import org.openremote.model.util.Pair;
+import org.openremote.model.util.TextUtil;
+import org.openremote.model.value.*;
+
+import javax.ws.rs.HttpMethod;
+import javax.ws.rs.client.Entity;
+import javax.ws.rs.client.Invocation;
+import javax.ws.rs.client.WebTarget;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedHashMap;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Future;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;
+
+/**
+ * This is a HTTP client protocol for communicating with HTTP servers; it uses the {@link WebTargetBuilder} factory to
+ * generate JAX-RS {@link javax.ws.rs.client.WebTarget}s that can be used to make arbitrary calls to endpoints on a HTTP
+ * server but it can also be extended and used as a JAX-RS client proxy.
+ * <p>
+ * <h1>Protocol Configurations</h1>
+ * <p>
+ * {@link Attribute}s that are configured as {@link ProtocolConfiguration}s for this protocol support the following meta
+ * items: <ul> <li>{@link #META_PROTOCOL_BASE_URI} (<b>required</b>)</li> <li>{@link #META_PROTOCOL_USERNAME}</li>
+ * <li>{@link #META_PROTOCOL_PASSWORD}</li> <li>{@link #META_PROTOCOL_OAUTH_GRANT}</li> <li>{@link
+ * #META_PROTOCOL_PING_PATH}</li> <li>{@link #META_PROTOCOL_PING_METHOD}</li> <li>{@link #META_PROTOCOL_PING_BODY}</li>
+ * <li>{@link #META_PROTOCOL_PING_QUERY_PARAMETERS}</li> <li>{@link #META_PROTOCOL_PING_SECONDS}</li> <li>{@link
+ * #META_PROTOCOL_FOLLOW_REDIRECTS}</li> <li>{@link #META_FAILURE_CODES}</li> <li>{@link #META_HEADERS}</li> </ul>
+ * <h1>Linked Attributes</h1>
+ * <p>
+ * {@link Attribute}s that are linked to this protocol using an {@link AssetMeta#AGENT_LINK} {@link MetaItem} support
+ * the following meta items: <ul> <li>{@link #META_ATTRIBUTE_PATH} (<b>if not supplied then base URI is used</b>)</li>
+ * <li>{@link #META_ATTRIBUTE_METHOD}</li> <li>{@link #META_ATTRIBUTE_BODY}</li> <li>{@link
+ * #META_ATTRIBUTE_POLLING_SECONDS} (<b>required if attribute value should be set by the response received from this
+ * endpoint</b>)</li> <li>{@link #META_QUERY_PARAMETERS}</li> <li>{@link #META_FAILURE_CODES}</li> <li>{@link #META_HEADERS}</li> </ul>
+ * <p>
+ * <h1>Response filtering</h1>
+ * <p>
+ * Any {@link Attribute} whose value is to be set by the HTTP server response (i.e. it has an {@link
+ * #META_ATTRIBUTE_POLLING_SECONDS} {@link MetaItem}) can use the standard <h1>Connection Status</h1>
+ * <p>
+ * The {@link ConnectionStatus} of the {@link ProtocolConfiguration} is determined by the ping {@link
+ * org.openremote.model.attribute.MetaItem}s on the protocol configuration. If specified then the {@link
+ * #META_PROTOCOL_PING_PATH} will be called every {@link #META_PROTOCOL_PING_SECONDS} this should be a lightweight
+ * endpoint (i.e. no response body or small response body) and if the HTTP server requires authentication then this ping
+ * endpoint should also be a secured endpoint to validate the credentials.
+ * <p>
+ * If the {@link #META_PROTOCOL_PING_PATH} is not configured then the {@link ConnectionStatus} will be set based on the
+ * responses received from any linked {@link Attribute} requests, the connection status is determined as follows:
+ * <p>
+ * <ul> <li>No request/response yet sent/received = {@link ConnectionStatus#UNKNOWN}</li> <li>Response status in 100
+ * range = {@link ConnectionStatus#ERROR}</li> <li>Response status in 200 range = {@link
+ * ConnectionStatus#CONNECTED}</li> <li>Response status in 300 range = {@link ConnectionStatus#ERROR} (unless {@link
+ * #META_PROTOCOL_FOLLOW_REDIRECTS} = true)</li> <li>Response status 401/402/403 = {@link
+ * ConnectionStatus#ERROR_AUTHENTICATION}</li> <li>Response status in 404+ range = {@link
+ * ConnectionStatus#ERROR_CONFIGURATION}</li> <li>Response status in 500 range = {@link ConnectionStatus#ERROR}</li>
+ * </ul>
+ * <p>
+ * <b>NOTE: if an exception is thrown during the request that means no response is returned then this is treated as if
+ * a 500 response has been received</b>
+ * <h1>Dynamic value injection</h1>
+ * This allows the {@link #META_ATTRIBUTE_PATH} and/or {@link #META_ATTRIBUTE_BODY} to contain the linked
+ * {@link Attribute} value when sending requests. To dynamically inject the attribute value use
+ * {@value #DYNAMIC_VALUE_PLACEHOLDER} as a placeholder and this will be dynamically replaced at request time.
+ * <h2>Path example</h2>
+ * {@link #META_ATTRIBUTE_PATH} = "volume/set/{$value}" and request received to set attribute value to 100. Actual path
+ * used for the request = "volume/set/100"
+ * <h2>Query parameter example</h2>
+ * {@link #META_QUERY_PARAMETERS} =
+ * <blockquote><pre>
+ * {@code
+ * {
+ * param1: ["val1", "val2"],
+ * param2: 12232,
+ * param3: "{$value}"
+ * }
+ * }
+ * </pre></blockquote>
+ * Request received to set attribute value to true. Actual query parameters injected into the request =
+ * "param1=val1&param1=val2&param2=12232&param3=true"
+ * <h2>Body examples</h2>
+ * {@link #META_ATTRIBUTE_BODY} = '<?xml version="1.0" encoding="UTF-8"?>{$value}</xml>' and request received to set attribute value to 100. Actual body
+ * used for the request = "{volume: 100}"
+ * <p>
+ * {@link #META_ATTRIBUTE_BODY} = '{myObject: "{$value}"}' and request received to set attribute value to:
+ * <blockquote><pre>
+ * {@code
+ * {
+ * prop1: true,
+ * prop2: "test",
+ * prop3: {
+ * prop4: 1234.4223
+ * }
+ * }
+ * }
+ * </pre></blockquote>
+ * Actual body used for the request = "{myObject: {prop1: true, prop2: "test", prop3: {prop4: 1234.4223}}}"
+ */
+public class HttpClientProtocol extends AbstractProtocol {
+
+ protected static class HttpClientRequest {
+
+ protected String path;
+ protected String method;
+ protected MultivaluedMap<String, String> headers;
+ protected MultivaluedMap<String, String> queryParameters;
+ protected List<Integer> failureCodes;
+ protected String body;
+ protected String contentType;
+ protected WebTarget client;
+ protected WebTarget requestTarget;
+ protected boolean dynamicQueryParameters;
+ protected boolean dynamicBody;
+ protected boolean updateConnectionStatus;
+
+ protected HttpClientRequest(WebTarget client,
+ String path,
+ String method,
+ MultivaluedMap<String, String> headers,
+ MultivaluedMap<String, String> queryParameters,
+ List<Integer> failureCodes,
+ boolean updateConnectionStatus,
+ Value bodyValue,
+ String contentType) {
+ this.client = client;
+ this.path = path;
+ this.method = method;
+ this.headers = headers;
+ this.queryParameters = queryParameters;
+ this.failureCodes = failureCodes;
+ this.updateConnectionStatus = updateConnectionStatus;
+ this.contentType = contentType;
+ dynamicQueryParameters = queryParameters != null
+ && queryParameters
+ .entrySet()
+ .stream()
+ .anyMatch(paramNameAndValues ->
+ paramNameAndValues.getValue() != null
+ && paramNameAndValues.getValue()
+ .stream()
+ .anyMatch(val -> val.contains(DYNAMIC_VALUE_PLACEHOLDER)));
+
+ if (bodyValue != null) {
+ if (contentType == null) {
+ this.contentType = bodyValue.getType() == ValueType.OBJECT || bodyValue.getType() == ValueType.ARRAY
+ ? MediaType.APPLICATION_JSON
+ : DEFAULT_CONTENT_TYPE;
+ }
+ body = bodyValue.toString();
+ }
+
+ dynamicBody = !TextUtil.isNullOrEmpty(body)
+ && body.contains(DYNAMIC_VALUE_PLACEHOLDER);
+
+ boolean dynamicPath = !TextUtil.isNullOrEmpty(path) && path.contains(DYNAMIC_VALUE_PLACEHOLDER);
+ if (!dynamicPath) {
+ requestTarget = createRequestTarget(path);
+ }
+ }
+
+ protected WebTarget createRequestTarget(String path) {
+ WebTarget requestTarget = client.path(path == null ? "" : path);
+
+ if (headers != null) {
+ requestTarget.register(new HeaderInjectorFilter(headers));
+ }
+
+ if (queryParameters != null) {
+ requestTarget.register(new QueryParameterInjectorFilter(queryParameters, dynamicQueryParameters ? DYNAMIC_VALUE_PLACEHOLDER_REGEXP : null));
+ }
+
+ return requestTarget;
+ }
+
+ protected Invocation.Builder getRequestBuilder(String dynamicRequestValue) {
+ Invocation.Builder requestBuilder;
+
+ if (requestTarget != null) {
+ requestBuilder = requestTarget.request();
+ } else {
+ // This means that the path is dynamic
+ String path = this.path.replaceAll(DYNAMIC_VALUE_PLACEHOLDER_REGEXP, dynamicRequestValue);
+ requestBuilder = createRequestTarget(path).request();
+ }
+
+ if (dynamicQueryParameters) {
+ requestBuilder.property(QueryParameterInjectorFilter.DYNAMIC_VALUE, dynamicRequestValue);
+ }
+
+ return requestBuilder;
+ }
+
+ protected Invocation buildInvocation(Invocation.Builder requestBuilder, String dynamicRequestValue) {
+ Invocation invocation;
+
+ if (body == null) {
+ invocation = requestBuilder.build(method);
+ } else {
+ String body = this.body;
+
+ if (dynamicBody) {
+ body = body.replaceAll(DYNAMIC_VALUE_PLACEHOLDER_REGEXP, dynamicRequestValue);
+ }
+ if (dynamicQueryParameters) {
+ requestBuilder.property(QueryParameterInjectorFilter.DYNAMIC_VALUE, dynamicRequestValue);
+ }
+ invocation = requestBuilder.build(method, Entity.entity(body, contentType));
+ }
+
+ return invocation;
+ }
+
+ protected Response invoke(String dynamicRequestValue) {
+ Invocation.Builder requestBuilder = getRequestBuilder(dynamicRequestValue);
+ Invocation invocation = buildInvocation(requestBuilder, dynamicRequestValue);
+ return invocation.invoke();
+ }
+
+ protected Future<Response> submit(String dynamicRequestValue) {
+ Invocation.Builder requestBuilder = getRequestBuilder(dynamicRequestValue);
+ Invocation invocation = buildInvocation(requestBuilder, dynamicRequestValue);
+ return invocation.submit();
+ }
+ }
+
+ public static final String PROTOCOL_NAME = PROTOCOL_NAMESPACE + ":httpClient";
+
+ /*--------------- META ITEMS TO BE USED ON PROTOCOL CONFIGURATIONS ---------------*/
+ /**
+ * Base URI for all requests to this server
+ */
+ public static final String META_PROTOCOL_BASE_URI = PROTOCOL_NAME + ":baseUri";
+ /**
+ * Basic authentication username (string)
+ */
+ public static final String META_PROTOCOL_USERNAME = PROTOCOL_NAME + ":username";
+ /**
+ * Basic authentication password (string)
+ */
+ public static final String META_PROTOCOL_PASSWORD = PROTOCOL_NAME + ":password";
+ /**
+ * OAuth grant ({@link OAuthGrant} stored as {@link ObjectValue})
+ */
+ public static final String META_PROTOCOL_OAUTH_GRANT = PROTOCOL_NAME + ":oAuthGrant";
+ /**
+ * Relative path to endpoint that should be used for connection status ping (string)
+ */
+ public static final String META_PROTOCOL_PING_PATH = PROTOCOL_NAME + ":pingPath";
+ /**
+ * HTTP method for connection status ping (integer default: {@value #DEFAULT_HTTP_METHOD})
+ */
+ public static final String META_PROTOCOL_PING_METHOD = PROTOCOL_NAME + ":pingMethod";
+ /**
+ * HTTP request body for connection status ping ({@link Value})
+ */
+ public static final String META_PROTOCOL_PING_BODY = PROTOCOL_NAME + ":pingBody";
+ /**
+ * Used to indicate the type of data sent in the ping body; (see {@link #META_ATTRIBUTE_CONTENT_TYPE} for details)
+ */
+ public static final String META_PROTOCOL_PING_CONTENT_TYPE = PROTOCOL_NAME + ":pingContentType";
+ /**
+ * Query parameters for connection status ping (see {@link #META_QUERY_PARAMETERS} for details)
+ */
+ public static final String META_PROTOCOL_PING_QUERY_PARAMETERS = PROTOCOL_NAME + ":pingQueryParameters";
+ /**
+ * Ping frequency in seconds (integer default: {@value #DEFAULT_PING_SECONDS})
+ */
+ public static final String META_PROTOCOL_PING_SECONDS = PROTOCOL_NAME + ":pingSeconds";
+ /**
+ * Flag to indicate whether redirect responses from the HTTP server should be followed (boolean)
+ */
+ public static final String META_PROTOCOL_FOLLOW_REDIRECTS = PROTOCOL_NAME + ":followRedirects";
+
+ /*--------------- META ITEMS TO BE USED ON LINKED ATTRIBUTES ---------------*/
+ /**
+ * Relative path to endpoint on the server; supports dynamic value insertion, see class javadoc for details
+ * (string)
+ */
+ public static final String META_ATTRIBUTE_PATH = PROTOCOL_NAME + ":path";
+ /**
+ * HTTP method for request (string default: {@value #DEFAULT_HTTP_METHOD})
+ */
+ public static final String META_ATTRIBUTE_METHOD = PROTOCOL_NAME + ":method";
+ /**
+ * HTTP request body; supports dynamic value insertion, see class javadoc for more details ({@link Value})
+ */
+ public static final String META_ATTRIBUTE_BODY = PROTOCOL_NAME + ":body";
+ /**
+ * Used to indicate the type of data sent in the body, a default will be used if not supplied; default is determined
+ * as follows:
+ * <ul>
+ * <li>{@link #META_ATTRIBUTE_BODY} value type = {@link ObjectValue} or {@link ArrayValue}: {@link MediaType#APPLICATION_JSON}</li>
+ * <li>{@link #META_ATTRIBUTE_BODY} value type = any other value type: {@value #DEFAULT_CONTENT_TYPE}</li>
+ * </ul>
+ */
+ public static final String META_ATTRIBUTE_CONTENT_TYPE = PROTOCOL_NAME + ":contentType";
+ /**
+ * Polling frequency in seconds for {@link Attribute}s whose value should come from the HTTP server
+ */
+ public static final String META_ATTRIBUTE_POLLING_SECONDS = PROTOCOL_NAME + ":pollingSeconds";
+
+ /*--------------- META ITEMS TO BE USED ON PROTOCOL CONFIGURATIONS OR LINKED ATTRIBUTES ---------------*/
+ /**
+ * HTTP response codes that will automatically disable the {@link ProtocolConfiguration} and in the process
+ * unlink all linked {@link Attribute}s; the {@link ConnectionStatus} will change to
+ * {@link ConnectionStatus#DISABLED} and this will prevent any further requests being sent to the HTTP
+ * server (permanent failure - can be reset by re-enabling the {@link ProtocolConfiguration}; failure codes defined
+ * on a linked attribute will be combined with values set on the {@link ProtocolConfiguration} for that request
+ * (integer array).
+ */
+ public static final String META_FAILURE_CODES = PROTOCOL_NAME + ":failureCodes";
+ /**
+ * HTTP headers to be added to requests, {@link ObjectValue} where the keys represent the header name and the value
+ * represents the header value(s) (value can be a single string or an {@link ArrayValue} of strings), a value of
+ * null will remove all headers by that name; headers defined on a linked attribute will be combined with headers
+ * defined on the {@link ProtocolConfiguration} for that request.
+ * <p>
+ * NOTE: It is possible to remove a header set by the {@link ProtocolConfiguration} for a specific request by using
+ * a value of null for the header value on the linked attribute.
+ */
+ public static final String META_HEADERS = PROTOCOL_NAME + ":headers";
+
+ /**
+ * Query parameters for the request; values specified on a {@link ProtocolConfiguration} will be appended to all
+ * requests, values specified on linked attributes will be added to those specified on the {@link
+ * ProtocolConfiguration}. {@link ObjectValue} where the keys represent the parameter name and the value represents
+ * the parameter value(s); supports dynamic value insertion on linked {@link Attribute}s, see class javadoc for more
+ * details (value can be a single string or an {@link ArrayValue} of strings).
+ */
+ public static final String META_QUERY_PARAMETERS = PROTOCOL_NAME + ":queryParameters";
+
+ private static final Logger LOG = Logger.getLogger(HttpClientProtocol.class.getName());
+ public static final String PROTOCOL_DISPLAY_NAME = "Http Client";
+ public static final String PROTOCOL_VERSION = "1.0";
+ protected static final String DYNAMIC_VALUE_PLACEHOLDER = "{$value}";
+ protected static final String DYNAMIC_VALUE_PLACEHOLDER_REGEXP = "\"?\\{\\$value}\"?";
+ private static TimeUnit POLLING_TIME_UNIT = TimeUnit.SECONDS; // Only here to allow override in tests
+ public static final int DEFAULT_PING_SECONDS = 60;
+ public static final String DEFAULT_HTTP_METHOD = HttpMethod.GET;
+ public static final String DEFAULT_CONTENT_TYPE = MediaType.TEXT_PLAIN;
+ protected final Map<AttributeRef, Pair<ResteasyWebTarget, List<Integer>>> clientMap = new HashMap<>();
+ protected final Map<AttributeRef, HttpClientRequest> requestMap = new HashMap<>();
+ protected final Map<AttributeRef, ScheduledFuture> pollingMap = new HashMap<>();
+
+ @Override
+ public void init(Container container) throws Exception {
+ super.init(container);
+ WebTargetBuilder.setExecutorService(executorService);
+ }
+
+ @Override
+ public void stop(Container container) throws Exception {
+ super.stop(container);
+ pollingMap.forEach((attributeRef, scheduledFuture) -> scheduledFuture.cancel(true));
+ pollingMap.clear();
+ requestMap.clear();
+ clientMap.clear();
+ WebTargetBuilder.close();
+ }
+
+ @Override
+ protected void doLinkProtocolConfiguration(AssetAttribute protocolConfiguration) {
+ final AttributeRef protocolRef = protocolConfiguration.getReferenceOrThrow();
+
+ if (!protocolConfiguration.isEnabled()) {
+ updateStatus(protocolRef, ConnectionStatus.DISABLED);
+ return;
+ }
+
+ String baseUri = protocolConfiguration.getMetaItem(META_PROTOCOL_BASE_URI)
+ .flatMap(AbstractValueHolder::getValueAsString).orElseThrow(() ->
+ new IllegalArgumentException("Missing or invalid require meta item: " + META_PROTOCOL_BASE_URI));
+
+ /* We're going to fail hard and fast if optional meta items are incorrectly configured */
+
+ Optional<OAuthGrant> oAuthGrant = getOAuthGrant(protocolConfiguration);
+
+ Optional<StringValue> username = Values.getMetaItemValueOrThrow(
+ protocolConfiguration,
+ META_PROTOCOL_USERNAME,
+ StringValue.class,
+ false,
+ true);
+
+ Optional<StringValue> password = Values.getMetaItemValueOrThrow(
+ protocolConfiguration,
+ META_PROTOCOL_PASSWORD,
+ StringValue.class,
+ false,
+ true);
+
+ boolean followRedirects = Values.getMetaItemValueOrThrow(
+ protocolConfiguration,
+ META_PROTOCOL_FOLLOW_REDIRECTS,
+ BooleanValue.class,
+ false,
+ true).map(BooleanValue::getBoolean).orElse(false);
+
+ List<Integer> failureCodes = protocolConfiguration.getMetaItem(META_FAILURE_CODES)
+ .flatMap(AbstractValueHolder::getValueAsArray)
+ .flatMap(arrayValue ->
+ Values.getArrayElements(
+ arrayValue,
+ NumberValue.class,
+ true,
+ false,
+ number -> Values.getIntegerCoerced(number).orElse(null)))
+ .orElse(null);
+
+ Optional<MultivaluedMap<String,String>> headers = Values.getMetaItemValueOrThrow(
+ protocolConfiguration,
+ META_HEADERS,
+ ObjectValue.class,
+ false,
+ true)
+ .flatMap(objectValue -> getMultivaluedMap(objectValue, true));
+
+ Optional<MultivaluedMap<String,String>> queryParams = Values.getMetaItemValueOrThrow(
+ protocolConfiguration,
+ META_QUERY_PARAMETERS,
+ ObjectValue.class,
+ false,
+ true)
+ .flatMap(objectValue -> getMultivaluedMap(objectValue, false));
+
+ String pingPath = Values.getMetaItemValueOrThrow(
+ protocolConfiguration,
+ META_PROTOCOL_PING_PATH,
+ StringValue.class,
+ false,
+ true)
+ .map(StringValue::getString)
+ .orElse(null);
+
+ if ((username.isPresent() && !password.isPresent()) || (!username.isPresent() && password.isPresent())) {
+ throw new IllegalArgumentException("Both username and password must be set for basic authentication");
+ }
+
+ WebTargetBuilder webTargetBuilder = new WebTargetBuilder(baseUri);
+ webTargetBuilder.setOAuthAuthentication(oAuthGrant.orElse(null));
+ //noinspection ConstantConditions
+ username.ifPresent(stringValue ->
+ webTargetBuilder.setBasicAuthentication(stringValue.getString(), password.get().getString()));
+ headers.ifPresent(webTargetBuilder::setInjectHeaders);
+ queryParams.ifPresent(webTargetBuilder::setInjectQueryParameters);
+ webTargetBuilder.followRedirects(followRedirects);
+
+ ResteasyWebTarget client = webTargetBuilder.build();
+ synchronized (clientMap) {
+ clientMap.put(protocolRef, new Pair<>(client, failureCodes));
+ }
+ updateStatus(protocolRef, ConnectionStatus.UNKNOWN);
+
+ if (pingPath == null) {
+ return;
+ }
+
+ String pingMethod = Values.getMetaItemValueOrThrow(
+ protocolConfiguration,
+ META_PROTOCOL_PING_METHOD,
+ StringValue.class,
+ false,
+ true)
+ .map(StringValue::getString)
+ .orElse(DEFAULT_HTTP_METHOD);
+
+ Value pingBody = protocolConfiguration
+ .getMetaItem(META_PROTOCOL_PING_BODY)
+ .flatMap(AbstractValueHolder::getValue)
+ .orElse(null);
+
+ MultivaluedMap<String,String> pingQueryParams = Values.getMetaItemValueOrThrow(
+ protocolConfiguration,
+ META_PROTOCOL_PING_QUERY_PARAMETERS,
+ ObjectValue.class,
+ false,
+ true)
+ .flatMap(objectValue -> getMultivaluedMap(objectValue, false))
+ .orElse(null);
+
+ Integer pingPollingSeconds = Values.getMetaItemValueOrThrow(
+ protocolConfiguration,
+ META_PROTOCOL_PING_SECONDS,
+ NumberValue.class,
+ false,
+ true)
+ .map(polling ->
+ Values.getIntegerCoerced(polling)
+ .map(seconds -> seconds < 1 ? null : seconds)
+ .orElseThrow(() ->
+ new IllegalArgumentException("Ping polling seconds meta item must be an integer >= 1")
+ ))
+ .orElse(DEFAULT_PING_SECONDS);
+
+ String contentType = Values.getMetaItemValueOrThrow(
+ protocolConfiguration,
+ META_PROTOCOL_PING_CONTENT_TYPE,
+ StringValue.class,
+ false,
+ true)
+ .map(StringValue::getString)
+ .orElse(null);
+
+ HttpClientRequest pollingRequest = buildClientRequest(
+ client,
+ pingPath,
+ pingMethod,
+ null,
+ pingQueryParams,
+ null,
+ true,
+ pingBody,
+ contentType);
+
+ synchronized (requestMap) {
+ requestMap.put(protocolRef, pollingRequest);
+ }
+
+ synchronized (pollingMap) {
+ pollingMap.put(protocolRef, schedulePollingRequest(
+ null,
+ protocolRef,
+ pollingRequest,
+ pingPollingSeconds));
+ }
+ }
+
+ @Override
+ protected void doUnlinkProtocolConfiguration(AssetAttribute protocolConfiguration) {
+ AttributeRef protocolConfigurationRef = protocolConfiguration.getReferenceOrThrow();
+ synchronized (clientMap) {
+ clientMap.remove(protocolConfigurationRef);
+ }
+ synchronized (requestMap) {
+ requestMap.remove(protocolConfigurationRef);
+ }
+ cancelPolling(protocolConfigurationRef);
+ }
+
+ @Override
+ protected void doLinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration) {
+ AttributeRef protocolConfigurationRef = protocolConfiguration.getReferenceOrThrow();
+ Pair<ResteasyWebTarget, List<Integer>> clientAndFailureCodes;
+ synchronized (clientMap) {
+ clientAndFailureCodes = clientMap.get(protocolConfigurationRef);
+ }
+ WebTarget client = clientAndFailureCodes != null ? clientAndFailureCodes.key : null;
+
+ if (client == null) {
+ LOG.finer("Attempt to link attribute to non existent protocol configuration: "
+ + attribute.getReferenceOrThrow());
+ return;
+ }
+
+ String method = Values.getMetaItemValueOrThrow(
+ attribute,
+ META_ATTRIBUTE_METHOD,
+ StringValue.class,
+ false,
+ true)
+ .map(StringValue::getString)
+ .orElse(DEFAULT_HTTP_METHOD);
+
+ String path = Values.getMetaItemValueOrThrow(
+ attribute,
+ META_ATTRIBUTE_PATH,
+ StringValue.class,
+ false,
+ true)
+ .map(StringValue::getString)
+ .orElse(null);
+
+ String contentType = Values.getMetaItemValueOrThrow(
+ attribute,
+ META_ATTRIBUTE_CONTENT_TYPE,
+ StringValue.class,
+ false,
+ true)
+ .map(StringValue::getString)
+ .orElse(null);
+
+ Value body = attribute
+ .getMetaItem(META_ATTRIBUTE_BODY)
+ .flatMap(AbstractValueHolder::getValue)
+ .orElse(null);
+
+ List<Integer> failureCodes = attribute.getMetaItem(META_FAILURE_CODES)
+ .flatMap(AbstractValueHolder::getValueAsArray)
+ .flatMap(arrayValue ->
+ Values.getArrayElements(
+ arrayValue,
+ NumberValue.class,
+ true,
+ false,
+ number -> Values.getIntegerCoerced(number).orElse(null)))
+ .map(fCodes -> {
+ if (clientAndFailureCodes.value != null) {
+ fCodes.addAll(clientAndFailureCodes.value);
+ }
+ return fCodes;
+ })
+ .orElseGet(() -> {
+ if (clientAndFailureCodes.value != null) {
+ return clientAndFailureCodes.value;
+ }
+ return null;
+ });
+
+ MultivaluedMap<String,String> headers = Values.getMetaItemValueOrThrow(
+ attribute,
+ META_HEADERS,
+ ObjectValue.class,
+ false,
+ true)
+ .flatMap(objectValue -> getMultivaluedMap(objectValue, true))
+ .orElse(null);
+
+ MultivaluedMap<String,String> queryParams = Values.getMetaItemValueOrThrow(
+ attribute,
+ META_QUERY_PARAMETERS,
+ ObjectValue.class,
+ false,
+ true)
+ .flatMap(objectValue -> getMultivaluedMap(objectValue, false))
+ .orElse(null);
+
+ Optional<Integer> pollingSeconds = Values.getMetaItemValueOrThrow(
+ attribute,
+ META_ATTRIBUTE_POLLING_SECONDS,
+ NumberValue.class,
+ false,
+ true)
+ .map(polling ->
+ Values.getIntegerCoerced(polling)
+ .map(seconds -> seconds < 1 ? null : seconds)
+ .orElseThrow(() ->
+ new IllegalArgumentException("Polling seconds meta item must be an integer >= 1")
+ ));
+
+
+ final AttributeRef attributeRef = attribute.getReferenceOrThrow();
+
+ synchronized (pollingMap) {
+ boolean updateConnectionStatus = !pollingMap.containsKey(protocolConfigurationRef);
+
+ HttpClientRequest clientRequest = buildClientRequest(
+ client,
+ path,
+ method,
+ headers,
+ queryParams,
+ failureCodes,
+ updateConnectionStatus,
+ body,
+ contentType);
+
+ synchronized (requestMap) {
+ requestMap.put(attributeRef, clientRequest);
+ }
+
+ pollingSeconds.ifPresent(seconds ->
+ pollingMap.put(attributeRef, schedulePollingRequest(
+ attributeRef,
+ protocolConfigurationRef,
+ clientRequest,
+ seconds)));
+ }
+ }
+
+ @Override
+ protected void doUnlinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration) {
+ AttributeRef attributeRef = attribute.getReferenceOrThrow();
+ synchronized (requestMap) {
+ requestMap.remove(attributeRef);
+ }
+ cancelPolling(attributeRef);
+ }
+
+ @Override
+ protected void processLinkedAttributeWrite(AttributeEvent event, AssetAttribute protocolConfiguration) {
+ AttributeRef protocolRef = protocolConfiguration.getReferenceOrThrow();
+ HttpClientRequest request;
+ Pair<ResteasyWebTarget, List<Integer>> clientAndFailureCodes;
+
+ synchronized (requestMap) {
+ request = requestMap.get(event.getAttributeRef());
+ }
+ synchronized (clientMap) {
+ clientAndFailureCodes = clientMap.get(protocolRef);
+ }
+
+ // If permanent failure code occurred then protocol configuration could be about to be unlinked (disabled)
+ // so the check here catches time between marked as disabled and actually being unlinked
+ if (request != null && clientAndFailureCodes != null) {
+
+ executeAttributeWriteRequest(request,
+ event.getValue().orElse(null),
+ response ->
+ onAttributeWriteResponse(
+ request,
+ response,
+ protocolRef
+ ));
+ } else {
+ LOG.finest("Ignoring attribute write request as either attribute or protocol configuration is not linked: " + event);
+ }
+ }
+
+ @Override
+ public String getProtocolName() {
+ return PROTOCOL_NAME;
+ }
+
+ @Override
+ public String getProtocolDisplayName() {
+ return PROTOCOL_DISPLAY_NAME;
+ }
+
+ @Override
+ public String getVersion() {
+ return PROTOCOL_VERSION;
+ }
+
+ public static Optional<OAuthGrant> getOAuthGrant(AssetAttribute attribute) throws IllegalArgumentException {
+ return !attribute.hasMetaItem(META_PROTOCOL_OAUTH_GRANT)
+ ? Optional.empty()
+ : Optional.of(attribute.getMetaItem(META_PROTOCOL_OAUTH_GRANT)
+ .flatMap(AbstractValueHolder::getValueAsObject)
+ .map(objValue -> {
+ String json = objValue.toJson();
+ try {
+ return Container.JSON.readValue(json, OAuthGrant.class);
+ } catch (IOException e) {
+ throw new IllegalArgumentException("OAuth Grant meta item is not valid", e);
+ }
+ })
+ .orElseThrow(() -> new IllegalArgumentException("OAuth grant meta item must be an ObjectValue")));
+ }
+
+ public static Optional<MultivaluedMap<String, String>> getMultivaluedMap(ObjectValue objectValue, boolean throwOnError) throws ClassCastException, IllegalArgumentException {
+ if (objectValue == null) {
+ return Optional.empty();
+ }
+
+ MultivaluedMap<String, String> multivaluedMap = new MultivaluedHashMap<>();
+ objectValue.stream()
+ .forEach((keyAndValue) -> {
+ if (keyAndValue.value != null) {
+ switch (keyAndValue.value.getType()) {
+
+ case OBJECT:
+ if (throwOnError) {
+ throw new IllegalArgumentException("Key '" + keyAndValue.key + "' is of unsupported type: ObjectValue");
+ }
+ break;
+ case ARRAY:
+ Values.getArrayElements(((ArrayValue)keyAndValue.value),
+ StringValue.class,
+ throwOnError,
+ false,
+ StringValue::getString)
+ .ifPresent(strs -> multivaluedMap.addAll(keyAndValue.key, strs));
+ break;
+ case STRING:
+ case NUMBER:
+ case BOOLEAN:
+ multivaluedMap.add(keyAndValue.key, keyAndValue.value.toString());
+ break;
+ }
+ } else {
+ multivaluedMap.add(keyAndValue.key, null);
+ }
+ });
+
+ return multivaluedMap.isEmpty() ? Optional.empty() : Optional.of(multivaluedMap);
+ }
+
+ protected HttpClientRequest buildClientRequest(WebTarget client, String path, String method, MultivaluedMap<String, String> headers, MultivaluedMap<String, String> queryParams, List<Integer> failureCodes, boolean updateConnectionStatus, Value body, String contentType) {
+ return new HttpClientRequest(
+ client,
+ path,
+ method,
+ headers,
+ queryParams,
+ failureCodes,
+ updateConnectionStatus,
+ body,
+ contentType);
+ }
+
+ protected ScheduledFuture schedulePollingRequest(AttributeRef attributeRef,
+ AttributeRef protocolConfigurationRef,
+ HttpClientRequest clientRequest,
+ int pollingSeconds) {
+ return executorService.scheduleWithFixedDelay(() ->
+ executePollingRequest(clientRequest, response ->
+ onPollingResponse(
+ clientRequest,
+ response,
+ attributeRef,
+ protocolConfigurationRef)
+ ), 0, pollingSeconds, POLLING_TIME_UNIT);
+ }
+
+ protected void executePollingRequest(HttpClientRequest clientRequest, Consumer<Response> responseConsumer) {
+ Response response = null;
+
+ try {
+ response = clientRequest.invoke(null);
+ } catch (Exception e) {
+ LOG.log(Level.SEVERE, "Exception thrown whilst doing polling request", e);
+ }
+
+ responseConsumer.accept(response);
+ }
+
+ protected void executeAttributeWriteRequest(HttpClientRequest clientRequest,
+ Value attributeValue,
+ Consumer<Response> responseConsumer) {
+ String valueStr = attributeValue == null ? null : attributeValue.toString();
+ Response response = null;
+
+ try {
+ response = clientRequest.invoke(valueStr);
+ } catch (Exception e) {
+ LOG.log(Level.SEVERE, "Exception thrown whilst doing attribute write request", e);
+ }
+
+ responseConsumer.accept(response);
+ }
+
+ protected void onPollingResponse(HttpClientRequest request,
+ Response response,
+ AttributeRef attributeRef,
+ AttributeRef protocolConfigurationRef) {
+
+ int responseCode = response != null ? response.getStatus() : 500;
+
+ if (request.updateConnectionStatus) {
+ updateConnectionStatus(protocolConfigurationRef, responseCode);
+ }
+
+ Value value = null;
+
+ if (response != null && response.getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL) {
+ try {
+ value = response.getEntity() != null ? Values.create(response.readEntity(String.class)) : null;
+ } catch (Exception e) {
+ LOG.log(Level.SEVERE, "Error occurred whilst trying to read response body", e);
+ if (request.updateConnectionStatus) {
+ updateConnectionStatus(protocolConfigurationRef, 500);
+ }
+ }
+ } else if (isPermanentFailure(responseCode, request.failureCodes)) {
+ doPermanentFailure(protocolConfigurationRef);
+ cancelPolling(attributeRef != null ? attributeRef : protocolConfigurationRef);
+ return;
+ }
+
+ if (attributeRef != null) {
+ updateLinkedAttribute(new AttributeState(attributeRef, value));
+ }
+ }
+
+ protected void onAttributeWriteResponse(HttpClientRequest request,
+ Response response,
+ AttributeRef protocolConfigurationRef) {
+
+ int responseCode = response != null ? response.getStatus() : 500;
+
+ if (request.updateConnectionStatus) {
+ updateConnectionStatus(protocolConfigurationRef, responseCode);
+ }
+
+ if (isPermanentFailure(responseCode, request.failureCodes)) {
+ doPermanentFailure(protocolConfigurationRef);
+ }
+ }
+
+ protected void cancelPolling(AttributeRef attributeRef) {
+ synchronized (pollingMap) {
+ ScheduledFuture pingPoll = pollingMap.remove(attributeRef);
+ if (pingPoll != null) {
+ pingPoll.cancel(false);
+ }
+ }
+ }
+
+ protected void updateConnectionStatus(AttributeRef protocolConfigurationRef, int responseCode) {
+ Response.Status status = Response.Status.fromStatusCode(responseCode);
+ ConnectionStatus connectionStatus = ConnectionStatus.CONNECTED;
+ if (status == null) {
+ connectionStatus = ConnectionStatus.UNKNOWN;
+ } else {
+ switch (status.getFamily()) {
+ case INFORMATIONAL:
+ connectionStatus = ConnectionStatus.ERROR;
+ break;
+ case SUCCESSFUL:
+ connectionStatus = ConnectionStatus.CONNECTED;
+ break;
+ case REDIRECTION:
+ connectionStatus = ConnectionStatus.ERROR;
+ break;
+ case CLIENT_ERROR:
+ if (responseCode == 401 || responseCode == 402 || responseCode == 403) {
+ connectionStatus = ConnectionStatus.ERROR_AUTHENTICATION;
+ } else {
+ connectionStatus = ConnectionStatus.ERROR_CONFIGURATION;
+ }
+ break;
+ case SERVER_ERROR:
+ connectionStatus = ConnectionStatus.ERROR;
+ break;
+ case OTHER:
+ break;
+ }
+ }
+
+ updateStatus(protocolConfigurationRef, connectionStatus);
+ }
+
+ protected boolean isPermanentFailure(int responseCode, List<Integer> failureCodes) {
+ return failureCodes != null && failureCodes.contains(responseCode);
+ }
+
+ protected void doPermanentFailure(AttributeRef protocolConfigurationRef) {
+ LOG.info("Permanent failure triggered for protocol configuration: " + protocolConfigurationRef);
+ LinkedProtocolInfo protocolInfo = linkedProtocolConfigurations.get(protocolConfigurationRef);
+
+ if (protocolInfo == null) {
+ LOG.warning("Attempt to mark unlinked protocol configuration as failed");
+ return;
+ }
+
+ LOG.fine("Updating protocol configuration enabled status to false");
+ updateLinkedProtocolConfiguration(
+ protocolInfo.getProtocolConfiguration(),
+ protocolConfig -> protocolConfig.setDisabled(true)
+ );
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/http/OAuthClientCredentialsGrant.java b/agent/src/main/java/org/openremote/agent/protocol/http/OAuthClientCredentialsGrant.java
new file mode 100644
index 000000000..124e757a7
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/http/OAuthClientCredentialsGrant.java
@@ -0,0 +1,45 @@
+/*
+ * 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.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonTypeName;
+
+@JsonTypeName(OAuthClientCredentialsGrant.CLIENT_CREDENTIALS_GRANT_TYPE)
+public class OAuthClientCredentialsGrant extends OAuthGrant {
+ public static final String CLIENT_CREDENTIALS_GRANT_TYPE = "client_credentials";
+
+ @JsonCreator
+ public OAuthClientCredentialsGrant(@JsonProperty("tokenEndpointUri") String tokenEndpointUri,
+ @JsonProperty(VALUE_KEY_CLIENT_ID) String clientId,
+ @JsonProperty(VALUE_KEY_CLIENT_SECRET) String clientSecret,
+ @JsonProperty(VALUE_KEY_SCOPE) String scope) {
+ this(tokenEndpointUri, CLIENT_CREDENTIALS_GRANT_TYPE, clientId, clientSecret, scope);
+ }
+
+ protected OAuthClientCredentialsGrant(String tokenEndpointUri,
+ String grantType,
+ String clientId,
+ String clientSecret,
+ String scope) {
+ super(tokenEndpointUri, grantType, clientId, clientSecret, scope);
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/http/OAuthFilter.java b/agent/src/main/java/org/openremote/agent/protocol/http/OAuthFilter.java
new file mode 100644
index 000000000..9a8c4ed46
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/http/OAuthFilter.java
@@ -0,0 +1,126 @@
+/*
+ * 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 org.openremote.model.syslog.SyslogCategory;
+
+import javax.ws.rs.client.ClientRequestContext;
+import javax.ws.rs.client.ClientRequestFilter;
+import javax.ws.rs.client.Entity;
+import javax.ws.rs.client.WebTarget;
+import javax.ws.rs.core.Form;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.io.IOException;
+import java.time.LocalDateTime;
+import java.util.Objects;
+import java.util.logging.Logger;
+
+import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
+
+/**
+ * A filter to support OAuth access token (including refresh)
+ */
+public class OAuthFilter implements ClientRequestFilter {
+
+ private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, OAuthFilter.class);
+ public static final String AUTH_TYPE = "Bearer";
+ protected OAuthServerResponse authServerResponse;
+ protected WebTarget authTarget;
+ protected OAuthGrant oAuthGrant;
+
+ public OAuthFilter(WebTarget authTarget, OAuthGrant oAuthGrant) {
+ Objects.requireNonNull(authTarget);
+ Objects.requireNonNull(oAuthGrant);
+ this.authTarget = authTarget;
+ this.oAuthGrant = oAuthGrant;
+ }
+
+ public String getAuthHeader() {
+ return AUTH_TYPE + " " + getAccessToken();
+ }
+
+ protected synchronized String getAccessToken() {
+ LocalDateTime expiryDateTime = authServerResponse == null ? null : authServerResponse.getExpiryDateTime();
+ boolean updateRequired = expiryDateTime == null || expiryDateTime.minusSeconds(10).isBefore(LocalDateTime.now());
+
+ if (updateRequired) {
+ updateToken();
+ }
+
+ return authServerResponse != null ? authServerResponse.accessToken : null;
+ }
+
+ protected synchronized void updateToken() {
+ LOG.info("Updating OAuth token");
+ Response response;
+
+ if (authServerResponse != null && authServerResponse.refreshToken != null) {
+ // Do a refresh
+ LOG.fine("Using Refresh grant");
+ response = requestTokenUsingRefresh();
+ if (response.getStatus() == 403) {
+ // Maybe the refresh token is not valid so do full auth
+ LOG.warning("OAuth token refresh failed, trying a full authentication");
+ authServerResponse = null;
+ updateToken();
+ return;
+ }
+ } else {
+ // Do full auth
+ LOG.fine("Doing full authentication");
+ response = requestToken();
+ }
+
+ if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
+ authServerResponse = null;
+ LOG.warning("OAuth server response error: " + response.getStatus());
+ } else {
+ authServerResponse = response.readEntity(OAuthServerResponse.class);
+ LOG.finest("OAuth server successfully returned an access token");
+ }
+ }
+
+ protected Response requestTokenUsingRefresh() {
+ OAuthRefreshTokenGrant refreshGrant = new OAuthRefreshTokenGrant(
+ oAuthGrant.getTokenEndpointUri(),
+ oAuthGrant.getClientId(),
+ oAuthGrant.getClientSecret(),
+ oAuthGrant.getScope(),
+ authServerResponse.refreshToken
+ );
+
+ return authTarget
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .post(Entity.entity(new Form(refreshGrant.valueMap), MediaType.APPLICATION_FORM_URLENCODED_TYPE));
+ }
+
+ protected Response requestToken() {
+ return authTarget
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .post(Entity.entity(new Form(oAuthGrant.valueMap), MediaType.APPLICATION_FORM_URLENCODED_TYPE));
+ }
+
+ @Override
+ public void filter(ClientRequestContext requestContext) throws IOException {
+ requestContext.getHeaders().putSingle(HttpHeaders.AUTHORIZATION, getAuthHeader());
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/http/OAuthGrant.java b/agent/src/main/java/org/openremote/agent/protocol/http/OAuthGrant.java
new file mode 100644
index 000000000..1a9fc8a1b
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/http/OAuthGrant.java
@@ -0,0 +1,88 @@
+/*
+ * 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.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonSubTypes;
+import com.fasterxml.jackson.annotation.JsonTypeInfo;
+
+import javax.ws.rs.core.MultivaluedHashMap;
+import javax.ws.rs.core.MultivaluedMap;
+
+import static org.openremote.model.util.TextUtil.requireNonNullAndNonEmpty;
+
+@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.EXISTING_PROPERTY, property = OAuthGrant.VALUE_KEY_GRANT_TYPE)
+@JsonSubTypes({
+ @JsonSubTypes.Type(name=OAuthPasswordGrant.PASSWORD_GRANT_TYPE, value=OAuthPasswordGrant.class),
+ @JsonSubTypes.Type(name=OAuthClientCredentialsGrant.CLIENT_CREDENTIALS_GRANT_TYPE, value=OAuthClientCredentialsGrant.class),
+ @JsonSubTypes.Type(name=OAuthRefreshTokenGrant.VALUE_KEY_REFRESH_TOKEN, value=OAuthRefreshTokenGrant.class),
+})
+public abstract class OAuthGrant {
+
+ public static final String VALUE_KEY_GRANT_TYPE = "grant_type";
+ public static final String VALUE_KEY_CLIENT_ID = "client_id";
+ public static final String VALUE_KEY_CLIENT_SECRET = "client_secret";
+ public static final String VALUE_KEY_SCOPE = "scope";
+ @JsonIgnore
+ protected MultivaluedMap<String, String> valueMap = new MultivaluedHashMap<>(6);
+ protected String tokenEndpointUri;
+
+ protected OAuthGrant(String tokenEndpointUri, String grantType, String clientId, String clientSecret, String scope) {
+ requireNonNullAndNonEmpty(tokenEndpointUri);
+ requireNonNullAndNonEmpty(grantType);
+ requireNonNullAndNonEmpty(clientId);
+ requireNonNullAndNonEmpty(clientSecret);
+ this.tokenEndpointUri = tokenEndpointUri;
+ valueMap.add(VALUE_KEY_GRANT_TYPE, grantType);
+ valueMap.add(VALUE_KEY_CLIENT_ID, clientId);
+ valueMap.add(VALUE_KEY_CLIENT_SECRET, clientSecret);
+ valueMap.add(VALUE_KEY_SCOPE, scope);
+ }
+
+ public MultivaluedMap<String, String> getValueMap() {
+ return valueMap;
+ }
+
+ @JsonProperty
+ public String getTokenEndpointUri() {
+ return tokenEndpointUri;
+ }
+
+ @JsonProperty(VALUE_KEY_GRANT_TYPE)
+ public String getGrantType() {
+ return valueMap.getFirst(VALUE_KEY_GRANT_TYPE);
+ }
+
+ @JsonProperty(VALUE_KEY_CLIENT_ID)
+ public String getClientId() {
+ return valueMap.getFirst(VALUE_KEY_CLIENT_ID);
+ }
+
+ @JsonProperty(VALUE_KEY_CLIENT_SECRET)
+ public String getClientSecret() {
+ return valueMap.getFirst(VALUE_KEY_CLIENT_SECRET);
+ }
+
+ @JsonProperty(VALUE_KEY_SCOPE)
+ public String getScope() {
+ return valueMap.getFirst(VALUE_KEY_SCOPE);
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/http/OAuthPasswordGrant.java b/agent/src/main/java/org/openremote/agent/protocol/http/OAuthPasswordGrant.java
new file mode 100644
index 000000000..0193cb1eb
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/http/OAuthPasswordGrant.java
@@ -0,0 +1,65 @@
+/*
+ * 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.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonTypeName;
+
+@JsonTypeName(OAuthPasswordGrant.PASSWORD_GRANT_TYPE)
+public class OAuthPasswordGrant extends OAuthClientCredentialsGrant {
+
+ public static final String VALUE_KEY_USERNAME = "username";
+ public static final String VALUE_KEY_PASSWORD = "password";
+ public static final String PASSWORD_GRANT_TYPE = "password";
+
+ @JsonCreator
+ public OAuthPasswordGrant(@JsonProperty("tokenEndpointUri") String tokenEndpointUri,
+ @JsonProperty(VALUE_KEY_CLIENT_ID) String clientId,
+ @JsonProperty(VALUE_KEY_CLIENT_SECRET) String clientSecret,
+ @JsonProperty(VALUE_KEY_SCOPE) String scope,
+ @JsonProperty(VALUE_KEY_USERNAME) String username,
+ @JsonProperty(VALUE_KEY_PASSWORD) String password) {
+ this(tokenEndpointUri, PASSWORD_GRANT_TYPE, clientId, clientSecret, scope, username, password);
+ }
+
+ protected OAuthPasswordGrant(String tokenEndpointUri,
+ String grantType,
+ String clientId,
+ String clientSecret,
+ String scope,
+ String username,
+ String password
+ ) {
+ super(tokenEndpointUri, grantType, clientId, clientSecret, scope);
+ valueMap.add(VALUE_KEY_USERNAME, username);
+ valueMap.add(VALUE_KEY_PASSWORD, password);
+ }
+
+ @JsonProperty
+ public String getUsername() {
+ return valueMap.getFirst(VALUE_KEY_USERNAME);
+ }
+
+ @JsonProperty
+ public String getPassword() {
+ return valueMap.getFirst(VALUE_KEY_PASSWORD);
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/http/OAuthRefreshTokenGrant.java b/agent/src/main/java/org/openremote/agent/protocol/http/OAuthRefreshTokenGrant.java
new file mode 100644
index 000000000..c2b0cf5d6
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/http/OAuthRefreshTokenGrant.java
@@ -0,0 +1,55 @@
+/*
+ * 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.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonTypeName;
+
+@JsonTypeName(OAuthRefreshTokenGrant.REFRESH_TOKEN_GRANT_TYPE)
+public class OAuthRefreshTokenGrant extends OAuthClientCredentialsGrant {
+
+ public static final String REFRESH_TOKEN_GRANT_TYPE = "refresh_token";
+ public static final String VALUE_KEY_REFRESH_TOKEN = "refresh_token";
+
+ @JsonCreator
+ public OAuthRefreshTokenGrant(@JsonProperty("tokenEndpointUri") String tokenEndpointUri,
+ @JsonProperty(VALUE_KEY_CLIENT_ID) String clientId,
+ @JsonProperty(VALUE_KEY_CLIENT_SECRET) String clientSecret,
+ @JsonProperty(VALUE_KEY_SCOPE) String scope,
+ @JsonProperty(VALUE_KEY_REFRESH_TOKEN) String refreshToken) {
+ this(tokenEndpointUri, REFRESH_TOKEN_GRANT_TYPE, clientId, clientSecret, scope, refreshToken);
+ }
+
+ protected OAuthRefreshTokenGrant(String tokenEndpointUri,
+ String grantType,
+ String clientId,
+ String clientSecret,
+ String scope,
+ String refreshToken) {
+ super(tokenEndpointUri, grantType, clientId, clientSecret, scope);
+ valueMap.add(VALUE_KEY_REFRESH_TOKEN, refreshToken);
+ }
+
+ @JsonProperty
+ public String getRefreshToken() {
+ return valueMap.getFirst(VALUE_KEY_REFRESH_TOKEN);
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/http/OAuthServerResponse.java b/agent/src/main/java/org/openremote/agent/protocol/http/OAuthServerResponse.java
new file mode 100644
index 000000000..ea1d53513
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/http/OAuthServerResponse.java
@@ -0,0 +1,75 @@
+/*
+ * 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.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+import java.time.LocalDateTime;
+
+public class OAuthServerResponse {
+
+ @JsonProperty("token_type")
+ protected String tokenType;
+ @JsonProperty("expires_in")
+ protected long expiresIn;
+ @JsonProperty("access_token")
+ protected String accessToken;
+ @JsonProperty("refresh_token")
+ protected String refreshToken;
+ @JsonIgnore
+ protected LocalDateTime createdDateTime = LocalDateTime.now();
+
+ public String getTokenType() {
+ return tokenType;
+ }
+
+ public void setTokenType(String tokenType) {
+ this.tokenType = tokenType;
+ }
+
+ public long getExpiresIn() {
+ return expiresIn;
+ }
+
+ public void setExpiresIn(long expiresIn) {
+ this.expiresIn = expiresIn;
+ }
+
+ public String getAccessToken() {
+ return accessToken;
+ }
+
+ public void setAccessToken(String accessToken) {
+ this.accessToken = accessToken;
+ }
+
+ public String getRefreshToken() {
+ return refreshToken;
+ }
+
+ public void setRefreshToken(String refreshToken) {
+ this.refreshToken = refreshToken;
+ }
+
+ public LocalDateTime getExpiryDateTime() {
+ return createdDateTime.plusSeconds(expiresIn);
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/http/PermanentFailureFilter.java b/agent/src/main/java/org/openremote/agent/protocol/http/PermanentFailureFilter.java
new file mode 100644
index 000000000..7c2a5f4d9
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/http/PermanentFailureFilter.java
@@ -0,0 +1,69 @@
+/*
+ * 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 org.openremote.model.syslog.SyslogCategory;
+
+import javax.ws.rs.client.ClientRequestContext;
+import javax.ws.rs.client.ClientRequestFilter;
+import javax.ws.rs.client.ClientResponseContext;
+import javax.ws.rs.client.ClientResponseFilter;
+import javax.ws.rs.core.Response;
+import java.io.IOException;
+import java.util.List;
+import java.util.logging.Logger;
+
+import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
+
+/**
+ * A filter that once a HTTP status code is received that matches any in the {@link #failureResponses} will result
+ * in all future requests being blocked (i.e. the request will not reach the server) and instead a
+ * {@link Response.Status#METHOD_NOT_ALLOWED} status will be returned.
+ */
+public class PermanentFailureFilter implements ClientRequestFilter, ClientResponseFilter {
+
+ private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, PermanentFailureFilter.class);
+ protected boolean failed;
+ protected List<Integer> failureResponses;
+
+ public PermanentFailureFilter(List<Integer> failureResponses) {
+ this.failureResponses = failureResponses;
+ }
+
+ @Override
+ public void filter(ClientRequestContext requestContext) throws IOException {
+ if (failed) {
+ requestContext.abortWith(Response.status(Response.Status.METHOD_NOT_ALLOWED).build());
+ }
+ }
+
+ @Override
+ public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
+
+ if (failureResponses == null) {
+ return;
+ }
+
+ if (failureResponses.contains(responseContext.getStatus())) {
+ LOG.warning("Server returned a response code that is set as permanent failure so future requests will be blocked: " + responseContext.getStatus());
+ failed = true;
+ }
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/http/QueryParameterInjectorFilter.java b/agent/src/main/java/org/openremote/agent/protocol/http/QueryParameterInjectorFilter.java
new file mode 100644
index 000000000..01a946f77
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/http/QueryParameterInjectorFilter.java
@@ -0,0 +1,86 @@
+/*
+ * 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 javax.ws.rs.client.ClientRequestContext;
+import javax.ws.rs.client.ClientRequestFilter;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.UriBuilder;
+import java.io.IOException;
+
+/**
+ * A filter for injecting query parameters into the request URI. If {@link #dynamicPlaceholderRegex} is set any request
+ * passing through this filter will be checked for a property called {@link #DYNAMIC_VALUE} if set then any occurrence
+ * of {@link #dynamicPlaceholderRegex} in the query parameter values will be replaced with the dynamic property value.
+ */
+public class QueryParameterInjectorFilter implements ClientRequestFilter {
+
+ /**
+ * Set a property on the request using this name to inject dynamic string values into
+ */
+ public static final String DYNAMIC_VALUE = QueryParameterInjectorFilter.class.getName() + ".dynamicValue";
+ protected MultivaluedMap<String, String> queryParameters;
+ protected String dynamicPlaceholderRegex;
+ protected boolean dynamic;
+
+ public QueryParameterInjectorFilter(MultivaluedMap<String, String> queryParameters,
+ String dynamicPlaceholderRegex) {
+ this.queryParameters = queryParameters;
+ this.dynamicPlaceholderRegex = dynamicPlaceholderRegex;
+
+ dynamic = queryParameters != null && dynamicPlaceholderRegex != null
+ && queryParameters
+ .entrySet()
+ .stream()
+ .anyMatch(paramNameAndValues ->
+ paramNameAndValues.getValue() != null
+ && paramNameAndValues.getValue()
+ .stream()
+ .anyMatch(val -> val.matches(dynamicPlaceholderRegex)));
+ }
+
+ @Override
+ public void filter(ClientRequestContext requestContext) throws IOException {
+ if (queryParameters != null) {
+ boolean dynamic = this.dynamic;
+ String dynamicValue = null;
+
+ if (dynamic) {
+ dynamicValue = (String) requestContext.getProperty(DYNAMIC_VALUE);
+ dynamic = dynamicValue != null;
+ }
+
+ UriBuilder uriBuilder = UriBuilder.fromUri(requestContext.getUri());
+ boolean finalDynamic = dynamic;
+ String finalDynamicValue = dynamicValue;
+
+ queryParameters.forEach((name, values) -> {
+ String[] valueArr = values.toArray(new String[values.size()]);
+ if (finalDynamic) {
+ for (int i = 0; i < valueArr.length; i++) {
+ valueArr[i] = valueArr[i].replaceAll(dynamicPlaceholderRegex, finalDynamicValue);
+ }
+ }
+ uriBuilder.queryParam(name, valueArr);
+ });
+ requestContext.setUri(uriBuilder.build());
+ }
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/http/WebTargetBuilder.java b/agent/src/main/java/org/openremote/agent/protocol/http/WebTargetBuilder.java
new file mode 100644
index 000000000..da8e91e4c
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/http/WebTargetBuilder.java
@@ -0,0 +1,222 @@
+/*
+ * 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 org.jboss.resteasy.client.jaxrs.BasicAuthentication;
+import org.jboss.resteasy.client.jaxrs.ResteasyClient;
+import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
+import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
+import org.jboss.resteasy.specimpl.ResteasyUriBuilder;
+import org.openremote.container.json.JacksonConfig;
+
+import javax.ws.rs.Priorities;
+import javax.ws.rs.client.WebTarget;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriBuilder;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+
+/**
+ * This is a factory for creating JAX-RS {@link javax.ws.rs.client.WebTarget} instances. The instances share a common
+ * {@link javax.ws.rs.client.Client} that uses a connection pool and has the following
+ * {@link javax.ws.rs.ext.ContextResolver}s registered (additional filters etc. should be registered on the
+ * {@link WebTargetBuilder} instances):
+ * <ul>
+ * <li>{@link org.openremote.container.json.JacksonConfig}.</li>
+ * </ul>
+ */
+// TODO: This should probably be amalgamated with WebClient somehow to provide a unified JAX-RS Client API
+public class WebTargetBuilder {
+
+ public static final int CONNECTION_POOL_SIZE = 200;
+ public static final long CONNECTION_CHECKOUT_TIMEOUT_MILLISECONDS = 5000;
+ public static final long CONNECTION_TIMEOUT_MILLISECONDS = 10000;
+ protected static ResteasyClient client;
+ protected static ExecutorService asyncExecutorService;
+ protected BasicAuthentication basicAuthentication;
+ protected OAuthGrant oAuthGrant;
+ protected UriBuilder uri;
+ protected List<Integer> failureResponses = new ArrayList<>();
+ protected MultivaluedMap<String, String> injectHeaders;
+ protected MultivaluedMap<String, String> injectQueryParameters;
+ protected boolean followRedirects = false;
+
+ public WebTargetBuilder(String uri) {
+ this(ResteasyUriBuilder.fromUri(uri));
+ }
+
+ public WebTargetBuilder(URI uri) {
+ this(ResteasyUriBuilder.fromUri(uri));
+ }
+
+ public WebTargetBuilder(UriBuilder uri) {
+ if (client == null) {
+ initClient();
+ }
+ this.uri = uri;
+ }
+
+ /**
+ * Set the executor service to be used for async operations (if none is supplied then one will be created
+ * automatically), this allows fine grained thread management at the application level.
+ */
+ public static void setExecutorService(ExecutorService executorService) {
+ if (client != null) {
+ throw new IllegalStateException("Executor service must be set before any call to create");
+ }
+
+ asyncExecutorService = executorService;
+ }
+
+ /**
+ * Add Basic authentication to requests sent by this {@link WebTarget}; this should not be used in conjunction with
+ * any other authentication.
+ */
+ public WebTargetBuilder setBasicAuthentication(String username, String password) {
+ this.basicAuthentication = new BasicAuthentication(username, password);
+ return this;
+ }
+
+ /**
+ * Add OAuth authentication to requests sent by this {@link WebTarget}; this should not be used in conjunction with
+ * any other authentication (note if basic authentication is also set then this OAuth authentication will take
+ * precedence).
+ */
+ public WebTargetBuilder setOAuthAuthentication(OAuthGrant oAuthGrant) {
+ this.oAuthGrant = oAuthGrant;
+ return this;
+ }
+
+
+ public WebTargetBuilder setInjectHeaders(MultivaluedMap<String, String> injectHeaders) {
+ this.injectHeaders = injectHeaders;
+ return this;
+ }
+
+ public WebTargetBuilder setInjectQueryParameters(MultivaluedMap<String ,String> injectQueryParameters) {
+ this.injectQueryParameters = injectQueryParameters;
+ return this;
+ }
+
+ /**
+ * If the specified status code is returned from the server then it will be treated as a permanent failure
+ * and the web authTarget will no longer be usable (any future requests will immediately return a
+ * {@link Response.Status#METHOD_NOT_ALLOWED} response without hitting the server.
+ * <p>
+ * <b>NOTE: Any response in 200 range will always be treated as successful.</b>
+ */
+ public WebTargetBuilder addPermanentFailureResponse(Response.Status...responseStatus) {
+ Collections.addAll(
+ failureResponses,
+ Arrays.stream(responseStatus)
+ .map(Response.Status::getStatusCode)
+ .toArray(Integer[]::new)
+ );
+ return this;
+ }
+ public WebTargetBuilder addPermanentFailureResponse(Integer...responseStatus) {
+ Collections.addAll(failureResponses, responseStatus);
+ return this;
+ }
+
+ public WebTargetBuilder removePermanentFailureResponse(Response.Status...responseStatus) {
+ failureResponses.removeAll(
+ Arrays.stream(responseStatus)
+ .map(Response.Status::getStatusCode)
+ .collect(Collectors.toList())
+ );
+ return this;
+ }
+
+ public WebTargetBuilder removePermanentFailureResponse(Integer...responseStatus) {
+ failureResponses.removeAll(Arrays.asList(responseStatus));
+ return this;
+ }
+
+ public WebTargetBuilder followRedirects(boolean followRedirects) {
+ this.followRedirects = followRedirects;
+ return this;
+ }
+
+ public ResteasyWebTarget build() {
+ ResteasyWebTarget target = client.target(uri);
+
+ if (!failureResponses.isEmpty()) {
+ // Put a filter with max priority in the filter chain
+ target.register(new PermanentFailureFilter(failureResponses), 1);
+ }
+
+ if (oAuthGrant != null) {
+ WebTarget authTarget = client.target(oAuthGrant.tokenEndpointUri);
+ OAuthFilter oAuthFilter = new OAuthFilter(authTarget, oAuthGrant);
+ target.register(oAuthFilter, Priorities.AUTHENTICATION);
+ } else if (basicAuthentication != null) {
+ target.register(basicAuthentication, Priorities.AUTHENTICATION);
+ }
+
+ if (injectHeaders != null) {
+ target.register(new HeaderInjectorFilter(injectHeaders));
+ }
+
+ if (injectQueryParameters != null) {
+ target.register(new QueryParameterInjectorFilter(injectQueryParameters, null));
+ }
+
+ if (followRedirects) {
+ target.register(new FollowRedirectFilter());
+ }
+
+ return target;
+ }
+
+ protected static void initClient() {
+ if (client != null) {
+ return;
+ }
+ ResteasyClientBuilder clientBuilder = new ResteasyClientBuilder()
+ .connectionPoolSize(CONNECTION_POOL_SIZE)
+ .connectionCheckoutTimeout(CONNECTION_CHECKOUT_TIMEOUT_MILLISECONDS, TimeUnit.MILLISECONDS)
+ .socketTimeout(CONNECTION_TIMEOUT_MILLISECONDS, TimeUnit.MILLISECONDS)
+ .establishConnectionTimeout(CONNECTION_TIMEOUT_MILLISECONDS, TimeUnit.MILLISECONDS)
+ .register(new JacksonConfig());
+
+ if (asyncExecutorService != null) {
+ clientBuilder.asyncExecutor(asyncExecutorService);
+ }
+
+ client = clientBuilder.build();
+ }
+
+ public static void close() {
+ if (client == null) {
+ return;
+ }
+
+ client.close();
+ client = null;
+ }
+}
diff --git a/agent/src/main/resources/META-INF/services/org.openremote.agent.protocol.Protocol b/agent/src/main/resources/META-INF/services/org.openremote.agent.protocol.Protocol
index 0b6d54fb7..da7bf465c 100644
--- a/agent/src/main/resources/META-INF/services/org.openremote.agent.protocol.Protocol
+++ b/agent/src/main/resources/META-INF/services/org.openremote.agent.protocol.Protocol
@@ -4,4 +4,5 @@ org.openremote.agent.protocol.timer.TimerProtocol
org.openremote.agent.protocol.knx.KNXProtocol
org.openremote.agent.protocol.upnp.UpnpProtocol
org.openremote.agent.protocol.velbus.VelbusSocketProtocol
-org.openremote.agent.protocol.velbus.VelbusSerialProtocol
\ No newline at end of file
+org.openremote.agent.protocol.velbus.VelbusSerialProtocol
+org.openremote.agent.protocol.http.HttpClientProtocol
\ No newline at end of file
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.groovy
new file mode 100644
index 000000000..53798c003
--- /dev/null
+++ b/test/src/test/groovy/org/openremote/test/protocol/http/HttpClientProtocolTest.groovy
@@ -0,0 +1,777 @@
+/*
+ * 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.jboss.resteasy.spi.ResteasyUriInfo
+import org.jboss.resteasy.util.BasicAuthHelper
+import org.openremote.agent.protocol.Protocol
+import org.openremote.agent.protocol.filter.RegexFilter
+import org.openremote.agent.protocol.http.*
+import org.openremote.container.Container
+import org.openremote.manager.server.agent.AgentService
+import org.openremote.manager.server.asset.AssetProcessingService
+import org.openremote.manager.server.asset.AssetStorageService
+import org.openremote.manager.server.asset.ServerAsset
+import org.openremote.model.Constants
+import org.openremote.model.asset.AssetAttribute
+import org.openremote.model.asset.AssetMeta
+import org.openremote.model.asset.AssetType
+import org.openremote.model.asset.agent.ConnectionStatus
+import org.openremote.model.attribute.AttributeEvent
+import org.openremote.model.attribute.AttributeRef
+import org.openremote.model.attribute.AttributeType
+import org.openremote.model.attribute.MetaItem
+import org.openremote.model.value.ObjectValue
+import org.openremote.model.value.Value
+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.HttpMethod
+import javax.ws.rs.client.ClientRequestContext
+import javax.ws.rs.client.ClientRequestFilter
+import javax.ws.rs.core.*
+import java.util.concurrent.TimeUnit
+
+import static org.openremote.model.asset.agent.ProtocolConfiguration.initProtocolConfiguration
+
+class HttpClientProtocolTest 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 client protocol configuration and linked attribute deployment"() {
+
+ given: "expected conditions"
+ def conditions = new PollingConditions(timeout: 15, initialDelay: 1, delay: 1)
+
+ and: "the HTTP client protocol polling time units are set to milliseconds"
+ HttpClientProtocol.POLLING_TIME_UNIT = TimeUnit.MILLISECONDS
+
+ when: "the container starts"
+ def serverPort = findEphemeralPort()
+ def container = startContainerNoDemoImport(defaultConfig(serverPort), defaultServices())
+ def httpClientProtocol = container.getService(HttpClientProtocol.class)
+ def assetStorageService = container.getService(AssetStorageService.class)
+ def assetProcessingService = container.getService(AssetProcessingService.class)
+ def agentService = container.getService(AgentService.class)
+
+ then: "the container should be running"
+ conditions.eventually {
+ assert container.isRunning()
+ }
+
+ when: "the web target builder is configured to use the mock server"
+ // Need to do this here as HTTP protocol must be initialised first
+ WebTargetBuilder.initClient()
+ if (!WebTargetBuilder.client.configuration.isRegistered(mockServer)) {
+ WebTargetBuilder.client.register(mockServer, Integer.MAX_VALUE)
+ }
+
+ and: "an agent with a HTTP client protocol configuration is created"
+ def agent = new ServerAsset()
+ agent.setRealmId(Constants.MASTER_REALM)
+ agent.setName("Test Agent")
+ agent.setType(AssetType.AGENT)
+ agent.setAttributes(
+ initProtocolConfiguration(new AssetAttribute("protocolConfig"), HttpClientProtocol.PROTOCOL_NAME)
+ .addMeta(
+ new MetaItem(
+ HttpClientProtocol.META_PROTOCOL_BASE_URI,
+ Values.create("https://mockapi")
+ ),
+ new MetaItem(
+ HttpClientProtocol.META_PROTOCOL_OAUTH_GRANT,
+ Values.<ObjectValue>parse(Container.JSON.writeValueAsString(
+ new OAuthPasswordGrant("https://mockapi/token",
+ "TestClient",
+ "TestSecret",
+ "scope1 scope2",
+ "testuser",
+ "password")
+ )).get()),
+ new MetaItem(
+ HttpClientProtocol.META_PROTOCOL_FOLLOW_REDIRECTS,
+ Values.create(true)
+ ),
+ new MetaItem(
+ HttpClientProtocol.META_PROTOCOL_PING_PATH,
+ Values.create("pingGet")
+ ),
+ new MetaItem(
+ HttpClientProtocol.META_PROTOCOL_PING_SECONDS,
+ Values.create(100) // Note for testing time unit is set to milliseconds
+ ),
+ new MetaItem(
+ HttpClientProtocol.META_HEADERS,
+ Values.<ObjectValue>parse(/{"header1": "header1Value1", "header2": ["header2Value1","header2Value2"]}/).get()
+ ),
+ new MetaItem(
+ HttpClientProtocol.META_QUERY_PARAMETERS,
+ Values.<ObjectValue>parse(/{"param1": "param1Value1", "param2": ["param2Value1","param2Value2"]}/).get()
+ )
+ )
+ )
+
+ and: "the agent is added to the asset service"
+ agent = assetStorageService.merge(agent)
+
+ then: "the protocol should authenticate and start pinging the server and the connection status should become CONNECTED"
+ conditions.eventually {
+ def status = agentService.getProtocolConnectionStatus(new AttributeRef(agent.id, "protocolConfig"))
+ assert status == ConnectionStatus.CONNECTED
+ assert mockServer.pingCount > 2
+ }
+
+ when: "the protocol configuration is removed"
+ agent.removeAttribute("protocolConfig")
+ agent = assetStorageService.merge(agent)
+
+ then: "the request client should be removed"
+ conditions.eventually {
+ assert httpClientProtocol.clientMap.isEmpty()
+ assert httpClientProtocol.requestMap.isEmpty()
+ assert httpClientProtocol.pollingMap.isEmpty()
+ }
+
+ and: "ping polling should have stopped"
+ def pingCount = mockServer.pingCount
+ Thread.sleep(50)
+ assert mockServer.pingCount == pingCount
+
+ /* Test ping using POST with body and query parameters */
+
+ when: "ping count is reset"
+ mockServer.pingCount = 0
+
+ and: "a protocol configuration is added to the agent that uses POST ping mechanism"
+ agent.addAttributes(
+ initProtocolConfiguration(new AssetAttribute("protocolConfig"), HttpClientProtocol.PROTOCOL_NAME)
+ .addMeta(
+ new MetaItem(
+ HttpClientProtocol.META_PROTOCOL_BASE_URI,
+ Values.create("https://mockapi")
+ ),
+ new MetaItem(
+ HttpClientProtocol.META_PROTOCOL_OAUTH_GRANT,
+ Values.<ObjectValue>parse(Container.JSON.writeValueAsString(
+ new OAuthPasswordGrant("https://mockapi/token",
+ "TestClient",
+ "TestSecret",
+ "scope1 scope2",
+ "testuser",
+ "password")
+ )).get()),
+ new MetaItem(
+ HttpClientProtocol.META_PROTOCOL_FOLLOW_REDIRECTS,
+ Values.create(true)
+ ),
+ new MetaItem(
+ HttpClientProtocol.META_HEADERS,
+ Values.<ObjectValue>parse(/{"header1": "header1Value1", "header2": ["header2Value1","header2Value2"]}/).get()
+ ),
+ new MetaItem(
+ HttpClientProtocol.META_QUERY_PARAMETERS,
+ Values.<ObjectValue>parse(/{"param1": "param1Value1", "param2": ["param2Value1","param2Value2"]}/).get()
+ ),
+ new MetaItem(
+ HttpClientProtocol.META_PROTOCOL_PING_PATH,
+ Values.create("pingPost")
+ ),
+ new MetaItem(
+ HttpClientProtocol.META_PROTOCOL_PING_SECONDS,
+ Values.create(100) // Note for testing time unit is set to milliseconds
+ ),
+ new MetaItem(
+ HttpClientProtocol.META_PROTOCOL_PING_METHOD,
+ Values.create(HttpMethod.POST)
+ ),
+ new MetaItem(
+ HttpClientProtocol.META_PROTOCOL_PING_BODY,
+ Values.<ObjectValue>parse(/{"prop1": "prop1Value", "prop2": "prop2Value"}/).get()
+ ),
+ new MetaItem(
+ HttpClientProtocol.META_PROTOCOL_PING_QUERY_PARAMETERS,
+ Values.<ObjectValue>parse(/{"param1": "param1Value2", "param3": "param3Value1"}/).get()
+ ),
+ )
+ )
+ agent = assetStorageService.merge(agent)
+
+ then: "the protocol should authenticate and start pinging the server and the connection status should become CONNECTED"
+ conditions.eventually {
+ def status = agentService.getProtocolConnectionStatus(new AttributeRef(agent.id, "protocolConfig"))
+ assert status == ConnectionStatus.CONNECTED
+ assert mockServer.pingCount > 2
+ }
+
+ when: "the ping content type is manually configured"
+ agent.getAttribute("protocolConfig").ifPresent{
+ it.addMeta(
+ new MetaItem(
+ HttpClientProtocol.META_PROTOCOL_PING_CONTENT_TYPE,
+ Values.create(MediaType.APPLICATION_XML)
+ )
+ )}
+
+ and: "the agent is merged to the asset service"
+ def currentClient = httpClientProtocol.clientMap.values().first()
+ agent = assetStorageService.merge(agent)
+
+ then: "the client should eventually be updated"
+ conditions.eventually {
+ assert httpClientProtocol.clientMap.size() == 1
+ assert httpClientProtocol.clientMap.values().first() != currentClient
+ }
+
+ and: "the protocol should authenticate and start pinging the server and the connection status should become CONNECTED"
+ conditions.eventually {
+ def status = agentService.getProtocolConnectionStatus(new AttributeRef(agent.id, "protocolConfig"))
+ assert status == ConnectionStatus.CONNECTED
+ assert mockServer.pingCount > 2
+ }
+
+ when: "an asset is created with attributes linked to the http protocol configuration"
+ def asset = new ServerAsset("Test Asset", AssetType.THING, agent)
+ asset.setAttributes(
+ // attribute that sends requests to the server using PUT with dynamic body and custom header to override parent
+ new AssetAttribute("putRequestWithHeaders", AttributeType.OBJECT)
+ .addMeta(
+ new MetaItem(AssetMeta.AGENT_LINK, new AttributeRef(agent.id, "protocolConfig").toArrayValue()),
+ new MetaItem(HttpClientProtocol.META_ATTRIBUTE_PATH, Values.create("put_request_with_headers")),
+ new MetaItem(HttpClientProtocol.META_ATTRIBUTE_METHOD, Values.create(HttpMethod.PUT)),
+ new MetaItem(
+ HttpClientProtocol.META_ATTRIBUTE_BODY,
+ Values.<ObjectValue>parse('{"prop1": "{$value}", "prop2": "prop2Value"}').get()
+ ),
+ new MetaItem(
+ HttpClientProtocol.META_HEADERS,
+ Values.createObject().put("header1", (Value)null)
+ ),
+ new MetaItem(
+ HttpClientProtocol.META_QUERY_PARAMETERS,
+ Values.<ObjectValue>parse(/{"param2": "param2Value3", "param3": "param3Value1"}/).get()
+ )
+ ),
+ // attribute that sends requests to the server using GET with dynamic path
+ new AssetAttribute("getRequestWithDynamicPath", AttributeType.OBJECT)
+ .addMeta(
+ new MetaItem(AssetMeta.AGENT_LINK, new AttributeRef(agent.id, "protocolConfig").toArrayValue()),
+ new MetaItem(HttpClientProtocol.META_ATTRIBUTE_PATH, Values.create('value/{$value}/set'))
+ ),
+ // attribute that polls the server using GET and uses regex filter on response
+ new AssetAttribute("getPollSlow", AttributeType.NUMBER)
+ .addMeta(
+ new MetaItem(AssetMeta.AGENT_LINK, new AttributeRef(agent.id, "protocolConfig").toArrayValue()),
+ new MetaItem(HttpClientProtocol.META_ATTRIBUTE_PATH, Values.create("get_poll_slow")),
+ new MetaItem(HttpClientProtocol.META_ATTRIBUTE_POLLING_SECONDS, Values.create(50)), // This is ms in testing
+ new MetaItem(
+ Protocol.META_PROTOCOL_FILTERS,
+ Values.createArray().add(new RegexFilter("\\d+", 0, 0).toValue().get())
+ )
+ ),
+ // attribute that polls the server using GET and uses regex filter on response
+ new AssetAttribute("getPollFast", AttributeType.NUMBER)
+ .addMeta(
+ new MetaItem(AssetMeta.AGENT_LINK, new AttributeRef(agent.id, "protocolConfig").toArrayValue()),
+ new MetaItem(HttpClientProtocol.META_ATTRIBUTE_PATH, Values.create("get_poll_fast")),
+ new MetaItem(HttpClientProtocol.META_ATTRIBUTE_POLLING_SECONDS, Values.create(40)), // This is ms in testing
+ new MetaItem(
+ Protocol.META_PROTOCOL_FILTERS,
+ Values.createArray().add(new RegexFilter("\\d+", 0, 1).toValue().get())
+ )
+ )
+ )
+
+ and: "the asset is merged into the asset service"
+ asset = assetStorageService.merge(asset)
+ def requestCount = httpClientProtocol.requestMap.size()
+
+ then: "new request maps should be created in the HTTP client protocol for the linked attributes"
+ conditions.eventually {
+ assert httpClientProtocol.requestMap.size() == requestCount + 4
+ }
+
+ and: "the polling attributes should be polling the server"
+ conditions.eventually {
+ assert mockServer.pollCountSlow > 0
+ assert mockServer.pollCountFast > 0
+ assert mockServer.pollCountFast > mockServer.pollCountSlow
+ }
+
+ and: "the polling attributes should have the correct values"
+ conditions.eventually {
+ asset = assetStorageService.find(asset.getId(), true)
+ assert asset.getAttribute("getPollSlow").flatMap({it.getValueAsInteger()}).orElse(null) == 100
+ assert asset.getAttribute("getPollFast").flatMap({it.getValueAsInteger()}).orElse(null) == 60
+ }
+
+ when: "a linked attribute value is updated"
+ def attributeEvent = new AttributeEvent(asset.id,
+ "putRequestWithHeaders",
+ Values.<ObjectValue>parse(/{"myProp1": 123,"myProp2": true}/).get())
+ assetProcessingService.sendAttributeEvent(attributeEvent)
+
+ then: "the server should have received the request"
+ conditions.eventually {
+ assert mockServer.putRequestWithHeadersCalled
+ }
+
+ when: "a protocol configurations are added to the agent that don't use ping mechanism"
+ agent.addAttributes(
+ initProtocolConfiguration(new AssetAttribute("protocolConfig2"), HttpClientProtocol.PROTOCOL_NAME)
+ .addMeta(
+ new MetaItem(
+ HttpClientProtocol.META_PROTOCOL_BASE_URI,
+ Values.create("https://mockapi")
+ ),
+ new MetaItem(
+ HttpClientProtocol.META_PROTOCOL_OAUTH_GRANT,
+ Values.<ObjectValue>parse(Container.JSON.writeValueAsString(
+ new OAuthPasswordGrant("https://mockapi/token",
+ "TestClient",
+ "TestSecret",
+ "scope1 scope2",
+ "testuser",
+ "password")
+ )).get()),
+ new MetaItem(
+ HttpClientProtocol.META_FAILURE_CODES,
+ Values.createArray()
+ .add(Values.create(Response.Status.UNAUTHORIZED.statusCode))
+ .add(Values.create(Response.Status.FORBIDDEN.statusCode))
+ )
+ ),
+ initProtocolConfiguration(new AssetAttribute("protocolConfig3"), HttpClientProtocol.PROTOCOL_NAME)
+ .addMeta(
+ new MetaItem(
+ HttpClientProtocol.META_PROTOCOL_BASE_URI,
+ Values.create("https://mockapi")
+ ),
+ new MetaItem(
+ HttpClientProtocol.META_PROTOCOL_OAUTH_GRANT,
+ Values.<ObjectValue>parse(Container.JSON.writeValueAsString(
+ new OAuthPasswordGrant("https://mockapi/token",
+ "TestClient",
+ "TestSecret",
+ "scope1 scope2",
+ "testuser",
+ "password")
+ )).get()),
+ new MetaItem(
+ HttpClientProtocol.META_FAILURE_CODES,
+ Values.createArray()
+ .add(Values.create(Response.Status.UNAUTHORIZED.statusCode))
+ .add(Values.create(Response.Status.FORBIDDEN.statusCode))
+ )
+ ),
+ initProtocolConfiguration(new AssetAttribute("protocolConfig4"), HttpClientProtocol.PROTOCOL_NAME)
+ .addMeta(
+ new MetaItem(
+ HttpClientProtocol.META_PROTOCOL_BASE_URI,
+ Values.create("https://mockapi")
+ ),
+ new MetaItem(
+ HttpClientProtocol.META_PROTOCOL_OAUTH_GRANT,
+ Values.<ObjectValue>parse(Container.JSON.writeValueAsString(
+ new OAuthPasswordGrant("https://mockapi/token",
+ "TestClient",
+ "TestSecret",
+ "scope1 scope2",
+ "testuser",
+ "password")
+ )).get()),
+ new MetaItem(
+ HttpClientProtocol.META_PROTOCOL_FOLLOW_REDIRECTS,
+ Values.create(true)
+ )
+ )
+ )
+ def protocolCount = httpClientProtocol.linkedProtocolConfigurations.size()
+ agent = assetStorageService.merge(agent)
+
+ then: "the protocol configuration should be linked with a connection status of unknown"
+ conditions.eventually {
+ assert httpClientProtocol.linkedProtocolConfigurations.size() == protocolCount + 3
+ assert agentService.getProtocolConnectionStatus(new AttributeRef(agent.id, "protocolConfig2")) == ConnectionStatus.UNKNOWN
+ assert agentService.getProtocolConnectionStatus(new AttributeRef(agent.id, "protocolConfig3")) == ConnectionStatus.UNKNOWN
+ assert agentService.getProtocolConnectionStatus(new AttributeRef(agent.id, "protocolConfig4")) == ConnectionStatus.UNKNOWN
+ }
+
+ when: "attributes are linked to these protocol configurations"
+ def asset2 = new ServerAsset("Test Asset 2", AssetType.THING, agent)
+ asset2.addAttributes(
+ new AssetAttribute("getSuccess", AttributeType.STRING)
+ .addMeta(
+ new MetaItem(AssetMeta.AGENT_LINK, new AttributeRef(agent.id, "protocolConfig2").toArrayValue()),
+ new MetaItem(HttpClientProtocol.META_ATTRIBUTE_PATH, Values.create("get_success_200"))
+ ),
+ new AssetAttribute("getFailure", AttributeType.STRING)
+ .addMeta(
+ new MetaItem(AssetMeta.AGENT_LINK, new AttributeRef(agent.id, "protocolConfig2").toArrayValue()),
+ new MetaItem(HttpClientProtocol.META_ATTRIBUTE_PATH, Values.create("get_failure_401"))
+ ),
+ new AssetAttribute("pollFailure", AttributeType.STRING)
+ .addMeta(
+ new MetaItem(AssetMeta.AGENT_LINK, new AttributeRef(agent.id, "protocolConfig3").toArrayValue()),
+ new MetaItem(HttpClientProtocol.META_ATTRIBUTE_PATH, Values.create("get_failure_401")),
+ new MetaItem(HttpClientProtocol.META_ATTRIBUTE_POLLING_SECONDS, Values.create(50)), // This is ms in testing
+ ),
+ new AssetAttribute("getSuccess2", AttributeType.STRING)
+ .addMeta(
+ new MetaItem(AssetMeta.AGENT_LINK, new AttributeRef(agent.id, "protocolConfig4").toArrayValue()),
+ new MetaItem(HttpClientProtocol.META_ATTRIBUTE_PATH, Values.create("get_success_200"))
+ ),
+ new AssetAttribute("getFailure2", AttributeType.STRING)
+ .addMeta(
+ new MetaItem(AssetMeta.AGENT_LINK, new AttributeRef(agent.id, "protocolConfig4").toArrayValue()),
+ new MetaItem(HttpClientProtocol.META_ATTRIBUTE_PATH, Values.create("get_failure_401"))
+ ),
+ new AssetAttribute("getRedirect", AttributeType.STRING)
+ .addMeta(
+ new MetaItem(AssetMeta.AGENT_LINK, new AttributeRef(agent.id, "protocolConfig4").toArrayValue()),
+ new MetaItem(HttpClientProtocol.META_ATTRIBUTE_PATH, Values.create("redirect"))
+ ),
+ )
+
+ and: "the asset is merged into the asset service"
+ requestCount = httpClientProtocol.requestMap.size()
+ asset2 = assetStorageService.merge(asset2)
+
+ then: "new request maps should be created in the HTTP client protocol for the linked attributes"
+ conditions.eventually {
+ assert httpClientProtocol.requestMap.size() == requestCount + 5
+ }
+
+ and: "the protocol config connection status linked to by the failing poll request should become DISABLED"
+ conditions.eventually {
+ assert agentService.getProtocolConnectionStatus(new AttributeRef(agent.id, "protocolConfig3")) == ConnectionStatus.DISABLED
+ }
+
+ and: "the poll request will no longer reach the server"
+ def count = mockServer.successFailureCount
+ Thread.sleep(50)
+ assert mockServer.successFailureCount == count
+
+ when: "a linked attribute value is updated"
+ attributeEvent = new AttributeEvent(asset2.id,
+ "getSuccess",
+ Values.create("OK"))
+ assetProcessingService.sendAttributeEvent(attributeEvent)
+
+ then: "the server should have received the request"
+ conditions.eventually {
+ assert mockServer.successFailureCount == count + 1
+ }
+
+ and: "the protocol connection status should now be CONNECTED"
+ conditions.eventually {
+ assert agentService.getProtocolConnectionStatus(new AttributeRef(agent.id, "protocolConfig2")) == ConnectionStatus.CONNECTED
+ }
+
+ when: "a linked attribute value is updated"
+ count = mockServer.successFailureCount
+ attributeEvent = new AttributeEvent(asset2.id,
+ "getFailure",
+ Values.create("OK"))
+ assetProcessingService.sendAttributeEvent(attributeEvent)
+
+ then: "the server should have received the request and returned a 401"
+ conditions.eventually {
+ assert mockServer.successFailureCount == count + 1
+ }
+
+ and: "the protocol connection status should now be DISABLED"
+ conditions.eventually {
+ assert agentService.getProtocolConnectionStatus(new AttributeRef(agent.id, "protocolConfig2")) == ConnectionStatus.DISABLED
+ }
+
+ when: "a linked attribute value is updated again"
+ count = mockServer.successFailureCount
+ attributeEvent = new AttributeEvent(asset2.id,
+ "getSuccess",
+ Values.create("OK"))
+ assetProcessingService.sendAttributeEvent(attributeEvent)
+
+ then: "the server should not have received the request"
+ Thread.sleep(50)
+ assert mockServer.successFailureCount == count
+
+ when: "a linked attribute value is updated"
+ attributeEvent = new AttributeEvent(asset2.id,
+ "getFailure2",
+ Values.create("OK"))
+ assetProcessingService.sendAttributeEvent(attributeEvent)
+
+ then: "the server should have received the request and returned a 401"
+ conditions.eventually {
+ assert mockServer.successFailureCount == count + 1
+ }
+
+ and: "the protocol connection status should now be ERROR_AUTHENTICATION"
+ conditions.eventually {
+ assert agentService.getProtocolConnectionStatus(new AttributeRef(agent.id, "protocolConfig4")) == ConnectionStatus.ERROR_AUTHENTICATION
+ }
+
+ when: "a linked attribute value is updated"
+ count = mockServer.successFailureCount
+ attributeEvent = new AttributeEvent(asset2.id,
+ "getSuccess2",
+ Values.create("OK"))
+ assetProcessingService.sendAttributeEvent(attributeEvent)
+
+ then: "the server should have received the request and returned a 200"
+ conditions.eventually {
+ assert mockServer.successFailureCount == count + 1
+ }
+
+ and: "the protocol connection status should now be CONNECTED"
+ conditions.eventually {
+ assert agentService.getProtocolConnectionStatus(new AttributeRef(agent.id, "protocolConfig4")) == ConnectionStatus.CONNECTED
+ }
+
+ when: "a linked attribute value is updated"
+ count = mockServer.successFailureCount
+ attributeEvent = new AttributeEvent(asset2.id,
+ "getRedirect",
+ Values.create("OK"))
+ assetProcessingService.sendAttributeEvent(attributeEvent)
+
+ then: "the server should have sent a redirect request and the redirected endpoint returned a 200"
+ conditions.eventually {
+ assert mockServer.successFailureCount == count + 1
+ }
+
+ cleanup: "the server should be stopped"
+ stopContainer(container)
+ }
+}
\ No newline at end of file
diff --git a/test/src/test/groovy/org/openremote/test/protocol/http/WebTargetTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/http/WebTargetTest.groovy
new file mode 100644
index 000000000..bd76419aa
--- /dev/null
+++ b/test/src/test/groovy/org/openremote/test/protocol/http/WebTargetTest.groovy
@@ -0,0 +1,526 @@
+/*
+ * 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.jboss.resteasy.spi.ResteasyUriInfo
+import org.jboss.resteasy.util.BasicAuthHelper
+import org.openremote.agent.protocol.http.*
+import org.openremote.container.Container
+import spock.lang.Shared
+import spock.lang.Specification
+
+import javax.ws.rs.client.ClientRequestContext
+import javax.ws.rs.client.ClientRequestFilter
+import javax.ws.rs.core.*
+
+class WebTargetTest extends Specification {
+
+ @Shared
+ def mockServer = new ClientRequestFilter() {
+
+ private boolean supportsRefresh
+ private int accessTokenCount
+ private int refreshTokenCount
+ private String accessToken = null
+ private String refreshToken = null
+
+ @Override
+ void filter(ClientRequestContext requestContext) throws IOException {
+ def requestUri = requestContext.uri
+ def requestPath = requestUri.scheme + "://" + requestUri.host + requestUri.path
+
+ switch (requestPath)
+ {
+ case "https://basicserver/get":
+ 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://oauthserver/token":
+ case "https://oauthreuseserver/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 ) == "client1"
+ && grant.getFirst(OAuthGrant.VALUE_KEY_CLIENT_SECRET ) == "secret1"
+ && grant.getFirst(OAuthGrant.VALUE_KEY_SCOPE ) == "scope1 scope2"
+ && grant.getFirst(OAuthPasswordGrant.VALUE_KEY_USERNAME) == "testuser"
+ && grant.getFirst(OAuthPasswordGrant.VALUE_KEY_PASSWORD) == "password1") {
+ accessToken = "accesstoken" + accessTokenCount++
+ def response = new OAuthServerResponse()
+ response.accessToken = accessToken
+ response.expiresIn = requestPath == "https://oauthserver/token" ? 1 : 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) == "client_credentials"
+ && grant.getFirst(OAuthGrant.VALUE_KEY_CLIENT_ID ) == "client1"
+ && grant.getFirst(OAuthGrant.VALUE_KEY_CLIENT_SECRET ) == "secret1"
+ && grant.getFirst(OAuthGrant.VALUE_KEY_SCOPE ) == "scope1 scope2") {
+ accessToken = "accesstoken" + accessTokenCount++
+ def response = new OAuthServerResponse()
+ response.accessToken = accessToken
+ response.expiresIn = requestPath == "https://oauthserver/token" ? 1 : 100
+ response.tokenType = "Bearer"
+
+ requestContext.abortWith(
+ Response.ok(response, MediaType.APPLICATION_JSON_TYPE).build()
+ )
+ return
+ } else if (supportsRefresh && grant.getFirst(OAuthGrant.VALUE_KEY_GRANT_TYPE) == "refresh_token"
+ && grant.getFirst(OAuthGrant.VALUE_KEY_CLIENT_ID ) == "client1"
+ && grant.getFirst(OAuthGrant.VALUE_KEY_CLIENT_SECRET ) == "secret1"
+ && 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 = requestPath == "https://oauthserver/token" ? 1 : 100
+ response.tokenType = "Bearer"
+
+ requestContext.abortWith(
+ Response.ok(response, MediaType.APPLICATION_JSON_TYPE).build()
+ )
+ return
+ }
+ break
+ case "https://oauthserver/get":
+ // Check access token is what we sent
+ def authHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION)
+ def accessToken = authHeader.substring(7)
+ if (accessToken != null && this.accessToken != null && accessToken == this.accessToken) {
+ requestContext.abortWith(Response.ok().build())
+ return
+ }
+ break
+ case "https://forbiddenserver":
+ // Use access token counter to track requests
+ accessTokenCount++
+ requestContext.abortWith(
+ Response.status(Response.Status.FORBIDDEN).build()
+ )
+ return
+ case "https://headerserver":
+ if (requestContext.getHeaderString("MyHeader") == "MyHeaderValue"
+ && requestContext.getHeaderString("MyMultiHeader") == "MyMultiHeaderValue1,MyMultiHeaderValue2") {
+ requestContext.abortWith(Response.ok().build())
+ return
+ }
+ break
+ case "https://headerserver/get":
+ if (requestContext.getHeaderString("MyHeader") == null
+ && requestContext.getHeaderString("MyHeaderNew") == "MyHeaderNewValue"
+ && requestContext.getHeaderString("MyMultiHeader") == "MyMultiHeaderValue1,MyMultiHeaderValue2,MyMultiHeaderValue3") {
+ requestContext.abortWith(Response.ok().build())
+ return
+ }
+ break
+ case "https://redirectserver":
+ requestContext.abortWith(Response.temporaryRedirect(new URI("https://redirectedserver")).build())
+ return
+ case "https://redirectedserver":
+ requestContext.abortWith(Response.ok().build())
+ return
+ case "https://paramserver":
+ 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.abortWith(Response.ok().build())
+ return
+ }
+ break
+ case "https://paramserver/get":
+ UriInfo uriInfo = new ResteasyUriInfo(requestUri)
+ def queryParams = uriInfo.getQueryParameters(true)
+ if (queryParams.get("param1").size() == 2
+ && queryParams.get("param1").get(0) == "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.get("param3").get(0) == "param3Value1") {
+
+ requestContext.abortWith(Response.ok().build())
+ return
+ }
+ break
+ case "https://dynamicparamserver":
+ UriInfo uriInfo = new ResteasyUriInfo(requestContext.uri)
+ def queryParams = uriInfo.getQueryParameters(true)
+ if (queryParams.get("param1").size() == 1
+ && queryParams.getFirst("param1") == "dynamicValue1"
+ && queryParams.get("param2").size() == 2
+ && queryParams.get("param2").get(0) == "param2Value1"
+ &&queryParams.get("param2").get(1) == "param2Value2") {
+
+ requestContext.abortWith(Response.ok().build())
+ return
+ }
+ }
+
+ requestContext.abortWith(Response.serverError().build())
+ }
+ }
+
+ def setupSpec() {
+ // Initialise the web target builder and load in the mock 'server'
+ WebTargetBuilder.initClient()
+ WebTargetBuilder.client.register(mockServer, Integer.MAX_VALUE)
+ }
+
+ def cleanupSpec() {
+ WebTargetBuilder.close()
+ }
+
+ def cleanup() {
+ mockServer.supportsRefresh = false
+ mockServer.accessToken = null
+ mockServer.refreshToken = null
+ mockServer.accessTokenCount = 0
+ mockServer.refreshTokenCount = 0
+ }
+
+ def "OAuth grant serialisation and deserialisation"() {
+
+ given: "a grant object"
+ OAuthPasswordGrant grant = new OAuthPasswordGrant("https://mockapi/token",
+ "TestClient",
+ "TestSecret",
+ "scope1 scope2",
+ "testuser",
+ "password")
+
+ when: "it is serialised"
+ String grantStr = Container.JSON.writeValueAsString(grant)
+
+ and: "deserialised again"
+ OAuthGrant grant2 = Container.JSON.readValue(grantStr, OAuthGrant.class)
+
+ then: "the two grant objects should be the same"
+ assert grant2.tokenEndpointUri == grant.tokenEndpointUri
+ assert grant2.grantType == grant.grantType
+ assert grant2.clientId == grant.clientId
+ assert grant2.clientSecret == grant.clientSecret
+ assert grant2.scope == grant.scope
+ assert ((OAuthPasswordGrant)grant2).username == grant.username
+ assert ((OAuthPasswordGrant)grant2).password == grant.password
+ }
+
+ def "Check Basic authentication"() {
+
+ given: "a web target for a server requiring basic authentication"
+ def target = new WebTargetBuilder("https://basicserver")
+ .setBasicAuthentication("testuser", "password1")
+ .build()
+
+ when: "a request is made to an endpoint on that server"
+ def response = target.path("get").request().get()
+
+ then: "the response should be 200 OK"
+ assert response.getStatus() == 200
+ }
+
+ def "Check OAuth resource owner credentials (password) grant authentication"() {
+
+ given: "a web target for a server requiring OAuth 'password' grant authentication"
+ def target = new WebTargetBuilder("https://oauthserver")
+ .setOAuthAuthentication(
+ new OAuthPasswordGrant(
+ "https://oauthserver/token",
+ "client1",
+ "secret1",
+ "scope1 scope2",
+ "testuser",
+ "password1"
+ )
+ )
+ .build()
+
+ when: "a request is made to an endpoint on that server"
+ def response = target.path("get").request().get()
+
+ then: "the response should be 200 OK"
+ assert response.getStatus() == 200
+
+ when: "another request is made to an endpoint on the server that will require renewing the access token"
+ response = target.path("get").request().get()
+
+ then: "the response should be 200 OK"
+ assert response.getStatus() == 200
+
+ and: "the server should have generated 2 access tokens but no refresh tokens"
+ assert mockServer.accessTokenCount == 2
+ assert mockServer.refreshTokenCount == 0
+
+ when: "the server supports token refresh"
+ mockServer.supportsRefresh = true
+ mockServer.accessToken = null
+ mockServer.refreshToken = null
+ mockServer.accessTokenCount = 0
+
+ and: "a request is made to an endpoint on that server"
+ response = target.path("get").request().get()
+
+ then: "the response should be 200 OK"
+ assert response.getStatus() == 200
+
+ when: "another request is made to an endpoint on the server that will require renewing the access token"
+ response = target.path("get").request().get()
+
+ then: "the response should be 200 OK"
+ assert response.getStatus() == 200
+
+ and: "the server should have generated 2 access tokens and 1 refresh token"
+ assert mockServer.accessTokenCount == 2
+ assert mockServer.refreshTokenCount == 1
+ }
+
+ def "Check OAuth client credentials grant authentication"() {
+
+ given: "a web target for a server requiring OAuth 'client_credentials' grant authentication"
+ def target = new WebTargetBuilder("https://oauthserver")
+ .setOAuthAuthentication(
+ new OAuthClientCredentialsGrant(
+ "https://oauthserver/token",
+ "client1",
+ "secret1",
+ "scope1 scope2"
+ )
+ )
+ .build()
+
+ when: "a request is made to an endpoint on that server"
+ def response = target.path("get").request().get()
+
+ then: "the response should be 200 OK"
+ assert response.getStatus() == 200
+
+ when: "another request is made to an endpoint on the server that will require renewing the access token"
+ response = target.path("get").request().get()
+
+ then: "the response should be 200 OK"
+ assert response.getStatus() == 200
+
+ and: "the server should have generated 2 access tokens but no refresh tokens"
+ assert mockServer.accessTokenCount == 2
+ assert mockServer.refreshTokenCount == 0
+ }
+
+ def "Check OAuth token reuse functionality"() {
+
+ given: "a web target for a server requiring OAuth 'client_credentials' grant authentication"
+ def target = new WebTargetBuilder("https://oauthserver/get")
+ .setOAuthAuthentication(
+ new OAuthClientCredentialsGrant(
+ "https://oauthreuseserver/token",
+ "client1",
+ "secret1",
+ "scope1 scope2"
+ ))
+ .build()
+
+ when: "a request is made to an endpoint on that server"
+ def response = target.request().get()
+
+ then: "the response should be 200 OK"
+ assert response.getStatus() == 200
+
+ when: "another request is made to an endpoint on the server"
+ response = target.request().get()
+
+ then: "the response should be 200 OK"
+ assert response.getStatus() == 200
+
+ and: "the server should have generated 1 access tokens and no refresh tokens"
+ assert mockServer.accessTokenCount == 1
+ assert mockServer.refreshTokenCount == 0
+ }
+
+ def "Check permanent failure functionality"() {
+
+ given: "a web target for a server set to permanently fail on 403 errors"
+ def target = new WebTargetBuilder("https://forbiddenserver")
+ .addPermanentFailureResponse(Response.Status.FORBIDDEN)
+ .build()
+
+ when: "a request is made that generates a 403 response"
+ def response = target.request().get()
+
+ then: "the server should have been hit and response should be 403 forbidden"
+ assert mockServer.accessTokenCount == 1
+ assert response.getStatus() == 403
+
+ when: "another request is made to the server"
+ response = target.request().get()
+
+ then: "the server should not have been hit and the response should be 405 method not allowed"
+ assert mockServer.accessTokenCount == 1
+ assert response.getStatus() == 405
+ }
+
+ def "Check header handling"() {
+
+ given: "custom headers to inject"
+ def headers = new MultivaluedHashMap<String, String>(2)
+ headers.add("MyHeader", "MyHeaderValue")
+ headers.put("MyMultiHeader", ["MyMultiHeaderValue1","MyMultiHeaderValue2"])
+
+ and: "a web target for a server"
+ def target = new WebTargetBuilder("https://headerserver")
+ .setInjectHeaders(headers)
+ .build()
+
+ when: "a request is made to the server"
+ def response = target.request().get()
+
+ then: "the response should be a 200 OK indicating the custom headers reached the server"
+ assert response.getStatus() == 200
+
+ when: "a request is made to the server with additional headers"
+ headers = new MultivaluedHashMap<String, String>(3)
+ headers.add("MyHeader", null)
+ headers.add("MyHeaderNew", "MyHeaderNewValue")
+ headers.add("MyMultiHeader", "MyMultiHeaderValue3")
+ response = target.path("get")
+ .register(new HeaderInjectorFilter(headers))
+ .request()
+ .get()
+
+ then: "the response should be a 200 OK indicating the custom headers reached the server"
+ assert response.getStatus() == 200
+ }
+
+ def "Check redirect handling"() {
+
+ given: "a web target for a server"
+ def target = new WebTargetBuilder("https://redirectserver")
+ .followRedirects(true)
+ .build()
+
+ when: "a request is made to the server that returns a redirect response"
+ def response = target.request().get()
+
+ then: "the response should be a 200 OK and it should have come from the redirected server"
+ assert response.getStatus() == 200
+ assert response.getLocation().toString() == "https://redirectedserver"
+ }
+
+ def "Check query parameter handling"() {
+
+ given: "query parameters to inject"
+ def params = new MultivaluedHashMap<String, String>(2)
+ params.add("param1", "param1Value1")
+ params.put("param2", ["param2Value1","param2Value2"])
+
+ and: "a web target for a server"
+ def target = new WebTargetBuilder("https://paramserver")
+ .setInjectQueryParameters(params)
+ .build()
+
+ when: "a request is made to the server"
+ def response = target.request().get()
+
+ then: "the response should be a 200 OK indicating the query parameters reached the server"
+ assert response.getStatus() == 200
+
+ when: "a request is made to the server with additional query parameters"
+ params = new MultivaluedHashMap<String, String>(3)
+ params.add("param1", "param1Value2")
+ params.add("param3", "param3Value1")
+ response = target.path("get")
+ .register(new QueryParameterInjectorFilter(params, null))
+ .request()
+ .get()
+
+ then: "the response should be a 200 OK indicating the custom headers reached the server"
+ assert response.getStatus() == 200
+ }
+
+ def "Check dynamic query parameter handling"() {
+
+ given: "query parameters to inject with dynamic placeholders"
+ def params = new MultivaluedHashMap<String, String>(2)
+ params.add("param1", "{\$value}")
+ params.put("param2", ["param2Value1","param2Value2"])
+
+ and: "a web target for a server"
+ def target = new WebTargetBuilder("https://dynamicparamserver")
+ .build()
+ .register(new QueryParameterInjectorFilter(params, /"{0,1}\{\$(value)\}"{0,1}/))
+
+ when: "a request is made to the server"
+ def response = target.request()
+ .property(QueryParameterInjectorFilter.DYNAMIC_VALUE, "dynamicValue1")
+ .get()
+
+ then: "the response should be a 200 OK indicating the query parameters reached the server"
+ assert response.getStatus() == 200
+ }
+
+
+// def "Check real OAuth resource owner credentials (password) grant authentication"() {
+//
+// given: "A web target for a server requiring OAuth 'password' grant authentication"
+// def target = new WebTargetBuilder("https://www.telecontrolnet.nl/api/v1")
+// .setOAuthAuthentication(
+// new OAuthPasswordGrant(
+// "https://www.telecontrolnet.nl/oauth/token",
+// "Ha7xO3cCNtNQDdx2bhY7.openremote.org",
+// "9ACGpDbVkirUpsh7df0e",
+// null,
+// "M5HtdBiRUCi4GKOoRNVL"
+// )
+// )
+// .build()
+//
+// when: "A request is made to an endpoint on that server"
+// def response = target.path("locations").request().get()
+//
+// then: "The response should be 200 OK"
+// def str = response.readEntity(String.class);
+// assert response.getStatus() == 200
+// }
+}
\ No newline at end of file