Skip to content

armgit / core

Public Imported from GitHub
0

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

JAX-RS client code cleanup (#2656)

Rich Turner2f1aba78dc7c
diff --git a/agent/src/main/java/org/openremote/agent/protocol/http/HTTPProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/http/HTTPProtocol.java
index 7e74cbf13..fead910a1 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/http/HTTPProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/http/HTTPProtocol.java
@@ -29,7 +29,6 @@ import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import org.apache.http.client.utils.URIBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
-import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import org.jboss.resteasy.core.Headers;
import org.jboss.resteasy.specimpl.BuiltResponse;
import org.jboss.resteasy.specimpl.ResponseBuilderImpl;
@@ -61,7 +60,6 @@ import java.time.Instant;
import java.util.*;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
@@ -69,7 +67,6 @@ import java.util.logging.Level;
import java.util.logging.Logger;
import static org.openremote.container.web.WebTargetBuilder.addHeaders;
-import static org.openremote.container.web.WebTargetBuilder.createClient;
import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
/**
@@ -277,18 +274,19 @@ public class HTTPProtocol extends AbstractProtocol<HTTPAgent, HTTPAgentLink> {
public static final String DEFAULT_HTTP_METHOD = HttpMethod.GET;
public static final String DEFAULT_CONTENT_TYPE = MediaType.TEXT_PLAIN;
protected static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, HTTPProtocol.class);
+ // Cannot be final due to adjustment needed in tests to speed up tests
public static int MIN_POLLING_MILLIS = 5000;
- protected static final AtomicReference<ResteasyClient> client = new AtomicReference<>();
+ public static final int DEFAULT_READ_TIMEOUT_MILLIS = 10000;
protected final Map<AttributeRef, HttpClientRequest> requestMap = new HashMap<>();
protected final Map<AttributeRef, ScheduledFuture<?>> pollingMap = new HashMap<>();
protected final Map<AttributeRef, Set<AttributeRef>> pollingLinkedAttributeMap = new HashMap<>();
- protected ResteasyWebTarget webTarget;
+ protected ResteasyClient client;
+ protected WebTarget webTarget;
public HTTPProtocol(HTTPAgent agent) {
super(agent);
-
- initClient();
+ client = createClient();
}
@Override
@@ -296,6 +294,10 @@ public class HTTPProtocol extends AbstractProtocol<HTTPAgent, HTTPAgentLink> {
pollingMap.forEach((attributeRef, scheduledFuture) -> scheduledFuture.cancel(true));
pollingMap.clear();
requestMap.clear();
+
+ if (client != null) {
+ client.close();
+ }
}
@Override
@@ -322,14 +324,7 @@ public class HTTPProtocol extends AbstractProtocol<HTTPAgent, HTTPAgentLink> {
Optional<OAuthGrant> oAuthGrant = agent.getOAuthGrant();
Optional<UsernamePassword> usernameAndPassword = agent.getUsernamePassword();
boolean followRedirects = agent.getFollowRedirects().orElse(false);
- Integer readTimeout = agent.getRequestTimeoutMillis().orElse(null);
-
- WebTargetBuilder webTargetBuilder;
- if (readTimeout != null) {
- webTargetBuilder = new WebTargetBuilder(WebTargetBuilder.createClient(executorService, WebTargetBuilder.CONNECTION_POOL_SIZE, readTimeout.longValue(), null), uri);
- } else {
- webTargetBuilder = new WebTargetBuilder(client.get(), uri);
- }
+ WebTargetBuilder webTargetBuilder = new WebTargetBuilder(client, uri);
if (oAuthGrant.isPresent()) {
LOG.info("Adding OAuth");
@@ -378,11 +373,6 @@ public class HTTPProtocol extends AbstractProtocol<HTTPAgent, HTTPAgentLink> {
}
}
- if (client == null) {
- LOG.warning("Client is undefined: " + this);
- return;
- }
-
// We pass in the combined headers as they can only be set on the invocation builder
MultivaluedMap<String, String> combinedHeaders;
Optional<MultivaluedMap<String, String>> agentHeaders = agent.getRequestHeaders().map(WebTargetBuilder::mapToMultivaluedMap);
@@ -461,14 +451,6 @@ public class HTTPProtocol extends AbstractProtocol<HTTPAgent, HTTPAgentLink> {
return webTarget != null ? webTarget.getUri().toString() : agent.getBaseURI().orElse("");
}
- protected static void initClient() {
- synchronized (client) {
- if (client.get() == null) {
- client.set(createClient(org.openremote.container.Container.SCHEDULED_EXECUTOR));
- }
- }
- }
-
protected HttpClientRequest buildClientRequest(String path, String method, MultivaluedMap<String, ?> headers, MultivaluedMap<String, ?> queryParams, boolean pagingEnabled, String contentType, TimerService timerService) {
return new HttpClientRequest(
webTarget,
@@ -564,17 +546,11 @@ public class HTTPProtocol extends AbstractProtocol<HTTPAgent, HTTPAgentLink> {
Object attributeValue,
Consumer<Response> responseConsumer) {
String valueStr = attributeValue == null ? null : ValueUtil.convert(attributeValue, String.class);
- Response response = null;
- try {
- response = clientRequest.invoke(valueStr);
+ try (Response response = clientRequest.invoke(valueStr)) {
responseConsumer.accept(response);
} catch (Exception e) {
LOG.log(Level.SEVERE, "Exception thrown whilst doing attribute write request", e);
- } finally {
- if (response != null) {
- response.close();
- }
}
}
@@ -635,4 +611,8 @@ public class HTTPProtocol extends AbstractProtocol<HTTPAgent, HTTPAgentLink> {
}
}
+ protected ResteasyClient createClient() {
+ Integer readTimeout = agent.getRequestTimeoutMillis().orElse(null);
+ return WebTargetBuilder.createClient(executorService, 1, Optional.ofNullable(readTimeout).orElse(DEFAULT_READ_TIMEOUT_MILLIS).longValue(), null);
+ }
}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/mail/MailClientBuilder.java b/agent/src/main/java/org/openremote/agent/protocol/mail/MailClientBuilder.java
index f103a3381..7bbaf61f7 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/mail/MailClientBuilder.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/mail/MailClientBuilder.java
@@ -19,26 +19,22 @@
*/
package org.openremote.agent.protocol.mail;
-import org.openremote.container.web.OAuthFilter;
-import org.openremote.container.web.WebTargetBuilder;
+import org.openremote.container.web.WebService;
import org.openremote.model.auth.OAuthGrant;
import org.openremote.model.auth.UsernamePassword;
-import jakarta.ws.rs.client.Client;
-import java.net.SocketException;
import java.nio.file.Path;
import java.util.Date;
import java.util.Objects;
import java.util.Properties;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.atomic.AtomicReference;
+import java.util.concurrent.*;
+
+import static org.openremote.container.web.WebTargetBuilder.getClient;
public class MailClientBuilder {
public static final String DEFAULT_FOLDER_NAME = "INBOX";
public static final int DEFAULT_CHECK_INTERVAL_SECONDS = 5 * 60;
protected static int MIN_CHECK_INTERVAL_SECONDS = 10;
- protected static final AtomicReference<Client> jaxrsClient = new AtomicReference<>();
protected ExecutorService executorService;
protected ScheduledExecutorService scheduledExecutorService;
protected int checkInitialDelaySeconds = 0;
@@ -50,7 +46,6 @@ public class MailClientBuilder {
protected String protocol;
protected String host;
protected OAuthGrant oAuthGrant;
- protected OAuthFilter oAuthFilter;
protected int port;
protected String user;
protected String password;
@@ -206,21 +201,12 @@ public class MailClientBuilder {
return new MailClient(this);
}
- public UsernamePassword getAuth() throws SocketException, NullPointerException {
+ public UsernamePassword getAuth() throws NullPointerException, ExecutionException, InterruptedException, TimeoutException {
Objects.requireNonNull(user, "User must be supplied");
if (oAuthGrant != null) {
- synchronized (jaxrsClient) {
- if (jaxrsClient.get() == null) {
- jaxrsClient.set(WebTargetBuilder.createClient(executorService));
- }
- }
- synchronized (this) {
- if (oAuthFilter == null) {
- oAuthFilter = new OAuthFilter(jaxrsClient.get(), oAuthGrant);
- }
- }
- return new UsernamePassword(user, oAuthFilter.getAccessToken());
+ String bearerToken = WebService.getBearerToken(executorService, getClient(), oAuthGrant).get(10000, TimeUnit.MILLISECONDS);
+ return new UsernamePassword(user, bearerToken);
}
Objects.requireNonNull(password, "Password must be supplied");
diff --git a/agent/src/main/java/org/openremote/agent/protocol/openweathermap/OpenWeatherMapProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/openweathermap/OpenWeatherMapProtocol.java
index e0f95164a..2e40f4172 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/openweathermap/OpenWeatherMapProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/openweathermap/OpenWeatherMapProtocol.java
@@ -19,18 +19,9 @@
*/
package org.openremote.agent.protocol.openweathermap;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ScheduledFuture;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicReference;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import org.jboss.resteasy.client.jaxrs.ResteasyClient;
+import jakarta.ws.rs.core.Response;
import org.openremote.agent.protocol.AbstractProtocol;
+import org.openremote.container.web.WebTargetBuilder;
import org.openremote.model.Container;
import org.openremote.model.asset.Asset;
import org.openremote.model.asset.agent.ConnectionStatus;
@@ -42,11 +33,17 @@ import org.openremote.model.attribute.MetaItem;
import org.openremote.model.datapoint.ValueDatapoint;
import org.openremote.model.geo.GeoJSONPoint;
import org.openremote.model.syslog.SyslogCategory;
-
-import jakarta.ws.rs.core.Response;
import org.openremote.model.util.UniqueIdentifierGenerator;
-import static org.openremote.container.web.WebTargetBuilder.createClient;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
import static org.openremote.model.value.MetaItemType.AGENT_LINK;
import static org.openremote.model.value.MetaItemType.HAS_PREDICTED_DATA_POINTS;
@@ -76,7 +73,6 @@ public class OpenWeatherMapProtocol extends AbstractProtocol<OpenWeatherMapAgent
private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, OpenWeatherMapProtocol.class);
public static final String PROTOCOL_DISPLAY_NAME = "OpenWeatherMap";
- private static final AtomicReference<ResteasyClient> client = new AtomicReference<>();
// Initial delay to allow system to populate agent links
private static final int INITIAL_POLLING_DELAY_MILLIS = 3000; // 3 seconds
@@ -86,7 +82,6 @@ public class OpenWeatherMapProtocol extends AbstractProtocol<OpenWeatherMapAgent
public OpenWeatherMapProtocol(OpenWeatherMapAgent agent) {
super(agent);
- initClient();
}
@Override
@@ -242,7 +237,7 @@ public class OpenWeatherMapProtocol extends AbstractProtocol<OpenWeatherMapAgent
* @return the OpenWeatherMapResponse from the API
*/
protected OpenWeatherMapResponse fetchWeatherData(String apiUrl) {
- try (Response response = client.get().target(apiUrl).request().get()) {
+ try (Response response = WebTargetBuilder.getClient().target(apiUrl).request().get()) {
if (response.getStatus() == 200) {
return response.readEntity(OpenWeatherMapResponse.class);
} else if (response.getStatus() == 401) {
@@ -380,7 +375,7 @@ public class OpenWeatherMapProtocol extends AbstractProtocol<OpenWeatherMapAgent
*/
protected boolean healthCheck() {
String apiUrl = buildApiUrl(0, 0);
- try (Response response = client.get().target(apiUrl).request().get()) {
+ try (Response response = WebTargetBuilder.getClient().target(apiUrl).request().get()) {
if (response.getStatus() != 200) {
LOG.warning("Health check failed with status: " + response.getStatus());
return false;
@@ -464,14 +459,6 @@ public class OpenWeatherMapProtocol extends AbstractProtocol<OpenWeatherMapAgent
"Weather data provided by OpenWeather (https://openweathermap.org/)"));
}
- protected static void initClient() {
- synchronized (client) {
- if (client.get() == null) {
- client.set(createClient(org.openremote.container.Container.SCHEDULED_EXECUTOR));
- }
- }
- }
-
/**
* Convert meters per second to kilometers per hour
*
diff --git a/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketAgentProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketAgentProtocol.java
index 69a0a65c7..f7a000f1f 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketAgentProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketAgentProtocol.java
@@ -25,9 +25,9 @@ import jakarta.ws.rs.client.Invocation;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.Response;
import org.apache.http.HttpHeaders;
-import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.util.BasicAuthHelper;
import org.openremote.agent.protocol.io.AbstractNettyIOClientProtocol;
+import org.openremote.container.web.WebService;
import org.openremote.container.web.WebTargetBuilder;
import org.openremote.model.Container;
import org.openremote.model.asset.agent.ConnectionStatus;
@@ -47,14 +47,13 @@ import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.logging.Logger;
import static org.openremote.agent.protocol.http.HTTPProtocol.DEFAULT_CONTENT_TYPE;
import static org.openremote.agent.protocol.http.HTTPProtocol.DEFAULT_HTTP_METHOD;
-import static org.openremote.container.web.WebTargetBuilder.createClient;
+import static org.openremote.container.web.WebTargetBuilder.getClient;
import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
/**
@@ -72,16 +71,14 @@ public class WebsocketAgentProtocol extends AbstractNettyIOClientProtocol<Websoc
public static final String PROTOCOL_DISPLAY_NAME = "Websocket Client";
private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, WebsocketAgentProtocol.class);
public static final int CONNECTED_SEND_DELAY_MILLIS = 2000;
- protected static final AtomicReference<ResteasyClient> resteasyClient = new AtomicReference<>();
protected List<Runnable> protocolConnectedTasks;
protected Map<AttributeRef, Runnable> attributeConnectedTasks;
protected Map<String, List<String>> clientHeaders;
protected final List<Pair<AttributeRef, Consumer<String>>> protocolMessageConsumers = new ArrayList<>();
+ protected WebService webService;
public WebsocketAgentProtocol(WebsocketAgent agent) {
super(agent);
-
- initClient();
}
@Override
@@ -89,10 +86,15 @@ public class WebsocketAgentProtocol extends AbstractNettyIOClientProtocol<Websoc
return PROTOCOL_DISPLAY_NAME;
}
+ @Override
+ protected void doStart(Container container) throws Exception {
+ super.doStart(container);
+ this.webService = container.getService(WebService.class);
+ }
+
@Override
protected void doStop(Container container) throws Exception {
super.doStop(container);
-
clientHeaders = null;
protocolConnectedTasks = null;
attributeConnectedTasks = null;
@@ -192,14 +194,6 @@ public class WebsocketAgentProtocol extends AbstractNettyIOClientProtocol<Websoc
attributeConnectedTasks.remove(attributeRef);
}
- protected static void initClient() {
- synchronized (resteasyClient) {
- if (resteasyClient.get() == null) {
- resteasyClient.set(createClient(org.openremote.container.Container.SCHEDULED_EXECUTOR));
- }
- }
- }
-
protected void onConnected() {
// Look for any subscriptions that need to be processed
if (protocolConnectedTasks != null) {
@@ -233,7 +227,7 @@ public class WebsocketAgentProtocol extends AbstractNettyIOClientProtocol<Websoc
try {
// Inject OAuth header
- String authHeaderValue = client.getAuthHeader().get();
+ String authHeaderValue = client.getAuthHeader().get(10000, TimeUnit.MILLISECONDS);
if (authHeaderValue != null) {
if (headers == null) {
headers = new MultivaluedHashMap<>();
@@ -289,7 +283,7 @@ public class WebsocketAgentProtocol extends AbstractNettyIOClientProtocol<Websoc
});
}
- WebTargetBuilder webTargetBuilder = new WebTargetBuilder(resteasyClient.get(), uri);
+ WebTargetBuilder webTargetBuilder = new WebTargetBuilder(getClient(), uri);
LOG.fine("Creating web target client for subscription '" + uri + "'");
Invocation.Builder request = webTargetBuilder.build().request();
diff --git a/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketIOClient.java b/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketIOClient.java
index 0dd6d373c..2d7425257 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketIOClient.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketIOClient.java
@@ -34,13 +34,12 @@ import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.handler.timeout.ReadTimeoutHandler;
-import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.openremote.agent.protocol.io.AbstractNettyIOClient;
import org.openremote.agent.protocol.io.IOClient;
-import org.openremote.container.web.OAuthFilter;
+import org.openremote.container.web.WebService;
import org.openremote.model.auth.OAuthGrant;
+import org.openremote.model.http.RequestParams;
import org.openremote.model.syslog.SyslogCategory;
-import org.openremote.model.util.TextUtil;
import javax.net.ssl.SSLException;
import java.net.InetSocketAddress;
@@ -54,8 +53,7 @@ import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
-import static org.openremote.container.web.WebTargetBuilder.CONNECTION_TIMEOUT_MILLISECONDS;
-import static org.openremote.container.web.WebTargetBuilder.createClient;
+import static org.openremote.container.web.WebTargetBuilder.getClient;
import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
/**
@@ -66,7 +64,6 @@ import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
public class WebsocketIOClient<T> extends AbstractNettyIOClient<T> {
private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, WebsocketIOClient.class);
- protected static ResteasyClient client;
// How long since the last read before a PING is sent
public static final long PING_MILLIS = 10000;
// How long to wait for a ping response (i.e. pong)
@@ -117,13 +114,6 @@ public class WebsocketIOClient<T> extends AbstractNettyIOClient<T> {
useSsl = "wss".equalsIgnoreCase(scheme);
}
- protected synchronized ResteasyClient getClient() {
- if (client == null) {
- client = createClient(executorService, 1, CONNECTION_TIMEOUT_MILLISECONDS, null);
- }
- return client;
- }
-
@Override
protected Class<? extends Channel> getChannelClass() {
return NioSocketChannel.class;
@@ -298,34 +288,11 @@ public class WebsocketIOClient<T> extends AbstractNettyIOClient<T> {
super.doDisconnect();
}
- /**
- * Get the auth header asynchronously
- */
- public CompletableFuture<String> getAuthHeader() {
+ protected CompletableFuture<String> getAuthHeader() {
if (oAuthGrant == null) {
return CompletableFuture.completedFuture(null);
}
-
- CompletableFuture<String> future = new CompletableFuture<>();
-
- executorService.submit(() -> {
- if (oAuthGrant != null) {
- LOG.finer("Retrieving OAuth access token: " + getClientUri());
-
- try {
- OAuthFilter oAuthFilter = new OAuthFilter(getClient(), oAuthGrant);
- String authHeaderValue = oAuthFilter.getAuthHeader();
- if (TextUtil.isNullOrEmpty(authHeaderValue)) {
- throw new RuntimeException("Returned access token is null");
- }
- LOG.finer("Retrieved access token via OAuth: " + getClientUri());
- future.complete(authHeaderValue);
- } catch (Exception e) {
- future.completeExceptionally(new Exception("Error retrieving OAuth access token for '" + getClientUri() + "': " + e.getMessage()));
- }
- }
- });
-
- return future;
+ return WebService.getBearerToken(executorService, getClient(), oAuthGrant)
+ .thenApply(bearerToken -> RequestParams.BEARER_AUTH_PREFIX + bearerToken);
}
}
diff --git a/container/src/main/java/org/openremote/container/Container.java b/container/src/main/java/org/openremote/container/Container.java
index f535f7417..c8edeb516 100644
--- a/container/src/main/java/org/openremote/container/Container.java
+++ b/container/src/main/java/org/openremote/container/Container.java
@@ -204,6 +204,13 @@ public class Container implements org.openremote.model.Container {
LOG.log(WARNING, "Exception thrown whilst trying to stop scheduled tasks", e);
}
+ try {
+ LOG.log(INFO, "Stopping executor");
+ EXECUTOR.shutdown();
+ } catch (Exception e) {
+ LOG.log(WARNING, "Exception thrown whilst trying to stop executor", e);
+ }
+
Metrics.globalRegistry.remove(meterRegistry);
PrometheusRegistry.defaultRegistry.clear();
meterRegistry = null;
diff --git a/container/src/main/java/org/openremote/container/security/BearerAuthClientRequestFilter.java b/container/src/main/java/org/openremote/container/security/BearerAuthClientRequestFilter.java
deleted file mode 100644
index 2e04c0220..000000000
--- a/container/src/main/java/org/openremote/container/security/BearerAuthClientRequestFilter.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright 2016, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.container.security;
-
-import jakarta.ws.rs.client.ClientRequestContext;
-import jakarta.ws.rs.client.ClientRequestFilter;
-import java.io.IOException;
-
-import static jakarta.ws.rs.core.HttpHeaders.AUTHORIZATION;
-import static org.openremote.container.web.WebClient.REQUEST_PROPERTY_ACCESS_TOKEN;
-
-/**
- * Add Bearer authentication header if request context is configured with accessToken.
- */
-public class BearerAuthClientRequestFilter implements ClientRequestFilter {
- @Override
- public void filter(ClientRequestContext requestContext) throws IOException {
- String accessToken = (String) requestContext.getConfiguration().getProperty(REQUEST_PROPERTY_ACCESS_TOKEN);
- if (accessToken != null) {
- String authorization = "Bearer " + accessToken;
- requestContext.getHeaders().add(AUTHORIZATION, authorization);
- }
- }
-}
-
diff --git a/container/src/main/java/org/openremote/container/security/ClientSecretRequestFilter.java b/container/src/main/java/org/openremote/container/security/ClientSecretRequestFilter.java
deleted file mode 100644
index db2daacb2..000000000
--- a/container/src/main/java/org/openremote/container/security/ClientSecretRequestFilter.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright 2016, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.container.security;
-
-import jakarta.ws.rs.client.ClientRequestContext;
-import jakarta.ws.rs.client.ClientRequestFilter;
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.util.Base64;
-
-import static jakarta.ws.rs.core.HttpHeaders.AUTHORIZATION;
-import static org.openremote.container.web.WebClient.REQUEST_PROPERTY_CLIENT_ID;
-import static org.openremote.container.web.WebClient.REQUEST_PROPERTY_CLIENT_SECRET;
-
-/**
- * Add Basic authentication header if request context is configured with clientId and clientSecret.
- */
-public class ClientSecretRequestFilter implements ClientRequestFilter {
-
- @Override
- public void filter(ClientRequestContext requestContext) throws IOException {
- String clientId = (String) requestContext.getConfiguration().getProperty(REQUEST_PROPERTY_CLIENT_ID);
- String clientSecret = (String) requestContext.getConfiguration().getProperty(REQUEST_PROPERTY_CLIENT_SECRET);
- if (clientSecret != null) {
- try {
- String authorization = "Basic " + Base64.getEncoder().encodeToString(
- (clientId + ":" + clientSecret).getBytes("utf-8")
- );
- requestContext.getHeaders().add(AUTHORIZATION, authorization);
- } catch (UnsupportedEncodingException ex) {
- throw new RuntimeException(ex);
- }
- }
- }
-}
-
diff --git a/container/src/main/java/org/openremote/container/security/keycloak/KeycloakIdentityProvider.java b/container/src/main/java/org/openremote/container/security/keycloak/KeycloakIdentityProvider.java
index 0a50bccea..44cba4558 100644
--- a/container/src/main/java/org/openremote/container/security/keycloak/KeycloakIdentityProvider.java
+++ b/container/src/main/java/org/openremote/container/security/keycloak/KeycloakIdentityProvider.java
@@ -32,7 +32,6 @@ import jakarta.ws.rs.NotFoundException;
import jakarta.ws.rs.core.UriBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
-import org.jboss.resteasy.client.jaxrs.internal.ResteasyClientBuilderImpl;
import org.keycloak.KeycloakPrincipal;
import org.keycloak.KeycloakSecurityContext;
import org.keycloak.adapters.KeycloakConfigResolver;
@@ -42,8 +41,6 @@ import org.keycloak.admin.client.resource.RealmsResource;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.adapters.config.AdapterConfig;
import org.openremote.container.security.IdentityProvider;
-import org.openremote.container.web.OAuthFilter;
-import org.openremote.container.web.WebClient;
import org.openremote.container.web.WebService;
import org.openremote.container.web.WebTargetBuilder;
import org.openremote.model.Constants;
@@ -60,14 +57,11 @@ import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ConcurrentLinkedQueue;
-import java.util.concurrent.TimeUnit;
import java.util.function.Function;
-import java.util.function.Supplier;
import java.util.logging.Level;
import java.util.logging.Logger;
import static java.util.concurrent.TimeUnit.MINUTES;
-import static org.openremote.container.web.WebClient.getTarget;
import static org.openremote.model.Constants.*;
import static org.openremote.model.util.MapAccess.getInteger;
import static org.openremote.model.util.MapAccess.getString;
@@ -92,12 +86,8 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
public static final int OR_KEYCLOAK_PORT_DEFAULT = 8081;
public static final String OR_KEYCLOAK_PATH = "OR_KEYCLOAK_PATH";
public static final String OR_KEYCLOAK_PATH_DEFAULT = "/auth";
- public static final String KEYCLOAK_CONNECT_TIMEOUT = "KEYCLOAK_CONNECT_TIMEOUT";
- public static final int KEYCLOAK_CONNECT_TIMEOUT_DEFAULT = 2000;
public static final String KEYCLOAK_REQUEST_TIMEOUT = "KEYCLOAK_REQUEST_TIMEOUT";
public static final int KEYCLOAK_REQUEST_TIMEOUT_DEFAULT = 10000;
- public static final String KEYCLOAK_CLIENT_POOL_SIZE = "KEYCLOAK_CLIENT_POOL_SIZE";
- public static final int KEYCLOAK_CLIENT_POOL_SIZE_DEFAULT = 20;
public static final String OR_IDENTITY_SESSION_MAX_MINUTES = "OR_IDENTITY_SESSION_MAX_MINUTES";
public static final int OR_IDENTITY_SESSION_MAX_MINUTES_DEFAULT = 60 * 24; // 1 day
public static final String OR_IDENTITY_SESSION_OFFLINE_TIMEOUT_MINUTES = "OR_IDENTITY_SESSION_OFFLINE_TIMEOUT_MINUTES";
@@ -111,8 +101,6 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
protected int sessionOfflineTimeoutSeconds;
// This will pass authentication ("NOT ATTEMPTED" state), but later fail any role authorization
final protected KeycloakDeployment notAuthenticatedKeycloakDeployment = new KeycloakDeployment();
- // The client we use to access Keycloak
- protected ResteasyClient httpClient;
protected ResteasyWebTarget keycloakTarget;
protected OAuthGrant oAuthGrant;
protected ConcurrentLinkedQueue<RealmsResource> realmsResourcePool = new ConcurrentLinkedQueue<>();
@@ -144,10 +132,6 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
@Override
public void init(Container container) {
- if (httpClient != null) {
- return;
- }
-
sessionMaxSeconds = getInteger(container.getConfig(), OR_IDENTITY_SESSION_MAX_MINUTES, OR_IDENTITY_SESSION_MAX_MINUTES_DEFAULT) * 60;
if (sessionMaxSeconds < 60) {
throw new IllegalArgumentException(OR_IDENTITY_SESSION_MAX_MINUTES + " must be more than 1 minute");
@@ -175,20 +159,6 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
LOG.info("Keycloak service URL: " + keycloakServiceUri.build());
- ResteasyClientBuilderImpl clientBuilder = new ResteasyClientBuilderImpl()
- .connectTimeout(
- getInteger(container.getConfig(), KEYCLOAK_CONNECT_TIMEOUT, KEYCLOAK_CONNECT_TIMEOUT_DEFAULT),
- TimeUnit.MILLISECONDS
- )
- .readTimeout(
- getInteger(container.getConfig(), KEYCLOAK_REQUEST_TIMEOUT, KEYCLOAK_REQUEST_TIMEOUT_DEFAULT),
- TimeUnit.MILLISECONDS
- )
- .connectionPoolSize(
- getInteger(container.getConfig(), KEYCLOAK_CLIENT_POOL_SIZE, KEYCLOAK_CLIENT_POOL_SIZE_DEFAULT)
- );
- httpClient = WebClient.registerDefaults(clientBuilder).build();
-
keycloakDeploymentCache = createKeycloakDeploymentCache();
keycloakConfigResolver = request -> {
@@ -258,8 +228,6 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
@Override
public void stop(Container container) {
- if (httpClient != null)
- httpClient.close();
}
@Override
@@ -321,21 +289,6 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
return keycloakServiceUri.clone().path("realms").path(realm).path("protocol/openid-connect/token").build();
}
- /**
- * Convenience method for generating access tokens from a given OAuth compliant server
- */
- public Supplier<String> getAccessTokenSupplier(OAuthGrant grant) {
- OAuthFilter oAuthFilter = new OAuthFilter(httpClient, grant);
- return () -> {
- try {
- return oAuthFilter.getAccessToken();
- } catch (Exception e) {
- LOG.log(Level.INFO, "Failed to get OAuth access token using grant: " + grant, e);
- }
- return null;
- };
- }
-
/**
* Update the active credentials used to perform keycloak API actions; the token endpoint will be overwritten with this
* instances keycloak server URI and for the master realm.
@@ -354,7 +307,7 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
}
URI proxyURI = keycloakServiceUri.build();
- WebTargetBuilder targetBuilder = new WebTargetBuilder(httpClient, proxyURI)
+ WebTargetBuilder targetBuilder = new WebTargetBuilder(WebTargetBuilder.getClient(), proxyURI)
.setOAuthAuthentication(grant);
keycloakTarget = targetBuilder.build();
realmsResourcePool.clear();
@@ -393,7 +346,7 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
LOG.finest("Loading adapter config for client '" + keycloakRealmClient.clientId + "' in realm '" + keycloakRealmClient.realm + "'");
//KeycloakResource keycloak = getKeycloak();
- KeycloakResource keycloak = getTarget(httpClient, keycloakServiceUri.build(), null, null, null).proxy(KeycloakResource.class);
+ KeycloakResource keycloak = new WebTargetBuilder(WebTargetBuilder.getClient(), keycloakServiceUri.build()).build().proxy(KeycloakResource.class);
// Can't get adapter for client in another realm
AdapterConfig adapterConfig = keycloak.getAdapterConfig(
diff --git a/container/src/main/java/org/openremote/container/web/ClientErrorExceptionHandler.java b/container/src/main/java/org/openremote/container/web/ClientErrorExceptionHandler.java
index 65fb2951a..7fa6d5f3a 100644
--- a/container/src/main/java/org/openremote/container/web/ClientErrorExceptionHandler.java
+++ b/container/src/main/java/org/openremote/container/web/ClientErrorExceptionHandler.java
@@ -32,7 +32,7 @@ public class ClientErrorExceptionHandler implements ExceptionMapper<ClientErrorE
@Override
public Response toResponse(ClientErrorException exception) {
- // We must build a new Response, and not just pass on the exception's ("Apache HttpClient") response
- return Response.status(exception.getResponse().getStatus()).build();
+ // Build a new local response while preserving status, headers and entity from the original response.
+ return Response.fromResponse(exception.getResponse()).build();
}
}
diff --git a/container/src/main/java/org/openremote/container/web/LoggingFilter.java b/container/src/main/java/org/openremote/container/web/LoggingFilter.java
new file mode 100644
index 000000000..cf931a9d0
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/web/LoggingFilter.java
@@ -0,0 +1,290 @@
+/*
+ * Copyright 2026, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.container.web;
+
+import jakarta.servlet.*;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import jakarta.servlet.http.HttpServletResponseWrapper;
+import jakarta.ws.rs.ext.Provider;
+import org.openremote.model.Constants;
+import org.openremote.model.syslog.SyslogCategory;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
+import java.security.Principal;
+
+/**
+ * A servlet {@link jakarta.servlet.Filter} that logs requests and responses to the {@link #LOG}.
+ */
+@Provider
+public class LoggingFilter implements Filter {
+
+ protected static final int MAX_BODY_BYTES = 1024;
+ protected static final String ORIGIN_HEADER = "Origin";
+ protected static final String FORWARDED_FOR_HEADER = "X-Forwarded-For";
+ public static final String FILTER_APPLIED_ATTR = LoggingFilter.class.getName() + ".FILTER_APPLIED";
+ protected static final System.Logger LOG = System.getLogger(LoggingFilter.class.getName() + "." + SyslogCategory.API.name());
+ protected final boolean devMode;
+
+ public LoggingFilter() {
+ this(false);
+ }
+
+ public LoggingFilter(boolean devMode) {
+ this.devMode = devMode;
+ }
+
+ public static void logException(boolean devMode, String source, System.Logger.Level level, Throwable t) {
+ logException(devMode, source, level, t, null, null, null);
+ }
+
+ public static void logException(
+ boolean devMode,
+ String source,
+ System.Logger.Level level,
+ Throwable t,
+ HttpServletRequest req,
+ Integer status,
+ String contentType
+ ) {
+ if (t == null) {
+ return;
+ }
+
+ if (LOG.isLoggable(level)) {
+ String message = buildHttpLogMessage(req, status, contentType, null, null, t, source);
+ if (devMode || level.getSeverity() >= System.Logger.Level.INFO.getSeverity()) {
+ LOG.log(level, message, t);
+ } else {
+ LOG.log(level, message);
+ }
+ }
+ }
+
+ protected static String buildHttpLogMessage(
+ HttpServletRequest req,
+ Integer status,
+ String contentType,
+ String body,
+ Long tookMillis,
+ Throwable thrown,
+ String source
+ ) {
+ String method = req != null ? req.getMethod() : null;
+ String requestPathAndQuery = req != null
+ ? req.getRequestURI() + (req.getQueryString() != null ? "?" + req.getQueryString() : "")
+ : null;
+ String requestRealm = req != null ? req.getHeader(Constants.REALM_PARAM_NAME) : null;
+ Principal principal = req != null ? req.getUserPrincipal() : null;
+ String username = principal != null ? principal.getName() : null;
+ String origin = req != null ? req.getHeader(ORIGIN_HEADER) : null;
+ String forwardedFor = req != null ? req.getHeader(FORWARDED_FOR_HEADER) : null;
+
+ return "HTTP request={"
+ + "method=" + method
+ + ", path=" + requestPathAndQuery
+ + ", requestRealm=" + requestRealm
+ + ", username=" + username
+ + ", origin=" + origin
+ + ", forwarded-for=" + forwardedFor
+ + "}, response={"
+ + (source != null ? "source=" + source + ", " : "")
+ + (tookMillis != null ? "tookMillis=" + tookMillis + ", " : "")
+ + "status=" + status
+ + ", contentType=" + contentType
+ + (body != null ? ", body=" + body : "")
+ + (thrown != null ? ", exception=" + thrown.getClass().getName() + ": " + thrown.getMessage() : "")
+ + "}";
+ }
+
+ /**
+ * Minimal response wrapper that tees response body into a buffer while still writing to the real response.
+ */
+ static final class BufferingHttpServletResponse extends HttpServletResponseWrapper {
+
+ private final ByteArrayOutputStream capture;
+ private final int maxBytes;
+ private int httpStatus = HttpServletResponse.SC_OK;
+ private PrintWriter teeWriter;
+
+ BufferingHttpServletResponse(HttpServletResponse response, int maxBytes) {
+ super(response);
+ this.capture = new ByteArrayOutputStream(Math.min(maxBytes, 8 * 1024));
+ this.maxBytes = maxBytes;
+ }
+
+ @Override
+ public void setStatus(int sc) {
+ this.httpStatus = sc;
+ super.setStatus(sc);
+ }
+
+ @Override
+ public void sendError(int sc) throws IOException {
+ this.httpStatus = sc;
+ super.sendError(sc);
+ }
+
+ @Override
+ public void sendError(int sc, String msg) throws IOException {
+ this.httpStatus = sc;
+ super.sendError(sc, msg);
+ }
+
+ @Override
+ public PrintWriter getWriter() throws IOException {
+ if (teeWriter != null) {
+ return teeWriter;
+ }
+
+ Charset cs = getCharacterEncoding() != null ? Charset.forName(getCharacterEncoding()) : StandardCharsets.UTF_8;
+
+ PrintWriter real = super.getWriter();
+ teeWriter = new PrintWriter(new TeeWriter(real, capture, cs, maxBytes), true);
+ return teeWriter;
+ }
+
+ @Override
+ public int getStatus() {
+ return httpStatus;
+ }
+
+ String getCapturedBodyAsString() {
+ Charset cs = getCharacterEncoding() != null ? Charset.forName(getCharacterEncoding()) : StandardCharsets.UTF_8;
+ return capture.toString(cs);
+ }
+ }
+
+ static final class TeeWriter extends java.io.Writer {
+ private final PrintWriter downstream;
+ private final ByteArrayOutputStream capture;
+ private final Charset charset;
+ private final int maxBytes;
+
+ TeeWriter(PrintWriter downstream, ByteArrayOutputStream capture, Charset charset, int maxBytes) {
+ this.downstream = downstream;
+ this.capture = capture;
+ this.charset = charset;
+ this.maxBytes = maxBytes;
+ }
+
+ @Override
+ public void write(char[] cbuf, int off, int len) {
+ downstream.write(cbuf, off, len);
+
+ if (capture.size() < maxBytes) {
+ byte[] bytes = new String(cbuf, off, len).getBytes(charset);
+ int remaining = maxBytes - capture.size();
+ capture.write(bytes, 0, Math.min(remaining, bytes.length));
+ }
+ }
+
+ @Override
+ public void flush() {
+ downstream.flush();
+ }
+
+ @Override
+ public void close() {
+ downstream.close();
+ }
+ }
+
+ @Override
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
+
+ if (!(request instanceof HttpServletRequest req) || !(response instanceof HttpServletResponse res)) {
+ chain.doFilter(request, response);
+ return;
+ }
+
+ req.setAttribute(FILTER_APPLIED_ATTR, Boolean.TRUE);
+
+ final long startNanos = System.nanoTime();
+ final boolean traceEnabled = LOG.isLoggable(System.Logger.Level.TRACE);
+
+ HttpServletResponse effectiveResponse = res;
+ BufferingHttpServletResponse wrapped = null;
+
+ if (traceEnabled) {
+ wrapped = new BufferingHttpServletResponse(res, MAX_BODY_BYTES);
+ effectiveResponse = wrapped;
+ }
+
+ Throwable thrown = null;
+
+ try {
+ chain.doFilter(request, effectiveResponse);
+ } catch (Throwable t) {
+ thrown = t;
+ // Ensure status is at least 500 if nothing was set
+ if (effectiveResponse.getStatus() < 400) {
+ effectiveResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ }
+ throw t;
+ } finally {
+ long tookMillis = (System.nanoTime() - startNanos) / 1_000_000;
+ int status = effectiveResponse.getStatus();
+
+ if (traceEnabled || status >= 400 || thrown != null) {
+
+ System.Logger.Level level = (status >= 500 || thrown != null)
+ ? System.Logger.Level.WARNING
+ : status >= 400 ? System.Logger.Level.TRACE : System.Logger.Level.DEBUG;
+
+ if (LOG.isLoggable(level)) {
+ String contentType = effectiveResponse.getContentType();
+ String body = null;
+
+ if (traceEnabled) {
+ boolean isTextual = contentType == null
+ || contentType.startsWith("text/")
+ || contentType.contains("json")
+ || contentType.contains("xml")
+ || contentType.contains("problem+json");
+ if (isTextual) {
+ body = wrapped.getCapturedBodyAsString();
+ }
+ }
+
+ String message = buildHttpLogMessage(
+ req,
+ status,
+ contentType,
+ traceEnabled ? body : null,
+ tookMillis,
+ thrown,
+ null
+ );
+
+ if (thrown != null && (devMode || level.getSeverity() >= System.Logger.Level.INFO.getSeverity())) {
+ LOG.log(level, message, thrown);
+ } else {
+ LOG.log(level, message);
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/container/src/main/java/org/openremote/container/web/OAuthFilter.java b/container/src/main/java/org/openremote/container/web/OAuthFilter.java
index ec4615b0f..a9ad264c5 100644
--- a/container/src/main/java/org/openremote/container/web/OAuthFilter.java
+++ b/container/src/main/java/org/openremote/container/web/OAuthFilter.java
@@ -22,6 +22,7 @@ package org.openremote.container.web;
import org.jboss.resteasy.util.BasicAuthHelper;
import org.openremote.model.auth.OAuthGrant;
import org.openremote.model.auth.OAuthRefreshTokenGrant;
+import org.openremote.model.http.RequestParams;
import org.openremote.model.syslog.SyslogCategory;
import org.openremote.model.util.TextUtil;
@@ -44,7 +45,6 @@ import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
public class OAuthFilter implements ClientRequestFilter {
private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, OAuthFilter.class);
- public static final String BEARER_AUTH = "Bearer";
protected OAuthServerResponse authServerResponse;
protected Client client;
protected WebTarget authTarget;
@@ -62,7 +62,7 @@ public class OAuthFilter implements ClientRequestFilter {
String accessToken = getAccessToken();
if (!TextUtil.isNullOrEmpty(accessToken)) {
- return BEARER_AUTH + " " + accessToken;
+ return RequestParams.BEARER_AUTH_PREFIX + accessToken;
}
return null;
diff --git a/container/src/main/java/org/openremote/container/web/ProxyClientRequestFilter.java b/container/src/main/java/org/openremote/container/web/ProxyClientRequestFilter.java
deleted file mode 100644
index 84c997ee3..000000000
--- a/container/src/main/java/org/openremote/container/web/ProxyClientRequestFilter.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright 2016, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.container.web;
-
-import jakarta.ws.rs.client.ClientRequestContext;
-import jakarta.ws.rs.client.ClientRequestFilter;
-import java.io.IOException;
-
-import static org.openremote.container.web.WebClient.*;
-
-/**
- * Add X-Forwarded-* headers if request context is configured with values.
- */
-public class ProxyClientRequestFilter implements ClientRequestFilter {
-
- @Override
- public void filter(ClientRequestContext requestContext) throws IOException {
- String forwardedFor = (String) requestContext.getConfiguration().getProperty(REQUEST_PROPERTY_X_FORWARDED_FOR);
- if (forwardedFor != null) {
- requestContext.getHeaders().add("X-Forwarded-For", forwardedFor);
- }
- String forwardedHost = (String) requestContext.getConfiguration().getProperty(REQUEST_PROPERTY_X_FORWARDED_HOST);
- if (forwardedHost != null) {
- requestContext.getHeaders().add("X-Forwarded-Host", forwardedHost);
- }
- String forwardedProto = (String) requestContext.getConfiguration().getProperty(REQUEST_PROPERTY_X_FORWARDED_PROTO);
- if (forwardedProto != null) {
- requestContext.getHeaders().add("X-Forwarded-Proto", forwardedProto);
- }
- Integer forwardedPort = (Integer) requestContext.getConfiguration().getProperty(REQUEST_PROPERTY_X_FORWARDED_PORT);
- if (forwardedPort != null && forwardedPort > 0) {
- requestContext.getHeaders().add("X-Forwarded-Port", forwardedPort);
- }
- }
-}
-
diff --git a/container/src/main/java/org/openremote/container/web/RequestLogger.java b/container/src/main/java/org/openremote/container/web/RequestLogger.java
deleted file mode 100644
index 2454a8ca1..000000000
--- a/container/src/main/java/org/openremote/container/web/RequestLogger.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright 2023, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.container.web;
-
-import org.openremote.container.security.keycloak.KeycloakIdentityProvider;
-import org.openremote.model.Constants;
-import org.openremote.model.syslog.SyslogCategory;
-
-import jakarta.servlet.http.HttpServletRequest;
-import jakarta.ws.rs.container.ContainerRequestContext;
-import jakarta.ws.rs.container.ContainerRequestFilter;
-import jakarta.ws.rs.core.Context;
-import jakarta.ws.rs.core.HttpHeaders;
-import jakarta.ws.rs.core.SecurityContext;
-import jakarta.ws.rs.ext.Provider;
-import java.io.IOException;
-
-/**
- * JAX-RS {@link ContainerRequestFilter} that logs incoming requests to the {@link #REQUEST_LOG}.
- */
-@Provider
-public class RequestLogger implements ContainerRequestFilter {
-
- protected static final System.Logger REQUEST_LOG = System.getLogger(RequestLogger.class.getName() + "." + SyslogCategory.API.name());
-
- @Context
- private HttpServletRequest request;
-
- @Context
- protected SecurityContext securityContext;
-
- @Override
- public void filter(ContainerRequestContext requestContext) throws IOException {
- REQUEST_LOG.log(System.Logger.Level.DEBUG, () -> {
- String requestPath = request.getRequestURI();
- String address = request.getRemoteAddr();
- String port = String.valueOf(request.getRemotePort());
- String forwardedAddress = requestContext.getHeaderString("X-Forwarded-For");
- String method = requestContext.getMethod();
- String realm = requestContext.getHeaderString(Constants.REALM_PARAM_NAME);
- String responseType = requestContext.getHeaderString(HttpHeaders.ACCEPT);
- String usernameAndRealm = securityContext != null
- ? KeycloakIdentityProvider.getSubjectNameAndRealm(securityContext.getUserPrincipal())
- : null;
-
- return "Client request '" + method + " " + requestPath +" (responseType=" + responseType
- + ")', requestRealm=" + realm + ", username="+ usernameAndRealm + ", origin="
- + address + ":" + port + ", forwarded-for=" + forwardedAddress;
- });
- }
-}
diff --git a/container/src/main/java/org/openremote/container/web/WebClient.java b/container/src/main/java/org/openremote/container/web/WebClient.java
deleted file mode 100644
index 112ccde55..000000000
--- a/container/src/main/java/org/openremote/container/web/WebClient.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright 2016, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.container.web;
-
-import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
-import org.jboss.resteasy.client.jaxrs.internal.ResteasyClientBuilderImpl;
-import org.jboss.resteasy.plugins.interceptors.GZIPDecodingInterceptor;
-import org.openremote.container.json.JacksonConfig;
-import org.openremote.container.security.BearerAuthClientRequestFilter;
-import org.openremote.container.security.ClientSecretRequestFilter;
-
-import jakarta.ws.rs.client.Client;
-import java.net.URI;
-
-public interface WebClient {
-
- String REQUEST_PROPERTY_ACCESS_TOKEN = WebClient.class.getName() + ".accessToken";
- String REQUEST_PROPERTY_CLIENT_ID = WebClient.class.getName() + ".clientId";
- String REQUEST_PROPERTY_CLIENT_SECRET = WebClient.class.getName() + ".clientSecret";
- String REQUEST_PROPERTY_X_FORWARDED_FOR = WebClient.class.getName() + ".xForwardedFor";
- String REQUEST_PROPERTY_X_FORWARDED_HOST = WebClient.class.getName() + ".xForwardedHost";
- String REQUEST_PROPERTY_X_FORWARDED_PROTO = WebClient.class.getName() + ".xForwardedProto";
- String REQUEST_PROPERTY_X_FORWARDED_PORT = WebClient.class.getName() + ".xForwardedPort";
-
- static ResteasyClientBuilderImpl registerDefaults(ResteasyClientBuilderImpl builder) {
- return builder
- .register(new JacksonConfig())
- .register(new ProxyClientRequestFilter())
- .register(new BearerAuthClientRequestFilter())
- .register(new ClientSecretRequestFilter())
- .register(new GZIPDecodingInterceptor());
- }
-
- static ResteasyWebTarget getTarget(Client client, URI uri, String accessToken, String forwardFor, URI forwardUri) {
- return getTarget(
- client,
- uri,
- accessToken,
- forwardFor,
- forwardUri != null ? forwardUri.getHost() : null,
- forwardUri != null ? forwardUri.getScheme() : null,
- forwardUri != null ? forwardUri.getPort() : null
- );
- }
-
- static ResteasyWebTarget getTarget(Client client, URI uri, String accessToken, String forwardFor, String forwardHost, String forwardProto, Integer forwardPort) {
- ResteasyWebTarget target = ((ResteasyWebTarget) client.target(uri));
- if (accessToken != null) {
- target.property(REQUEST_PROPERTY_ACCESS_TOKEN, accessToken);
- }
- if (forwardFor != null) {
- target.property(REQUEST_PROPERTY_X_FORWARDED_FOR, forwardFor);
- }
- if (forwardHost != null) {
- target.property(REQUEST_PROPERTY_X_FORWARDED_HOST, forwardHost);
- }
- if (forwardProto != null) {
- target.property(REQUEST_PROPERTY_X_FORWARDED_PROTO, forwardProto);
- }
- if (forwardPort != null) {
- target.property(REQUEST_PROPERTY_X_FORWARDED_PORT, forwardPort);
- }
- return target;
- }
-
- static ResteasyWebTarget getTarget(Client client, URI uri, String clientId, String clientSecret) {
- ResteasyWebTarget target = getTarget(client, uri, null, null, null, null, null);
- if (clientId != null) {
- target.property(REQUEST_PROPERTY_CLIENT_ID, clientId);
- }
- if (clientSecret != null) {
- target.property(REQUEST_PROPERTY_CLIENT_SECRET, clientSecret);
- }
- return target;
- }
-
- static <T> T getTargetResource(ResteasyWebTarget target, Class<T> resourceType) {
- return target.proxy(resourceType);
- }
-}
diff --git a/container/src/main/java/org/openremote/container/web/WebService.java b/container/src/main/java/org/openremote/container/web/WebService.java
index 39cab200f..137ba9c87 100644
--- a/container/src/main/java/org/openremote/container/web/WebService.java
+++ b/container/src/main/java/org/openremote/container/web/WebService.java
@@ -44,6 +44,8 @@ import io.undertow.util.Headers;
import io.undertow.util.HttpString;
import io.undertow.websockets.core.WebSocketChannel;
import jakarta.servlet.*;
+import jakarta.validation.constraints.NotNull;
+import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.core.Application;
import jakarta.ws.rs.core.UriBuilder;
import org.jboss.resteasy.core.ResteasyDeploymentImpl;
@@ -53,6 +55,7 @@ import org.openremote.container.json.JacksonConfig;
import org.openremote.container.security.IdentityService;
import org.openremote.model.Container;
import org.openremote.model.ContainerService;
+import org.openremote.model.auth.OAuthGrant;
import org.openremote.model.http.HTTPMethod;
import org.openremote.model.util.Config;
import org.openremote.model.util.TextUtil;
@@ -62,6 +65,8 @@ import java.net.Inet4Address;
import java.net.URI;
import java.nio.file.Path;
import java.util.*;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;
import static java.lang.System.Logger.Level.*;
@@ -95,6 +100,7 @@ public abstract class WebService implements ContainerService {
protected boolean devMode;
protected String host;
protected IdentityService identityService;
+ protected ExecutorService executorService;
protected int port;
protected Undertow undertow;
protected long maxEntitySize = OR_WEBSERVER_MAX_ENTITY_SIZE_DEFAULT;
@@ -102,7 +108,7 @@ public abstract class WebService implements ContainerService {
protected URI containerHostUri;
protected PathHandler pathHandler = Handlers.path();
- public static final Map<String, String> MIME_TYPES = Map.of(
+ public static final Map<String, String> MIME_TYPES = Map.of(
"pbf", "application/x-protobuf",
"wsdl", "application/xml",
"xsl", "text/xsl");
@@ -124,6 +130,7 @@ public abstract class WebService implements ContainerService {
@Override
public void init(Container container) throws Exception {
identityService = container.getService(IdentityService.class);
+ executorService = container.getExecutor();
devMode = container.isDevMode();
Map<String, String> config = container.getConfig();
@@ -250,12 +257,9 @@ public abstract class WebService implements ContainerService {
*/
public static List<Object> getStandardProviders(boolean devMode, Integer realmIndex) {
List<Object> providers = Lists.newArrayList(
- new RequestLogger(),
- new WebServiceExceptions.DefaultResteasyExceptionMapper(devMode),
- new WebServiceExceptions.ForbiddenResteasyExceptionMapper(devMode),
- new WebServiceExceptions.ServletUndertowExceptionHandler(devMode),
- new JacksonConfig(),
- new ClientErrorExceptionHandler()
+ new WebServiceExceptions.JAXRSExceptionMapper(devMode),
+ new JacksonConfig(),
+ new ClientErrorExceptionHandler()
);
if (realmIndex != null) {
@@ -336,7 +340,6 @@ public abstract class WebService implements ContainerService {
if (secure) {
deployment.setSecurityEnabled(true);
- //servlet.setInitParameter(ResteasyContextParameters.RESTEASY_ROLE_BASED_SECURITY, "true");
}
}
};
@@ -429,7 +432,6 @@ public abstract class WebService implements ContainerService {
boolean secure,
CORSConfig corsOverride) {
-
if (corsOverride == null) {
// Just use default CORS config
corsOverride = new CORSConfig();
@@ -489,6 +491,14 @@ public abstract class WebService implements ContainerService {
identityService.secureDeployment(deploymentInfo);
}
+ Filter loggingFilter = new LoggingFilter(devMode);
+ FilterInfo loggingFilterInfo = Servlets.filter(
+ "Logging Filter",
+ LoggingFilter.class,
+ () -> new ImmediateInstanceHandle<>(loggingFilter)).setAsyncSupported(true);
+ deploymentInfo.addFilter(loggingFilterInfo);
+ deploymentInfo.addFilterUrlMapping("Logging Filter","/*", DispatcherType.REQUEST);
+
// Cannot set config on constructor as init method will overwrite it
CORSFilter corsFilter = new CORSFilter();
@@ -498,10 +508,10 @@ public abstract class WebService implements ContainerService {
() -> new ImmediateInstanceHandle<>(corsFilter)).setAsyncSupported(true);
getCORSConfiguration(corsOverride).forEach((k,v) -> corsFilterInfo.addInitParam(k.toString(), v.toString()));
deploymentInfo.addFilter(corsFilterInfo);
- deploymentInfo.addFilterUrlMapping( "CORS Filter","/*", DispatcherType.REQUEST);
+ deploymentInfo.addFilterUrlMapping("CORS Filter","/*", DispatcherType.REQUEST);
// This will catch anything not handled by Resteasy/Servlets, such as IOExceptions "at the wrong time"
- deploymentInfo.setExceptionHandler(new WebServiceExceptions.ServletUndertowExceptionHandler(devMode));
+ deploymentInfo.setExceptionHandler(new WebServiceExceptions.ServletExceptionHandler(devMode));
}
public Undertow getUndertow() {
@@ -551,4 +561,36 @@ public abstract class WebService implements ContainerService {
return props;
}
+
+ public CompletableFuture<String> getBearerToken(@NotNull OAuthGrant oAuthGrant) {
+ return getBearerToken(executorService, WebTargetBuilder.getClient(), oAuthGrant);
+ }
+
+ /**
+ * Retrieve bearer tokens for the provided {@link OAuthGrant}.
+ */
+ public static CompletableFuture<String> getBearerToken(ExecutorService executorService, Client client, @NotNull OAuthGrant oAuthGrant) {
+ if (oAuthGrant == null) {
+ return CompletableFuture.failedFuture(new NullPointerException(OAuthGrant.class.getSimpleName() + " cannot be null"));
+ }
+ CompletableFuture<String> future = new CompletableFuture<>();
+
+ executorService.submit(() -> {
+ LOG.log(DEBUG, "Retrieving OAuth access token: " + oAuthGrant);
+
+ try {
+ OAuthFilter oAuthFilter = new OAuthFilter(client, oAuthGrant);
+ String authHeaderValue = oAuthFilter.getAccessToken();
+ if (TextUtil.isNullOrEmpty(authHeaderValue)) {
+ throw new RuntimeException("Returned access token is null");
+ }
+ LOG.log(DEBUG,"Retrieved access token via OAuth: " + oAuthGrant);
+ future.complete(authHeaderValue);
+ } catch (Exception e) {
+ future.completeExceptionally(new Exception("Error retrieving OAuth access token for '" + oAuthGrant + "': " + e.getMessage()));
+ }
+ });
+
+ return future;
+ }
}
diff --git a/container/src/main/java/org/openremote/container/web/WebServiceExceptions.java b/container/src/main/java/org/openremote/container/web/WebServiceExceptions.java
index bd002c943..3934a0f76 100644
--- a/container/src/main/java/org/openremote/container/web/WebServiceExceptions.java
+++ b/container/src/main/java/org/openremote/container/web/WebServiceExceptions.java
@@ -22,21 +22,18 @@ package org.openremote.container.web;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.servlet.api.ExceptionHandler;
-import io.undertow.util.HttpString;
-
+import io.undertow.util.Headers;
import jakarta.persistence.OptimisticLockException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
-import jakarta.ws.rs.ForbiddenException;
+import jakarta.servlet.http.HttpServletRequest;
import jakarta.ws.rs.NotAllowedException;
import jakarta.ws.rs.WebApplicationException;
-import jakarta.ws.rs.core.*;
+import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
-import jakarta.ws.rs.ext.Provider;
+
import java.io.PrintWriter;
import java.io.StringWriter;
-import java.util.logging.Level;
-import java.util.logging.Logger;
import static jakarta.ws.rs.core.MediaType.TEXT_PLAIN_TYPE;
@@ -50,160 +47,188 @@ import static jakarta.ws.rs.core.MediaType.TEXT_PLAIN_TYPE;
* debug logging is enabled. We never want to send a stacktrace or some crappy HTML to a
* client in production.
* <p>
- * TODO: Fine-grained logging for exception, filter which should be logged at INFO or WARN in production
- * TODO: Websocket session errors
*/
public class WebServiceExceptions {
- private static final Logger LOG = Logger.getLogger(WebServiceExceptions.class.getName());
-
- @Provider
- public static class DefaultResteasyExceptionMapper implements ExceptionMapper<Exception> {
- @Context
- protected Request request;
-
- @Context
- protected UriInfo uriInfo;
+ private static final System.Logger LOG = System.getLogger(WebServiceExceptions.class.getName());
+ /**
+ * The mapper handles JAX-RS exceptions
+ */
+ public static class JAXRSExceptionMapper implements ExceptionMapper<Throwable> {
final protected boolean devMode;
- public DefaultResteasyExceptionMapper(boolean devMode) {
+ public JAXRSExceptionMapper(boolean devMode) {
this.devMode = devMode;
}
@Override
- public Response toResponse(Exception exception) {
- return handleResteasyException(devMode, "RESTEasy Dispatch", request, uriInfo, exception);
+ public Response toResponse(Throwable exception) {
+ return handleResteasyException(devMode, exception);
}
}
- // bburke hardcoded a response entity in "new ForbiddenException", which means we can't handle it anymore,
- // according to JAX-RS rules. however, he then checks if there is an exact matching handler, so it's
- // still possible...
- @Provider
- public static class ForbiddenResteasyExceptionMapper implements ExceptionMapper<ForbiddenException> {
-
- @Context
- protected Request request;
-
- @Context
- protected UriInfo uriInfo;
-
+ /**
+ * An exception handler for any exception that bubbles out of a servlet or occurs within Undertow itself
+ */
+ public static class RootUndertowExceptionHandler extends io.undertow.server.handlers.ExceptionHandler {
final protected boolean devMode;
- public ForbiddenResteasyExceptionMapper(boolean devMode) {
+ public RootUndertowExceptionHandler(boolean devMode, HttpHandler next) {
+ super(next);
this.devMode = devMode;
- }
-
- @Override
- public Response toResponse(ForbiddenException exception) {
- return handleResteasyException(devMode, "RESTEasy Role Security", request, uriInfo, exception);
+ addExceptionHandler(Throwable.class, (HttpServerExchange exchange) -> {
+ // Get the exception that was thrown
+ Throwable throwable = exchange.getAttachment(io.undertow.server.handlers.ExceptionHandler.THROWABLE);
+ LoggingFilter.logException(
+ devMode,
+ "Undertow",
+ System.Logger.Level.ERROR,
+ throwable,
+ null,
+ 500,
+ TEXT_PLAIN_TYPE.toString()
+ );
+
+ // Send a clean response to the client
+ if (!exchange.isResponseStarted()) {
+ exchange.setStatusCode(500);
+ exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, TEXT_PLAIN_TYPE.toString());
+ exchange.getResponseSender().send(devMode ? renderDevModeError(500, throwable) : renderProductionError(500, throwable));
+ }
+ });
}
}
- public static class RootUndertowExceptionHandler implements HttpHandler {
-
+ /**
+ * Exception handler for servlet deployments to prevent HTML error pages being returned
+ */
+ public static class ServletExceptionHandler implements ExceptionHandler {
final protected boolean devMode;
- final protected HttpHandler nextHandler;
- public RootUndertowExceptionHandler(boolean devMode, HttpHandler nextHandler) {
+ public ServletExceptionHandler(boolean devMode) {
this.devMode = devMode;
- this.nextHandler = nextHandler;
}
@Override
- public void handleRequest(HttpServerExchange exchange) throws Exception {
- try {
- if (nextHandler == null)
- throw new IllegalStateException("This Undertow handler must wrap another handler");
- nextHandler.handleRequest(exchange);
- } catch (Throwable t) {
- handleUndertowException(devMode, "Undertow Root Dispatch", false, exchange, t);
+ public boolean handleThrowable(HttpServerExchange exchange, ServletRequest request, ServletResponse response, Throwable throwable) {
+ Throwable effectiveException = throwable;
+ int status = 500;
+
+ // Unpack ServletException to see if the root cause is a WebApplicationException
+ if (throwable instanceof jakarta.servlet.ServletException && throwable.getCause() != null) {
+ effectiveException = throwable.getCause();
}
- }
- }
- public static class ServletUndertowExceptionHandler implements ExceptionHandler {
- final protected boolean devMode;
+ if (effectiveException instanceof OptimisticLockException) {
+ // We get here if JPA entity id is set on merge but it doesn't already exist (unless ID generator is configured to allow ID to be assigned)
+ // Or we get here is JPA entity version doesn't match what's in the DB
+ effectiveException = new NotAllowedException(effectiveException);
+ }
- public ServletUndertowExceptionHandler(boolean devMode) {
- this.devMode = devMode;
- }
+ if (effectiveException instanceof WebApplicationException webApplicationException) {
+ status = webApplicationException.getResponse().getStatus();
+ }
- @Override
- public boolean handleThrowable(HttpServerExchange exchange,
- ServletRequest request,
- ServletResponse response,
- Throwable throwable) {
+ boolean filterApplied = Boolean.TRUE.equals(request.getAttribute(LoggingFilter.FILTER_APPLIED_ATTR));
+ if (!filterApplied) {
+ System.Logger.Level level = status >= 500 ? System.Logger.Level.ERROR : status >= 400 ? System.Logger.Level.DEBUG : System.Logger.Level.TRACE;
+ LoggingFilter.logException(
+ devMode,
+ "Servlet",
+ level,
+ effectiveException,
+ request instanceof HttpServletRequest httpRequest ? httpRequest : null,
+ status,
+ response.getContentType()
+ );
+ }
- // We handle the exception (return true), so we must send correct status to browser
if (!exchange.isResponseStarted()) {
- // The only exceptions we receive here should be unexpected server errors
- exchange.setStatusCode(500);
+ exchange.setStatusCode(status);
+ exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, TEXT_PLAIN_TYPE.toString());
+ exchange.getResponseSender().send(devMode ?
+ renderDevModeError(status, effectiveException) :
+ renderProductionError(status, effectiveException));
}
- handleUndertowException(devMode, "Undertow Servlet Dispatch", response.isCommitted(), exchange, throwable);
return true;
}
}
- public static Response handleResteasyException(boolean devMode, String origin, Request request, UriInfo uriInfo, Throwable throwable) {
-
- logException(throwable, origin, request.getMethod() + " " + uriInfo.getRequestUri());
+ public static Response handleResteasyException(boolean devMode, Throwable throwable) {
+ Throwable effectiveException = throwable;
+ int status = 500;
+ Response webApplicationResponse = null;
- int statusCode = 500;
+ // Unpack ServletException to see if the root cause is a WebApplicationException
+ if (throwable instanceof jakarta.servlet.ServletException && throwable.getCause() != null) {
+ effectiveException = throwable.getCause();
+ }
- if (throwable instanceof OptimisticLockException) {
- // We get here if JPA entity id is set on merge but it doesn't already exist (unless ID generator is configured to allow ID to be assigned)
- // Or we get here is JPA entity version doesn't match what's in the DB
- throwable = new NotAllowedException(throwable);
+ if (effectiveException instanceof OptimisticLockException) {
+ // We get here if JPA entity id is set on merge but it doesn't already exist (unless ID generator is
+ // configured to allow ID to be assigned). Or we get here is JPA entity version doesn't match what's in the DB
+ effectiveException = new NotAllowedException(effectiveException);
}
- if (throwable instanceof WebApplicationException) {
- Response response = ((WebApplicationException) throwable).getResponse();
- switch (response.getStatusInfo().getFamily()) {
+ if (effectiveException instanceof WebApplicationException webApplicationException) {
+ webApplicationResponse = webApplicationException.getResponse();
+
+ switch (webApplicationResponse.getStatusInfo().getFamily()) {
case CLIENT_ERROR:
+ status = webApplicationResponse.getStatus();
+ break;
case SERVER_ERROR:
- statusCode = response.getStatus();
+ status = webApplicationResponse.getStatus();
break;
default:
+ LoggingFilter.logException(
+ devMode,
+ "JAX-RS",
+ System.Logger.Level.TRACE,
+ effectiveException,
+ null,
+ webApplicationResponse.getStatus(),
+ webApplicationResponse.getMediaType() != null ? webApplicationResponse.getMediaType().toString() : null
+ );
// If it's not a client or server error, it's not really an "exception" to
// be handled but a status that should be returned to the client
- return response;
+ return webApplicationResponse;
}
}
+
try {
- if (devMode) {
- return Response.status(statusCode).entity(renderDevModeError(statusCode, throwable)).type(TEXT_PLAIN_TYPE).build();
- } else {
- return Response.status(statusCode).entity(renderProductionError(statusCode, throwable)).type(TEXT_PLAIN_TYPE).build();
+ System.Logger.Level level = status >= 500 ? System.Logger.Level.ERROR : status >= 400 ? System.Logger.Level.DEBUG : System.Logger.Level.TRACE;
+ LoggingFilter.logException(
+ devMode,
+ "JAX-RS",
+ level,
+ effectiveException,
+ null,
+ status,
+ webApplicationResponse != null && webApplicationResponse.getMediaType() != null
+ ? webApplicationResponse.getMediaType().toString()
+ : TEXT_PLAIN_TYPE.toString()
+ );
+
+ if (webApplicationResponse != null && webApplicationResponse.hasEntity()) {
+ return Response.fromResponse(webApplicationResponse).build();
}
+
+ Response.ResponseBuilder responseBuilder = webApplicationResponse != null
+ ? Response.fromResponse(webApplicationResponse)
+ : Response.status(status);
+ String errorBody = devMode
+ ? renderDevModeError(status, effectiveException)
+ : renderProductionError(status, effectiveException);
+ return responseBuilder.entity(errorBody).type(TEXT_PLAIN_TYPE).build();
} catch (Exception ex) {
- LOG.log(Level.SEVERE, "Couldn't render server error trace response", ex);
+ LOG.log(System.Logger.Level.ERROR, "Couldn't render server error trace response", ex);
return Response.serverError().build();
}
}
- public static void handleUndertowException(boolean devMode, String origin, boolean logOnly, HttpServerExchange exchange, Throwable throwable) {
-
- logException(throwable, origin, exchange.toString());
-
- if (!logOnly && exchange.isResponseChannelAvailable()) {
- exchange.getResponseHeaders().put(
- HttpString.tryFromString(HttpHeaders.CONTENT_TYPE), "text/plain"
- );
- try {
- if (devMode) {
- exchange.getResponseSender().send(renderDevModeError(exchange.getStatusCode(), throwable));
- } else {
- exchange.getResponseSender().send(renderProductionError(exchange.getStatusCode(), throwable));
- }
- } catch (Exception ex2) {
- LOG.log(Level.SEVERE, "Couldn't render server error response", ex2);
- }
- }
- }
-
public static String renderDevModeError(int statusCode, Throwable t) {
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
@@ -212,58 +237,13 @@ public class WebServiceExceptions {
+ statusCode
+ (status != null ? " " + status.getReasonPhrase() : "")
+ "\n\n"
- + sw.toString();
+ + sw;
}
public static String renderProductionError(int statusCode, Throwable t) {
Response.Status status = Response.Status.fromStatusCode(statusCode);
return "Request failed with HTTP error status: "
+ statusCode
- + (status != null ? " " + status.getReasonPhrase() : "")
- + "\n\n"
- + "Please contact the help desk.";
- }
-
- public static void logException(Throwable throwable, String origin, String info) {
- // Ignore dropped connection errors
- if ("java.io.IOException: Broken pipe".equals(getRootCause(throwable).toString()))
- return;
- if ("java.io.IOException: Connection reset by peer".equals(getRootCause(throwable).toString()))
- return;
-
- if (throwable instanceof WebApplicationException) {
- int statusCode = ((WebApplicationException) throwable).getResponse().getStatus();
- if (statusCode == 404) {
- // Don't stack trace 404s just want request uri
- LOG.log(Level.FINE, "Web service exception (404) in '" + origin + "' for '" + info + "'");
- return;
- } else if (statusCode >= 200 && statusCode < 300) {
- LOG.log(Level.FINE, "Web service response ("+statusCode+") in '" + origin + "' for '" + info + "'");
- return;
- }
- }
-
- if (LOG.isLoggable(Level.FINE)) {
- LOG.log(Level.FINE, "Web service exception in '" + origin + "' for '" + info + "'" + " type = " + throwable.getClass().getSimpleName() + ", message=" + throwable.getMessage(), throwable);
- } else {
- LOG.log(Level.INFO, "Web service exception in '" + origin + "' for '" + info + "', root cause: " + getRootCause(throwable));
- }
- }
-
- public static Throwable getRootCause(Throwable throwable) {
- Throwable last;
- do {
- last = throwable;
- throwable = getCause(throwable);
- }
- while (throwable != null);
- return last;
- }
-
- public static Throwable getCause(Throwable throwable) {
- // Prevent endless loop when t == t.getCause()
- if (throwable != null && throwable.getCause() != null && throwable != throwable.getCause())
- return throwable.getCause();
- return null;
+ + (status != null ? " " + status.getReasonPhrase() : "");
}
}
diff --git a/container/src/main/java/org/openremote/container/web/WebTargetBuilder.java b/container/src/main/java/org/openremote/container/web/WebTargetBuilder.java
index 57bcbe834..1fe4ee5c4 100644
--- a/container/src/main/java/org/openremote/container/web/WebTargetBuilder.java
+++ b/container/src/main/java/org/openremote/container/web/WebTargetBuilder.java
@@ -21,48 +21,44 @@ package org.openremote.container.web;
import jakarta.validation.constraints.NotNull;
import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.client.ClientResponseFilter;
import jakarta.ws.rs.client.Invocation;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
-import org.apache.http.client.HttpClient;
-import org.apache.http.client.config.CookieSpecs;
-import org.apache.http.client.config.RequestConfig;
-import org.apache.http.impl.client.HttpClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import org.jboss.resteasy.client.jaxrs.internal.BasicAuthentication;
import org.jboss.resteasy.client.jaxrs.internal.ResteasyClientBuilderImpl;
+import org.jboss.resteasy.plugins.interceptors.GZIPDecodingInterceptor;
import org.openremote.container.json.JacksonConfig;
import org.openremote.model.auth.OAuthGrant;
+import org.openremote.model.syslog.SyslogCategory;
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
import java.net.URI;
+import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.UnaryOperator;
-import java.util.stream.Collectors;
+import java.util.logging.Level;
+import java.util.logging.Logger;
/**
- * This is a factory for creating JAX-RS {@link WebTarget} instances. The instances share a common
- * {@link jakarta.ws.rs.client.Client} that uses a connection pool and has the following
- * {@link jakarta.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>
+ * This is a factory for creating JAX-RS {@link WebTarget} client instances that provide built-in authentication:
*/
-// TODO: This should probably be amalgamated with WebClient somehow to provide a unified JAX-RS Client API and a default
-// client should be made available on the Container
public class WebTargetBuilder {
- public static final int CONNECTION_POOL_SIZE = 10;
- public static final long CONNECTION_CHECKOUT_TIMEOUT_MILLISECONDS = 5000;
- public static final long CONNECTION_TIMEOUT_MILLISECONDS = 10000;
+ protected static final Logger LOG = SyslogCategory.getLogger(SyslogCategory.AGENT, WebTargetBuilder.class.getName());
+ protected static final int CONNECTION_POOL_SIZE = 10;
+ protected static final long CONNECTION_CHECKOUT_TIMEOUT_MILLISECONDS = 5000;
+ protected static final long CONNECTION_TIMEOUT_MILLISECONDS = 10000;
+ protected static final AtomicReference<ResteasyClient> BUILT_IN_CLIENT = new AtomicReference<>();
protected ResteasyClient client;
- protected static ExecutorService executorService;
protected BasicAuthentication basicAuthentication;
protected OAuthGrant oAuthGrant;
protected URI baseUri;
@@ -125,7 +121,7 @@ public class WebTargetBuilder {
failureResponses.removeAll(
Arrays.stream(responseStatus)
.map(Response.Status::getStatusCode)
- .collect(Collectors.toList())
+ .toList()
);
return this;
}
@@ -168,6 +164,20 @@ public class WebTargetBuilder {
return target;
}
+ public static ResteasyClient getClient() {
+ return BUILT_IN_CLIENT.updateAndGet(client -> {
+ if (client == null) {
+ return createClient(org.openremote.container.Container.EXECUTOR,
+ CONNECTION_POOL_SIZE,
+ CONNECTION_TIMEOUT_MILLISECONDS,
+ (resteasyClientBuilder ->
+ // Don't limit pool usage by request route
+ resteasyClientBuilder.maxPooledPerRoute(CONNECTION_POOL_SIZE)));
+ }
+ return client;
+ });
+ }
+
public static ResteasyClient createClient(ExecutorService executorService) {
return createClient(executorService, CONNECTION_POOL_SIZE, CONNECTION_TIMEOUT_MILLISECONDS, null);
}
@@ -179,7 +189,8 @@ public class WebTargetBuilder {
.connectionCheckoutTimeout(CONNECTION_CHECKOUT_TIMEOUT_MILLISECONDS, TimeUnit.MILLISECONDS)
.readTimeout(overrideSocketTimeout, TimeUnit.MILLISECONDS)
.connectTimeout(CONNECTION_TIMEOUT_MILLISECONDS, TimeUnit.MILLISECONDS)
- .register(new JacksonConfig());
+ .register(new JacksonConfig())
+ .register(new GZIPDecodingInterceptor());
if (executorService != null) {
clientBuilder.executorService(executorService);
@@ -189,6 +200,24 @@ public class WebTargetBuilder {
clientBuilder = builderConfigurator.apply(clientBuilder);
}
+ if (LOG.isLoggable(Level.FINEST)) {
+ clientBuilder.register((ClientResponseFilter) (clientRequestContext, clientResponseContext) -> {
+ int status = clientResponseContext.getStatus();
+ if (status < 400) return;
+
+ byte[] bytes = null;
+ String body = "<no body>";
+
+ if (clientResponseContext.hasEntity()) {
+ InputStream is = clientResponseContext.getEntityStream();
+ bytes = is.readAllBytes();
+ clientResponseContext.setEntityStream(new ByteArrayInputStream(bytes)); // allow RESTEasy to read it later
+ body = new String(bytes, StandardCharsets.UTF_8);
+ }
+ LOG.log(Level.FINEST, "Received {0} response from {1} with body: {2}", new Object[]{status, clientRequestContext.getUri().getPath(), body});
+ });
+ }
+
return clientBuilder.build();
}
diff --git a/extension/energy/src/main/java/org/openremote/extension/energy/manager/ForecastSolarService.java b/extension/energy/src/main/java/org/openremote/extension/energy/manager/ForecastSolarService.java
index 3fa986152..07a1d1a21 100644
--- a/extension/energy/src/main/java/org/openremote/extension/energy/manager/ForecastSolarService.java
+++ b/extension/energy/src/main/java/org/openremote/extension/energy/manager/ForecastSolarService.java
@@ -3,10 +3,10 @@ package org.openremote.extension.energy.manager;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.ws.rs.core.Response;
import org.apache.camel.builder.RouteBuilder;
-import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import org.openremote.container.message.MessageBrokerService;
import org.openremote.container.timer.TimerService;
+import org.openremote.container.web.WebTargetBuilder;
import org.openremote.extension.energy.model.ElectricityProducerSolarAsset;
import org.openremote.manager.asset.AssetProcessingService;
import org.openremote.manager.asset.AssetStorageService;
@@ -29,6 +29,7 @@ import org.openremote.model.query.AssetQuery;
import org.openremote.model.syslog.SyslogCategory;
import java.io.IOException;
+import java.net.URI;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
@@ -37,7 +38,6 @@ import java.time.format.DateTimeFormatterBuilder;
import java.util.*;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -45,10 +45,10 @@ import static java.time.format.DateTimeFormatter.ISO_LOCAL_DATE;
import static java.time.format.DateTimeFormatter.ISO_LOCAL_TIME;
import static org.openremote.container.persistence.PersistenceService.PERSISTENCE_TOPIC;
import static org.openremote.container.persistence.PersistenceService.isPersistenceEventForEntityType;
-import static org.openremote.model.util.MapAccess.getString;
-import static org.openremote.container.web.WebTargetBuilder.createClient;
+import static org.openremote.container.web.WebTargetBuilder.getClient;
import static org.openremote.manager.gateway.GatewayService.isNotForGateway;
import static org.openremote.model.syslog.SyslogCategory.DATA;
+import static org.openremote.model.util.MapAccess.getString;
/**
* Fills in power forecast from ForecastSolar (https://forecast.solar) for {@link ElectricityProducerSolarAsset}.
@@ -88,7 +88,6 @@ public class ForecastSolarService extends RouteBuilder implements ContainerServi
protected TimerService timerService;
protected static final Logger LOG = SyslogCategory.getLogger(DATA, ForecastSolarService.class.getName());
- protected static final AtomicReference<ResteasyClient> resteasyClient = new AtomicReference<>();
protected ResteasyWebTarget forecastSolarTarget;
private String forecastSolarApiKey;
private final Map<String, ElectricityProducerSolarAsset> electricityProducerSolarAssetMap = new HashMap<>();
@@ -124,10 +123,7 @@ public class ForecastSolarService extends RouteBuilder implements ContainerServi
return;
}
- initClient();
-
- forecastSolarTarget = resteasyClient.get()
- .target("https://api.forecast.solar/" + forecastSolarApiKey + "/estimate");
+ forecastSolarTarget = new WebTargetBuilder(getClient(), URI.create("https://api.forecast.solar/" + forecastSolarApiKey + "/estimate")).build();
container.getService(MessageBrokerService.class).getContext().addRoutes(this);
@@ -162,15 +158,7 @@ public class ForecastSolarService extends RouteBuilder implements ContainerServi
@Override
public void stop(Container container) throws Exception {
- scheduledExecutorService.shutdown();
- }
-
- protected static void initClient() {
- synchronized (resteasyClient) {
- if (resteasyClient.get() == null) {
- resteasyClient.set(createClient(org.openremote.container.Container.EXECUTOR));
- }
- }
+ // empty
}
protected synchronized void processElectricityProducerSolarAssetAttributeEvent(AttributeEvent attributeEvent) {
diff --git a/extension/energy/src/main/java/org/openremote/extension/energy/manager/ForecastWindService.java b/extension/energy/src/main/java/org/openremote/extension/energy/manager/ForecastWindService.java
index e578e5798..c00269988 100644
--- a/extension/energy/src/main/java/org/openremote/extension/energy/manager/ForecastWindService.java
+++ b/extension/energy/src/main/java/org/openremote/extension/energy/manager/ForecastWindService.java
@@ -2,10 +2,11 @@ package org.openremote.extension.energy.manager;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.UriBuilder;
import org.apache.camel.builder.RouteBuilder;
-import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import org.openremote.container.message.MessageBrokerService;
+import org.openremote.container.web.WebTargetBuilder;
import org.openremote.extension.energy.model.ElectricityProducerAsset;
import org.openremote.extension.energy.model.ElectricityProducerWindAsset;
import org.openremote.manager.asset.AssetProcessingService;
@@ -32,16 +33,15 @@ import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import java.util.logging.Logger;
import static org.openremote.container.persistence.PersistenceService.PERSISTENCE_TOPIC;
import static org.openremote.container.persistence.PersistenceService.isPersistenceEventForEntityType;
-import static org.openremote.model.util.MapAccess.getString;
-import static org.openremote.container.web.WebTargetBuilder.createClient;
+import static org.openremote.container.web.WebTargetBuilder.getClient;
import static org.openremote.manager.gateway.GatewayService.isNotForGateway;
import static org.openremote.model.syslog.SyslogCategory.DATA;
+import static org.openremote.model.util.MapAccess.getString;
/**
* Calculates power generation for {@link ElectricityProducerWindAsset}.
@@ -111,7 +111,6 @@ public class ForecastWindService extends RouteBuilder implements ContainerServic
public static final String OR_OPEN_WEATHER_API_APP_ID = "OR_OPEN_WEATHER_API_APP_ID";
protected static final Logger LOG = SyslogCategory.getLogger(DATA, ForecastWindService.class.getName());
- protected static final AtomicReference<ResteasyClient> resteasyClient = new AtomicReference<>();
protected AssetStorageService assetStorageService;
protected AssetProcessingService assetProcessingService;
protected GatewayService gatewayService;
@@ -154,13 +153,12 @@ public class ForecastWindService extends RouteBuilder implements ContainerServic
return;
}
- initClient();
-
- weatherForecastWebTarget = resteasyClient.get()
- .target("https://api.openweathermap.org/data/2.5")
- .queryParam("units", "metric")
- .queryParam("exclude", "minutely,daily,alerts")
- .queryParam("appid", openWeatherAppId);
+ weatherForecastWebTarget = new WebTargetBuilder(
+ getClient(),
+ UriBuilder.fromUri("https://api.openweathermap.org/data/2.5")
+ .queryParam("units", "metric")
+ .queryParam("exclude", "minutely,daily,alerts")
+ .queryParam("appid", openWeatherAppId).build()).build();
container.getService(MessageBrokerService.class).getContext().addRoutes(this);
@@ -192,14 +190,6 @@ public class ForecastWindService extends RouteBuilder implements ContainerServic
new ArrayList<>(calculationFutures.keySet()).forEach(this::stopCalculation);
}
- protected static void initClient() {
- synchronized (resteasyClient) {
- if (resteasyClient.get() == null) {
- resteasyClient.set(createClient(org.openremote.container.Container.SCHEDULED_EXECUTOR));
- }
- }
- }
-
protected void processAttributeEvent(AttributeEvent attributeEvent) {
processElectricityProducerWindAssetAttributeEvent(attributeEvent);
}
diff --git a/extension/energy/src/test/groovy/org/openremote/extension/energy/ForecastSolarServiceTest.groovy b/extension/energy/src/test/groovy/org/openremote/extension/energy/ForecastSolarServiceTest.groovy
index 2b6bed715..74077dd2b 100644
--- a/extension/energy/src/test/groovy/org/openremote/extension/energy/ForecastSolarServiceTest.groovy
+++ b/extension/energy/src/test/groovy/org/openremote/extension/energy/ForecastSolarServiceTest.groovy
@@ -1,5 +1,6 @@
package org.openremote.extension.energy
+import org.openremote.container.web.WebTargetBuilder
import org.openremote.extension.energy.model.ElectricityProducerSolarAsset
import org.openremote.extension.energy.manager.ForecastSolarService
import org.openremote.manager.asset.AssetProcessingService
@@ -31,8 +32,12 @@ class ForecastSolarServiceTest extends Specification implements ManagerContainer
@Shared
def mockServer = new ClientRequestFilter() {
+ boolean finished = false
+
@Override
void filter(ClientRequestContext requestContext) throws IOException {
+ if (finished) return
+
def requestUri = requestContext.uri
switch (requestUri.host) {
@@ -129,11 +134,7 @@ class ForecastSolarServiceTest extends Specification implements ManagerContainer
def conditions = new PollingConditions(timeout: 10, delay: 0.2)
def config = defaultConfig()
config << [(OR_FORECAST_SOLAR_API_KEY): "test-key"]
-
- ForecastSolarService.initClient()
- if (!ForecastSolarService.resteasyClient.get().configuration.isRegistered(mockServer)) {
- ForecastSolarService.resteasyClient.get().register(mockServer, Integer.MAX_VALUE)
- }
+ WebTargetBuilder.client.register(mockServer, Integer.MAX_VALUE)
def container = startContainer(config, defaultServices())
def managerTestSetup = container.getService(SetupService.class).getTaskOfType(ManagerTestSetup.class)
@@ -207,9 +208,7 @@ class ForecastSolarServiceTest extends Specification implements ManagerContainer
assert newSolarAsset2.getAttribute(ElectricityProducerSolarAsset.POWER).flatMap { it.value }.orElse(0d) != 0d
}
- cleanup: "remove mock"
- if (ForecastSolarService.resteasyClient.get() != null) {
- ForecastSolarService.resteasyClient.set(null)
- }
+ cleanup: "disable mock filter"
+ mockServer.finished = true
}
}
diff --git a/extension/energy/src/test/groovy/org/openremote/extension/energy/ForecastWindServiceTest.groovy b/extension/energy/src/test/groovy/org/openremote/extension/energy/ForecastWindServiceTest.groovy
index ee828e1e3..76d33a4e1 100644
--- a/extension/energy/src/test/groovy/org/openremote/extension/energy/ForecastWindServiceTest.groovy
+++ b/extension/energy/src/test/groovy/org/openremote/extension/energy/ForecastWindServiceTest.groovy
@@ -1,8 +1,12 @@
package org.openremote.extension.energy
-import org.openremote.extension.energy.model.ElectricityProducerWindAsset
-import org.openremote.extension.energy.manager.ForecastSolarService
+import jakarta.ws.rs.client.ClientRequestContext
+import jakarta.ws.rs.client.ClientRequestFilter
+import jakarta.ws.rs.core.MediaType
+import jakarta.ws.rs.core.Response
+import org.openremote.container.web.WebTargetBuilder
import org.openremote.extension.energy.manager.ForecastWindService
+import org.openremote.extension.energy.model.ElectricityProducerWindAsset
import org.openremote.manager.asset.AssetProcessingService
import org.openremote.manager.asset.AssetStorageService
import org.openremote.manager.datapoint.AssetPredictedDatapointService
@@ -18,10 +22,6 @@ import spock.lang.Shared
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
-import jakarta.ws.rs.client.ClientRequestContext
-import jakarta.ws.rs.client.ClientRequestFilter
-import jakarta.ws.rs.core.MediaType
-import jakarta.ws.rs.core.Response
import java.time.LocalDateTime
import java.time.ZoneOffset
import java.time.temporal.ChronoUnit
@@ -33,9 +33,13 @@ class ForecastWindServiceTest extends Specification implements ManagerContainerT
@Shared
def mockServer = new ClientRequestFilter() {
+ boolean finished = true
@Override
void filter(ClientRequestContext requestContext) throws IOException {
+ if (finished) {
+ return
+ }
def requestUri = requestContext.uri
switch (requestUri.path) {
@@ -641,11 +645,7 @@ class ForecastWindServiceTest extends Specification implements ManagerContainerT
def conditions = new PollingConditions(timeout: 10, delay: 0.2)
def config = defaultConfig()
config << [(OR_OPEN_WEATHER_API_APP_ID): "test-key"]
-
- ForecastWindService.initClient()
- if (!ForecastWindService.resteasyClient.get().configuration.isRegistered(mockServer)) {
- ForecastWindService.resteasyClient.get().register(mockServer, Integer.MAX_VALUE)
- }
+ WebTargetBuilder.client.register(mockServer, Integer.MAX_VALUE)
def container = startContainer(config, defaultServices())
def managerTestSetup = container.getService(SetupService.class).getTaskOfType(ManagerTestSetup.class)
@@ -772,9 +772,7 @@ class ForecastWindServiceTest extends Specification implements ManagerContainerT
assert assetPredictedDatapointService.getDatapoints(new AttributeRef(newWindAsset3.getId(), ElectricityProducerWindAsset.POWER_FORECAST.getName())).size() > 0
}
- cleanup: "remove mock"
- if (ForecastSolarService.resteasyClient.get() != null) {
- ForecastSolarService.resteasyClient.set(null)
- }
+ cleanup: "disable mock filter"
+ mockServer.finished = true
}
}
diff --git a/manager/src/main/java/org/openremote/manager/apps/AppResourceImpl.java b/manager/src/main/java/org/openremote/manager/apps/AppResourceImpl.java
index a2a3d6903..dec111439 100644
--- a/manager/src/main/java/org/openremote/manager/apps/AppResourceImpl.java
+++ b/manager/src/main/java/org/openremote/manager/apps/AppResourceImpl.java
@@ -56,14 +56,14 @@ public class AppResourceImpl extends WebResource implements AppResource {
}
@Override
- public Response getAppInfos(RequestParams requestParams) {
+ public Map<String, Object> getAppInfos(RequestParams requestParams) {
Path consoleAppDocRoot = consoleAppService.getConsoleAppDocRoot();
if (consoleAppDocRoot == null || !Files.isDirectory(consoleAppDocRoot)) {
- return Response
+ throw new WebApplicationException(Response
.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(String.format("%s is not a directory", consoleAppDocRoot))
.type(MediaType.APPLICATION_JSON_TYPE)
- .build();
+ .build());
}
if (consoleAppInfoMap == null) {
@@ -83,24 +83,24 @@ public class AppResourceImpl extends WebResource implements AppResource {
}
}
- return Response.ok(consoleAppInfoMap, MediaType.APPLICATION_JSON).build();
+ return consoleAppInfoMap;
}
@Override
- public Response getConsoleConfig(RequestParams requestParams) {
+ public Object getConsoleConfig(RequestParams requestParams) {
Path consoleAppDocRoot = consoleAppService.getConsoleAppDocRoot();
if (consoleAppDocRoot == null || !Files.isDirectory(consoleAppDocRoot)) {
- return Response
+ throw new WebApplicationException(Response
.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(String.format("%s is not a directory", consoleAppDocRoot))
.type(MediaType.APPLICATION_JSON_TYPE)
- .build();
+ .build());
}
if (!Files.exists(consoleAppDocRoot.resolve("console_config.json"))) {
- return Response
+ throw new WebApplicationException(Response
.status(Response.Status.NOT_FOUND)
- .build();
+ .build());
}
if (consoleConfig == null) {
@@ -110,7 +110,7 @@ public class AppResourceImpl extends WebResource implements AppResource {
throw new WebApplicationException(e);
}
}
- return Response.ok(consoleConfig, MediaType.APPLICATION_JSON).build();
+ return consoleConfig;
}
@Deprecated
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java b/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java
index e8824363a..8d59867a2 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java
@@ -417,14 +417,12 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
}
@Override
- public Response writeAttributeValue(RequestParams requestParams, String assetId, String attributeName, Object value) {
+ public AttributeWriteResult writeAttributeValue(RequestParams requestParams, String assetId, String attributeName, Object value) {
return writeAttributeValue(requestParams, assetId, attributeName, null, value);
}
@Override
- public Response writeAttributeValue(RequestParams requestParams, String assetId, String attributeName, Long timestamp, Object value) {
- Response.Status status = Response.Status.OK;
-
+ public AttributeWriteResult writeAttributeValue(RequestParams requestParams, String assetId, String attributeName, Long timestamp, Object value) {
if (value instanceof NullNode) {
value = null;
}
@@ -440,15 +438,16 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
AttributeWriteResult result = doAttributeWrite(event);
if (result.getFailure() != null) {
- status = switch (result.getFailure()) {
+ Response.Status status = switch (result.getFailure()) {
case ASSET_NOT_FOUND, ATTRIBUTE_NOT_FOUND -> NOT_FOUND;
case INVALID_VALUE -> NOT_ACCEPTABLE;
case QUEUE_FULL -> TOO_MANY_REQUESTS;
default -> BAD_REQUEST;
};
+ throw new WebApplicationException(Response.status(status).entity(result).type(MediaType.APPLICATION_JSON_TYPE).build());
}
- return Response.status(status).entity(result).type(MediaType.APPLICATION_JSON_TYPE).build();
+ return result;
}
@Override
diff --git a/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointResourceImpl.java b/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointResourceImpl.java
index 21d5787cc..ec47885e3 100644
--- a/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointResourceImpl.java
+++ b/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointResourceImpl.java
@@ -37,11 +37,7 @@ import org.openremote.model.Constants;
import org.openremote.model.asset.Asset;
import org.openremote.model.attribute.Attribute;
import org.openremote.model.attribute.AttributeRef;
-import org.openremote.model.datapoint.AssetDatapointResource;
-import org.openremote.model.datapoint.DatapointPeriod;
-import org.openremote.model.datapoint.DatapointExportFormat;
-import org.openremote.model.datapoint.DatapointQueryTooLargeException;
-import org.openremote.model.datapoint.ValueDatapoint;
+import org.openremote.model.datapoint.*;
import org.openremote.model.datapoint.query.AssetDatapointQuery;
import org.openremote.model.http.RequestParams;
import org.openremote.model.security.ClientRole;
@@ -49,7 +45,9 @@ import org.openremote.model.syslog.SyslogCategory;
import org.openremote.model.util.UniqueIdentifierGenerator;
import org.openremote.model.value.MetaItemType;
-import java.io.*;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PipedInputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
@@ -60,7 +58,6 @@ import static org.openremote.model.util.ValueUtil.JSON;
public class AssetDatapointResourceImpl extends ManagerWebResource implements AssetDatapointResource {
- private static final Logger LOG = Logger.getLogger(AssetDatapointResourceImpl.class.getName());
private static final Logger DATA_EXPORT_LOG = SyslogCategory.getLogger(DATA, AssetDatapointResourceImpl.class);
protected final AssetStorageService assetStorageService;
@@ -104,7 +101,6 @@ public class AssetDatapointResourceImpl extends ManagerWebResource implements As
// If logged in, user should have READ ASSETS role
if(isAuthenticated() && !hasResourceRole(ClientRole.READ_ASSETS.getValue(), Constants.KEYCLOAK_CLIENT_ID)) {
- LOG.info("Forbidden access for user '" + getUsername() + "': " + asset.getRealm());
throw new WebApplicationException(Response.Status.FORBIDDEN);
}
@@ -157,7 +153,6 @@ public class AssetDatapointResourceImpl extends ManagerWebResource implements As
}
if (!isRealmActiveAndAccessible(asset.getRealm())) {
- LOG.info("Forbidden access for user '" + getUsername() + "': " + asset);
throw new WebApplicationException(Response.Status.FORBIDDEN);
}
@@ -198,7 +193,6 @@ public class AssetDatapointResourceImpl extends ManagerWebResource implements As
}
if (!isRealmActiveAndAccessible(asset.getRealm())) {
- DATA_EXPORT_LOG.info("Forbidden access for user '" + getUsername() + "': " + asset);
throw new WebApplicationException(Response.Status.FORBIDDEN);
}
diff --git a/manager/src/main/java/org/openremote/manager/security/UserResourceImpl.java b/manager/src/main/java/org/openremote/manager/security/UserResourceImpl.java
index 69d9a42e1..7cffaa6fc 100644
--- a/manager/src/main/java/org/openremote/manager/security/UserResourceImpl.java
+++ b/manager/src/main/java/org/openremote/manager/security/UserResourceImpl.java
@@ -32,16 +32,19 @@ import org.openremote.model.query.filter.StringPredicate;
import org.openremote.model.security.*;
import jakarta.ws.rs.*;
+import org.openremote.model.syslog.SyslogCategory;
import org.openremote.model.util.TextUtil;
import java.util.*;
import java.util.AbstractMap;
+import java.util.logging.Logger;
import static org.openremote.model.Constants.KEYCLOAK_CLIENT_ID;
import static org.openremote.model.Constants.MASTER_REALM;
public class UserResourceImpl extends ManagerWebResource implements UserResource {
+ protected static final Logger LOG = SyslogCategory.getLogger(SyslogCategory.API, UserResourceImpl.class.getName());
protected MQTTBrokerService mqttBrokerService;
public UserResourceImpl(TimerService timerService, ManagerIdentityService identityService, MQTTBrokerService mqttBrokerService) {
@@ -336,7 +339,7 @@ public class UserResourceImpl extends ManagerWebResource implements UserResource
clientId,
roles);
} catch (ClientErrorException ex) {
- ex.printStackTrace(System.out);
+ LOG.warning("Failed to update user client roles: " + ex.getMessage());
throw new WebApplicationException(ex.getCause(), ex.getResponse().getStatus());
} catch (Exception ex) {
throw new WebApplicationException(ex);
@@ -353,7 +356,7 @@ public class UserResourceImpl extends ManagerWebResource implements UserResource
userId,
roles);
} catch (ClientErrorException ex) {
- ex.printStackTrace(System.out);
+ LOG.warning("Failed to update user realm roles: " + ex.getMessage());
throw new WebApplicationException(ex.getCause(), ex.getResponse().getStatus());
} catch (Exception ex) {
throw new WebApplicationException(ex);
@@ -388,7 +391,7 @@ public class UserResourceImpl extends ManagerWebResource implements UserResource
clientId,
roles);
} catch (ClientErrorException ex) {
- ex.printStackTrace(System.out);
+ LOG.warning("Failed to update client roles: " + ex.getMessage());
throw new WebApplicationException(ex.getCause(), ex.getResponse().getStatus());
} catch (Exception ex) {
throw new NotFoundException(ex);
diff --git a/manager/src/main/java/org/openremote/manager/setup/KeycloakInitService.java b/manager/src/main/java/org/openremote/manager/setup/KeycloakInitService.java
index 561587172..dad03fe8b 100644
--- a/manager/src/main/java/org/openremote/manager/setup/KeycloakInitService.java
+++ b/manager/src/main/java/org/openremote/manager/setup/KeycloakInitService.java
@@ -20,20 +20,15 @@
package org.openremote.manager.setup;
+import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriBuilder;
-import org.jboss.resteasy.client.jaxrs.ResteasyClient;
-import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
-import org.jboss.resteasy.client.jaxrs.internal.ResteasyClientBuilderImpl;
import org.openremote.container.persistence.PersistenceService;
-import org.openremote.container.security.keycloak.KeycloakResource;
-import org.openremote.container.web.WebClient;
import org.openremote.container.web.WebTargetBuilder;
import org.openremote.model.Container;
import org.openremote.model.ContainerService;
import org.openremote.model.util.TextUtil;
-import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import static jakarta.ws.rs.core.Response.Status.Family.REDIRECTION;
@@ -94,29 +89,14 @@ public class KeycloakInitService implements ContainerService {
keycloakServiceUri.path(keycloakPath);
}
- ResteasyClientBuilderImpl clientBuilder = new ResteasyClientBuilderImpl()
- .connectTimeout(
- getInteger(container.getConfig(), KEYCLOAK_CONNECT_TIMEOUT, KEYCLOAK_CONNECT_TIMEOUT_DEFAULT),
- TimeUnit.MILLISECONDS
- )
- .readTimeout(
- getInteger(container.getConfig(), KEYCLOAK_REQUEST_TIMEOUT, KEYCLOAK_REQUEST_TIMEOUT_DEFAULT),
- TimeUnit.MILLISECONDS
- )
- .connectionPoolSize(
- getInteger(container.getConfig(), KEYCLOAK_CLIENT_POOL_SIZE, KEYCLOAK_CLIENT_POOL_SIZE_DEFAULT)
- );
- ResteasyClient httpClient = WebClient.registerDefaults(clientBuilder).build();
-
boolean keycloakAvailable = false;
- WebTargetBuilder targetBuilder = new WebTargetBuilder(httpClient, keycloakServiceUri.build());
- ResteasyWebTarget target = targetBuilder.build();
- KeycloakResource keycloakResource = target.proxy(KeycloakResource.class);
+ WebTargetBuilder targetBuilder = new WebTargetBuilder(WebTargetBuilder.getClient(), keycloakServiceUri.build());
+ WebTarget target = targetBuilder.build();
while (!keycloakAvailable) {
LOG.info("Connecting to Keycloak server: " + keycloakServiceUri.build());
try {
- pingKeycloak(keycloakResource);
+ pingKeycloak(target);
keycloakAvailable = true;
LOG.info("Successfully connected to Keycloak server: " + keycloakServiceUri.build());
} catch (Exception ex) {
@@ -130,20 +110,15 @@ public class KeycloakInitService implements ContainerService {
}
}
- protected static void pingKeycloak(KeycloakResource resource) throws Exception {
- Response response = null;
+ protected static void pingKeycloak(WebTarget target) throws Exception {
- try {
- response = resource.getWelcomePage();
+ try (Response response = target.path("/realms/master/.well-known/openid-configuration").request().head()) {
if (response != null &&
- (response.getStatusInfo().getFamily() == SUCCESSFUL
- || response.getStatusInfo().getFamily() == REDIRECTION)) {
+ (response.getStatusInfo().getFamily() == SUCCESSFUL
+ || response.getStatusInfo().getFamily() == REDIRECTION)) {
return;
}
throw new Exception();
- } finally {
- if (response != null)
- response.close();
}
}
}
diff --git a/manager/src/main/java/org/openremote/manager/webhook/WebhookService.java b/manager/src/main/java/org/openremote/manager/webhook/WebhookService.java
index e40181f2a..ced87ffd0 100644
--- a/manager/src/main/java/org/openremote/manager/webhook/WebhookService.java
+++ b/manager/src/main/java/org/openremote/manager/webhook/WebhookService.java
@@ -26,49 +26,31 @@ import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.apache.camel.builder.RouteBuilder;
-import org.jboss.resteasy.client.jaxrs.ResteasyClient;
-import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
-import org.jboss.resteasy.client.jaxrs.internal.ResteasyClientBuilderImpl;
import org.openremote.container.web.WebTargetBuilder;
import org.openremote.model.Container;
import org.openremote.model.ContainerService;
import org.openremote.model.webhook.Webhook;
import java.net.URI;
-import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
-import static org.openremote.model.util.MapAccess.getInteger;
+import static org.openremote.container.web.WebTargetBuilder.getClient;
public class WebhookService extends RouteBuilder implements ContainerService {
private static final Logger LOG = Logger.getLogger(WebhookService.class.getName());
- protected ResteasyClientBuilder clientBuilder;
-
- public static final String WEBHOOK_CONNECT_TIMEOUT = "WEBHOOK_CONNECT_TIMEOUT";
- public static final int WEBHOOK_CONNECT_TIMEOUT_DEFAULT = 2000;
- public static final String WEBHOOK_REQUEST_TIMEOUT = "WEBHOOK_REQUEST_TIMEOUT";
- public static final int WEBHOOK_REQUEST_TIMEOUT_DEFAULT = 10000;
-
- @Override
- public void init(Container container) throws Exception {
- this.clientBuilder = new ResteasyClientBuilderImpl()
- .connectTimeout(
- getInteger(container.getConfig(), WEBHOOK_CONNECT_TIMEOUT, WEBHOOK_CONNECT_TIMEOUT_DEFAULT),
- TimeUnit.MILLISECONDS
- )
- .readTimeout(
- getInteger(container.getConfig(), WEBHOOK_REQUEST_TIMEOUT, WEBHOOK_REQUEST_TIMEOUT_DEFAULT),
- TimeUnit.MILLISECONDS
- );
- }
@Override
public void configure() throws Exception {
// empty
}
- @Override
+ @Override
+ public void init(Container container) throws Exception {
+ // empty
+ }
+
+ @Override
public void start(Container container) throws Exception {
// empty
}
@@ -95,9 +77,7 @@ public class WebhookService extends RouteBuilder implements ContainerService {
}
public WebTarget buildWebTarget(Webhook webhook) {
-
- ResteasyClient client = this.clientBuilder.build();
- WebTargetBuilder builder = new WebTargetBuilder(client, URI.create(webhook.getUrl()));
+ WebTargetBuilder builder = new WebTargetBuilder(getClient(), URI.create(webhook.getUrl()));
// Authentication
if (webhook.getUsernamePassword() != null) {
diff --git a/manager/src/main/resources/logging-debug.properties b/manager/src/main/resources/logging-debug.properties
index 217ebdeac..dee085ba8 100644
--- a/manager/src/main/resources/logging-debug.properties
+++ b/manager/src/main/resources/logging-debug.properties
@@ -61,7 +61,7 @@ org.openremote.manager.mqtt.level=FINE
# Set to fine to log WS connections
org.openremote.manager.event.ClientEventService.level=FINE
# Set to fine to log HTTP requests for servlet deployments
-#org.openremote.container.web.RequestLogger.level=FINE
+#org.openremote.container.web.LoggingFilter.level=FINE
# Set to fine to log all HTTP requests (not just deployments)
#org.openremote.container.web.WebService.level=INFO
diff --git a/manager/src/main/resources/logging-dev.properties b/manager/src/main/resources/logging-dev.properties
index fbf6d6f4d..e141c296a 100644
--- a/manager/src/main/resources/logging-dev.properties
+++ b/manager/src/main/resources/logging-dev.properties
@@ -41,7 +41,7 @@ org.openremote.level=FINEST
# Set to fine to log WS connections
#org.openremote.manager.event.ClientEventService.level=FINE
# Set to fine to log HTTP requests for servlet deployments
-#org.openremote.container.web.RequestLogger.level=FINE
+org.openremote.container.web.LoggingFilter.level=FINE
# Set to fine to log all HTTP requests (not just deployments)
#org.openremote.container.web.WebService.level=INFO
diff --git a/manager/src/main/resources/logging.properties b/manager/src/main/resources/logging.properties
index 4403e5231..3466f5bab 100644
--- a/manager/src/main/resources/logging.properties
+++ b/manager/src/main/resources/logging.properties
@@ -61,7 +61,7 @@ org.openremote.manager.mqtt.level=FINE
# Set to fine to log WS connections
org.openremote.manager.event.ClientEventService.level=FINE
# Set to fine to log HTTP requests for servlet deployments
-#org.openremote.container.web.RequestLogger.level=FINE
+#org.openremote.container.web.LoggingFilter.level=FINE
# Set to fine to log all HTTP requests (not just deployments)
#org.openremote.container.web.WebService.level=INFO
diff --git a/model/src/main/java/org/openremote/model/apps/AppResource.java b/model/src/main/java/org/openremote/model/apps/AppResource.java
index 40c6af377..d9cedba59 100644
--- a/model/src/main/java/org/openremote/model/apps/AppResource.java
+++ b/model/src/main/java/org/openremote/model/apps/AppResource.java
@@ -21,10 +21,13 @@ package org.openremote.model.apps;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
+import jakarta.ws.rs.BeanParam;
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.Produces;
import org.openremote.model.http.RequestParams;
-import jakarta.ws.rs.*;
-import jakarta.ws.rs.core.Response;
+import java.util.Map;
import static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;
@@ -47,7 +50,7 @@ public interface AppResource {
@Produces(APPLICATION_JSON)
@Path("info")
@Operation(operationId = "getAppInfos", summary = "Retrieve the info of the available applications")
- Response getAppInfos(@BeanParam RequestParams requestParams);
+ Map<String, Object> getAppInfos(@BeanParam RequestParams requestParams);
/**
* Retrieve console app config.
@@ -56,5 +59,5 @@ public interface AppResource {
@Produces(APPLICATION_JSON)
@Path("consoleConfig")
@Operation(operationId = "getConsoleConfig", summary = "Retrieve the console configuration")
- Response getConsoleConfig(@BeanParam RequestParams requestParams);
+ Object getConsoleConfig(@BeanParam RequestParams requestParams);
}
diff --git a/model/src/main/java/org/openremote/model/asset/AssetResource.java b/model/src/main/java/org/openremote/model/asset/AssetResource.java
index 620e67a38..daf5eead7 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetResource.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetResource.java
@@ -28,7 +28,6 @@ import jakarta.annotation.security.RolesAllowed;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import jakarta.ws.rs.*;
-import jakarta.ws.rs.core.Response;
import org.openremote.model.Constants;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeRef;
@@ -245,7 +244,7 @@ public interface AssetResource {
@ApiResponse(description = "The result of the write operation",
content = @Content(mediaType = "application/json",
schema = @Schema(implementation = AttributeWriteResult.class)))})
- Response writeAttributeValue(@BeanParam RequestParams requestParams, @PathParam("assetId") String assetId, @PathParam("attributeName") String attributeName, Object value);
+ AttributeWriteResult writeAttributeValue(@BeanParam RequestParams requestParams, @PathParam("assetId") String assetId, @PathParam("attributeName") String attributeName, Object value);
@PUT
//TODO: Using {timestamp:(\\d+)?} does not correctly tokenize when using the assetResource proxy client in Groovy tests.
@@ -257,7 +256,7 @@ public interface AssetResource {
description = "The result of the write operation",
content = @Content(mediaType = "application/json", schema = @Schema(implementation = AttributeWriteResult.class))
)})
- Response writeAttributeValue(@BeanParam RequestParams requestParams,
+ AttributeWriteResult writeAttributeValue(@BeanParam RequestParams requestParams,
@PathParam("assetId") String assetId,
@PathParam("attributeName") String attributeName,
@PathParam("timestamp") Long timestamp,
diff --git a/model/src/main/java/org/openremote/model/auth/OAuthGrant.java b/model/src/main/java/org/openremote/model/auth/OAuthGrant.java
index 5378b1399..10b2d52a9 100644
--- a/model/src/main/java/org/openremote/model/auth/OAuthGrant.java
+++ b/model/src/main/java/org/openremote/model/auth/OAuthGrant.java
@@ -45,7 +45,6 @@ public abstract class OAuthGrant implements Serializable {
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";
- @NotNull
protected String tokenEndpointUri;
protected boolean basicAuthHeader;
protected Map<String, List<String>> additionalValueMap = null;
@@ -60,7 +59,6 @@ public abstract class OAuthGrant implements Serializable {
String scope;
protected OAuthGrant(String tokenEndpointUri, String grantType, String clientId, String clientSecret, String scope) {
- requireNonNullAndNonEmpty(tokenEndpointUri);
requireNonNullAndNonEmpty(grantType);
requireNonNullAndNonEmpty(clientId);
this.grantType = grantType;
@@ -145,7 +143,6 @@ public abstract class OAuthGrant implements Serializable {
", basicAuthHeader=" + basicAuthHeader +
", grantType='" + grantType + '\'' +
", clientId='" + clientId + '\'' +
- ", clientSecret='" + clientSecret + '\'' +
", scope='" + scope + '\'' +
'}';
}
diff --git a/model/src/main/java/org/openremote/model/http/RequestParams.java b/model/src/main/java/org/openremote/model/http/RequestParams.java
index b7f9e3080..49832d459 100644
--- a/model/src/main/java/org/openremote/model/http/RequestParams.java
+++ b/model/src/main/java/org/openremote/model/http/RequestParams.java
@@ -19,14 +19,19 @@
*/
package org.openremote.model.http;
+import jakarta.ws.rs.HeaderParam;
+import jakarta.ws.rs.core.Context;
+import jakarta.ws.rs.core.HttpHeaders;
+import jakarta.ws.rs.core.UriBuilder;
+import jakarta.ws.rs.core.UriInfo;
import org.openremote.model.util.TextUtil;
-import jakarta.ws.rs.HeaderParam;
-import jakarta.ws.rs.core.*;
import java.net.URI;
public class RequestParams {
+ public static final String BEARER_AUTH_PREFIX = "Bearer ";
+
@Context
public HttpHeaders headers;
@@ -42,12 +47,6 @@ public class RequestParams {
@Context
public UriInfo uriInfo;
- public String getBearerAuth() {
- if (authorization == null || !authorization.startsWith("Bearer ") || authorization.split(" ").length != 2)
- return null;
- return authorization.split(" ")[1];
- }
-
public URI getExternalSchemeHostAndPort() {
return getExternalBaseUriBuilder().replacePath("").build();
}
diff --git a/test/src/main/groovy/org/openremote/test/ContainerTrait.groovy b/test/src/main/groovy/org/openremote/test/ContainerTrait.groovy
index cddb1f37c..b3ebdfa1f 100644
--- a/test/src/main/groovy/org/openremote/test/ContainerTrait.groovy
+++ b/test/src/main/groovy/org/openremote/test/ContainerTrait.groovy
@@ -20,24 +20,22 @@
package org.openremote.test
import jakarta.persistence.TypedQuery
+import jakarta.ws.rs.client.ClientRequestContext
+import jakarta.ws.rs.client.ClientRequestFilter
+import jakarta.ws.rs.core.HttpHeaders
import jakarta.ws.rs.core.UriBuilder
import org.apache.camel.ProducerTemplate
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.client.jaxrs.internal.ResteasyClientBuilderImpl
-import org.keycloak.representations.AccessTokenResponse
+import org.keycloak.admin.client.token.TokenService
import org.openremote.container.Container
import org.openremote.container.message.MessageBrokerService
import org.openremote.container.persistence.PersistenceService
-import org.openremote.container.security.ClientCredentialsAuthForm
-import org.openremote.container.security.IdentityService
-import org.openremote.container.security.PasswordAuthForm
import org.openremote.container.security.keycloak.KeycloakIdentityProvider
-import org.openremote.container.security.keycloak.KeycloakResource
import org.openremote.container.timer.TimerService
import org.openremote.container.util.LogUtil
-import org.openremote.container.web.WebClient
+import org.openremote.container.web.WebService
+import org.openremote.container.web.WebTargetBuilder
import org.openremote.manager.agent.AgentService
import org.openremote.manager.asset.AssetProcessingService
import org.openremote.manager.asset.AssetStorageService
@@ -52,7 +50,10 @@ import org.openremote.model.asset.Asset
import org.openremote.model.asset.UserAssetLink
import org.openremote.model.asset.agent.Agent
import org.openremote.model.asset.agent.Protocol
+import org.openremote.model.auth.OAuthClientCredentialsGrant
+import org.openremote.model.auth.OAuthPasswordGrant
import org.openremote.model.gateway.GatewayConnection
+import org.openremote.model.http.RequestParams
import org.openremote.model.query.AssetQuery
import org.openremote.model.query.RulesetQuery
import org.openremote.model.rules.AssetRuleset
@@ -63,20 +64,23 @@ import org.openremote.model.security.User
import org.openremote.model.util.MapAccess
import org.slf4j.Logger
import org.slf4j.LoggerFactory
+import spock.lang.Shared
-import javax.net.ssl.SSLSession
import java.util.concurrent.TimeUnit
+import java.util.concurrent.atomic.AtomicReference
import java.util.logging.Handler
import java.util.stream.Collectors
import java.util.stream.IntStream
-import static java.util.concurrent.TimeUnit.SECONDS
import static org.openremote.container.web.WebService.OR_WEBSERVER_LISTEN_PORT
import static org.openremote.model.Constants.MASTER_REALM
import static org.openremote.model.Constants.MASTER_REALM_ADMIN_USER
trait ContainerTrait {
+ @Shared
+ AtomicReference<ResteasyClient> testClient = new AtomicReference<>()
+
static {
LogUtil.initialiseJUL()
}
@@ -478,13 +482,6 @@ trait ContainerTrait {
def identityProvider = container.getService(ManagerIdentityService.class).getIdentityProvider()
List<User> users = identityProvider.queryUsers()
return users
-// List<Pair<User, Pair<Role[], Role[]>>> results = []
-// users.forEach {user ->
-// def roles = identityProvider.getUserRoles(user.realm, user.id, Constants.KEYCLOAK_CLIENT_ID)
-// def realmRoles = identityProvider.getUserRealmRoles(user.realm, user.id)
-// results.add(new Pair<User, Pair<Role[],Role[]>>(user, new Pair<>(roles, realmRoles)))
-// }
-// return results
}
Container getContainer() {
@@ -502,13 +499,10 @@ trait ContainerTrait {
container.running
}
- ResteasyClientBuilder createClient() {
- ResteasyClientBuilder clientBuilder =
- new ResteasyClientBuilderImpl()
- .connectTimeout(2, SECONDS)
- .readTimeout(15, SECONDS)
- .connectionPoolSize(10)
- return WebClient.registerDefaults(clientBuilder)
+ ResteasyClient createClient(String accessToken) {
+ testClient.updateAndGet {it != null ? it :
+ // Use a long timeout to make debugging a bit easier
+ WebTargetBuilder.createClient(Container.EXECUTOR, 1, 120000, null)}
}
UriBuilder serverUri(int serverPort) {
@@ -525,6 +519,11 @@ trait ContainerTrait {
try {
if (container != null) {
container.stop()
+ // Clear out the Built in JAX-RS client as the executor service it uses will be aggressively shutdown by Camel
+ WebTargetBuilder.BUILT_IN_CLIENT.getAndUpdate {if (it != null) {
+ it.close()
+ return null
+ }}
}
} catch (Exception e) {
LOG.warn("Failed to stop container", e)
@@ -532,27 +531,26 @@ trait ContainerTrait {
}
ResteasyWebTarget getClientTarget(UriBuilder serverUri, String accessToken) {
- WebClient.getTarget(createClient().build(), serverUri.build(), accessToken, null, null)
+ def target = createClient(accessToken).target(serverUri)
+ if (accessToken != null) {
+ ClientRequestFilter authFilter = {context ->
+ (context as ClientRequestContext).getHeaders().putSingle(HttpHeaders.AUTHORIZATION, RequestParams.BEARER_AUTH_PREFIX + accessToken)
+ }
+ target.register(authFilter)
+ }
+ return target
}
ResteasyWebTarget getClientApiTarget(UriBuilder serverUri, String realm) {
- WebClient.getTarget(createClient().build(), serverUri.clone().replacePath(ManagerWebService.API_PATH).path(realm).build(), null, null, null)
+ getClientTarget(serverUri.clone().replacePath(ManagerWebService.API_PATH).path(realm), null)
}
ResteasyWebTarget getClientApiTarget(UriBuilder serverUri, String realm, String accessToken) {
- WebClient.getTarget(createClient().build(), serverUri.clone().replacePath(ManagerWebService.API_PATH).path(realm).build(), accessToken, null, null)
+ getClientTarget(serverUri.clone().replacePath(ManagerWebService.API_PATH).path(realm), accessToken)
}
ResteasyWebTarget getClientApiTarget(UriBuilder serverUri, String realm, String path, String accessToken) {
- WebClient.getTarget(createClient().build(), serverUri.clone().replacePath(ManagerWebService.API_PATH).path(realm).path(path).build(), accessToken, null, null)
- }
-
- ResteasyWebTarget getClientApiTarget(ResteasyClient client, UriBuilder serverUri, String realm, String accessToken) {
- WebClient.getTarget(client, serverUri.clone().replacePath(ManagerWebService.API_PATH).path(realm).build(), accessToken, null, null)
- }
-
- ResteasyWebTarget getClientApiTarget(ResteasyClient client, UriBuilder serverUri, String realm, String path, String accessToken) {
- WebClient.getTarget(client, serverUri.clone().replacePath(ManagerWebService.API_PATH).path(realm).path(path).build(), accessToken, null, null)
+ getClientTarget(serverUri.clone().replacePath(ManagerWebService.API_PATH).path(realm).path(path), null)
}
int findEphemeralPort() {
@@ -562,20 +560,30 @@ trait ContainerTrait {
return port
}
- AccessTokenResponse authenticate(Container container, String realm, String clientId, String username, String password) {
- ((KeycloakIdentityProvider)container.getService(IdentityService.class).getIdentityProvider()).getKeycloak()
- .getAccessToken(realm, new PasswordAuthForm(clientId, username, password))
+ String authenticate(Container container, String realm, String clientId, String username, String password) {
+ container.getService(WebService.class).getBearerToken(
+ new OAuthPasswordGrant(
+ ((KeycloakIdentityProvider)container.getService(ManagerIdentityService.class).getIdentityProvider()).getTokenUri(realm).toString(),
+ clientId,
+ null,
+ null,
+ username,
+ password)).get(10, TimeUnit.SECONDS)
}
- AccessTokenResponse authenticate(Container container, String realm, String clientId, String clientSecret) {
- ((KeycloakIdentityProvider)container.getService(IdentityService.class).getIdentityProvider()).getKeycloak()
- .getAccessToken(realm, new ClientCredentialsAuthForm(clientId, clientSecret))
+ String authenticate(Container container, String realm, String clientId, String clientSecret) {
+ container.getService(WebService.class).getBearerToken(
+ new OAuthClientCredentialsGrant(
+ ((KeycloakIdentityProvider)container.getService(ManagerIdentityService.class).getIdentityProvider()).getTokenUri(realm).toString(),
+ clientId,
+ clientSecret,
+ null)).get(10, TimeUnit.SECONDS)
}
/**
* Makes a call to a remote OpenRemote manager to retrieve an access token for a given user
* */
- AccessTokenResponse authenticate(boolean secure,
+ String authenticate(boolean secure,
String host,
String realm,
String clientId,
@@ -585,20 +593,13 @@ trait ContainerTrait {
String scheme = secure ? "https" : "http"
String basePath = "/auth"
String baseUrl = "${scheme}://${host}${basePath}"
+ ResteasyWebTarget target = new WebTargetBuilder(WebTargetBuilder.getClient(), URI.create(baseUrl)).build()
+ TokenService keycloak = target.proxy(TokenService)
- ResteasyClient client = ResteasyClientBuilder.newBuilder().hostnameVerifier {String h, SSLSession s -> true }.build()
- ResteasyWebTarget target = (ResteasyWebTarget) client.target(baseUrl)
-
- KeycloakResource keycloak = target.proxy(KeycloakResource)
-
- try {
- return keycloak.getAccessToken(
- realm,
- new PasswordAuthForm(clientId, username, password)
- )
- } finally {
- client.close()
- }
+ return keycloak.grantToken(
+ realm,
+ new OAuthPasswordGrant(null, clientId, null, null, username, password)
+ .asMultivaluedMap()).token
}
ProducerTemplate getMessageProducerTemplate(Container container) {
diff --git a/test/src/test/groovy/org/openremote/test/alarm/AlarmResourceTest.groovy b/test/src/test/groovy/org/openremote/test/alarm/AlarmResourceTest.groovy
index 3f1883082..3412a44ec 100644
--- a/test/src/test/groovy/org/openremote/test/alarm/AlarmResourceTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/alarm/AlarmResourceTest.groovy
@@ -41,6 +41,8 @@ import spock.lang.Unroll
import spock.lang.Shared
import spock.util.concurrent.PollingConditions
+import java.util.concurrent.CopyOnWriteArrayList
+
import static org.openremote.container.security.IdentityProvider.OR_ADMIN_PASSWORD
import static org.openremote.container.security.IdentityProvider.OR_ADMIN_PASSWORD_DEFAULT
import static org.openremote.model.util.MapAccess.getString
@@ -77,7 +79,7 @@ class AlarmResourceTest extends Specification implements ManagerContainerTrait {
static NotificationService notificationService
@Shared
- static List<AbstractNotificationMessage> notificationMessages = []
+ static List<AbstractNotificationMessage> notificationMessages = new CopyOnWriteArrayList<>()
def setupSpec() {
def container = startContainer(defaultConfig(), defaultServices())
@@ -91,7 +93,7 @@ class AlarmResourceTest extends Specification implements ManagerContainerTrait {
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
regularUserResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM).proxy(AlarmResource.class)
adminResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, adminAccessToken).proxy(AlarmResource.class)
@@ -110,7 +112,7 @@ class AlarmResourceTest extends Specification implements ManagerContainerTrait {
KEYCLOAK_CLIENT_ID,
"testuser4",
"testuser4",
- ).token
+ )
superAdminResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, superAdminAccessToken).proxy(AlarmResource.class)
@@ -240,7 +242,10 @@ class AlarmResourceTest extends Specification implements ManagerContainerTrait {
then:
WebApplicationException ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
where:
title | content | severity | status
@@ -255,7 +260,10 @@ class AlarmResourceTest extends Specification implements ManagerContainerTrait {
then:
WebApplicationException ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
}
// Get alarms as admin
@@ -285,14 +293,20 @@ class AlarmResourceTest extends Specification implements ManagerContainerTrait {
then:
WebApplicationException ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when:
regularUserResource.getAlarm(null, 1L)
then:
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
}
// Update alarm as admin
@@ -340,12 +354,16 @@ class AlarmResourceTest extends Specification implements ManagerContainerTrait {
}
@Unroll
- def "should not update an alarm with id 'null'"() {
+ def "should not update an alarm with id 0"() {
when:
- adminResource.updateAlarm(null, null, new SentAlarm().setTitle('title').setContent('content').setSeverity(Severity.LOW).setStatus(Alarm.Status.OPEN))
+ adminResource.updateAlarm(null, 0, new SentAlarm().setTitle('title').setContent('content').setSeverity(Severity.LOW).setStatus(Alarm.Status.OPEN))
then:
- NullPointerException ex = thrown()
+ WebApplicationException ex = thrown()
+ ex.response.withCloseable { r ->
+ assert r.status == 404
+ return true
+ }
}
// Update alarm without write:alarm role
@@ -357,7 +375,10 @@ class AlarmResourceTest extends Specification implements ManagerContainerTrait {
then:
WebApplicationException ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
where:
title | content | severity | status
@@ -374,7 +395,10 @@ class AlarmResourceTest extends Specification implements ManagerContainerTrait {
then:
WebApplicationException ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
}
// Delete alarms without write:alarm role
@@ -387,30 +411,43 @@ class AlarmResourceTest extends Specification implements ManagerContainerTrait {
then:
WebApplicationException ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
}
// Delete empty or null alarms
def "should not delete null or empty alarms"() {
when:
- adminResource.removeAlarm(null, null)
+ adminResource.removeAlarm(null, 0)
then:
- NullPointerException npe = thrown()
+ WebApplicationException ex = thrown()
+ ex.response.withCloseable { r ->
+ assert r.status == 404
+ return true
+ }
when:
adminResource.removeAlarms(null, [])
then:
- WebApplicationException ex = thrown()
- ex.response.status == 400
+ ex = thrown()
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
when:
adminResource.removeAlarms(null, [null])
then:
ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
}
// Delete invalid alarms
@@ -420,14 +457,20 @@ class AlarmResourceTest extends Specification implements ManagerContainerTrait {
then:
WebApplicationException ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
when:
adminResource.removeAlarms(null, [-1L, 0L, 1L])
then:
ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
}
// Delete non-exising alarms
@@ -437,14 +480,20 @@ class AlarmResourceTest extends Specification implements ManagerContainerTrait {
then:
WebApplicationException ex = thrown()
- ex.response.status == 404
+ ex.response.withCloseable { r ->
+ assert r.status == 404
+ return true
+ }
when:
adminResource.removeAlarms(null, [1L, 2L, 3L])
then:
ex = thrown()
- ex.response.status == 404
+ ex.response.withCloseable { r ->
+ assert r.status == 404
+ return true
+ }
}
// Delete one alarm as admin
@@ -574,7 +623,10 @@ class AlarmResourceTest extends Specification implements ManagerContainerTrait {
then:
WebApplicationException ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
}
// Creating invalid alarm links
@@ -585,21 +637,30 @@ class AlarmResourceTest extends Specification implements ManagerContainerTrait {
then:
WebApplicationException ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
when:
adminResource.setAssetLinks(null, [null])
then:
ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
when:
adminResource.setAssetLinks(null, [new AlarmAssetLink(null, null, null)])
then:
ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
when:
@@ -607,27 +668,39 @@ class AlarmResourceTest extends Specification implements ManagerContainerTrait {
then:
ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
when:
adminResource.setAssetLinks(null, [new AlarmAssetLink(MASTER_REALM, -1L, null)])
then:
ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
when:
adminResource.setAssetLinks(null, [new AlarmAssetLink(MASTER_REALM, alarm.id, null)])
then:
ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
when:
adminResource.setAssetLinks(null, [new AlarmAssetLink(MASTER_REALM, alarm.id, "")])
then:
ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
}
}
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetDatapointExportTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetDatapointExportTest.groovy
index 046b172c8..f5fed168a 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetDatapointExportTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetDatapointExportTest.groovy
@@ -19,7 +19,6 @@ import spock.util.concurrent.PollingConditions
import java.nio.charset.StandardCharsets
import java.time.LocalDateTime
import java.time.ZoneId
-import java.util.zip.ZipInputStream
import static org.openremote.model.Constants.KEYCLOAK_CLIENT_ID
@@ -218,7 +217,7 @@ class AssetDatapointExportTest extends Specification implements ManagerContainer
KEYCLOAK_CLIENT_ID,
"smartcity",
"smartcity"
- ).token
+ )
def response = null
when: "exporting with a malicious attribute name via REST API"
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy
index 5b3901065..279e06c32 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy
@@ -129,7 +129,7 @@ class AssetDatapointTest extends Specification implements ManagerContainerTrait
KEYCLOAK_CLIENT_ID,
"testuser1",
"testuser1"
- ).token
+ )
// Resteasy client has issues with @Suspended annotation so not used for now
//def datapointResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(AssetDatapointResource.class)
def predictedDatapointResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(AssetPredictedDatapointResource.class)
@@ -537,7 +537,7 @@ class AssetDatapointTest extends Specification implements ManagerContainerTrait
KEYCLOAK_CLIENT_ID,
"testuser1",
"testuser1"
- ).token
+ )
def predictedDatapointResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(AssetPredictedDatapointResource.class)
and: "a websocket client authenticated in the same realm"
@@ -717,7 +717,7 @@ class AssetDatapointTest extends Specification implements ManagerContainerTrait
KEYCLOAK_CLIENT_ID,
"testuser2",
"testuser2"
- ).token
+ )
def predictedDatapointResource = getClientApiTarget(serverUri(serverPort), "building", accessToken).proxy(AssetPredictedDatapointResource.class)
and: "a restricted websocket client in the same realm"
@@ -800,7 +800,7 @@ class AssetDatapointTest extends Specification implements ManagerContainerTrait
KEYCLOAK_CLIENT_ID,
"testuser2",
"testuser2"
- ).token
+ )
def predictedDatapointResource = getClientApiTarget(serverUri(serverPort), "building", accessToken).proxy(AssetPredictedDatapointResource.class)
and: "a restricted websocket client in the same realm"
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy
index c9eb9ca5b..672d8ca72 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy
@@ -46,7 +46,7 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTrait
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
and: "the asset resource"
def serverUri = serverUri(serverPort)
@@ -68,16 +68,18 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTrait
testAsset.addOrReplaceAttributes(
new Attribute<>("illegal- Attribute:name&&&", ValueType.TEXT)
)
-
assetResource.update(null, testAsset.getId(), testAsset)
then: "the request should fail validation and return a validation report indicating the failure(s)"
WebApplicationException ex = thrown()
- ex.response.status == 400
- def report = ex.response.readEntity(ViolationReport)
- report != null
- report.propertyViolations.size() == 1
- report.propertyViolations.get(0).path == "attributes[illegal- Attribute:name&&&].name"
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ def report = r.readEntity(ViolationReport)
+ assert report != null
+ assert report.propertyViolations.size() == 1
+ assert report.propertyViolations.get(0).path == "attributes[illegal- Attribute:name&&&].name"
+ return true
+ }
when: "an asset is stored with a non-empty attribute value"
testAsset = assetResource.get(null, testAsset.getId())
@@ -121,7 +123,10 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTrait
then: "the request should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "an asset is updated with a new realm"
testAsset.setRealm(keycloakTestSetup.realmBuilding.name)
@@ -129,7 +134,10 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTrait
then: "the request should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "an asset is created with a non existent realm"
newTestAsset.setId(null)
@@ -138,7 +146,10 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTrait
then: "the request should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "an asset is updated with a non-existent parent"
testAsset = assetResource.get(null, testAsset.getId())
@@ -147,7 +158,10 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTrait
then: "the request should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "an asset is updated with itself as a parent"
testAsset = assetResource.get(null, testAsset.getId())
@@ -156,7 +170,10 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTrait
then: "the request should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "an asset is updated with a parent in a different realm"
testAsset = assetResource.get(null, testAsset.getId())
@@ -165,14 +182,20 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTrait
then: "the request should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "an asset is deleted but has children"
assetResource.delete(null, [managerTestSetup.apartment1Id])
then: "the request should be bad"
ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
}
def "Batch parent updates reject unknown child asset ids as superuser"() {
@@ -188,7 +211,7 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTrait
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
and: "there's an asset in the master realm"
def assetResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(AssetResource.class)
@@ -216,7 +239,7 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTrait
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
and: "there's an asset in the master realm"
def assetResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(AssetResource.class)
@@ -244,7 +267,7 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTrait
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
and: "there's an asset in the master realm"
def assetResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(AssetResource.class)
@@ -272,7 +295,7 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTrait
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
and: "there are assets in the master and building realms"
def assetResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(AssetResource.class)
@@ -302,7 +325,7 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTrait
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
and: "there's an asset in the master realm"
def assetResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(AssetResource.class)
@@ -337,7 +360,7 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTrait
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
and: "there is an asset hierarchy in the master realm"
def assetResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(AssetResource.class)
@@ -368,7 +391,7 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTrait
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
and: "there is a group parent that only accepts room assets"
def assetResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(AssetResource.class)
@@ -399,7 +422,7 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTrait
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
and: "there is a locally registered gateway asset in the building realm"
GatewayAsset gateway = assetStorageService.merge(new GatewayAsset("Test gateway")
@@ -436,7 +459,7 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTrait
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
and: "there is a locally registered gateway asset and a gateway descendant in the building realm"
GatewayAsset gateway = assetStorageService.merge(new GatewayAsset("Test gateway")
@@ -480,7 +503,7 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTrait
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
and: "the asset resource"
def serverUri = serverUri(serverPort)
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy
index 75cc42e65..4496eef86 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy
@@ -17,10 +17,10 @@ import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
-import static org.openremote.model.util.MapAccess.getString
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD_DEFAULT
import static org.openremote.model.Constants.*
+import static org.openremote.model.util.MapAccess.getString
import static org.openremote.model.value.MetaItemType.*
import static org.openremote.model.value.ValueType.BOOLEAN
import static org.openremote.model.value.ValueType.NUMBER
@@ -41,7 +41,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
and: "the asset resource"
def assetResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(AssetResource.class)
@@ -167,7 +167,10 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
then: "the asset should not be found"
WebApplicationException ex = thrown()
- ex.response.status == 404
+ ex.response.withCloseable { r ->
+ assert r.status == 404
+ return true
+ }
when: "an asset is deleted in a foreign realm"
assetResource.delete(null, [managerTestSetup.apartment2LivingroomId])
@@ -175,7 +178,10 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
then: "the asset should be not found"
ex = thrown()
- ex.response.status == 404
+ ex.response.withCloseable { r ->
+ assert r.status == 404
+ return true
+ }
when: "an asset attribute is written in the authenticated realm"
assetResource.writeAttributeValue(null, managerTestSetup.smartOfficeId, BuildingAsset.STREET.name, '"Teststreet 123"')
@@ -189,16 +195,24 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
}
when: "an non-existent assets attribute is written in the authenticated realm"
- def response = assetResource.writeAttributeValue(null, "doesnotexist", BuildingAsset.STREET.name, '"Teststreet 123"')
+ assetResource.writeAttributeValue(null, "doesnotexist", BuildingAsset.STREET.name, '"Teststreet 123"')
then: "the attribute should be not found"
- response.status == 404
+ ex = thrown()
+ ex.response.withCloseable { r ->
+ assert r.status == 404
+ return true
+ }
when: "an non-existent attribute is written in the authenticated realm"
- response = assetResource.writeAttributeValue(null, managerTestSetup.smartOfficeId, "doesnotexist", '"Teststreet 123"')
+ assetResource.writeAttributeValue(null, managerTestSetup.smartOfficeId, "doesnotexist", '"Teststreet 123"')
then: "the attribute should be not found"
- response.status == 404
+ ex = thrown()
+ ex.response.withCloseable { r ->
+ assert r.status == 404
+ return true
+ }
when: "an asset attribute is written in a foreign realm"
assetResource.writeAttributeValue(null, managerTestSetup.smartBuildingId, BuildingAsset.STREET.name, '"Teststreet 456"')
@@ -226,7 +240,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
KEYCLOAK_CLIENT_ID,
"testuser1",
"testuser1"
- ).token
+ )
and: "the asset resource"
def assetResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(AssetResource.class)
@@ -302,7 +316,10 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
/* ############################################## WRITE ####################################### */
@@ -332,7 +349,10 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "an asset is updated with a new parent in a foreign realm"
testAsset.setParentId(managerTestSetup.smartBuildingId)
@@ -340,7 +360,10 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "an asset is deleted in the authenticated realm"
assetResource.delete(null, [managerTestSetup.thingId])
@@ -348,14 +371,20 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
then: "the asset should not be found"
ex = thrown()
- ex.response.status == 404
+ ex.response.withCloseable { r ->
+ assert r.status == 404
+ return true
+ }
when: "an asset is deleted in a foreign realm"
assetResource.delete(null, [managerTestSetup.apartment2LivingroomId])
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "an asset attribute is written in the authenticated realm"
assetResource.writeAttributeValue(null, managerTestSetup.smartOfficeId, BuildingAsset.STREET.name, '"Teststreet 123"')
@@ -367,10 +396,14 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
}
when: "an asset attribute is written in a foreign realm"
- def response = assetResource.writeAttributeValue(null, managerTestSetup.smartBuildingId, BuildingAsset.STREET.name, '"Teststreet 456"')
+ assetResource.writeAttributeValue(null, managerTestSetup.smartBuildingId, BuildingAsset.STREET.name, '"Teststreet 456"')
then: "access should be forbidden"
- response.status == 403
+ ex = thrown()
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
}
def "Access assets as testuser2"() {
@@ -386,7 +419,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
KEYCLOAK_CLIENT_ID,
"testuser2",
"testuser2"
- ).token
+ )
and: "the asset resource"
def assetResource = getClientApiTarget(serverUri(serverPort), keycloakTestSetup.realmBuilding.name, accessToken).proxy(AssetResource.class)
@@ -450,7 +483,10 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
then: "access should be forbidden"
WebApplicationException ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
/* ############################################## WRITE ####################################### */
@@ -461,7 +497,10 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "an asset is made a root asset in the authenticated realm"
testAsset = assetResource.get(null, managerTestSetup.apartment1Id)
@@ -470,7 +509,10 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "an asset is created in the authenticated realm"
testAsset = new RoomAsset("Test Room")
@@ -479,33 +521,50 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "an asset is deleted in the authenticated realm"
assetResource.delete(null, [managerTestSetup.apartment2LivingroomId])
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "an asset is deleted in a foreign realm"
assetResource.delete(null, [managerTestSetup.thingId])
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "an asset attribute is written in the authenticated realm"
- def response = assetResource.writeAttributeValue(null, managerTestSetup.smartBuildingId, BuildingAsset.STREET.name, '"Teststreet 123"')
+ assetResource.writeAttributeValue(null, managerTestSetup.smartBuildingId, BuildingAsset.STREET.name, '"Teststreet 123"')
then: "access should be forbidden"
- response.status == 403
+ ex = thrown()
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "an asset attribute is written in a foreign realm"
- response = assetResource.writeAttributeValue(null, managerTestSetup.smartOfficeId, BuildingAsset.STREET.name, '"Teststreet 456"')
+ assetResource.writeAttributeValue(null, managerTestSetup.smartOfficeId, BuildingAsset.STREET.name, '"Teststreet 456"')
then: "access should be forbidden"
- response.status == 403
+ ex = thrown()
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
}
def "Access assets as restricted testuser3"() {
@@ -522,7 +581,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
KEYCLOAK_CLIENT_ID,
"testuser3",
"testuser3"
- ).token
+ )
and: "the asset resource"
def assetResource = getClientApiTarget(serverUri(serverPort), keycloakTestSetup.realmBuilding.name, accessToken).proxy(AssetResource.class)
@@ -626,7 +685,10 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
then: "access should be forbidden"
WebApplicationException ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "a user asset is retrieved by ID in the authenticated realm"
apartment1Livingroom = assetResource.get(null, managerTestSetup.apartment1LivingroomId)
@@ -654,7 +716,10 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "all linked assets of the user are retrieved"
assets = assetResource.queryAssets(null, null)
@@ -671,7 +736,10 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "an asset is made a root asset in the authenticated realm"
testAsset = assetResource.get(null, managerTestSetup.apartment1LivingroomId)
@@ -716,57 +784,90 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "an asset is deleted in the authenticated realm"
assetResource.delete(null, [managerTestSetup.apartment1LivingroomId])
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "an asset is deleted in a foreign realm"
assetResource.delete(null, [managerTestSetup.thingId])
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "a private asset attribute is written on a user asset"
- def response = assetResource.writeAttributeValue(null, managerTestSetup.apartment1LivingroomId, "lightSwitch", false)
+ assetResource.writeAttributeValue(null, managerTestSetup.apartment1LivingroomId, "lightSwitch", false)
then: "access should be forbidden"
- response.status == 403
+ ex = thrown()
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "an attribute is written on a non-existent user asset"
- response = assetResource.writeAttributeValue(null, "doesnotexist", "lightSwitch", false)
+ assetResource.writeAttributeValue(null, "doesnotexist", "lightSwitch", false)
then: "access should be forbidden"
- response.status == 403
+ ex = thrown()
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "an non-existent attribute is written on a user asset"
- response = assetResource.writeAttributeValue(null, managerTestSetup.apartment1LivingroomId, "doesnotexist", '"foo"')
+ assetResource.writeAttributeValue(null, managerTestSetup.apartment1LivingroomId, "doesnotexist", '"foo"')
then: "access should be forbidden"
- response.status == 403
+ ex = thrown()
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "an asset attribute is written on a non-user asset"
- response = assetResource.writeAttributeValue(null, managerTestSetup.apartment3LivingroomId, "lightSwitch", false)
+ assetResource.writeAttributeValue(null, managerTestSetup.apartment3LivingroomId, "lightSwitch", false)
then: "access should be forbidden"
- response.status == 403
+ ex = thrown()
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "an asset attribute is written in a foreign realm"
- response = assetResource.writeAttributeValue(null, managerTestSetup.smartOfficeId, BuildingAsset.STREET.name, '"Teststreet 123"')
+ assetResource.writeAttributeValue(null, managerTestSetup.smartOfficeId, BuildingAsset.STREET.name, '"Teststreet 123"')
then: "access should be forbidden"
- response.status == 403
+ ex = thrown()
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "a non-writable attribute value is written on a user asset"
- response = assetResource.writeAttributeValue(null, managerTestSetup.apartment1KitchenId, "presenceDetected", true)
+ assetResource.writeAttributeValue(null, managerTestSetup.apartment1KitchenId, "presenceDetected", true)
then: "access should be forbidden"
- response.status == 403
+ ex = thrown()
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "a non-writable attribute value is updated on a user asset"
testAsset = assetResource.get(null, managerTestSetup.apartment1KitchenId)
@@ -827,7 +928,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
KEYCLOAK_CLIENT_ID,
"testuser1",
"testuser1"
- ).token
+ )
and: "there are assets in the authenticated realm"
def assetResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(AssetResource.class)
@@ -862,7 +963,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
and: "there are child assets with parents in different accessible realms"
def assetResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(AssetResource.class)
@@ -890,7 +991,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
KEYCLOAK_CLIENT_ID,
"testuser1",
"testuser1"
- ).token
+ )
and: "there is an asset in the authenticated realm"
def assetResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(AssetResource.class)
@@ -918,7 +1019,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
KEYCLOAK_CLIENT_ID,
"testuser1",
"testuser1"
- ).token
+ )
and: "there's an asset in the authenticated realm"
def assetResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(AssetResource.class)
@@ -946,7 +1047,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
KEYCLOAK_CLIENT_ID,
"testuser3",
"testuser3"
- ).token
+ )
when: "a restricted user tries to move a linked asset"
def assetResource = getClientApiTarget(serverUri(serverPort), keycloakTestSetup.realmBuilding.name, accessToken).proxy(AssetResource.class)
@@ -971,7 +1072,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
KEYCLOAK_CLIENT_ID,
"testuser3",
"testuser3"
- ).token
+ )
when: "a restricted user tries to clear the parent of a linked asset"
def assetResource = getClientApiTarget(serverUri(serverPort), keycloakTestSetup.realmBuilding.name, accessToken).proxy(AssetResource.class)
@@ -1032,12 +1133,13 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
assert writeResults.find {it.ref.id == managerTestSetup.apartment2LivingroomId && it.ref.name == Asset.LOCATION.name}.failure == AttributeWriteFailure.INSUFFICIENT_ACCESS
when: "an attribute with public write=false is written to anonymously"
- def response = assetResource.writeAttributeValue(null, managerTestSetup.apartment1Id, BuildingAsset.STREET.name, '"Should fail"')
+ def result = assetResource.writeAttributeValue(null, managerTestSetup.apartment1Id, BuildingAsset.STREET.name, '"Should fail"')
- then: "the request should fail"
- response.withCloseable { r ->
- assert r.status == 403
- true
+ then: "the request should fail with an exception"
+ WebApplicationException ex = thrown()
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
}
}
}
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetTreeTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetTreeTest.groovy
index ff0fe511a..b86bb970a 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetTreeTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetTreeTest.groovy
@@ -37,7 +37,7 @@ class AssetTreeTest extends Specification implements ManagerContainerTrait {
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
and: "the asset resource is available"
def assetResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(AssetResource.class)
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetUserLinkingTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetUserLinkingTest.groovy
index 00c478773..796af6665 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetUserLinkingTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetUserLinkingTest.groovy
@@ -5,10 +5,10 @@ import org.openremote.container.security.keycloak.AccessTokenAuthContext
import org.openremote.container.timer.TimerService
import org.openremote.manager.security.ManagerIdentityService
import org.openremote.manager.setup.SetupService
-import org.openremote.setup.integration.KeycloakTestSetup
-import org.openremote.setup.integration.ManagerTestSetup
import org.openremote.model.asset.AssetResource
import org.openremote.model.asset.UserAssetLink
+import org.openremote.setup.integration.KeycloakTestSetup
+import org.openremote.setup.integration.ManagerTestSetup
import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
@@ -36,22 +36,22 @@ class AssetUserLinkingTest extends Specification implements ManagerContainerTrai
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
and: "the asset resource"
def assetResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessTokenString).proxy(AssetResource.class)
/* ############################################## READ ####################################### */
and: "user access tokens"
- def testUserAccessToken = authenticate(container, MASTER_REALM, KEYCLOAK_CLIENT_ID, "testuser1", "testuser1").token
+ def testUserAccessToken = authenticate(container, MASTER_REALM, KEYCLOAK_CLIENT_ID, "testuser1", "testuser1")
def accessToken = AdapterTokenVerifier.verifyToken(testUserAccessToken, keycloakTestSetup.getKeycloakProvider().getKeycloakDeployment(MASTER_REALM, KEYCLOAK_CLIENT_ID))
def testUser1Token = new AccessTokenAuthContext(MASTER_REALM, accessToken)
- testUserAccessToken = authenticate(container, keycloakTestSetup.realmBuilding.name, KEYCLOAK_CLIENT_ID, "testuser2", "testuser2").token
+ testUserAccessToken = authenticate(container, keycloakTestSetup.realmBuilding.name, KEYCLOAK_CLIENT_ID, "testuser2", "testuser2")
accessToken = AdapterTokenVerifier.verifyToken(testUserAccessToken, keycloakTestSetup.getKeycloakProvider().getKeycloakDeployment(keycloakTestSetup.realmBuilding.name, KEYCLOAK_CLIENT_ID))
def testUser2Token = new AccessTokenAuthContext(keycloakTestSetup.realmBuilding.name, accessToken)
- testUserAccessToken = authenticate(container, keycloakTestSetup.realmBuilding.name, KEYCLOAK_CLIENT_ID, "testuser3", "testuser3").token
+ testUserAccessToken = authenticate(container, keycloakTestSetup.realmBuilding.name, KEYCLOAK_CLIENT_ID, "testuser3", "testuser3")
accessToken = AdapterTokenVerifier.verifyToken(testUserAccessToken, keycloakTestSetup.getKeycloakProvider().getKeycloakDeployment(keycloakTestSetup.realmBuilding.name, KEYCLOAK_CLIENT_ID))
def testUser3Token = new AccessTokenAuthContext(keycloakTestSetup.realmBuilding.name, accessToken)
@@ -125,14 +125,20 @@ class AssetUserLinkingTest extends Specification implements ManagerContainerTrai
then: "an error response should be returned"
WebApplicationException ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
when: "the realm doesn't exist"
assetResource.getUserAssetLinks(null, "doesnotexist", keycloakTestSetup.testuser3Id, null)
then: "an error response should be returned"
ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
when: "all user assets are retrieved of a realm and user"
userAssetLinks = assetResource.getUserAssetLinks(null, keycloakTestSetup.realmBuilding.name, null, managerTestSetup.apartment1Id)
diff --git a/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy b/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy
index 434f2b979..988cfa0a9 100644
--- a/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy
@@ -68,7 +68,10 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
def response = requestTarget.request().get()
then: "the endpoint should return 404"
- response.status == 404
+ response.withCloseable {r ->
+ assert r.status == 404
+ return true
+ }
cleanup:
if (response != null) {
@@ -90,7 +93,10 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
def response = requestTarget.request().get()
then: "the endpoint should return 200"
- response.status == 200
+ response.withCloseable { r ->
+ assert r.status == 200
+ return true
+ }
cleanup:
if (response != null) {
@@ -117,10 +123,13 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
def response = requestTarget.request().get()
then: "both apps are returned"
- response.status == 200
- def appList = parse(response.readEntity(String.class)).orElse([])
- appList.contains("appBuiltin")
- appList.contains("appCustom")
+ response.withCloseable { r ->
+ assert r.status == 200
+ def appList = parse(r.readEntity(String.class)).orElse("") as String
+ appList.contains("appBuiltin")
+ appList.contains("appCustom")
+ return true
+ }
cleanup:
if (response != null) {
@@ -151,14 +160,14 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
def response = requestTarget.request().get()
then: "the response includes the app info"
- response.status == 200
- def infoMap = parse(response.readEntity(String.class)).orElse([:])
- infoMap.containsKey("appInfo")
+ response.withCloseable { r ->
+ assert r.status == 200
+ Map infoMap = parse(response.readEntity(String.class)).orElse([:])
+ infoMap.containsKey("appInfo")
+ return true
+ }
cleanup:
- if (response != null) {
- response.close()
- }
Files.deleteIfExists(appDir.resolve("info.json"))
Files.deleteIfExists(appDir)
Files.deleteIfExists(customDocRoot)
@@ -232,7 +241,7 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
KEYCLOAK_CLIENT_ID,
"testuser3",
"testuser3"
- ).token
+ )
and: "authenticated and anonymous console, rules and asset resources"
def authenticatedConsoleResource = getClientApiTarget(serverUri(serverPort), keycloakTestSetup.realmBuilding.name, accessToken).proxy(ConsoleResource.class)
@@ -374,7 +383,10 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
then: "the result should be bad request"
WebApplicationException ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
when: "a console registers with an id that doesn't exist"
def unusedId = UniqueIdentifierGenerator.generateId("UnusedConsoleId")
@@ -409,7 +421,10 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
then: "the result should be bad request"
ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
when: "a console is registered anonymously"
consoleRegistration.id = null
@@ -500,7 +515,9 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
//
// then: "the result should be forbidden"
// ex = thrown()
-// ex.response.status == 403
+// ex.response.withCloseable { r ->
+// assert r.status == 403
+// }
when: "a console's location is updated to be at the Smart Building"
authenticatedAssetResource.writeAttributeValue(null, testUser3Console2.id, Asset.LOCATION.name, SMART_BUILDING_LOCATION)
@@ -586,7 +603,9 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
//
// then: "the result should be a forbidden request"
// ex = thrown()
-// ex.response.status == 403
+// ex.response.withCloseable { r ->
+// assert r.status == 403
+// }
when: "the geofences of testUser3Console2 are retrieved"
geofences = authenticatedRulesResource.getAssetGeofences(null, testUser3Console2.id)
diff --git a/test/src/test/groovy/org/openremote/test/dashboard/DashboardTest.groovy b/test/src/test/groovy/org/openremote/test/dashboard/DashboardTest.groovy
index e3ff6251d..1697c4299 100644
--- a/test/src/test/groovy/org/openremote/test/dashboard/DashboardTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/dashboard/DashboardTest.groovy
@@ -40,21 +40,21 @@ class DashboardTest extends Specification implements ManagerContainerTrait {
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
def privateUser1AccessToken = authenticate(
container,
MASTER_REALM,
KEYCLOAK_CLIENT_ID,
"testuser1",
"testuser1"
- ).token
+ )
def smartcityUserAccessToken = authenticate(
container,
keycloakTestSetup.realmCity.name,
KEYCLOAK_CLIENT_ID,
"smartcity",
"smartcity"
- ).token
+ )
and: "the admin user has been retrieved"
def serverUri = serverUri(serverPort)
@@ -64,16 +64,16 @@ class DashboardTest extends Specification implements ManagerContainerTrait {
and: "an additional user without READ_INSIGHTS is created"
ClientRole[] noInsightsRoles = new ClientRole[] { ClientRole.READ_ASSETS }
User noAccessUser = keycloakTestSetup.createUser(MASTER_REALM, "noinsights", "noinsights", "firstName", "lastName", "[email protected]", true, noInsightsRoles)
- def noAccessUserToken = authenticate(container, MASTER_REALM, KEYCLOAK_CLIENT_ID, "noinsights", "noinsights").token
+ def noAccessUserToken = authenticate(container, MASTER_REALM, KEYCLOAK_CLIENT_ID, "noinsights", "noinsights")
and: "an additional user without WRITE_INSIGHTS is created"
ClientRole[] readonlyRoles = new ClientRole[] { ClientRole.READ_ASSETS, ClientRole.READ_INSIGHTS }
User readonlyUser = keycloakTestSetup.createUser(MASTER_REALM, "readinsights", "readinsights", "firstName", "lastName", "[email protected]", true, readonlyRoles)
- def readonlyUserToken = authenticate(container, MASTER_REALM, KEYCLOAK_CLIENT_ID, "readinsights", "readinsights").token
+ def readonlyUserToken = authenticate(container, MASTER_REALM, KEYCLOAK_CLIENT_ID, "readinsights", "readinsights")
and: "an additional user with all permissions is created"
User alternativeUser = keycloakTestSetup.createUser(MASTER_REALM, "alternativeuser", "alternativeuser", "alternative", "user", "[email protected]", true, KeycloakTestSetup.REGULAR_USER_ROLES)
- def alternativeUserToken = authenticate(container, MASTER_REALM, KEYCLOAK_CLIENT_ID, "alternativeuser", "alternativeuser").token
+ def alternativeUserToken = authenticate(container, MASTER_REALM, KEYCLOAK_CLIENT_ID, "alternativeuser", "alternativeuser")
and: "the dashboard resource"
def adminUserDashboardResource = getClientApiTarget(serverUri, MASTER_REALM, adminUserAccessToken).proxy(DashboardResource.class)
@@ -314,7 +314,7 @@ class DashboardTest extends Specification implements ManagerContainerTrait {
KEYCLOAK_CLIENT_ID,
"testuser3",
"testuser3"
- ).token
+ )
def restrictedUserDashboardResource = getClientApiTarget(serverUri, keycloakTestSetup.realmBuilding.name, restrictedUser1AccessToken).proxy(DashboardResource.class)
and: "a restricted user tries to query a dashboard without access to the assets shown"
diff --git a/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovy b/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovy
index 111db2d18..12e3f514a 100644
--- a/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovy
@@ -1,7 +1,7 @@
package org.openremote.test.gateway
import io.netty.channel.ChannelHandler
-import jakarta.ws.rs.ForbiddenException
+import jakarta.ws.rs.WebApplicationException
import org.apache.http.client.utils.URIBuilder
import org.jboss.resteasy.client.jaxrs.ResteasyClient
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder
@@ -116,14 +116,18 @@ class GatewayTest extends Specification implements ManagerContainerTrait {
managerTestSetup.realmBuildingName,
gateway.getClientId().orElse(""),
gateway.getClientSecret().orElse("")
- ).token
+ )
def assetResource = getClientApiTarget(serverUri(serverPort), managerTestSetup.realmBuildingName, accessToken).proxy(AssetResource.class)
and: "the realm assets are requested"
def realmAssets = assetResource.queryAssets(null, null)
then: "an exception should be thrown"
- thrown(ForbiddenException.class)
+ WebApplicationException ex = thrown()
+ ex.response.withCloseable {
+ assert ex.response.status == 403
+ true
+ }
when: "the Gateway client is created"
def gatewayClient = new WebsocketIOClient(
@@ -139,12 +143,14 @@ class GatewayTest extends Specification implements ManagerContainerTrait {
and: "we add callback consumers to the client"
def connectionStatus = gatewayClient.getConnectionStatus()
- List<String> clientReceivedMessages = []
- gatewayClient.addMessageConsumer({
- message -> clientReceivedMessages.add(message as String)
+ List<String> clientReceivedMessages = new CopyOnWriteArrayList<>()
+ gatewayClient.addMessageConsumer({message ->
+ getLOG().info("Message received from central manager: $message")
+ clientReceivedMessages.add(message as String)
})
- gatewayClient.addConnectionStatusConsumer({
- status -> connectionStatus = status
+ gatewayClient.addConnectionStatusConsumer({status ->
+ getLOG().info("Gateway client connection staus changed: $status")
+ connectionStatus = status
})
and: "the gateway connects to this manager"
@@ -171,10 +177,10 @@ class GatewayTest extends Specification implements ManagerContainerTrait {
}
when: "the gateway client assets are defined"
- List<String> agentAssetIds = []
- List<HTTPAgent> agentAssets = []
- List<String> assetIds = []
- List<Asset> assets = []
+ List<String> agentAssetIds = new CopyOnWriteArrayList<>()
+ List<HTTPAgent> agentAssets = new CopyOnWriteArrayList<>()
+ List<String> assetIds = new CopyOnWriteArrayList<>()
+ List<Asset> assets = new CopyOnWriteArrayList<>()
IntStream.rangeClosed(1, 5).forEach { i ->
agentAssetIds.add(UniqueIdentifierGenerator.generateId("Test Agent $i"))
@@ -238,7 +244,7 @@ class GatewayTest extends Specification implements ManagerContainerTrait {
}
and: "the gateway client replies to the central manager with the assets of the gateway"
- List<Asset> sendAssets = []
+ List<Asset> sendAssets = new CopyOnWriteArrayList<>()
sendAssets.addAll(agentAssets)
sendAssets.addAll(assets)
def readAssetsReplyEvent = new AssetsEvent(sendAssets)
@@ -262,7 +268,7 @@ class GatewayTest extends Specification implements ManagerContainerTrait {
}
when: "the gateway returns the requested assets"
- sendAssets = []
+ sendAssets = new CopyOnWriteArrayList<>()
sendAssets.addAll(agentAssets)
sendAssets.addAll(Arrays.stream(readAssetsEvent.assetQuery.ids).filter { !agentAssetIds.contains(it) }.map { id -> assets.stream().filter { asset -> asset.id == id }.findFirst().orElse(null) }.collect(Collectors.toList()))
readAssetsReplyEvent = new AssetsEvent(sendAssets)
@@ -324,7 +330,7 @@ class GatewayTest extends Specification implements ManagerContainerTrait {
}
when: "the gateway returns the requested assets"
- sendAssets = []
+ sendAssets = new CopyOnWriteArrayList<>()
sendAssets.addAll(Arrays.stream(readAssetsEvent.assetQuery.ids).map { id -> assets.stream().filter { asset -> asset.id == id }.findFirst().orElse(null) }.collect(Collectors.toList()))
readAssetsReplyEvent = new AssetsEvent(sendAssets)
readAssetsReplyEvent.setMessageID(messageId)
@@ -692,7 +698,7 @@ class GatewayTest extends Specification implements ManagerContainerTrait {
}
when: "the gateway returns the requested assets"
- sendAssets = []
+ sendAssets = new CopyOnWriteArrayList<>()
sendAssets.addAll(Arrays.stream(readAssetsEvent.assetQuery.ids).map { id -> assets.stream().filter { asset -> asset.id == id }.findFirst().orElse(null) }.collect(Collectors.toList()))
readAssetsReplyEvent = new AssetsEvent(sendAssets)
readAssetsReplyEvent.setMessageID(messageId)
@@ -779,7 +785,7 @@ class GatewayTest extends Specification implements ManagerContainerTrait {
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
and: "the gateway client resource"
@@ -1181,7 +1187,7 @@ class GatewayTest extends Specification implements ManagerContainerTrait {
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
and: "the gateway client resource"
def gatewayClientResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(GatewayClientResource.class)
@@ -1328,7 +1334,7 @@ class GatewayTest extends Specification implements ManagerContainerTrait {
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
def gatewayResource = getClientApiTarget(serverUri((isCentralInstanceSecure), centralInstanceHostname, centralInstancePort), MASTER_REALM, accessToken).proxy(GatewayServiceResource.class)
when: "a new gateway client connection is created to connect to the central instance"
@@ -1403,27 +1409,19 @@ class GatewayTest extends Specification implements ManagerContainerTrait {
* */
and: "We request a new admin token from the tunnel URL"
- def x = authenticate(true,
+ def token = authenticate(true,
centralManagerTunnelInfo.id + "." + centralManagerTunnelInfo.hostname,
MASTER_REALM,
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT))
- then: "the request should be successful"
-
- assert x.error == null
-
- and: "Response contains a valid access token"
-
- assert x.getExpiresIn() > 0
-
when: "We request the info endpoint of the currently running manager"
String scheme = isCentralInstanceSecure ? "https" : "http"
String basePath = "/api/master"
String baseUrl = "${scheme}://$centralManagerTunnelInfo.id.$centralManagerTunnelInfo.hostname$basePath"
-
+ // TODO: Use WebTarget class and built in client for this
ResteasyClient client = ResteasyClientBuilder.newBuilder().hostnameVerifier { String h, SSLSession s -> true }.build()
ResteasyWebTarget target = (ResteasyWebTarget) client.target(baseUrl)
diff --git a/test/src/test/groovy/org/openremote/test/map/MapResourceTest.groovy b/test/src/test/groovy/org/openremote/test/map/MapResourceTest.groovy
index f10a13668..808a2b362 100644
--- a/test/src/test/groovy/org/openremote/test/map/MapResourceTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/map/MapResourceTest.groovy
@@ -41,7 +41,7 @@ class MapResourceTest extends Specification implements ManagerContainerTrait {
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
and: "a test client target set"
clientTarget = getClientApiTarget(serverUri(serverPort), realm, accessToken)
@@ -146,7 +146,10 @@ class MapResourceTest extends Specification implements ManagerContainerTrait {
.post(Entity.entity(Files.readAllBytes(Path.of("manager/src/map/mapsettings.json")), MediaType.APPLICATION_OCTET_STREAM_TYPE))
then: "an internal server error should occur"
- response.status == 500
+ response.withCloseable { r ->
+ assert r.status == 500
+ return true
+ }
when: "illegal filename was specified"
response = clientTarget
@@ -156,7 +159,10 @@ class MapResourceTest extends Specification implements ManagerContainerTrait {
.post(Entity.entity(Files.readAllBytes(Path.of("manager/src/map/mapdata.mbtiles")), MediaType.APPLICATION_OCTET_STREAM_TYPE))
then: "bad request error should occur"
- response.status == 400
+ response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
when: "the tiles are too large"
container.getService(MapService.class).customMapLimit = 10
@@ -167,7 +173,10 @@ class MapResourceTest extends Specification implements ManagerContainerTrait {
.post(Entity.entity(Files.readAllBytes(Path.of("manager/src/map/mapdata.mbtiles")), MediaType.APPLICATION_OCTET_STREAM_TYPE))
then: "request entity too large error should occur"
- response.status == 413
+ response.withCloseable { r ->
+ assert r.status == 413
+ return true
+ }
}
def "Configure custom tile server URL"() {
diff --git a/test/src/test/groovy/org/openremote/test/metrics/MetricsEndpointTest.groovy b/test/src/test/groovy/org/openremote/test/metrics/MetricsEndpointTest.groovy
index e996e92af..57c7c4dfa 100644
--- a/test/src/test/groovy/org/openremote/test/metrics/MetricsEndpointTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/metrics/MetricsEndpointTest.groovy
@@ -22,22 +22,23 @@ class MetricsEndpointTest extends Specification implements ManagerContainerTrait
and: "a resource client is created"
// Resteasy client has issues with @Suspended annotation so not used for now
//def datapointResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(AssetDatapointResource.class)
- def requestTarget = getClientTarget(serverUri(HealthService.OR_METRICS_PORT_DEFAULT).path("metrics"), MASTER_REALM)
+ def requestTarget = getClientTarget(serverUri(HealthService.OR_METRICS_PORT_DEFAULT).path("metrics"), null)
when: "requesting the metrics endpoint"
def response = requestTarget.request().get()
then: "the response should contain metrics data"
- response.getStatus() == 200
- def responseStr = response.readEntity(String.class)
- responseStr.contains("executor_pool_core_threads{name=\"ContainerExecutor\"}")
-
- and: "JVM related metrics are present"
- responseStr.contains("jvm_info")
- responseStr.contains("jvm_buffer_")
- responseStr.contains("jvm_gc_")
- responseStr.contains("jvm_memory_")
- responseStr.contains("jvm_threads_")
+ response.withCloseable { r ->
+ def responseStr = r.readEntity(String.class)
+ assert responseStr.contains("executor_pool_core_threads{name=\"ContainerExecutor\"}")
+ assert responseStr.contains("jvm_info")
+ assert responseStr.contains("jvm_buffer_")
+ assert responseStr.contains("jvm_gc_")
+ assert responseStr.contains("jvm_memory_")
+ assert responseStr.contains("jvm_threads_")
+ assert r.status == 200
+ return true
+ }
cleanup: "clean up"
if (response != null) {
diff --git a/test/src/test/groovy/org/openremote/test/model/AssetModelTest.groovy b/test/src/test/groovy/org/openremote/test/model/AssetModelTest.groovy
index d3e15b2cd..2103ecaf3 100644
--- a/test/src/test/groovy/org/openremote/test/model/AssetModelTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/model/AssetModelTest.groovy
@@ -108,7 +108,7 @@ class AssetModelTest extends Specification implements ManagerContainerTrait {
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
stopPseudoClock()
and: "the asset resource"
@@ -128,7 +128,10 @@ class AssetModelTest extends Specification implements ManagerContainerTrait {
then: "a constraint violation exception should be thrown"
WebApplicationException ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
def report = ex.response.readEntity(ViolationReport)
report.propertyViolations.size() == 1
report.propertyViolations.get(0).path == "attributes[positiveInt].value"
@@ -247,7 +250,10 @@ class AssetModelTest extends Specification implements ManagerContainerTrait {
then: "a constraint violation exception should be thrown"
ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
when: "the report is extracted"
report = ex.response.readEntity(ViolationReport)
@@ -360,7 +366,10 @@ class AssetModelTest extends Specification implements ManagerContainerTrait {
then: "a constraint violation exception should be thrown"
ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
when: "the report is extracted"
report = ex.response.readEntity(ViolationReport)
diff --git a/test/src/test/groovy/org/openremote/test/mqtt/MqttBrokerTest.groovy b/test/src/test/groovy/org/openremote/test/mqtt/MqttBrokerTest.groovy
index 5807c40b1..cbcb2b761 100644
--- a/test/src/test/groovy/org/openremote/test/mqtt/MqttBrokerTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/mqtt/MqttBrokerTest.groovy
@@ -48,6 +48,7 @@ class MqttBrokerTest extends Specification implements ManagerContainerTrait {
List<SharedEvent> receivedEvents = new CopyOnWriteArrayList<>()
List<SharedEvent> restrictedReceivedEvents = new CopyOnWriteArrayList<>()
List<Object> receivedValues = new CopyOnWriteArrayList<>()
+ List<ConnectionStatus> clientConnectionStatuses = new CopyOnWriteArrayList<>()
MQTT_IOClient client = null
MQTT_IOClient newClient = null
def conditions = new PollingConditions(timeout: 15, initialDelay: 0.1, delay: 0.2)
@@ -68,15 +69,24 @@ class MqttBrokerTest extends Specification implements ManagerContainerTrait {
when: "a mqtt client connects with invalid credentials"
def wrongUsername = "master:" + keycloakTestSetup.serviceUser.username
client = new MQTT_IOClient(mqttClientId, mqttHost, mqttPort, false, true, new UsernamePassword(wrongUsername, password), null, null)
+ client.addConnectionStatusConsumer {clientConnectionStatuses.add(it)}
client.connect()
- then: "the client connection status should be in error"
+ then: "the client should fail connection and retry"
conditions.eventually {
- assert client.getConnectionStatus() == ConnectionStatus.CONNECTING
+ assert clientConnectionStatuses.contains(ConnectionStatus.CONNECTING)
+ assert clientConnectionStatuses.contains(ConnectionStatus.WAITING)
}
- when: "a mqtt client connects with valid credentials"
+ when: "the client disconnects"
client.disconnect()
+
+ then: "the status should be reported and reconnect cancelled"
+ conditions.eventually {
+ assert clientConnectionStatuses.contains(ConnectionStatus.DISCONNECTED)
+ }
+
+ when: "a mqtt client connects with valid credentials"
mqttClientId = UniqueIdentifierGenerator.generateId()
client = new MQTT_IOClient(mqttClientId, mqttHost, mqttPort, false, true, new UsernamePassword(username, password), null, null)
client.connect()
diff --git a/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy b/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy
index bbc9382b2..8455b1c9f 100644
--- a/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy
@@ -32,6 +32,7 @@ import spock.util.concurrent.PollingConditions
import java.time.Instant
import java.time.temporal.ChronoUnit
+import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.TimeUnit
import static org.openremote.model.util.MapAccess.getString
@@ -45,10 +46,10 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
def "Check push notification functionality"() {
- List<String> notificationIds = []
- List<Notification.TargetType> notificationTargetTypes = []
- List<String> notificationTargetIds = []
- List<AbstractNotificationMessage> notificationMessages = []
+ List<String> notificationIds = new CopyOnWriteArrayList<>()
+ List<Notification.TargetType> notificationTargetTypes = new CopyOnWriteArrayList<>()
+ List<String> notificationTargetIds = new CopyOnWriteArrayList<>()
+ List<AbstractNotificationMessage> notificationMessages = new CopyOnWriteArrayList<>()
given: "the container environment is started with the mock handler"
def conditions = new PollingConditions(timeout: 10, initialDelay: 0.1, delay: 0.2)
@@ -90,21 +91,21 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
KEYCLOAK_CLIENT_ID,
"testuser1",
"testuser1"
- ).token
+ )
def testuser2AccessToken = authenticate(
container,
realm,
KEYCLOAK_CLIENT_ID,
"testuser2",
"testuser2"
- ).token
+ )
def testuser3AccessToken = authenticate(
container,
realm,
KEYCLOAK_CLIENT_ID,
"testuser3",
"testuser3"
- ).token
+ )
and: "an authenticated superuser"
def adminAccessToken = authenticate(
@@ -113,7 +114,7 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
def notification = new Notification("TestAction",
new PushNotificationMessage("Test Action",
@@ -136,7 +137,7 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
def testuser3ConsoleResource = getClientApiTarget(serverUri(serverPort), realm, testuser3AccessToken).proxy(ConsoleResource.class)
def adminConsoleResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, adminAccessToken).proxy(ConsoleResource.class)
def anonymousConsoleResource = getClientApiTarget(serverUri(serverPort), realm).proxy(ConsoleResource.class)
- SentNotification[] notifications = []
+ SentNotification[] notifications = new CopyOnWriteArrayList<>()
when: "various consoles are registered"
def consoleRegistration = new ConsoleRegistration(null,
@@ -200,7 +201,10 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
then: "no notification should have been sent"
WebApplicationException ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
when: "the admin user sends a notification to a user in a different realm with emailNotificationsDisabled set to true"
notification.targets = [new Notification.Target(Notification.TargetType.USER, keycloakTestSetup.testuser2Id)]
@@ -209,7 +213,10 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
then: "no notification should have been sent"
ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
notificationIds.size() == 3
when: "the admin user sends a notification to a user in a different realm with emailNotificationsDisabled set to false"
@@ -228,7 +235,10 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
then: "no notification should have been sent"
ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
when: "a restricted user sends a push notification to another user in the same realm"
notification.targets = [new Notification.Target(Notification.TargetType.USER, keycloakTestSetup.testuser2Id)]
@@ -236,14 +246,20 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
then: "no notification should have been sent"
ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
when: "an anonymous user sends a push notification to a user"
anonymousNotificationResource.sendNotification(null, notification)
then: "no notification should have been sent"
ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
when: "the admin user sends a push notification to the console assets in building realm"
notificationIds.clear()
@@ -268,7 +284,10 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
then: "no notification should have been sent"
ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
when: "a regular user sends a push notification to the console assets in the same realm"
notificationIds.clear()
@@ -302,7 +321,10 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
then: "no notification should have been sent"
ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
when: "a restricted user sends a push notification to some consoles linked to them and some not linked to them"
notificationIds.clear()
@@ -314,7 +336,10 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
then: "no notification should have been sent"
ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
and: "no new notifications should have been sent"
notificationIds.size() == 0
@@ -363,7 +388,10 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
then: "a bad request exception should be thrown"
ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
and: "the notification should be recorded in the DB with the exception set as the error"
conditions.eventually {
@@ -418,7 +446,10 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "a regular user marks a console notification for their own console as delivered"
testuser3NotificationResource.notificationDelivered(null, testuser3Console1.id, notifications.find {n -> n.targetId == testuser3Console1.id}.id)
@@ -434,7 +465,9 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
//
// then: "access should be forbidden"
// ex = thrown()
-// ex.response.status == 403
+// ex.response.withCloseable { r ->
+// assert r.status == 403
+// }
when: "an anonymous user marks a console notification for their own console as delivered"
notifications = adminNotificationResource.getNotifications(null, null, null, null, null, null, null, anonymousConsole.id)
@@ -450,14 +483,20 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "a restricted user tries to remove notifications"
testuser3NotificationResource.removeNotifications(null, null, PushNotificationMessage.TYPE, null, null, realm, null, null)
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "the admin user removes notifications by timestamp and the notifications are retrieved again"
notifications = adminNotificationResource.getNotifications(null, null, PushNotificationMessage.TYPE, null, null, null, null, null).reverse(true)
@@ -494,7 +533,10 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
then: "request should not be allowed"
ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
// -----------------------------------------------
// Check notification repeat frequency
@@ -587,7 +629,7 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
def "Check email notification functionality"() {
- List<Message> sentEmails = []
+ List<Message> sentEmails = new CopyOnWriteArrayList<>()
given: "the container environment is started with the mock handler"
def conditions = new PollingConditions(timeout: 10, delay: 0.2)
@@ -670,15 +712,15 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
def "Check localized notification functionality"() {
- List<String> localizedNotificationIds = []
- List<Notification.TargetType> localizedNotificationTargetTypes = []
- List<String> localizedNotificationTargetIds = []
- List<AbstractNotificationMessage> localizedNotificationMessages = []
+ List<String> localizedNotificationIds = new CopyOnWriteArrayList<>()
+ List<Notification.TargetType> localizedNotificationTargetTypes = new CopyOnWriteArrayList<>()
+ List<String> localizedNotificationTargetIds = new CopyOnWriteArrayList<>()
+ List<AbstractNotificationMessage> localizedNotificationMessages = new CopyOnWriteArrayList<>()
- List<String> pushNotificationIds = []
- List<Notification.TargetType> pushNotificationTargetTypes = []
- List<String> pushNotificationTargetIds = []
- List<AbstractNotificationMessage> pushNotificationMessages = []
+ List<String> pushNotificationIds = new CopyOnWriteArrayList<>()
+ List<Notification.TargetType> pushNotificationTargetTypes = new CopyOnWriteArrayList<>()
+ List<String> pushNotificationTargetIds = new CopyOnWriteArrayList<>()
+ List<AbstractNotificationMessage> pushNotificationMessages = new CopyOnWriteArrayList<>()
given: "the container environment is started with the mock handler"
def conditions = new PollingConditions(timeout: 10, initialDelay: 0.1, delay: 0.2)
@@ -747,7 +789,7 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
def notification = new Notification(
"MultiLanguageAction",
@@ -837,7 +879,7 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
KEYCLOAK_CLIENT_ID,
"testuser1",
"testuser1"
- ).token
+ )
and: "their language is updated to dutch"
def testuser1 = identityService.getIdentityProvider().getUserByUsername(MASTER_REALM, "testuser1")
@@ -949,7 +991,7 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
complexNotification.targets = [new Notification.Target(Notification.TargetType.REALM, MASTER_REALM)]
and: "the mock email notification handler has been added"
- List<Message> sentEmails = []
+ List<Message> sentEmails = new CopyOnWriteArrayList<>()
def emailNotificationHandler = container.getService(EmailNotificationHandler.class)
EmailNotificationHandler mockEmailNotificationHandler = Spy(emailNotificationHandler)
mockEmailNotificationHandler.isValid() >> true
diff --git a/test/src/test/groovy/org/openremote/test/protocol/KNXImportTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/KNXImportTest.groovy
index fca3035bf..8235d3a84 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/KNXImportTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/KNXImportTest.groovy
@@ -72,7 +72,7 @@ class KNXImportTest extends Specification implements ManagerContainerTrait {
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
and: "the agent resource"
def agentResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(AgentResource.class)
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
index 0802b963c..2eb8e596c 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/http/HttpClientProtocolTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/http/HttpClientProtocolTest.groovy
@@ -83,6 +83,7 @@ class HttpClientProtocolTest extends Specification implements ManagerContainerTr
void filter(ClientRequestContext requestContext) throws IOException {
def requestUri = requestContext.uri
def requestPath = requestUri.scheme + "://" + requestUri.host + requestUri.path
+ getLOG().info("MOCK SERVER: $requestPath")
switch (requestPath) {
case "https://mockapi/basicauth":
@@ -297,13 +298,7 @@ class HttpClientProtocolTest extends Specification implements ManagerContainerTr
def assetProcessingService = container.getService(AssetProcessingService.class)
def agentService = container.getService(AgentService.class)
- when: "the web target builder is configured to use the mock server"
- HTTPProtocol.initClient()
- if (!HTTPProtocol.client.get().configuration.isRegistered(mockServer)) {
- HTTPProtocol.client.get().register(mockServer, Integer.MAX_VALUE)
- }
-
- and: "a HTTP client agent is created"
+ when: "a HTTP client agent is created"
HTTPAgent agent = new HTTPAgent("Test agent")
.setRealm(Constants.MASTER_REALM)
.setBaseURI("https://mockapi")
@@ -332,7 +327,12 @@ class HttpClientProtocolTest extends Specification implements ManagerContainerTr
assert agent.getAgentStatus().orElse(ConnectionStatus.DISCONNECTED) == ConnectionStatus.CONNECTED
}
- when: "an asset is created with attributes linked to the agent"
+ when: "the mock filter is registered on the protocol instance client to mock auth and requests"
+ def protocolInstance = agentService.getProtocolInstance(agent.id) as HTTPProtocol
+ protocolInstance.client.register(mockServer, Integer.MAX_VALUE)
+ protocolInstance.doStart(getContainer())
+
+ and: "an asset is created with attributes linked to the agent"
def asset = new ThingAsset("Test Asset")
.setParent(agent)
.addOrReplaceAttributes(
@@ -515,7 +515,15 @@ class HttpClientProtocolTest extends Specification implements ManagerContainerTr
assert agentService.getAgent(agent4.id).getAgentStatus().orElse(null) == ConnectionStatus.CONNECTED
}
- when: "attributes are linked to these agents"
+ when: "mock filters are registered"
+ ((HTTPProtocol)agentService.getProtocolInstance(agent2.id)).client.register(mockServer, Integer.MAX_VALUE)
+ ((HTTPProtocol)agentService.getProtocolInstance(agent2.id)).doStart(getContainer())
+ ((HTTPProtocol)agentService.getProtocolInstance(agent3.id)).client.register(mockServer, Integer.MAX_VALUE)
+ ((HTTPProtocol)agentService.getProtocolInstance(agent3.id)).doStart(getContainer())
+ ((HTTPProtocol)agentService.getProtocolInstance(agent4.id)).client.register(mockServer, Integer.MAX_VALUE)
+ ((HTTPProtocol)agentService.getProtocolInstance(agent4.id)).doStart(getContainer())
+
+ and: "attributes are linked to these agents"
def asset2 = new ThingAsset("Test Asset 2")
.setRealm(Constants.MASTER_REALM)
.addOrReplaceAttributes(
@@ -586,11 +594,6 @@ class HttpClientProtocolTest extends Specification implements ManagerContainerTr
conditions.eventually {
assert mockServer.successCount == 1
}
-
- cleanup: "remove mock"
- if (HTTPProtocol.client.get() != null) {
- HTTPProtocol.client.set(null)
- }
}
def "Check HTTP client dynamic time feature"() {
@@ -608,16 +611,7 @@ class HttpClientProtocolTest extends Specification implements ManagerContainerTr
def agentService = container.getService(AgentService.class)
def timerService = container.getService(TimerService.class)
-
-
- when: "the web target builder is configured to use the mock server"
- HTTPProtocol.initClient()
- if (!HTTPProtocol.client.get().configuration.isRegistered(mockServer)) {
- HTTPProtocol.client.get().register(mockServer, Integer.MAX_VALUE)
- }
-
-
- and: "a HTTP client agent is created"
+ when: "a HTTP client agent is created"
HTTPAgent agent = new HTTPAgent("Test agent")
.setRealm(Constants.MASTER_REALM)
.setBaseURI("https://mockapi")
@@ -630,18 +624,20 @@ class HttpClientProtocolTest extends Specification implements ManagerContainerTr
"password")
)
.setFollowRedirects(true)
-
- and: "the agent is added to the asset service"
agent = assetStorageService.merge(agent)
then: "the protocol should authenticate and the connection status should become CONNECTED"
conditions.eventually {
agent = assetStorageService.find(agent.id, HTTPAgent.class)
assert agent.getAgentStatus().orElse(ConnectionStatus.DISCONNECTED) == ConnectionStatus.CONNECTED
+ assert agentService.getProtocolInstance(agent.id) != null
}
+ when: "the mock filter is added"
+ ((HTTPProtocol)agentService.getProtocolInstance(agent.id)).client.register(mockServer, Integer.MAX_VALUE)
+ ((HTTPProtocol)agentService.getProtocolInstance(agent.id)).doStart(getContainer())
- when: "An asset is created"
+ and: "An asset is created"
def asset = new ThingAsset("Test Asset")
.setParent(agent)
.addOrReplaceAttributes(
diff --git a/test/src/test/groovy/org/openremote/test/protocol/http/HttpServerProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/http/HttpServerProtocolTest.groovy
index aa0f2bbb2..cdf5dec7e 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/http/HttpServerProtocolTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/http/HttpServerProtocolTest.groovy
@@ -60,215 +60,6 @@ import static org.openremote.model.value.ValueType.TEXT
class HttpServerProtocolTest extends Specification implements ManagerContainerTrait {
- @Shared
- def mockServer = new ClientRequestFilter() {
-
- private boolean supportsRefresh
- private int accessTokenCount
- private int refreshTokenCount
- private String accessToken = null
- private String refreshToken = null
- private int pingCount = 0
- private int pollCountFast = 0
- private int pollCountSlow = 0
- private boolean putRequestWithHeadersCalled = false
- private int successFailureCount = 0
-
- @Override
- void filter(ClientRequestContext requestContext) throws IOException {
- def requestUri = requestContext.uri
- def requestPath = requestUri.scheme + "://" + requestUri.host + requestUri.path
-
- switch (requestPath) {
- case "https://mockapi/basicauth":
- def authHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION)
- if (authHeader != null) {
- def usernameAndPassword = BasicAuthHelper.parseHeader(authHeader)
- if (usernameAndPassword != null
- && usernameAndPassword[0] == "testuser"
- && usernameAndPassword[1] == "password1") {
- requestContext.abortWith(Response.ok().build())
- return
- }
- }
- break
- case "https://mockapi/token":
- // OAuth token request extract the grant info
- def grant = ((Form) requestContext.getEntity()).asMap()
- if (grant.getFirst(OAuthGrant.VALUE_KEY_GRANT_TYPE) == "password"
- && grant.getFirst(OAuthGrant.VALUE_KEY_CLIENT_ID) == "TestClient"
- && grant.getFirst(OAuthGrant.VALUE_KEY_CLIENT_SECRET) == "TestSecret"
- && grant.getFirst(OAuthGrant.VALUE_KEY_SCOPE) == "scope1 scope2"
- && grant.getFirst(OAuthPasswordGrant.VALUE_KEY_USERNAME) == "testuser"
- && grant.getFirst(OAuthPasswordGrant.VALUE_KEY_PASSWORD) == "password") {
- accessToken = "accesstoken" + accessTokenCount++
- def response = new OAuthServerResponse()
- response.accessToken = accessToken
- response.expiresIn = 100
- response.tokenType = "Bearer"
-
- // Include refresh token if configured to support it
- if (supportsRefresh) {
- refreshToken = "refreshtoken" + accessTokenCount
- response.refreshToken = refreshToken
- }
-
- requestContext.abortWith(
- Response.ok(response, MediaType.APPLICATION_JSON_TYPE).build()
- )
- return
- } else if (grant.getFirst(OAuthGrant.VALUE_KEY_GRANT_TYPE) == "refresh_token"
- && grant.getFirst(OAuthGrant.VALUE_KEY_CLIENT_ID) == "TestClient"
- && grant.getFirst(OAuthGrant.VALUE_KEY_CLIENT_SECRET) == "TestSecret"
- && grant.getFirst(OAuthGrant.VALUE_KEY_SCOPE) == "scope1 scope2"
- && grant.getFirst(OAuthRefreshTokenGrant.REFRESH_TOKEN_GRANT_TYPE) == 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()
- ObjectNode body = ValueUtil.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()
- ObjectNode body = ValueUtil.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 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 tryPost(TestResource authenticatedTestResource, Asset testAsset) {
// There's some weird behaviour where sometimes a forbidden exception is thrown and sometimes not
try {
@@ -296,7 +87,7 @@ class HttpServerProtocolTest extends Specification implements ManagerContainerTr
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
when: "a test HTTP server agent with a test deployment is created"
def agent = new HTTPServerTestAgent("Test agent")
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
index 82185fd1b..fe54d2a5f 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/http/WebTargetTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/http/WebTargetTest.groovy
@@ -34,6 +34,7 @@ import org.openremote.model.auth.OAuthGrant
import org.openremote.model.auth.OAuthPasswordGrant
import org.openremote.model.auth.OAuthRefreshTokenGrant
import org.openremote.model.util.ValueUtil
+import spock.lang.AutoCleanup
import spock.lang.Shared
import spock.lang.Specification
@@ -211,6 +212,7 @@ class WebTargetTest extends Specification {
}
}
+ @AutoCleanup
@Shared
ResteasyClient client
diff --git a/test/src/test/groovy/org/openremote/test/protocol/io/NettyIOClientTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/io/NettyIOClientTest.groovy
index eeb5a0fc9..39560cdc2 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/io/NettyIOClientTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/io/NettyIOClientTest.groovy
@@ -94,6 +94,5 @@ class NettyIOClientTest extends Specification implements ManagerContainerTrait {
cleanup:
AbstractNettyIOClient.RECONNECT_DELAY_INITIAL_MILLIS = oldDelay
- client.executorService.shutdownNow()
}
}
diff --git a/test/src/test/groovy/org/openremote/test/protocol/lorawan/chirpstack/ChirpStackTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/lorawan/chirpstack/ChirpStackTest.groovy
index c321873a6..143bdbf59 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/lorawan/chirpstack/ChirpStackTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/lorawan/chirpstack/ChirpStackTest.groovy
@@ -178,7 +178,7 @@ class ChirpStackTest extends Specification implements ManagerContainerTrait {
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
and: "the agent resource"
def agentResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(AgentResource.class)
@@ -294,7 +294,7 @@ class ChirpStackTest extends Specification implements ManagerContainerTrait {
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
and: "the agent resource"
def agentResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(AgentResource.class)
diff --git a/test/src/test/groovy/org/openremote/test/protocol/lorawan/tts/TheThingsStackTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/lorawan/tts/TheThingsStackTest.groovy
index b6a328938..6cf13b658 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/lorawan/tts/TheThingsStackTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/lorawan/tts/TheThingsStackTest.groovy
@@ -201,7 +201,7 @@ class TheThingsStackTest extends Specification implements ManagerContainerTrait
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
and: "the agent resource"
def agentResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(AgentResource.class)
diff --git a/test/src/test/groovy/org/openremote/test/protocol/modbus/ModbusSerialTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/modbus/ModbusSerialTest.groovy
index a8997c3da..7d8d5e7b2 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/modbus/ModbusSerialTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/modbus/ModbusSerialTest.groovy
@@ -47,6 +47,7 @@ import spock.util.concurrent.PollingConditions
import java.nio.ByteBuffer
import java.nio.ByteOrder
+import java.util.concurrent.CopyOnWriteArrayList
import static org.openremote.model.Constants.MASTER_REALM
import static org.openremote.model.value.MetaItemType.AGENT_LINK
@@ -796,7 +797,7 @@ class ModbusSerialTest extends Specification implements ManagerContainerTrait {
def attributeRef = new org.openremote.model.attribute.AttributeRef(device.getId(), "continuousWrite")
then: "multiple write events should be observed"
- def writeRequests = []
+ def writeRequests = new CopyOnWriteArrayList<>()
conditions.eventually {
def request = latestRequest
if (request != null) {
diff --git a/test/src/test/groovy/org/openremote/test/protocol/openweathermap/OpenWeatherMapProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/openweathermap/OpenWeatherMapProtocolTest.groovy
index 944924726..b480e6abd 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/openweathermap/OpenWeatherMapProtocolTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/openweathermap/OpenWeatherMapProtocolTest.groovy
@@ -19,21 +19,20 @@
*/
package org.openremote.test.protocol.openweathermap
+import jakarta.ws.rs.client.ClientRequestContext
+import jakarta.ws.rs.client.ClientRequestFilter
+import jakarta.ws.rs.core.MediaType
+import jakarta.ws.rs.core.Response
import org.openremote.agent.protocol.openweathermap.OpenWeatherMapAgent
-import org.openremote.agent.protocol.openweathermap.OpenWeatherMapAgentLink
import org.openremote.agent.protocol.openweathermap.OpenWeatherMapProtocol
-import org.openremote.agent.protocol.openweathermap.OpenWeatherMapProperty
import org.openremote.agent.protocol.openweathermap.OpenWeatherMapResponse
+import org.openremote.container.web.WebTargetBuilder
import org.openremote.manager.agent.AgentService
-import org.openremote.manager.asset.AssetProcessingService
import org.openremote.manager.asset.AssetStorageService
import org.openremote.manager.datapoint.AssetPredictedDatapointService
import org.openremote.model.asset.agent.ConnectionStatus
import org.openremote.model.asset.impl.WeatherAsset
-import org.openremote.model.attribute.Attribute
-import org.openremote.model.attribute.AttributeEvent
import org.openremote.model.attribute.AttributeRef
-import org.openremote.model.attribute.MetaItem
import org.openremote.model.geo.GeoJSONPoint
import org.openremote.model.util.ValueUtil
import org.openremote.test.ManagerContainerTrait
@@ -41,10 +40,6 @@ import spock.lang.Shared
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
-import jakarta.ws.rs.client.ClientRequestContext
-import jakarta.ws.rs.client.ClientRequestFilter
-import jakarta.ws.rs.core.MediaType
-import jakarta.ws.rs.core.Response
import java.time.LocalDateTime
import java.time.ZoneOffset
import java.time.temporal.ChronoUnit
@@ -57,8 +52,13 @@ class OpenWeatherMapProtocolTest extends Specification implements ManagerContain
@Shared
def mockServer = new ClientRequestFilter() {
+ boolean finished = false
+
@Override
void filter(ClientRequestContext requestContext) throws IOException {
+ if (finished) {
+ return
+ }
def requestUri = requestContext.uri
switch (requestUri.host) {
@@ -237,13 +237,7 @@ class OpenWeatherMapProtocolTest extends Specification implements ManagerContain
def "OpenWeatherMap Integration Tests"() {
given: "the container environment is started"
def conditions = new PollingConditions(timeout: 10, delay: 0.2)
-
- OpenWeatherMapProtocol.initClient()
-
- if (!OpenWeatherMapProtocol.client.get().configuration.isRegistered(mockServer)) {
- OpenWeatherMapProtocol.client.get().register(mockServer, Integer.MAX_VALUE)
- }
-
+ WebTargetBuilder.client.register(mockServer, Integer.MAX_VALUE)
def container = startContainer(defaultConfig(), defaultServices())
def assetStorageService = container.getService(AssetStorageService.class)
def assetPredictedDatapointService = container.getService(AssetPredictedDatapointService.class)
@@ -409,10 +403,7 @@ class OpenWeatherMapProtocolTest extends Specification implements ManagerContain
assert assetPredictedDatapointService.getDatapoints(new AttributeRef(weatherAsset2.id, WeatherAsset.UV_INDEX.name)).size() == 3
}
-
- cleanup: "remove mock client"
- if (OpenWeatherMapProtocol.client.get() != null) {
- OpenWeatherMapProtocol.client.set(null)
- }
+ cleanup: "disable mock filter"
+ mockServer.finished = true
}
}
diff --git a/test/src/test/groovy/org/openremote/test/protocol/velbus/VelbusProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/velbus/VelbusProtocolTest.groovy
index 9c39f553d..81beb4993 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/velbus/VelbusProtocolTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/velbus/VelbusProtocolTest.groovy
@@ -132,7 +132,7 @@ class VelbusProtocolTest extends Specification implements ManagerContainerTrait
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
and: "the agent resource"
def agentResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(AgentResource.class)
@@ -224,7 +224,7 @@ class VelbusProtocolTest extends Specification implements ManagerContainerTrait
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
and: "the agent resource"
def agentResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(AgentResource.class)
diff --git a/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientProtocolTest.groovy
index 14cc35a67..4f62a8575 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientProtocolTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientProtocolTest.groovy
@@ -19,8 +19,15 @@
*/
package org.openremote.test.protocol.websocket
+import jakarta.ws.rs.HttpMethod
+import jakarta.ws.rs.client.ClientRequestContext
+import jakarta.ws.rs.client.ClientRequestFilter
+import jakarta.ws.rs.core.HttpHeaders
+import jakarta.ws.rs.core.MediaType
+import jakarta.ws.rs.core.Response
import org.openremote.agent.protocol.simulator.SimulatorProtocol
import org.openremote.agent.protocol.websocket.*
+import org.openremote.container.web.WebTargetBuilder
import org.openremote.manager.agent.AgentService
import org.openremote.manager.asset.AssetProcessingService
import org.openremote.manager.asset.AssetStorageService
@@ -49,18 +56,11 @@ import spock.lang.Shared
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
-import jakarta.ws.rs.HttpMethod
-import jakarta.ws.rs.client.ClientRequestContext
-import jakarta.ws.rs.client.ClientRequestFilter
-import jakarta.ws.rs.core.HttpHeaders
-import jakarta.ws.rs.core.MediaType
-import jakarta.ws.rs.core.Response
-
-import static org.openremote.model.util.MapAccess.getString
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD_DEFAULT
import static org.openremote.model.Constants.KEYCLOAK_CLIENT_ID
import static org.openremote.model.Constants.MASTER_REALM_ADMIN_USER
+import static org.openremote.model.util.MapAccess.getString
import static org.openremote.model.value.MetaItemType.AGENT_LINK
import static org.openremote.model.value.ValueType.NUMBER
@@ -72,12 +72,21 @@ class WebsocketClientProtocolTest extends Specification implements ManagerContai
private boolean agentSubscriptionDone = false
private boolean attribute1SubscriptionDone = false
private boolean attribute2SubscriptionDone = false
+ private boolean finished = false
@Override
void filter(ClientRequestContext requestContext) throws IOException {
+ if (finished) {
+ return
+ }
+
def requestUri = requestContext.uri
def requestPath = requestUri.scheme + "://" + requestUri.host + requestUri.path
+ if (!requestPath.contains("mockapi")) {
+ return
+ }
+
// Check auth header is present
def authHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION)
if (authHeader == null || authHeader.length() < 8) {
@@ -130,11 +139,8 @@ class WebsocketClientProtocolTest extends Specification implements ManagerContai
def managerTestSetup = container.getService(SetupService.class).getTaskOfType(ManagerTestSetup.class)
def clientEventService = container.getService(ClientEventService.class)
- when: "the web target builder is configured to use the mock HTTP server (to test subscriptions)"
- WebsocketAgentProtocol.initClient()
- if (!WebsocketAgentProtocol.resteasyClient.get().configuration.isRegistered(mockServer)) {
- WebsocketAgentProtocol.resteasyClient.get().register(mockServer, Integer.MAX_VALUE)
- }
+ and: "the built in JAX-RS client is injected with the mock server filter"
+ WebTargetBuilder.client.register(mockServer, Integer.MAX_VALUE)
and: "a Websocket client agent is created to connect to this tests manager"
def agent = new WebsocketAgent("Test agent")
@@ -166,7 +172,7 @@ class WebsocketClientProtocolTest extends Specification implements ManagerContai
] as WebsocketSubscription[]
)
- and: "the agent is added to the asset service"
+ when: "the agent is added to the asset service"
agent = assetStorageService.merge(agent)
then: "the protocol should authenticate and the agent status should become CONNECTED"
@@ -307,9 +313,7 @@ class WebsocketClientProtocolTest extends Specification implements ManagerContai
assert asset.getAttribute("readCo2Level").flatMap{it.getValue()}.orElse(null) == 600d
}
- cleanup: "remove mock"
- if (WebsocketAgentProtocol.resteasyClient.get() != null) {
- WebsocketAgentProtocol.resteasyClient.set(null)
- }
+ cleanup: "disable mock filter"
+ mockServer.finished = true
}
}
diff --git a/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientTest.groovy
index cda8917b6..7102cc118 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientTest.groovy
@@ -43,22 +43,27 @@ import org.openremote.setup.integration.KeycloakTestSetup
import org.openremote.setup.integration.ManagerTestSetup
import org.openremote.model.asset.AssetFilter
import org.openremote.model.asset.agent.ConnectionStatus
+import org.openremote.model.attribute.Attribute
import org.openremote.model.attribute.AttributeEvent
import org.openremote.model.auth.OAuthPasswordGrant
import org.openremote.model.event.TriggeredEventSubscription
import org.openremote.model.event.shared.EventSubscription
+import org.openremote.model.event.shared.SharedEvent
import org.openremote.model.util.ValueUtil
+import org.openremote.model.value.ValueType
+import org.openremote.setup.integration.KeycloakTestSetup
+import org.openremote.setup.integration.ManagerTestSetup
import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
import java.util.concurrent.CopyOnWriteArrayList
-import static org.openremote.model.util.MapAccess.getString
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD_DEFAULT
import static org.openremote.model.Constants.KEYCLOAK_CLIENT_ID
import static org.openremote.model.Constants.MASTER_REALM_ADMIN_USER
+import static org.openremote.model.util.MapAccess.getString
/**
* This tests the {@link WebsocketIOClient} by connecting to the manager web socket API which means it also tests
@@ -154,22 +159,28 @@ class WebsocketClientTest extends Specification implements ManagerContainerTrait
List<Object> receivedMessages2 = new CopyOnWriteArrayList<>()
List<Object> receivedMessages3 = new CopyOnWriteArrayList<>()
client.addMessageConsumer({
- message -> receivedMessages.add(messageFromString(message))
+ getLOG().info("Client1 message received: $it")
+ receivedMessages.add(messageFromString(it))
})
client.addConnectionStatusConsumer({
- status -> connectionStatus = status
+ getLOG().info("Client1 status change: $it")
+ connectionStatus = it
})
client2.addMessageConsumer({
- message -> receivedMessages2.add(messageFromString(message))
+ getLOG().info("Client2 message received: $it")
+ receivedMessages2.add(messageFromString(it))
})
client2.addConnectionStatusConsumer({
- status -> connectionStatus2 = status
+ getLOG().info("Client1 status change: $it")
+ connectionStatus2 = it
})
client3.addMessageConsumer({
- message -> receivedMessages3.add(messageFromString(message))
+ getLOG().info("Client3 message received: $it")
+ receivedMessages3.add(messageFromString(it))
})
client3.addConnectionStatusConsumer({
- status -> connectionStatus3 = status
+ getLOG().info("Client3 status change: $it")
+ connectionStatus3 = it
})
and: "the system settles down"
diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovy
index ad0be214e..f64fc9c69 100644
--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovy
@@ -47,7 +47,7 @@ class BasicRulesDeploymentTest extends Specification implements ManagerContainer
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
expect: "the rules engines to be ready"
conditions.eventually {
diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesTimedExecutionTest.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesTimedExecutionTest.groovy
index eebc2f6ac..7fc4fde9b 100644
--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesTimedExecutionTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesTimedExecutionTest.groovy
@@ -11,6 +11,8 @@ import spock.lang.Ignore
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
+import java.util.concurrent.CopyOnWriteArrayList
+
import static java.util.concurrent.TimeUnit.SECONDS
import static org.openremote.setup.integration.ManagerTestSetup.DEMO_RULE_STATES_GLOBAL
@@ -19,7 +21,7 @@ class BasicRulesTimedExecutionTest extends Specification implements ManagerConta
RulesEngine globalEngine
- List<String> globalEngineFiredRules = []
+ List<String> globalEngineFiredRules = new CopyOnWriteArrayList<>()
def resetRuleExecutionLoggers() {
globalEngineFiredRules.clear()
diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovy
index 3d3f32b87..aa7b6b79d 100644
--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovy
@@ -41,7 +41,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
and: "the ruleset resource"
def rulesetResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(RulesResource.class)
@@ -139,7 +139,10 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "the result should be not found"
WebApplicationException ex = thrown()
- ex.response.status == 404
+ ex.response.withCloseable { r ->
+ assert r.status == 404
+ return true
+ }
and: "the ruleset should be removed from the engine"
conditions.eventually {
@@ -153,7 +156,10 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "the result should be not found"
ex = thrown()
- ex.response.status == 404
+ ex.response.withCloseable { r ->
+ assert r.status == 404
+ return true
+ }
when: "a realm ruleset is created in the authenticated realm"
def realmRuleset = new RealmRuleset(MASTER_REALM, "Test realm definition", GROOVY, "SomeRulesCode")
@@ -206,7 +212,10 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "the request should be bad"
ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
when: "a realm ruleset is updated with an invalid id"
realmRuleset.realm = MASTER_REALM
@@ -215,14 +224,20 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "the request should be bad"
ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
when: "a non-existent realm ruleset is updated"
rulesetResource.updateRealmRuleset(null, 1234567890l, realmRuleset)
then: "the result should be not found"
ex = thrown()
- ex.response.status == 404
+ ex.response.withCloseable { r ->
+ assert r.status == 404
+ return true
+ }
when: "a realm ruleset is deleted"
rulesetResource.deleteRealmRuleset(null, rulesetId)
@@ -230,7 +245,10 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "the result should be not found"
ex = thrown()
- ex.response.status == 404
+ ex.response.withCloseable { r ->
+ assert r.status == 404
+ return true
+ }
and: "the ruleset should be removed from the engine"
conditions.eventually {
@@ -312,7 +330,10 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "the request should be bad"
ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
when: "an asset ruleset is updated with an invalid id"
assetRuleset.assetId = managerTestSetup.smartOfficeId
@@ -321,14 +342,20 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "the request should be bad"
ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
when: "a non-existent asset ruleset is updated"
rulesetResource.updateAssetRuleset(null, 1234567890l, assetRuleset)
then: "the result should be not found"
ex = thrown()
- ex.response.status == 404
+ ex.response.withCloseable { r ->
+ assert r.status == 404
+ return true
+ }
when: "an asset ruleset is deleted"
rulesetResource.deleteAssetRuleset(null, rulesetId)
@@ -336,7 +363,10 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "the result should be not found"
ex = thrown()
- ex.response.status == 404
+ ex.response.withCloseable { r ->
+ assert r.status == 404
+ return true
+ }
and: "the ruleset should be removed from the engine"
conditions.eventually {
@@ -388,7 +418,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
KEYCLOAK_CLIENT_ID,
"testuser1",
"testuser1"
- ).token
+ )
and: "the ruleset resource"
def rulesetResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(RulesResource.class)
@@ -405,7 +435,10 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "access should be forbidden"
WebApplicationException ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "some realm rules are retrieved"
def ruleDefinitions = rulesetResource.getRealmRulesets(null, keycloakTestSetup.realmMaster.name, null, false)
@@ -419,14 +452,20 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "some asset rules in a non-authenticated realm are retrieved"
rulesetResource.getAssetRulesets(null, managerTestSetup.apartment2Id, null, false)
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
/* ############################################## WRITE ####################################### */
@@ -436,21 +475,30 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "a global rule is updated"
rulesetResource.updateGlobalRuleset(null, 1234567890l, ruleDefinition)
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "a global rule is deleted"
rulesetResource.deleteGlobalRuleset(null, 1234567890l)
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ return true
+ }
when: "a realm ruleset is created in the authenticated realm"
def realmRuleset = new RealmRuleset(MASTER_REALM, "Test realm definition", Ruleset.Lang.JSON, "SomeRulesCode")
@@ -503,7 +551,10 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "the request should be bad"
ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
when: "a realm ruleset is updated with an invalid id"
realmRuleset.realm = keycloakTestSetup.realmMaster.name
@@ -512,14 +563,20 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "the request should be bad"
ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
when: "a non-existent realm ruleset is updated"
rulesetResource.updateRealmRuleset(null, 1234567890l, realmRuleset)
then: "the result should be not found"
ex = thrown()
- ex.response.status == 404
+ ex.response.withCloseable { r ->
+ assert r.status == 404
+ return true
+ }
when: "a realm ruleset is deleted"
rulesetResource.deleteRealmRuleset(null, rulesetId)
@@ -527,7 +584,10 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "the result should be not found"
ex = thrown()
- ex.response.status == 404
+ ex.response.withCloseable { r ->
+ assert r.status == 404
+ true
+ }
and: "the ruleset should be removed from the engine"
conditions.eventually {
@@ -541,7 +601,10 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ true
+ }
when: "a realm ruleset is created in a non-authenticated realm"
realmRuleset = new RealmRuleset(keycloakTestSetup.realmBuilding.name, "Test realm definition", FLOW, "SomeRulesCode")
@@ -549,7 +612,10 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ true
+ }
when: "an asset ruleset is created in the authenticated realm"
def assetRuleset = new AssetRuleset(managerTestSetup.smartOfficeId, "Test asset definition", FLOW, "SomeRulesCode")
@@ -602,7 +668,10 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "the request should be bad"
ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ true
+ }
when: "an asset ruleset is updated with an invalid id"
assetRuleset.assetId = managerTestSetup.smartOfficeId
@@ -611,14 +680,20 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "the request should be bad"
ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ true
+ }
when: "a non-existent asset ruleset is updated"
rulesetResource.updateAssetRuleset(null, 1234567890l, assetRuleset)
then: "the result should be not found"
ex = thrown()
- ex.response.status == 404
+ ex.response.withCloseable { r ->
+ assert r.status == 404
+ true
+ }
when: "an asset ruleset is deleted"
rulesetResource.deleteAssetRuleset(null, rulesetId)
@@ -626,7 +701,10 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "the result should be not found"
ex = thrown()
- ex.response.status == 404
+ ex.response.withCloseable { r ->
+ assert r.status == 404
+ true
+ }
and: "the ruleset should reach the engine"
conditions.eventually {
@@ -639,9 +717,11 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
-
- }
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ true
+ }
+ }
def "Access rules as testuser2"() {
@@ -663,7 +743,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
KEYCLOAK_CLIENT_ID,
"testuser2",
"testuser2"
- ).token
+ )
and: "the ruleset resource"
def rulesetResource = getClientApiTarget(serverUri(serverPort), keycloakTestSetup.realmBuilding.name, accessToken).proxy(RulesResource.class)
@@ -680,14 +760,20 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "access should be forbidden"
WebApplicationException ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ true
+ }
when: "some realm rules in a non-authenticated realm are retrieved"
rulesetResource.getRealmRulesets(null, keycloakTestSetup.realmMaster.name, null, false)
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ true
+ }
when: "some realm rules in the authenticated realm are retrieved by user without rules read role"
def rulesets = rulesetResource.getRealmRulesets(null, keycloakTestSetup.realmBuilding.name, null, false)
@@ -709,21 +795,30 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ true
+ }
when: "a global rule is updated"
rulesetResource.updateGlobalRuleset(null, 1234567890l, ruleDefinition)
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ true
+ }
when: "a global rule is deleted"
rulesetResource.deleteGlobalRuleset(null, 1234567890l)
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ true
+ }
when: "a realm ruleset is created in the authenticated realm"
def realmRuleset = new RealmRuleset(keycloakTestSetup.realmBuilding.name, "Test realm definition", GROOVY, "SomeRulesCode")
@@ -731,21 +826,30 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ true
+ }
when: "a realm ruleset is updated"
rulesetResource.updateRealmRuleset(null, 1234567890l, realmRuleset)
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ true
+ }
when: "a realm ruleset is deleted"
rulesetResource.deleteRealmRuleset(null, 1234567890l)
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ true
+ }
when: "a realm ruleset is created in a non-authenticated realm"
realmRuleset = new RealmRuleset(keycloakTestSetup.realmCity.name, "Test realm definition", GROOVY, "SomeRulesCode")
@@ -753,7 +857,10 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ true
+ }
when: "a realm ruleset is created in the authenticated realm"
def assetRuleset = new AssetRuleset(keycloakTestSetup.realmBuilding.name, "Test asset definition", GROOVY, "SomeRulesCode")
@@ -761,21 +868,30 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ true
+ }
when: "a realm ruleset is updated"
rulesetResource.updateAssetRuleset(null, 1234567890l, assetRuleset)
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ true
+ }
when: "a realm ruleset is deleted"
rulesetResource.deleteAssetRuleset(null, 1234567890l)
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ true
+ }
when: "a realm ruleset is created in a non-authenticated realm"
assetRuleset = new AssetRuleset(keycloakTestSetup.realmCity.name, "Test asset definition", GROOVY, "SomeRulesCode")
@@ -783,9 +899,12 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ true
+ }
- }
+ }
def "Access rules as testuser3"() {
@@ -807,7 +926,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
KEYCLOAK_CLIENT_ID,
"testuser3",
"testuser3"
- ).token
+ )
and: "the ruleset resource"
def rulesetResource = getClientApiTarget(serverUri(serverPort), keycloakTestSetup.realmBuilding.name, accessToken).proxy(RulesResource.class)
@@ -824,14 +943,20 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "access should be forbidden"
WebApplicationException ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ true
+ }
when: "some realm rules in a non-authenticated realm are retrieved"
rulesetResource.getRealmRulesets(null, keycloakTestSetup.realmMaster.name, null, false)
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ true
+ }
when: "some realm rules in the authenticated realm are retrieved by the restricted user"
def rulesets = rulesetResource.getRealmRulesets(null, keycloakTestSetup.realmBuilding.name, null, false)
@@ -860,21 +985,30 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ true
+ }
when: "a global rule is updated"
rulesetResource.updateGlobalRuleset(null, 1234567890l, ruleDefinition)
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ true
+ }
when: "a global rule is deleted"
rulesetResource.deleteGlobalRuleset(null, 1234567890l)
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ true
+ }
when: "a realm ruleset is created in the authenticated realm"
def realmRuleset = new RealmRuleset(keycloakTestSetup.realmBuilding.name, "Test realm definition", GROOVY, "SomeRulesCode")
@@ -882,14 +1016,20 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ true
+ }
when: "a realm ruleset is updated"
rulesetResource.updateRealmRuleset(null, 1234567890l, realmRuleset)
then: "result should be not found"
ex = thrown()
- ex.response.status == 404
+ ex.response.withCloseable { r ->
+ assert r.status == 404
+ true
+ }
when: "a realm ruleset is deleted"
rulesetResource.deleteRealmRuleset(null, 1234567890l)
@@ -897,7 +1037,10 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "the result should be not found"
ex = thrown()
- ex.response.status == 404
+ ex.response.withCloseable { r ->
+ assert r.status == 404
+ true
+ }
when: "a realm ruleset is created in a non-authenticated realm"
realmRuleset = new RealmRuleset(keycloakTestSetup.realmCity.name, "Test realm definition", FLOW, "SomeRulesCode")
@@ -905,7 +1048,10 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ true
+ }
when: "an asset ruleset is created in the authenticated realm"
def assetRuleset = new AssetRuleset(
@@ -961,7 +1107,10 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "the request should be bad"
ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ true
+ }
when: "an asset ruleset is updated with a changed invalid asset ID"
assetRuleset.assetId = "thisdoesnotexist"
@@ -969,7 +1118,10 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "the request should be bad"
ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ true
+ }
when: "an asset ruleset is updated with an invalid id"
assetRuleset.assetId = managerTestSetup.apartment1Id
@@ -978,14 +1130,20 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "the request should be bad"
ex = thrown()
- ex.response.status == 400
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ true
+ }
when: "a non-existent asset ruleset is updated"
rulesetResource.updateAssetRuleset(null, 1234567890l, assetRuleset)
then: "the result should be not found"
ex = thrown()
- ex.response.status == 404
+ ex.response.withCloseable { r ->
+ assert r.status == 404
+ true
+ }
when: "an asset ruleset is deleted"
rulesetResource.deleteAssetRuleset(null, rulesetId)
@@ -993,7 +1151,10 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "the result should be not found"
ex = thrown()
- ex.response.status == 404
+ ex.response.withCloseable { r ->
+ assert r.status == 404
+ true
+ }
and: "the ruleset should be removed from the engine"
conditions.eventually {
@@ -1006,7 +1167,10 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ true
+ }
when: "an asset ruleset is created in a non-authenticated realm"
assetRuleset = new AssetRuleset(managerTestSetup.smartOfficeId, "Test asset definition", FLOW, "SomeRulesCode")
@@ -1014,9 +1178,11 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
then: "access should be forbidden"
ex = thrown()
- ex.response.status == 403
-
- }
+ ex.response.withCloseable { r ->
+ assert r.status == 403
+ true
+ }
+ }
def "JavaScript ruleset create requests are rejected"() {
@@ -1031,7 +1197,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
and: "the ruleset resource"
def rulesetResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(RulesResource.class)
@@ -1072,7 +1238,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
and: "the ruleset resource"
def rulesetResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(RulesResource.class)
@@ -1127,7 +1293,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
and: "the ruleset resource"
def rulesetResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(RulesResource.class)
diff --git a/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy b/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy
index c7b9994ec..65a59303a 100644
--- a/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy
@@ -1,6 +1,5 @@
package org.openremote.test.rules.residence
-
import com.google.firebase.messaging.Message
import jakarta.mail.internet.InternetAddress
import jakarta.ws.rs.client.ClientRequestContext
@@ -11,13 +10,11 @@ import net.fortuna.ical4j.model.Recur
import net.fortuna.ical4j.transform.recurrence.Frequency
import org.openremote.container.timer.TimerService
import org.openremote.container.util.MailUtil
-import org.openremote.manager.notification.LocalizedNotificationHandler
-import org.openremote.model.notification.EmailNotificationMessage
-import org.openremote.model.notification.LocalizedNotificationMessage
-import org.openremote.model.util.UniqueIdentifierGenerator
+import org.openremote.container.web.WebTargetBuilder
import org.openremote.manager.asset.AssetProcessingService
import org.openremote.manager.asset.AssetStorageService
import org.openremote.manager.notification.EmailNotificationHandler
+import org.openremote.manager.notification.LocalizedNotificationHandler
import org.openremote.manager.notification.NotificationService
import org.openremote.manager.notification.PushNotificationHandler
import org.openremote.manager.rules.JsonRulesBuilder
@@ -30,8 +27,8 @@ import org.openremote.manager.webhook.WebhookService
import org.openremote.model.asset.Asset
import org.openremote.model.asset.UserAssetLink
import org.openremote.model.asset.impl.ConsoleAsset
-import org.openremote.model.asset.impl.ThingAsset
import org.openremote.model.asset.impl.LightAsset
+import org.openremote.model.asset.impl.ThingAsset
import org.openremote.model.attribute.Attribute
import org.openremote.model.attribute.AttributeEvent
import org.openremote.model.attribute.MetaItem
@@ -40,13 +37,11 @@ import org.openremote.model.console.ConsoleProvider
import org.openremote.model.console.ConsoleRegistration
import org.openremote.model.console.ConsoleResource
import org.openremote.model.geo.GeoJSONPoint
-import org.openremote.model.notification.AbstractNotificationMessage
-import org.openremote.model.notification.Notification
-import org.openremote.model.notification.NotificationSendResult
-import org.openremote.model.notification.PushNotificationMessage
+import org.openremote.model.notification.*
import org.openremote.model.rules.RealmRuleset
import org.openremote.model.rules.Ruleset
import org.openremote.model.rules.json.JsonRulesetDefinition
+import org.openremote.model.util.UniqueIdentifierGenerator
import org.openremote.model.util.ValueUtil
import org.openremote.model.value.MetaItemType
import org.openremote.model.value.ValueType
@@ -60,6 +55,7 @@ import spock.util.concurrent.PollingConditions
import java.time.Duration
import java.time.Instant
import java.time.temporal.ChronoUnit
+import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.TimeUnit
import static java.util.concurrent.TimeUnit.HOURS
@@ -73,12 +69,15 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
@Shared
def mockServer = new ClientRequestFilter() {
-
+ boolean finished = false
private int successCount = 0
private int failureCount = 0
@Override
void filter(ClientRequestContext requestContext) throws IOException {
+ if (finished) {
+ return
+ }
def requestUri = requestContext.uri
def requestPath = requestUri.scheme + "://" + requestUri.host + requestUri.path
@@ -106,17 +105,12 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
}
}
- def cleanup() {
- mockServer.successCount = 0
- mockServer.failureCount = 0
- }
-
def "Turn all lights off when console exits the residence geofence"() {
- List<Tuple2<Notification.Target, PushNotificationMessage>> pushTargetsAndMessages = []
- List<jakarta.mail.Message> emailMessages = []
- List<Notification.Target> emailTargets = []
- List<LocalizedNotificationMessage> localizedMessages = []
+ List<Tuple2<Notification.Target, PushNotificationMessage>> pushTargetsAndMessages = new CopyOnWriteArrayList<>()
+ List<jakarta.mail.Message> emailMessages = new CopyOnWriteArrayList<>()
+ List<Notification.Target> emailTargets = new CopyOnWriteArrayList<>()
+ List<LocalizedNotificationMessage> localizedMessages = new CopyOnWriteArrayList<>()
given: "the geofence notifier debounce is set to a small value for testing"
Integer originalDebounceMillis = ORConsoleGeofenceAssetAdapter.NOTIFY_ASSETS_DEBOUNCE_MILLIS
@@ -214,7 +208,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
KEYCLOAK_CLIENT_ID,
"testuser3",
"testuser3"
- ).token
+ )
and: "another user authenticates"
def accessToken2 = authenticate(
@@ -223,7 +217,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
KEYCLOAK_CLIENT_ID,
"building",
"building"
- ).token
+ )
and: "a console is registered by the first user"
def authenticatedConsoleResource = getClientApiTarget(serverUri(serverPort), keycloakTestSetup.realmBuilding.name, accessToken).proxy(ConsoleResource.class)
@@ -1705,10 +1699,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
RulesEngine realmBuildingEngine
and: "the web target builder is configured to use the mock server"
- if (!webhookService.clientBuilder.configuration.isRegistered(mockServer)) {
- webhookService.clientBuilder.register(mockServer, Integer.MAX_VALUE)
- }
- assert webhookService.clientBuilder.configuration.isRegistered(mockServer)
+ WebTargetBuilder.client.register(mockServer, Integer.MAX_VALUE)
and: "a thing asset is added to the building realm"
def thingId = UniqueIdentifierGenerator.generateId("TestThing")
@@ -1767,5 +1758,8 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
assert mockServer.successCount == 2
assert mockServer.failureCount == 0
}
+
+ cleanup: "disable mock filter"
+ mockServer.finished = true
}
}
diff --git a/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceNotifyAlarmTriggerTest.groovy b/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceNotifyAlarmTriggerTest.groovy
index 54bd63089..4dc571f38 100644
--- a/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceNotifyAlarmTriggerTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceNotifyAlarmTriggerTest.groovy
@@ -40,6 +40,7 @@ import java.time.LocalDateTime
import java.time.ZoneId
import java.time.temporal.ChronoField
import java.time.temporal.ChronoUnit
+import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.TimeUnit
import static org.openremote.setup.integration.ManagerTestSetup.DEMO_RULE_STATES_APARTMENT_1
@@ -63,10 +64,10 @@ class ResidenceNotifyAlarmTriggerTest extends Specification implements ManagerCo
def "Trigger notification when presence is detected and alarm enabled"() {
- def notificationIds = []
- def targetTypes = []
- def targetIds = []
- def messages = []
+ def notificationIds = new CopyOnWriteArrayList<>()
+ def targetTypes = new CopyOnWriteArrayList<>()
+ def targetIds = new CopyOnWriteArrayList<>()
+ def messages = new CopyOnWriteArrayList<>()
given: "the container environment is started with the mock handler"
def conditions = new PollingConditions(timeout: 20, delay: 0.2)
@@ -128,7 +129,7 @@ class ResidenceNotifyAlarmTriggerTest extends Specification implements ManagerCo
KEYCLOAK_CLIENT_ID,
"testuser3",
"testuser3"
- ).token
+ )
and: "the notification and console resources"
def authenticatedConsoleResource = getClientApiTarget(serverUri(serverPort), realm, accessToken).proxy(ConsoleResource.class)
diff --git a/test/src/test/groovy/org/openremote/test/services/ExternalServiceTest.groovy b/test/src/test/groovy/org/openremote/test/services/ExternalServiceTest.groovy
index 48b476cc3..afa65c9fc 100644
--- a/test/src/test/groovy/org/openremote/test/services/ExternalServiceTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/services/ExternalServiceTest.groovy
@@ -37,7 +37,7 @@ class ExternalServiceTest extends Specification implements ManagerContainerTrait
KEYCLOAK_CLIENT_ID,
"testuser1",
"testuser1"
- ).token
+ )
// building service user for single tenant logic
def buildingServiceUserAccessToken = authenticate(
@@ -45,14 +45,14 @@ class ExternalServiceTest extends Specification implements ManagerContainerTrait
keycloakTestSetup.realmBuilding.getName(),
keycloakTestSetup.serviceUser.username,
keycloakTestSetup.serviceUser.secret
- ).token
+ )
def buildingServiceUser2AccessToken = authenticate(
container,
keycloakTestSetup.realmBuilding.getName(),
keycloakTestSetup.serviceUser2.username,
keycloakTestSetup.serviceUser2.secret
- ).token
+ )
// master service user for multi-tenant logic
def superServiceUserAccessToken = authenticate(
@@ -60,7 +60,7 @@ class ExternalServiceTest extends Specification implements ManagerContainerTrait
MASTER_REALM,
keycloakTestSetup.superServiceUser.username,
keycloakTestSetup.superServiceUser.secret
- ).token
+ )
then: "the users have been authenticated and the tokens are retrieved"
conditions.eventually {
@@ -125,14 +125,20 @@ class ExternalServiceTest extends Specification implements ManagerContainerTrait
then: "the heartbeat should be rejected, and a forbidden response received"
ex = thrown(WebApplicationException)
- assert ex.response.status == Response.Status.FORBIDDEN.getStatusCode()
+ ex.response.withCloseable { r ->
+ assert r.status == Response.Status.FORBIDDEN.getStatusCode()
+ return true
+ }
when: "another service user tries to de-register the same external service"
buildingExternalServiceResource2.deregisterService(null, registeredBuildingExternalService.serviceId, registeredBuildingExternalService.instanceId)
then: "the de-registration should be rejected, and a forbidden response received"
ex = thrown(WebApplicationException)
- assert ex.response.status == Response.Status.FORBIDDEN.getStatusCode()
+ ex.response.withCloseable { r ->
+ assert r.status == Response.Status.FORBIDDEN.getStatusCode()
+ return true
+ }
when: "the building service user de-registers the external service"
buildingExternalServiceResource.deregisterService(null, registeredBuildingExternalService.serviceId, registeredBuildingExternalService.instanceId)
@@ -147,14 +153,20 @@ class ExternalServiceTest extends Specification implements ManagerContainerTrait
then: "the building service user should receive a 404 not found response"
ex = thrown(WebApplicationException)
- assert ex.response.status == Response.Status.NOT_FOUND.getStatusCode()
+ ex.response.withCloseable { r ->
+ assert r.status == Response.Status.NOT_FOUND.getStatusCode()
+ return true
+ }
when: "the building service user tries to retrieve the external services from an inaccessible realm"
buildingExternalServiceResource.getServices(null, MASTER_REALM)
then: "the building service user should receive a 403 forbidden response"
ex = thrown(WebApplicationException)
- assert ex.response.status == Response.Status.FORBIDDEN.getStatusCode()
+ ex.response.withCloseable { r ->
+ assert r.status == Response.Status.FORBIDDEN.getStatusCode()
+ return true
+ }
// === Tests related to global service registration and management ===
@@ -235,14 +247,20 @@ class ExternalServiceTest extends Specification implements ManagerContainerTrait
then: "the building service user should receive a 403 forbidden response"
ex = thrown(WebApplicationException)
- assert ex.response.status == Response.Status.FORBIDDEN.getStatusCode()
+ ex.response.withCloseable { r ->
+ assert r.status == Response.Status.FORBIDDEN.getStatusCode()
+ return true
+ }
when: "the building service user tries to deregister the global external service"
buildingExternalServiceResource.deregisterService(null, registeredGlobalExternalService.serviceId, registeredGlobalExternalService.instanceId)
then: "the building service user should receive a 403 forbidden response"
ex = thrown(WebApplicationException)
- assert ex.response.status == Response.Status.FORBIDDEN.getStatusCode()
+ ex.response.withCloseable { r ->
+ assert r.status == Response.Status.FORBIDDEN.getStatusCode()
+ return true
+ }
// == Tests related to a regular user trying to interact with external services ===
@@ -268,21 +286,30 @@ class ExternalServiceTest extends Specification implements ManagerContainerTrait
then: "the regular user should receive a 403 forbidden response"
ex = thrown(WebApplicationException)
- assert ex.response.status == Response.Status.FORBIDDEN.getStatusCode()
+ ex.response.withCloseable { r ->
+ assert r.status == Response.Status.FORBIDDEN.getStatusCode()
+ return true
+ }
when: "the regular user tries to send a heartbeat for an external service"
regularUserExternalServiceResource.heartbeat(null, registeredBuildingExternalService2.serviceId, registeredBuildingExternalService2.instanceId)
then: "the regular user should receive a 401 unauthorized response"
ex = thrown(WebApplicationException)
- assert ex.response.status == Response.Status.UNAUTHORIZED.getStatusCode()
+ ex.response.withCloseable { r ->
+ assert r.status == Response.Status.UNAUTHORIZED.getStatusCode()
+ return true
+ }
when: "the regular user tries to deregister an external service"
regularUserExternalServiceResource.deregisterService(null, registeredBuildingExternalService2.serviceId, registeredBuildingExternalService2.instanceId)
then: "the regular user should receive a 401 unauthorized response"
ex = thrown(WebApplicationException)
- assert ex.response.status == Response.Status.UNAUTHORIZED.getStatusCode()
+ ex.response.withCloseable { r ->
+ assert r.status == Response.Status.UNAUTHORIZED.getStatusCode()
+ return true
+ }
when: "the regular user tries to register an external service"
def regularUserNewService = new ExternalService(
@@ -295,14 +322,20 @@ class ExternalServiceTest extends Specification implements ManagerContainerTrait
then: "the regular user should receive a 401 unauthorized response"
ex = thrown(WebApplicationException)
- assert ex.response.status == Response.Status.UNAUTHORIZED.getStatusCode()
+ ex.response.withCloseable { r ->
+ assert r.status == Response.Status.UNAUTHORIZED.getStatusCode()
+ return true
+ }
when: "the regular user tries to register a global external service"
regularUserExternalServiceResource.registerGlobalService(null, regularUserNewService)
then: "the regular user should receive a 401 unauthorized response"
ex = thrown(WebApplicationException)
- assert ex.response.status == Response.Status.UNAUTHORIZED.getStatusCode()
+ ex.response.withCloseable { r ->
+ assert r.status == Response.Status.UNAUTHORIZED.getStatusCode()
+ return true
+ }
// == Additional miscellaneous tests ==
diff --git a/test/src/test/groovy/org/openremote/test/users/UserResourceTest.groovy b/test/src/test/groovy/org/openremote/test/users/UserResourceTest.groovy
index 9f589773e..18156ee7f 100644
--- a/test/src/test/groovy/org/openremote/test/users/UserResourceTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/users/UserResourceTest.groovy
@@ -79,7 +79,7 @@ class UserResourceTest extends Specification implements ManagerContainerTrait {
KEYCLOAK_CLIENT_ID,
MASTER_REALM_ADMIN_USER,
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
- ).token
+ )
def regularMasterAccessToken = authenticate(
container,
@@ -87,7 +87,7 @@ class UserResourceTest extends Specification implements ManagerContainerTrait {
KEYCLOAK_CLIENT_ID,
"testuser1",
"testuser1"
- ).token
+ )
def regularBuildingAccessToken = authenticate(
container,
@@ -95,7 +95,7 @@ class UserResourceTest extends Specification implements ManagerContainerTrait {
KEYCLOAK_CLIENT_ID,
"testuser3",
"testuser3"
- ).token
+ )
def adminBuildingAccessToken = authenticate(
container,
@@ -103,7 +103,7 @@ class UserResourceTest extends Specification implements ManagerContainerTrait {
KEYCLOAK_CLIENT_ID,
"testuser4",
"testuser4"
- ).token
+ )
adminUserResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(UserResource.class)
regularUserMasterResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, regularMasterAccessToken).proxy(UserResource.class)
@@ -373,7 +373,7 @@ class UserResourceTest extends Specification implements ManagerContainerTrait {
KEYCLOAK_CLIENT_ID,
"testuser2",
"newPassword"
- ).token
+ )
testUser2BuildingAccessToken != null
}