100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Improve reliability of gateway status reporting and gateway connector logging (#1981)
Rich Turner02cc3c1944b0
diff --git a/manager/src/main/java/org/openremote/manager/gateway/GatewayConnector.java b/manager/src/main/java/org/openremote/manager/gateway/GatewayConnector.javaindex ddec0f543..db37a43af 100644--- a/manager/src/main/java/org/openremote/manager/gateway/GatewayConnector.java+++ b/manager/src/main/java/org/openremote/manager/gateway/GatewayConnector.java@@ -19,6 +19,7 @@*/package org.openremote.manager.gateway;+import org.openremote.container.timer.TimerService;import org.openremote.manager.asset.AssetProcessingService;import org.openremote.manager.asset.AssetStorageService;import org.openremote.model.asset.*;@@ -57,7 +58,7 @@ public class GatewayConnector {public static final String ASSET_READ_EVENT_NAME_INITIAL = "INITIAL";public static final String ASSET_READ_EVENT_NAME_BATCH = "BATCH";public static final long RESPONSE_TIMEOUT_MILLIS = 10000;- protected static final Map<String, Pair<Function<String, String>, Function<String, String>>> ASSET_ID_MAPPERS = new HashMap<>();+ protected static final Map<String, Pair<Function<String, String>, Function<String, String>>> ASSET_ID_MAPPERS = new ConcurrentHashMap<>();protected final String realm;protected final String gatewayId;protected final AssetStorageService assetStorageService;@@ -65,6 +66,7 @@ public class GatewayConnector {protected final ScheduledExecutorService scheduledExecutorService;protected final AssetProcessingService assetProcessingService;protected final GatewayService gatewayService;+ protected final TimerService timerService;protected List<AssetEvent> cachedAssetEvents;protected List<AttributeEvent> cachedAttributeEvents;protected Consumer<Object> gatewayMessageConsumer;@@ -102,6 +104,7 @@ public class GatewayConnector {ExecutorService executorService,ScheduledExecutorService scheduledExecutorService,GatewayService gatewayService,+ TimerService timerService,GatewayAsset gateway) {this.assetStorageService = assetStorageService;@@ -109,6 +112,7 @@ public class GatewayConnector {this.executorService = executorService;this.scheduledExecutorService = scheduledExecutorService;this.gatewayService = gatewayService;+ this.timerService = timerService;this.disabled = gateway.getDisabled().orElse(false);this.realm = gateway.getRealm();this.gatewayId = gateway.getId();@@ -119,16 +123,22 @@ public class GatewayConnector {eventConsumerMap.put(AssetEvent.class, (e) -> onAssetEvent((AssetEvent) e));eventConsumerMap.put(AttributeEvent.class, (e) -> onAttributeEvent((AttributeEvent) e));}- publishAttributeEvent(new AttributeEvent(gatewayId, GatewayAsset.STATUS, ConnectionStatus.DISCONNECTED));+ LOG.finest("Setting connection status=" + ConnectionStatus.DISCONNECTED + ": " + getGatewayIdString());+ publishAttributeEvent(new AttributeEvent(gatewayId, GatewayAsset.STATUS, ConnectionStatus.DISCONNECTED, timerService.getNow()));}protected void sendMessageToGateway(Object message) {try {if (gatewayMessageConsumer != null) {gatewayMessageConsumer.accept(message);+ if (LOG.isLoggable(Level.FINEST)) {+ LOG.fine(() -> "Sending message '" + message + "': " + getGatewayIdString());+ } else {+ LOG.fine(() -> "Sending message: " + getGatewayIdString());+ }}} catch (Exception e) {- LOG.log(Level.SEVERE, "Failed to send message to gateway: " + this, e);+ LOG.log(Level.WARNING, "Failed to send message: " + getGatewayIdString(), e.getMessage());}}@@ -137,7 +147,7 @@ public class GatewayConnector {*/protected void connected(String sessionId, Consumer<Object> gatewayMessageConsumer, Runnable requestDisconnect) {- LOG.fine("Gateway connector connected: " + this);+ LOG.info("Connected: " + getGatewayIdString());synchronized (this.sessionId) {if (getSessionId() != null) {@@ -157,7 +167,8 @@ public class GatewayConnector {syncIndex = 0;syncErrors = 0;- publishAttributeEvent(new AttributeEvent(gatewayId, GatewayAsset.STATUS, ConnectionStatus.CONNECTING));+ LOG.finest("Setting connection status=" + ConnectionStatus.CONNECTING + ": " + getGatewayIdString());+ publishAttributeEvent(new AttributeEvent(gatewayId, GatewayAsset.STATUS, ConnectionStatus.CONNECTING, timerService.getNow()));startSync();}@@ -173,18 +184,19 @@ public class GatewayConnector {}requestDisconnect.run();- LOG.fine("Gateway connector disconnected: " + this);+ LOG.fine("Disconnected: " + getGatewayIdString());if (syncProcessorFuture != null) {- LOG.finest("Aborting active sync process: " + this);+ LOG.finest("Aborting active sync process: " + getGatewayIdString());syncProcessorFuture.cancel(true);}if (capabilitiesFuture != null) {- LOG.finest("Aborting capabilities request: " + this);+ LOG.finest("Aborting capabilities request: " + getGatewayIdString());capabilitiesFuture.cancel(true);}initialSyncInProgress = false;- publishAttributeEvent(new AttributeEvent(gatewayId, GatewayAsset.STATUS, ConnectionStatus.DISCONNECTED));+ LOG.finest("Setting connection status=" + ConnectionStatus.DISCONNECTED + ": " + getGatewayIdString());+ publishAttributeEvent(new AttributeEvent(gatewayId, GatewayAsset.STATUS, ConnectionStatus.DISCONNECTED, timerService.getNow()));}protected void disconnect(GatewayDisconnectEvent.Reason reason) {@@ -213,13 +225,13 @@ public class GatewayConnector {/*** Request for gateway capabilities such as tunneling support*/- protected CompletableFuture<GatewayCapabilitiesResponseEvent> getCapabilities() {+ protected void getCapabilities() {CompletableFuture<GatewayCapabilitiesResponseEvent> future = new CompletableFuture<>();synchronized (eventConsumerMap) {if (eventConsumerMap.containsKey(GatewayCapabilitiesResponseEvent.class)) {- return CompletableFuture.failedFuture(new IllegalArgumentException("A capabilities request is already pending"));+ return;}eventConsumerMap.put(GatewayCapabilitiesResponseEvent.class, (e) -> {@@ -228,25 +240,34 @@ public class GatewayConnector {});}+ LOG.finest("Requesting gateway capabilities: " + getGatewayIdString());sendMessageToGateway(new GatewayCapabilitiesRequestEvent());- return future+ future.orTimeout(RESPONSE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)- .whenComplete((result, ex) -> {+ .whenComplete ((response, error) -> {synchronized (eventConsumerMap) {eventConsumerMap.remove(GatewayCapabilitiesResponseEvent.class); // Cleanup}- if (ex != null && !(ex instanceof TimeoutException)) {- // Re-throw unexpected exceptions- throw new RuntimeException("Failed to get gateway response", ex);+ if (error != null) {+ if (error instanceof TimeoutException) {+ LOG.warning("Capabilities request timeout error, assuming no support: " + getGatewayIdString());+ } else {+ LOG.warning("Capabilities request error [" + error.getMessage() + "] assuming no support: " + getGatewayIdString());+ }}+ tunnellingSupported = response != null && response.isTunnelingSupported();+ LOG.finest("Tunnelling supported=" + tunnellingSupported + ": " + getGatewayIdString());+ publishAttributeEvent(new AttributeEvent(gatewayId, GatewayAsset.TUNNELING_SUPPORTED, tunnellingSupported));+ LOG.finest("Setting connection status=" + ConnectionStatus.CONNECTED + ": " + getGatewayIdString());+ publishAttributeEvent(new AttributeEvent(gatewayId, GatewayAsset.STATUS, ConnectionStatus.CONNECTED, timerService.getNow()));});}protected CompletableFuture<Void> startTunnel(GatewayTunnelInfo tunnelInfo) {if (!isConnected() || isInitialSyncInProgress()) {- String msg = "Gateway is not connected or initial sync in progress so cannot start tunnel: " + this;+ String msg = "Start tunnel failed not connected or initial sync in progress: " + getGatewayIdString();LOG.info(msg);throw new IllegalStateException(msg);}@@ -357,7 +378,7 @@ public class GatewayConnector {}}} catch (Exception ex) {- LOG.log(Level.WARNING, ex, () -> "An error occurred while processing a gateway event: event=" + e + ", connector=" + this);+ LOG.log(Level.WARNING, ex, () -> "An error occurred while processing a gateway event: event=" + e + ": " + getGatewayIdString());disconnect(GatewayDisconnectEvent.Reason.SYNC_ERROR);}}@@ -386,7 +407,7 @@ public class GatewayConnector {return;}- LOG.info("Gateway sync timeout occurred: " + this);+ LOG.info("Asset sync timeout occurred: " + getGatewayIdString());syncErrors++;if (syncAborted()) {@@ -403,7 +424,7 @@ public class GatewayConnector {protected boolean syncAborted() {if (syncErrors == MAX_SYNC_RETRIES) {- LOG.warning("Gateway sync max retries reached so disconnecting the gateway: " + this);+ LOG.warning("Asset sync max retries reached so disconnecting: " + getGatewayIdString());disconnect(GatewayDisconnectEvent.Reason.SYNC_ERROR);return true;}@@ -423,7 +444,7 @@ public class GatewayConnector {String[] requestAssetIds = syncAssetIds.stream().skip(syncIndex).limit(SYNC_ASSET_BATCH_SIZE).toArray(String[]::new);expectedSyncResponseName = ASSET_READ_EVENT_NAME_BATCH + syncIndex;- LOG.fine("Synchronising gateway assets " + syncIndex+1 + "-" + syncIndex + requestAssetIds.length + " of " + syncAssetIds.size() + ": " + this);+ LOG.fine("Synchronising assets " + syncIndex+1 + "-" + syncIndex + requestAssetIds.length + " of " + syncAssetIds.size() + ": " + getGatewayIdString());ReadAssetsEvent event = new ReadAssetsEvent(new AssetQuery().ids(requestAssetIds)@@ -441,7 +462,7 @@ public class GatewayConnector {String messageId = e.getMessageID();if (!expectedSyncResponseName.equalsIgnoreCase(messageId)) {- LOG.info("Unexpected response from gateway so ignoring (expected=" + expectedSyncResponseName + ", actual =" + messageId + "): " + this);+ LOG.warning("Unexpected asset sync response so ignoring (expected=" + expectedSyncResponseName + ", actual =" + messageId + "): " + getGatewayIdString());return;}@@ -482,7 +503,7 @@ public class GatewayConnector {} else {if (syncAssetIds == null) {- LOG.warning("Unexpected gateway initialisation message, requesting disconnect: " + this);+ LOG.warning("Unexpected asset sync message, so requesting disconnect: " + getGatewayIdString());disconnect(GatewayDisconnectEvent.Reason.SYNC_ERROR);return;}@@ -502,7 +523,7 @@ public class GatewayConnector {});if (returnedAssets.size() != requestedAssetIds.size() || !returnedAssets.stream().allMatch(asset -> requestedAssetIds.contains(asset.getId()))) {- LOG.warning("Retrieved gateway asset batch count or ID mismatch, attempting to re-send the request: " + this);+ LOG.warning("Unexpected asset sync response invalid batch count or ID mismatch, attempting to re-send the request: " + getGatewayIdString());syncErrors++;requestAssets();return;@@ -532,7 +553,7 @@ public class GatewayConnector {// Request next batch or move onsyncIndex += requestedAssetIds.size();if (syncIndex >= syncAssetIds.size()) {- LOG.info("All requested gateway assets retrieved: " + this);+ LOG.finest("Asset sync completed: " + getGatewayIdString());Set<String> refreshAssets = new HashSet<>();@@ -545,7 +566,7 @@ public class GatewayConnector {try {saveAssetLocally(assetEvent.getAsset());} catch (Exception ex) {- LOG.log(Level.SEVERE, "Failed to add new gateway asset (Asset=" + assetEvent.getAsset() + "): " + this, ex);+ LOG.log(Level.WARNING, "Failed to add new gateway asset (Asset=" + assetEvent.getAsset() + "): " + getGatewayIdString(), ex);}} else {refreshAssets.add(assetEvent.getId());@@ -560,7 +581,7 @@ public class GatewayConnector {cachedAttributeEvents.forEach(attributeEvent -> {String assetId = attributeEvent.getId();if (!refreshAssets.contains(assetId)) {- LOG.info("1 or more gateway asset attribute values have changed so requesting the asset again (Asset<?> ID=" + assetId + ": " + this);+ LOG.info("1 or more asset attribute values have changed so requesting the asset again (Asset<?> ID=" + assetId + ": " + getGatewayIdString());refreshAssets.add(assetId);}});@@ -592,24 +613,17 @@ public class GatewayConnector {if (!obsoleteLocalAssetIds.isEmpty()) {boolean deleted = deleteAssetsLocally(obsoleteLocalAssetIds);if (!deleted) {- LOG.warning("Failed to delete obsolete local gateway assets; assets are not correctly synced: " + this);+ LOG.warning("Failed to delete obsolete local assets; assets are not correctly synced: " + getGatewayIdString());}}}protected void onInitialSyncComplete() {+ LOG.info("Initial sync complete: " + gatewayId);initialSyncInProgress = false;cachedAssetEvents.clear();cachedAttributeEvents.clear();-- getCapabilities().whenComplete ((response, error) -> {- if (error != null) {- LOG.warning("An error occurred whilst getting the gateway capabilities, assuming no support: " + this);- }- tunnellingSupported = response != null && response.isTunnelingSupported();- publishAttributeEvent(new AttributeEvent(gatewayId, GatewayAsset.TUNNELING_SUPPORTED, tunnellingSupported));- publishAttributeEvent(new AttributeEvent(gatewayId, GatewayAsset.STATUS, ConnectionStatus.CONNECTED));- });+ getCapabilities();}@SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")@@ -631,12 +645,12 @@ public class GatewayConnector {asset.setId(mapAssetId(gatewayId, assetId, false));asset.setParentId(asset.getParentId() != null ? mapAssetId(gatewayId, asset.getParentId(), false) : gatewayId);asset.setRealm(realm);- LOG.fine("Creating/updating gateway asset: Asset ID=" + assetId + ", Asset ID Mapped=" + asset.getId() + ": " + this);+ LOG.finest("Creating/updating asset: Asset ID=" + assetId + ", Asset ID Mapped=" + asset.getId() + ": " + getGatewayIdString());return assetStorageService.merge(asset, true, gatewayAsset, null);}protected boolean deleteAssetsLocally(List<String> assetIds) {- LOG.fine("Removing gateway asset: Asset IDs=" + Arrays.toString(assetIds.toArray()) + ": " + this);+ LOG.finest("Removing gateway asset: Asset IDs=" + Arrays.toString(assetIds.toArray()) + ": " + getGatewayIdString());return assetStorageService.delete(assetIds, true);}@@ -651,6 +665,10 @@ public class GatewayConnector {'}';}+ protected String getGatewayIdString() {+ return "GatewayID=" + gatewayId;+ }+/*** An easily reversible mathematical way of ensuring gateway asset IDs are unique by incrementing the first two* characters by adding the first two characters of the gateway ID for inbound IDs and the reverse for outbound.diff --git a/manager/src/main/java/org/openremote/manager/gateway/GatewayService.java b/manager/src/main/java/org/openremote/manager/gateway/GatewayService.javaindex 7d522afd4..97ee28262 100644--- a/manager/src/main/java/org/openremote/manager/gateway/GatewayService.java+++ b/manager/src/main/java/org/openremote/manager/gateway/GatewayService.java@@ -238,7 +238,7 @@ public class GatewayService extends RouteBuilder implements ContainerService {gateways = gateways.stream().filter(gateway ->Arrays.stream(gateway.getPath()).noneMatch(p -> !p.equals(gateway.getId()) && gatewayIds.contains(p)))- .collect(Collectors.toList());+ .toList();if (!gateways.isEmpty()) {LOG.info("Directly registered gateways found = " + gateways.size());@@ -254,7 +254,7 @@ public class GatewayService extends RouteBuilder implements ContainerService {}// Create connector- GatewayConnector connector = new GatewayConnector(assetStorageService, assetProcessingService, executorService, scheduledExecutorService, this, gateway);+ GatewayConnector connector = new GatewayConnector(assetStorageService, assetProcessingService, executorService, scheduledExecutorService, this, timerService, gateway);gatewayConnectorMap.put(gateway.getId().toLowerCase(Locale.ROOT), connector);// Get IDs of all assets under this gateway@@ -656,7 +656,7 @@ public class GatewayService extends RouteBuilder implements ContainerService {}if (connector.isDisabled()) {- LOG.warning("Gateway is currently disabled so will be ignored: " + this);+ LOG.warning("Gateway is currently disabled so will be ignored: GatewayID=" + gatewayId);clientEventService.sendToWebsocketSession(sessionId, new GatewayDisconnectEvent(GatewayDisconnectEvent.Reason.DISABLED));clientEventService.closeWebsocketSession(sessionId);return;@@ -701,7 +701,7 @@ public class GatewayService extends RouteBuilder implements ContainerService {case CREATE -> {createUpdateGatewayServiceUser(gateway);- GatewayConnector connector = new GatewayConnector(assetStorageService, assetProcessingService, executorService, scheduledExecutorService, this, gateway);+ GatewayConnector connector = new GatewayConnector(assetStorageService, assetProcessingService, executorService, scheduledExecutorService, this, timerService, gateway);gatewayConnectorMap.put(gateway.getId().toLowerCase(Locale.ROOT), connector);}case UPDATE -> {diff --git a/model/src/main/java/org/openremote/model/attribute/AttributeEvent.java b/model/src/main/java/org/openremote/model/attribute/AttributeEvent.javaindex 38bb2cd00..b65f0054e 100644--- a/model/src/main/java/org/openremote/model/attribute/AttributeEvent.java+++ b/model/src/main/java/org/openremote/model/attribute/AttributeEvent.java@@ -33,6 +33,7 @@ import org.openremote.model.validation.AttributeInfoValid;import org.openremote.model.value.AttributeDescriptor;import org.openremote.model.value.ValueDescriptor;+import java.time.Instant;import java.util.Date;import java.util.Objects;import java.util.Optional;@@ -85,6 +86,14 @@ public class AttributeEvent extends SharedEvent implements AttributeInfo {this(assetId, attributeDescriptor.getName(), value);}+ public <T> AttributeEvent(String assetId, AttributeDescriptor<T> attributeDescriptor, T value, Long timestamp) {+ this(assetId, attributeDescriptor.getName(), value, timestamp);+ }++ public <T> AttributeEvent(String assetId, AttributeDescriptor<T> attributeDescriptor, T value, Instant timestamp) {+ this(assetId, attributeDescriptor.getName(), value, timestamp);+ }+public AttributeEvent(String assetId, String attributeName, Object value) {this(new AttributeRef(assetId, attributeName), value);}@@ -93,6 +102,10 @@ public class AttributeEvent extends SharedEvent implements AttributeInfo {this(new AttributeRef(assetId, attributeName), value, timestamp);}+ public AttributeEvent(String assetId, String attributeName, Object value, Instant timestamp) {+ this(new AttributeRef(assetId, attributeName), value, timestamp.toEpochMilli());+ }+public AttributeEvent(AttributeState attributeState) {this(attributeState.getRef(), attributeState.getValue().orElse(null));}@@ -101,10 +114,18 @@ public class AttributeEvent extends SharedEvent implements AttributeInfo {this(attributeState.getRef(), attributeState.getValue().orElse(null), timestamp);}+ public AttributeEvent(AttributeState attributeState, Instant timestamp) {+ this(attributeState.getRef(), attributeState.getValue().orElse(null), timestamp.toEpochMilli());+ }+public AttributeEvent(AttributeRef attributeRef, Object value) {this(attributeRef, value, 0L);}+ public AttributeEvent(AttributeRef ref, Object value, Instant timestamp) {+ this(ref, value, timestamp.toEpochMilli());+ }+public AttributeEvent(AttributeRef ref, Object value, Long timestamp) {super(timestamp);Objects.requireNonNull(ref);diff --git a/model/src/main/java/org/openremote/model/gateway/GatewayDisconnectEvent.java b/model/src/main/java/org/openremote/model/gateway/GatewayDisconnectEvent.javaindex e8ff9da94..373afd060 100644--- a/model/src/main/java/org/openremote/model/gateway/GatewayDisconnectEvent.java+++ b/model/src/main/java/org/openremote/model/gateway/GatewayDisconnectEvent.java@@ -58,4 +58,11 @@ public class GatewayDisconnectEvent extends SharedEvent {public Reason getReason() {return reason;}++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "reason=" + reason ++ '}';+ }}diff --git a/test/src/main/groovy/org/openremote/test/ContainerTrait.groovy b/test/src/main/groovy/org/openremote/test/ContainerTrait.groovyindex 79a7e6294..972c8e9e5 100644--- a/test/src/main/groovy/org/openremote/test/ContainerTrait.groovy+++ b/test/src/main/groovy/org/openremote/test/ContainerTrait.groovy@@ -30,6 +30,7 @@ import org.keycloak.representations.AccessTokenResponseimport org.openremote.container.Containerimport org.openremote.container.message.MessageBrokerServiceimport org.openremote.container.persistence.PersistenceService+import org.openremote.container.security.ClientCredentialsAuthFormimport org.openremote.container.security.IdentityServiceimport org.openremote.container.security.PasswordAuthFormimport org.openremote.container.security.keycloak.KeycloakIdentityProvider@@ -526,6 +527,11 @@ trait ContainerTrait {.getAccessToken(realm, new PasswordAuthForm(clientId, username, password))}+ AccessTokenResponse authenticate(Container container, String realm, String clientId, String clientSecret) {+ ((KeycloakIdentityProvider)container.getService(IdentityService.class).getIdentityProvider()).getKeycloak()+ .getAccessToken(realm, new ClientCredentialsAuthForm(clientId, clientSecret))+ }+ProducerTemplate getMessageProducerTemplate(Container container) {return container.getService(MessageBrokerService.class).getContext().createProducerTemplate()}diff --git a/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovy b/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovyindex d300ad2dd..9f751c415 100644--- a/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovy+++ b/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovy@@ -2,6 +2,7 @@ package org.openremote.test.gatewayimport io.netty.channel.ChannelHandler+import jakarta.ws.rs.ForbiddenExceptionimport org.apache.http.client.utils.URIBuilderimport org.openremote.agent.protocol.http.HTTPAgentimport org.openremote.agent.protocol.http.HTTPAgentLink@@ -20,6 +21,7 @@ import org.openremote.manager.setup.SetupServiceimport org.openremote.model.Constantsimport org.openremote.model.asset.Assetimport org.openremote.model.asset.AssetEvent+import org.openremote.model.asset.AssetResourceimport org.openremote.model.asset.AssetsEventimport org.openremote.model.asset.ReadAssetsEventimport org.openremote.model.asset.agent.ConnectionStatus@@ -69,7 +71,6 @@ class GatewayTest extends Specification implements ManagerContainerTrait {def conditions = new PollingConditions(timeout: 15, delay: 0.2)def container = startContainer(defaultConfig(), defaultServices())def assetProcessingService = container.getService(AssetProcessingService.class)- def executorService = container.getScheduledExecutor()def timerService = container.getService(TimerService.class)def assetStorageService = container.getService(AssetStorageService.class)def agentService = container.getService(AgentService.class)@@ -95,7 +96,6 @@ class GatewayTest extends Specification implements ManagerContainerTrait {and: "a set of credentials should have been created for this gateway and be stored against the gateway for easy reference"conditions.eventually {gateway = assetStorageService.find(gateway.getId(), true) as GatewayAsset- assert gateway.getAttribute("clientId").isPresent()assert !isNullOrEmpty(gateway.getClientId().orElse(""))assert !isNullOrEmpty(gateway.getClientSecret().orElse(""))}@@ -106,6 +106,21 @@ class GatewayTest extends Specification implements ManagerContainerTrait {assert gatewayService.gatewayConnectorMap.get(gateway.getId().toLowerCase(Locale.ROOT)).gatewayId == gateway.getId()}+ when: "the gateway service user credentials are used to try and access the asset resources"+ def accessToken = authenticate(+ container,+ 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)+when: "the Gateway client is created"def gatewayClient = new GatewayIOClient(new URIBuilder("ws://127.0.0.1:$serverPort/websocket/events?Realm=$managerTestSetup.realmBuildingName").build(),