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
Cleanup of console code and finished ConsoleTest
Rich Turner1039aae8a035
diff --git a/console/android/src/main/java/org/openremote/android/ORFirebaseMessagingService.java b/console/android/src/main/java/org/openremote/android/ORFirebaseMessagingService.javaindex ebc7845a1..3d6761c7b 100644--- a/console/android/src/main/java/org/openremote/android/ORFirebaseMessagingService.java+++ b/console/android/src/main/java/org/openremote/android/ORFirebaseMessagingService.java@@ -167,22 +167,24 @@ public class ORFirebaseMessagingService extends com.google.firebase.messaging.Fi.setPriority(Notification.PRIORITY_MAX).setSound(defaultSoundUri);- for (AlertAction alertAction : actions) {- Intent actionIntent = new Intent(this, ORMessagingActionService.class);-- actionIntent.putExtra("notificationId", id);- actionIntent.putExtra("action", alertAction);- actionIntent.setAction(Long.toString(System.currentTimeMillis()));- PendingIntent actionPendingIntent = PendingIntent.getService(this,- 0,- actionIntent,- PendingIntent.FLAG_ONE_SHOT);- notificationBuilder = notificationBuilder.addAction(new NotificationCompat.Action(R.drawable.empty,- alertAction.getTitle(),- actionPendingIntent));+ if (actions != null && actions.length > 0) {+ for (AlertAction alertAction : actions) {+ Intent actionIntent = new Intent(this, ORMessagingActionService.class);++ actionIntent.putExtra("notificationId", id);+ actionIntent.putExtra("action", alertAction);+ actionIntent.setAction(Long.toString(System.currentTimeMillis()));+ PendingIntent actionPendingIntent = PendingIntent.getService(this,+ 0,+ actionIntent,+ PendingIntent.FLAG_ONE_SHOT);+ notificationBuilder = notificationBuilder.addAction(new NotificationCompat.Action(R.drawable.empty,+ alertAction.getTitle(),+ actionPendingIntent));+ }}- LOG.fine("Showing notification (" + actions.length + " actions): " + body);+ LOG.fine("Showing notification (" + (actions != null ? actions.length + " actions): " : "") + body);NotificationManager notificationManager =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);diff --git a/manager/src/main/java/org/openremote/manager/asset/console/ConsoleResourceImpl.java b/manager/src/main/java/org/openremote/manager/asset/console/ConsoleResourceImpl.javaindex b0a51405d..f8279b46d 100644--- a/manager/src/main/java/org/openremote/manager/asset/console/ConsoleResourceImpl.java+++ b/manager/src/main/java/org/openremote/manager/asset/console/ConsoleResourceImpl.java@@ -19,7 +19,6 @@*/package org.openremote.manager.asset.console;-import org.openremote.container.security.IdentityService;import org.openremote.container.timer.TimerService;import org.openremote.container.util.UniqueIdentifierGenerator;import org.openremote.manager.asset.AssetStorageService;@@ -37,12 +36,15 @@ import org.openremote.model.security.Tenant;import org.openremote.model.util.TextUtil;import javax.ws.rs.BadRequestException;+import javax.ws.rs.ForbiddenException;+import javax.ws.rs.WebApplicationException;import javax.ws.rs.core.Response;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;+import static javax.ws.rs.core.Response.Status.FORBIDDEN;import static org.openremote.container.concurrent.GlobalLock.withLockReturning;public class ConsoleResourceImpl extends ManagerWebResource implements ConsoleResource {@@ -69,12 +71,6 @@ public class ConsoleResourceImpl extends ManagerWebResource implements ConsoleRe// If console registration has an id and asset exists then ensure asset type is consoleif (!TextUtil.isNullOrEmpty(consoleRegistration.getId())) {consoleAsset = assetStorageService.find(consoleRegistration.getId(), true);- // If asset doesn't exist then no harm in registering console using the supplied ID- if (consoleAsset != null) {- if (consoleAsset.getWellKnownType() != AssetType.CONSOLE) {- throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST).entity(new ValidationFailure[] {new ValidationFailure(Asset.AssetTypeFailureReason.ASSET_TYPE_MISMATCH)}).build());- }- }}if (consoleAsset == null) {@@ -83,14 +79,40 @@ public class ConsoleResourceImpl extends ManagerWebResource implements ConsoleReconsoleRegistration.getName(),consoleRegistration.getVersion(),consoleRegistration.getPlatform(),- consoleRegistration.getProviders());+ consoleRegistration.getProviders(),+ !isAuthenticated(),+ true);+if (!isAuthenticated()) {consoleAsset.setAccessPublicRead(true);}+consoleAsset.setRealmId(getRequestTenant().getId());consoleAsset.setParentId(getConsoleParentAssetId(getRequestRealm()));consoleAsset.setId(consoleRegistration.getId());} else {+ // Check existing asset is a console+ if (consoleAsset.getWellKnownType() != AssetType.CONSOLE) {+ throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST).entity(new ValidationFailure[] {new ValidationFailure(Asset.AssetTypeFailureReason.ASSET_TYPE_MISMATCH)}).build());+ }++ // Check authenticated user is already linked to this console; if anonymous request then check console isn't linked to any users+ if (isAuthenticated()) {+ List<UserAsset> consoleUserAssets = assetStorageService.findUserAssets(getAuthenticatedTenant().getId(),+ null,+ consoleRegistration.getId());+ if (consoleUserAssets.isEmpty()) {+ throw new WebApplicationException(FORBIDDEN);+ }+ } else {+ List<UserAsset> consoleUserAssets = assetStorageService.findUserAssets(getRequestTenant().getId(),+ null,+ consoleRegistration.getId());+ if (!consoleUserAssets.isEmpty()) {+ throw new WebApplicationException(FORBIDDEN);+ }+ }+ConsoleConfiguration.setConsoleName(consoleAsset, consoleRegistration.getName());ConsoleConfiguration.setConsolePlatform(consoleAsset, consoleRegistration.getPlatform());ConsoleConfiguration.setConsoleVersion(consoleAsset, consoleRegistration.getVersion());diff --git a/manager/src/main/java/org/openremote/manager/rules/AssetLocationPredicateProcessor.java b/manager/src/main/java/org/openremote/manager/rules/AssetLocationPredicateProcessor.javanew file mode 100644index 000000000..245846668--- /dev/null+++ b/manager/src/main/java/org/openremote/manager/rules/AssetLocationPredicateProcessor.java@@ -0,0 +1,29 @@+/*+ * Copyright 2017, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.manager.rules;++import java.util.List;++@FunctionalInterface+public interface AssetLocationPredicateProcessor {++ void accept(RulesEngine t, List<RulesEngine.AssetStateLocationPredicates> u);+}+diff --git a/manager/src/main/java/org/openremote/manager/rules/AssetQueryPredicate.java b/manager/src/main/java/org/openremote/manager/rules/AssetQueryPredicate.javaindex 814a86dbc..e4c881979 100644--- a/manager/src/main/java/org/openremote/manager/rules/AssetQueryPredicate.java+++ b/manager/src/main/java/org/openremote/manager/rules/AssetQueryPredicate.java@@ -24,6 +24,7 @@ import com.vividsolutions.jts.geom.Envelope;import org.geotools.referencing.GeodeticCalculator;import org.openremote.model.asset.BaseAssetQuery;import org.openremote.model.asset.BaseAssetQuery.*;+import org.openremote.model.attribute.AttributeType;import org.openremote.model.geo.GeoJSONPoint;import org.openremote.model.rules.AssetState;@@ -91,7 +92,7 @@ public class AssetQueryPredicate implements Predicate<AssetState> {}if (query.location != null) {- GeoJSONPoint coords = assetState.getValue().flatMap(GeoJSONPoint::fromValue).orElse(null);+ GeoJSONPoint coords = AttributeType.LOCATION.getName().equals(assetState.getAttributeName()) ? assetState.getValue().flatMap(GeoJSONPoint::fromValue).orElse(null) : null;if (coords != null) {Coordinate coordinate = new Coordinate(coords.getY(), coords.getX());diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.javaindex b6c769ed4..e9f013c0d 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java@@ -84,7 +84,7 @@ public class RulesEngine<T extends Ruleset> {final protected Assets assetsFacade;final protected Users usersFacade;final protected ConsolesFacade consolesFacade;- final protected AssetLocationPredicateConsumer assetLocationPredicatesConsumer;+ final protected AssetLocationPredicateProcessor assetLocationPredicatesConsumer;final protected Map<Long, RulesetDeployment> deployments = new LinkedHashMap<>();final protected RulesFacts facts;@@ -108,7 +108,7 @@ public class RulesEngine<T extends Ruleset> {AssetProcessingService assetProcessingService,NotificationService notificationService,RulesEngineId<T> id,- AssetLocationPredicateConsumer assetLocationPredicatesConsumer) {+ AssetLocationPredicateProcessor assetLocationPredicatesConsumer) {this.timerService = timerService;this.executorService = executorService;this.assetStorageService = assetStorageService;diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesResourceImpl.java b/manager/src/main/java/org/openremote/manager/rules/RulesResourceImpl.javaindex f549d30eb..d154bc55f 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesResourceImpl.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesResourceImpl.java@@ -297,7 +297,7 @@ public class RulesResourceImpl extends ManagerWebResource implements RulesResour}@Override- public GeofenceDefinition[] getAssetGeofences(String assetId) {+ public GeofenceDefinition[] getAssetGeofences(@BeanParam RequestParams requestParams, String assetId) {Asset asset;asset = assetStorageService.find(@@ -308,21 +308,17 @@ public class RulesResourceImpl extends ManagerWebResource implements RulesResourif (asset == null)return new GeofenceDefinition[0];- // If asset is linked to users then only those users can get the geofences for it- List<UserAsset> userAssetLinks = assetStorageService.findUserAssets(asset.getRealmId(), null, assetId);-// If not linked to users check if asset is marked as public read- // TODO: Change for public write when implemented- if (userAssetLinks.isEmpty() && !asset.isAccessPublicRead()) {- throw new WebApplicationException(Response.Status.FORBIDDEN);- }+ if (!asset.isAccessPublicRead()) {- if (isAuthenticated()) {- // Check asset is linked to authenticated user or super user is logged in- if (!isSuperUser() || userAssetLinks.stream().noneMatch(userAssetLink -> userAssetLink.getId().getUserId().equals(getUserId()))) {- throw new WebApplicationException(Response.Status.FORBIDDEN);- }+ // If asset is linked to users then only those users can get the geofences for it+ List<UserAsset> userAssetLinks = assetStorageService.findUserAssets(asset.getRealmId(), null, assetId);+ if (!userAssetLinks.isEmpty()) {+ if (!isAuthenticated() || userAssetLinks.stream().noneMatch(userAssetLink -> userAssetLink.getId().getUserId().equals(getUserId()))) {+ throw new WebApplicationException(Response.Status.FORBIDDEN);+ }+ }}return rulesService.getAssetGeofences(assetId);diff --git a/manager/src/main/java/org/openremote/manager/rules/geofence/GeofenceAssetAdapter.java b/manager/src/main/java/org/openremote/manager/rules/geofence/GeofenceAssetAdapter.javaindex 85bdf4c9b..8f0cfe3e6 100644--- a/manager/src/main/java/org/openremote/manager/rules/geofence/GeofenceAssetAdapter.java+++ b/manager/src/main/java/org/openremote/manager/rules/geofence/GeofenceAssetAdapter.java@@ -66,7 +66,7 @@ public interface GeofenceAssetAdapter {* hence adapters should be more concerned with delta changes (but this is really up to the adapter).* <p>* If an adapter handles the location predicates for a particular asset then the adapter should remove that item- * from the list to prevent other adapters from also handling it. If an {@link RulesEngine.AssetStateLocationPredicates#getLocationPredicates()}+ * from the list to prevent other adapters from also handling it. If an {@link RulesEngine.AssetStateLocationPredicates#getLocationPredicates}* is empty then it means there are no longer any location predicates associated with that asset*/void processLocationPredicates(List<RulesEngine.AssetStateLocationPredicates> modifiedAssetLocationPredicates,diff --git a/manager/src/main/java/org/openremote/manager/rules/geofence/ORConsoleGeofenceAssetAdapter.java b/manager/src/main/java/org/openremote/manager/rules/geofence/ORConsoleGeofenceAssetAdapter.javaindex 82f3601c2..0c497fdcc 100644--- a/manager/src/main/java/org/openremote/manager/rules/geofence/ORConsoleGeofenceAssetAdapter.java+++ b/manager/src/main/java/org/openremote/manager/rules/geofence/ORConsoleGeofenceAssetAdapter.java@@ -25,6 +25,7 @@ import org.openremote.container.ContainerService;import org.openremote.container.message.MessageBrokerSetupService;import org.openremote.container.persistence.PersistenceEvent;import org.openremote.manager.asset.AssetStorageService;+import org.openremote.manager.concurrent.ManagerExecutorService;import org.openremote.manager.notification.NotificationService;import org.openremote.manager.rules.RulesEngine;import org.openremote.manager.security.ManagerIdentityService;@@ -38,6 +39,8 @@ import org.openremote.model.rules.geofence.GeofenceDefinition;import org.openremote.model.util.TextUtil;import java.util.*;+import java.util.concurrent.ScheduledFuture;+import java.util.concurrent.atomic.AtomicBoolean;import java.util.logging.Logger;import java.util.stream.Collectors;@@ -59,18 +62,22 @@ public class ORConsoleGeofenceAssetAdapter extends RouteBuilder implements Geofepublic static final String NAME = "ORConsole";public static final String HTTP_METHOD = "PUT";public static final String LOCATION_URL_FORMAT_TEMPLATE = "/asset/%1$s/attribute/location";+ public static int NOTIFY_ASSETS_DEBOUNCE_MILLIS = 60000;protected Map<String, RulesEngine.AssetStateLocationPredicates> assetLocationPredicatesMap = new HashMap<>();protected NotificationService notificationService;protected AssetStorageService assetStorageService;protected ManagerIdentityService identityService;+ protected ManagerExecutorService executorService;protected Map<String, String> consoleIdRealmMap;-+ protected ScheduledFuture notifyAssetsScheduledFuture;+ protected Set<String> notifyAssets;@Overridepublic void init(Container container) throws Exception {this.assetStorageService = container.getService(AssetStorageService.class);this.notificationService = container.getService(NotificationService.class);this.identityService = container.getService(ManagerIdentityService.class);+ this.executorService = container.getService(ManagerExecutorService.class);container.getService(MessageBrokerSetupService.class).getContext().addRoutes(this);}@@ -125,40 +132,61 @@ public class ORConsoleGeofenceAssetAdapter extends RouteBuilder implements Geofe@Overridepublic void processLocationPredicates(List<RulesEngine.AssetStateLocationPredicates> modifiedAssetLocationPredicates, boolean initialising) {- Set<String> notifyAssets = new HashSet<>(modifiedAssetLocationPredicates.size());+ withLock(getClass().getSimpleName() + "::processLocationPredicates", () -> {- modifiedAssetLocationPredicates.removeIf(assetStateLocationPredicates -> {- boolean remove = consoleIdRealmMap.containsKey(assetStateLocationPredicates.getAssetId());+ AtomicBoolean notifierDebounce = new AtomicBoolean(false);- if (remove) {- assetStateLocationPredicates- .getLocationPredicates()- .removeIf(locationPredicate ->- !(locationPredicate instanceof BaseAssetQuery.RadialLocationPredicate));+ if (notifyAssets == null) {+ notifyAssets = new HashSet<>(modifiedAssetLocationPredicates.size());+ }- if (!initialising) {+ // Remove all entries that relate to consoles that are compatible with this adapter+ modifiedAssetLocationPredicates.removeIf(assetStateLocationPredicates -> {+ boolean remove = consoleIdRealmMap.containsKey(assetStateLocationPredicates.getAssetId());++ if (remove) {+ // Keep only radial location predicates (only these are supported on iOS and Android)+ assetStateLocationPredicates+ .getLocationPredicates()+ .removeIf(locationPredicate ->+ !(locationPredicate instanceof BaseAssetQuery.RadialLocationPredicate));++ // If not initialising compare existing with new predicates and notify affected assets+ if (!initialising) {++ RulesEngine.AssetStateLocationPredicates existingPredicates = assetLocationPredicatesMap.get(+ assetStateLocationPredicates.getAssetId());+ if (existingPredicates == null || !existingPredicates.getLocationPredicates().equals(assetStateLocationPredicates.getLocationPredicates())) {+ // We're not comparing before and after state as RulesService has done that although it could be+ // that rectangular location predicates have changed but this will do for now+ notifyAssets.add(assetStateLocationPredicates.getAssetId());+ notifierDebounce.set(true);+ }+ }- RulesEngine.AssetStateLocationPredicates existingPredicates = assetLocationPredicatesMap.get(- assetStateLocationPredicates.getAssetId());- if ((existingPredicates == null || existingPredicates.getLocationPredicates().isEmpty()) && !assetStateLocationPredicates.getLocationPredicates().isEmpty()) {- // We're not comparing before and after state as RulesService has done that although it could be- // that rectangular location predicates have changed but this will do for now- notifyAssets.add(assetStateLocationPredicates.getAssetId());+ if (assetStateLocationPredicates.getLocationPredicates().isEmpty()) {+ assetLocationPredicatesMap.remove(assetStateLocationPredicates.getAssetId());+ } else {+ assetLocationPredicatesMap.put(assetStateLocationPredicates.getAssetId(),+ assetStateLocationPredicates);}}- if (assetStateLocationPredicates.getLocationPredicates().isEmpty()) {- assetLocationPredicatesMap.remove(assetStateLocationPredicates.getAssetId());- } else {- assetLocationPredicatesMap.put(assetStateLocationPredicates.getAssetId(),- assetStateLocationPredicates);+ return remove;+ });++ if (notifierDebounce.get()) {+ if (notifyAssetsScheduledFuture == null || notifyAssetsScheduledFuture.cancel(false)) {+ notifyAssetsScheduledFuture = executorService.schedule(() ->+ withLock(getClass().getSimpleName() + "::notifyAssets",+ () -> {+ notifyAssets.forEach(this::notifyAssetGeofencesChanged);+ notifyAssetsScheduledFuture = null;+ }),+ NOTIFY_ASSETS_DEBOUNCE_MILLIS);}}-- return remove;});-- notifyAssets.forEach(this::notifyAssetGeofencesChanged);}@Overridediff --git a/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.java b/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.javaindex 1980837a3..e0ac7d27b 100644--- a/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.java+++ b/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.java@@ -60,12 +60,14 @@ public class ManagerDemoSetup extends AbstractManagerSetup {public static final int DEMO_RULE_STATES_APARTMENT_3 = 0;public static final int DEMO_RULE_STATES_SMART_OFFICE = 1;public static final int DEMO_RULE_STATES_SMART_HOME = DEMO_RULE_STATES_APARTMENT_1 + DEMO_RULE_STATES_APARTMENT_2 + DEMO_RULE_STATES_APARTMENT_3;- public static final int DEMO_RULE_STATES_CUSTOMER_A = DEMO_RULE_STATES_SMART_HOME + 1; // 1 is for console location attribute+ public static final int DEMO_RULE_STATES_CUSTOMER_A = DEMO_RULE_STATES_SMART_HOME;public static final int DEMO_RULE_STATES_GLOBAL = DEMO_RULE_STATES_CUSTOMER_A + DEMO_RULE_STATES_SMART_OFFICE;public static final int DEMO_RULE_STATES_APARTMENT_1_WITH_SCENES = DEMO_RULE_STATES_APARTMENT_1 + 28;public static final int DEMO_RULE_STATES_SMART_HOME_WITH_SCENES = DEMO_RULE_STATES_APARTMENT_1_WITH_SCENES + DEMO_RULE_STATES_APARTMENT_2 + DEMO_RULE_STATES_APARTMENT_3;public static final int DEMO_RULE_STATES_CUSTOMER_A_WITH_SCENES = DEMO_RULE_STATES_SMART_HOME_WITH_SCENES;public static final int DEMO_RULE_STATES_GLOBAL_WITH_SCENES = DEMO_RULE_STATES_CUSTOMER_A_WITH_SCENES;+ public static GeoJSONPoint SMART_OFFICE_LOCATION = new GeoJSONPoint(5.460315214821094, 51.44541688237109);+ public static GeoJSONPoint SMART_HOME_LOCATION = new GeoJSONPoint(5.470945, 51.438000);public final String agentProtocolConfigName = "simulator123";public final String thingLightToggleAttributeName = "light1Toggle";final protected boolean importDemoScenes;@@ -87,8 +89,6 @@ public class ManagerDemoSetup extends AbstractManagerSetup {public String apartment3LivingroomId;public String masterRealmId;public String customerARealmId;- public String consolesId;- public String consoleId;public ManagerDemoSetup(Container container, boolean importDemoScenes) {super(container);@@ -106,7 +106,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {// ################################ Demo assets for 'master' realm ###################################- ObjectValue locationValue = new GeoJSONPoint(5.460315214821094, 51.44541688237109).toValue();+ ObjectValue locationValue = SMART_OFFICE_LOCATION.toValue();Asset smartOffice = new Asset();smartOffice.setRealmId(masterTenant.getId());@@ -368,7 +368,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {// ################################ Demo assets for 'customerA' realm ###################################- ObjectValue locationValueA = new GeoJSONPoint(5.470945, 51.438000).toValue();+ ObjectValue locationValueA = SMART_HOME_LOCATION.toValue();Asset smartHome = new Asset();smartHome.setRealmId(customerATenant.getId());@@ -634,29 +634,6 @@ public class ManagerDemoSetup extends AbstractManagerSetup {apartment3Livingroom = assetStorageService.merge(apartment3Livingroom);apartment3LivingroomId = apartment3Livingroom.getId();-- Asset consoleParent = ConsoleResourceImpl.getConsoleParentAsset(assetStorageService, keycloakDemoSetup.customerATenant);- consolesId = consoleParent.getId();-- Asset console = ConsoleConfiguration.initConsoleConfiguration(- new Asset("Demo Console", CONSOLE, consoleParent),- "Demo Console",- "1.0",- "Android 7.1.2",- new HashMap<String, ConsoleProvider>() {- {- put("geofence", new ConsoleProvider(- ORConsoleGeofenceAssetAdapter.NAME,- true,- true,- false,- null- ));- }- });- console = assetStorageService.merge(console);- consoleId = console.getId();-// ################################ Link demo users and assets ###################################assetStorageService.storeUserAsset(new UserAsset(keycloakDemoSetup.customerATenant.getId(),@@ -675,10 +652,6 @@ public class ManagerDemoSetup extends AbstractManagerSetup {keycloakDemoSetup.testuser3Id,apartment2Id));- assetStorageService.storeUserAsset(new UserAsset(keycloakDemoSetup.customerATenant.getId(),- keycloakDemoSetup.testuser3Id,- consoleId));-// ################################ Make users restricted ###################################UserConfiguration testuser3Config = identityService.getUserConfiguration(keycloakDemoSetup.testuser3Id);diff --git a/manager/src/main/java/org/openremote/manager/setup/builtin/RulesDemoSetup.java b/manager/src/main/java/org/openremote/manager/setup/builtin/RulesDemoSetup.javaindex 570fa58d7..ceef54750 100644--- a/manager/src/main/java/org/openremote/manager/setup/builtin/RulesDemoSetup.java+++ b/manager/src/main/java/org/openremote/manager/setup/builtin/RulesDemoSetup.java@@ -97,7 +97,7 @@ public class RulesDemoSetup extends AbstractManagerSetup {apartmentActionsRulesetId = rulesetStorageService.merge(ruleset).getId();}- try (InputStream inputStream = RulesDemoSetup.class.getResourceAsStream("/demo/rules/ConsoleLocationPredicate.groovy")) {+ try (InputStream inputStream = RulesDemoSetup.class.getResourceAsStream("/demo/rules/DemoConsoleLocation.groovy")) {String rules = IOUtils.toString(inputStream, Charset.forName("utf-8"));Ruleset ruleset = new TenantRuleset("Demo Console Location", keycloakDemoSetup.customerATenant.getId(), rules, Ruleset.Lang.GROOVYdiff --git a/manager/src/main/resources/demo/rules/ConsoleLocationPredicate.groovy b/manager/src/main/resources/demo/rules/ConsoleLocationPredicate.groovydeleted file mode 100644index febb07914..000000000--- a/manager/src/main/resources/demo/rules/ConsoleLocationPredicate.groovy+++ /dev/null@@ -1,19 +0,0 @@-package demo.rules--import org.openremote.manager.rules.RulesBuilder-import org.openremote.model.asset.AssetQuery-import org.openremote.model.asset.BaseAssetQuery--RulesBuilder rules = binding.rules--rules.add()- .name("Radial location predicate")- .when(- { facts ->- facts.matchFirstAssetState(new AssetQuery().location(new BaseAssetQuery.RadialLocationPredicate(100, 50, 100))).isPresent() &&- !facts.matchFirst("RadialLocation").isPresent()- })- .then(- { facts ->- facts.put("RadialLocation", "fired")- })diff --git a/manager/src/main/resources/demo/rules/DemoConsoleLocation.groovy b/manager/src/main/resources/demo/rules/DemoConsoleLocation.groovynew file mode 100644index 000000000..f0029464d--- /dev/null+++ b/manager/src/main/resources/demo/rules/DemoConsoleLocation.groovy@@ -0,0 +1,87 @@+package demo.rules++import org.openremote.manager.rules.RulesBuilder+import org.openremote.manager.rules.facade.ConsolesFacade+import org.openremote.manager.setup.builtin.ManagerDemoSetup+import org.openremote.model.asset.AssetQuery+import org.openremote.model.asset.AssetType+import org.openremote.model.asset.BaseAssetQuery+import org.openremote.model.attribute.AttributeType+import org.openremote.model.notification.AlertNotification+import org.openremote.model.rules.Assets++import java.util.logging.Logger++Logger LOG = binding.LOG+RulesBuilder rules = binding.rules+ConsolesFacade consolesFacade = binding.consoles+Assets assets = binding.assets++rules.add()+ .name("Welcome home")+ .when({+ facts ->++ def consoleIds = facts.matchAssetState(new AssetQuery()+ .type(AssetType.CONSOLE)+ .location(+ new BaseAssetQuery.RadialLocationPredicate(100, ManagerDemoSetup.SMART_HOME_LOCATION.y, ManagerDemoSetup.SMART_HOME_LOCATION.x)))+ .filter({!facts.getOptional("welcomeHome" + "_${it.id}").isPresent()})+ .map({it.id})+ .collect()++ if (consoleIds.size() > 0) {+ facts.bind("consoleIds", consoleIds)+ true+ } else {+ false+ }+ })+ .then({+ facts ->++ List<String> consoleIds = facts.bound("consoleIds")++ AlertNotification alert = new AlertNotification(+ title: "Welcome Home",+ message: "No new events to report"+ )++ consoleIds.forEach({+ LOG.info("Welcome Home triggered: $it")+ consolesFacade.notify(it, alert)+ facts.put("welcomeHome" + "_${it}", it)+ })+ })++rules.add()+ .name("Welcome home reset")+ .when({+ facts ->++ def consoleIds = facts.matchAssetState(new AssetQuery()+ .type(AssetType.CONSOLE)+ .attributeValue(AttributeType.LOCATION.name, new BaseAssetQuery.ValueEmptyPredicate()))+ .filter({facts.getOptional("welcomeHome" + "_${it.id}").isPresent()})+ .map({it.id})+ .collect()++ if (consoleIds.size() > 0) {+ facts.bind("consoleIds", consoleIds)+ true+ } else {+ false+ }++ })+ .then(+ {+ facts ->++ List<String> consoleIds = facts.bound("consoleIds")++ consoleIds.forEach({+ LOG.info("Welcome Home Reset Triggered: $it")+ facts.remove("welcomeHome" + "_${it}")+ })+ })diff --git a/model/src/main/java/org/openremote/model/console/ConsoleConfiguration.java b/model/src/main/java/org/openremote/model/console/ConsoleConfiguration.javaindex a26004057..609d20aac 100644--- a/model/src/main/java/org/openremote/model/console/ConsoleConfiguration.java+++ b/model/src/main/java/org/openremote/model/console/ConsoleConfiguration.java@@ -24,8 +24,10 @@ import org.openremote.model.ValidationFailure;import org.openremote.model.ValueHolder;import org.openremote.model.asset.Asset;import org.openremote.model.asset.AssetAttribute;+import org.openremote.model.asset.AssetMeta;import org.openremote.model.asset.AssetType;import org.openremote.model.attribute.AttributeType;+import org.openremote.model.attribute.Meta;import org.openremote.model.attribute.MetaItem;import org.openremote.model.util.Pair;import org.openremote.model.util.TextUtil;@@ -40,6 +42,7 @@ import java.util.Optional;import java.util.stream.Collectors;import static org.openremote.model.asset.AssetMeta.ACCESS_PUBLIC_WRITE;+import static org.openremote.model.asset.AssetMeta.ACCESS_RESTRICTED_WRITE;import static org.openremote.model.asset.AssetMeta.RULE_STATE;public final class ConsoleConfiguration {@@ -53,7 +56,7 @@ public final class ConsoleConfiguration {private ConsoleConfiguration() {}- public static Asset initConsoleConfiguration(Asset asset, String name, String version, String platform, Map<String, ConsoleProvider> providerMap) {+ public static Asset initConsoleConfiguration(Asset asset, String name, String version, String platform, Map<String, ConsoleProvider> providerMap, boolean allowPublicLocationWrite, boolean allowRestrictedLocationWrite) {if (!isConsole(asset)) {throw new IllegalArgumentException("Asset must be of type console");}@@ -66,12 +69,16 @@ public final class ConsoleConfiguration {setConsolePlatform(asset, platform);setConsolProviders(asset, providerMap);+ Meta locationMeta = new Meta(new MetaItem(RULE_STATE));+ if (allowPublicLocationWrite) {+ locationMeta.add(new MetaItem(ACCESS_PUBLIC_WRITE));+ }+ if (allowRestrictedLocationWrite) {+ locationMeta.add(new MetaItem(ACCESS_RESTRICTED_WRITE));+ }asset.replaceAttribute(new AssetAttribute(AttributeType.LOCATION)- .setMeta(- new MetaItem(RULE_STATE),- new MetaItem(ACCESS_PUBLIC_WRITE)- )+ .setMeta(locationMeta));return asset;diff --git a/model/src/main/java/org/openremote/model/geo/GeoJSONPoint.java b/model/src/main/java/org/openremote/model/geo/GeoJSONPoint.javaindex 7423b113d..645720e12 100644--- a/model/src/main/java/org/openremote/model/geo/GeoJSONPoint.java+++ b/model/src/main/java/org/openremote/model/geo/GeoJSONPoint.java@@ -101,7 +101,7 @@ public class GeoJSONPoint extends GeoJSONGeometry {Double x = coords.getNumber(0).orElse(null);Double y = coords.getNumber(1).orElse(null);- Double z = coords.length() == 3 ? coords.getNumber(3).orElse(null) : null;+ Double z = coords.getNumber(2).orElse(null);if (x == null || y == null) {return null;diff --git a/model/src/main/java/org/openremote/model/rules/RulesResource.java b/model/src/main/java/org/openremote/model/rules/RulesResource.javaindex 82aba4b09..24404c643 100644--- a/model/src/main/java/org/openremote/model/rules/RulesResource.java+++ b/model/src/main/java/org/openremote/model/rules/RulesResource.java@@ -238,5 +238,5 @@ public interface RulesResource {@Produces(APPLICATION_JSON)@SuccessStatusCode(200)@SuppressWarnings("unusable-by-js")- GeofenceDefinition[] getAssetGeofences(@PathParam("assetId") String assetId);+ GeofenceDefinition[] getAssetGeofences(@BeanParam RequestParams requestParams, @PathParam("assetId") String assetId);}diff --git a/model/src/main/java/org/openremote/model/rules/geofence/GeofenceDefinition.java b/model/src/main/java/org/openremote/model/rules/geofence/GeofenceDefinition.javaindex 01a2b4ec1..ab6523ffc 100644--- a/model/src/main/java/org/openremote/model/rules/geofence/GeofenceDefinition.java+++ b/model/src/main/java/org/openremote/model/rules/geofence/GeofenceDefinition.java@@ -19,6 +19,9 @@*/package org.openremote.model.rules.geofence;+import com.fasterxml.jackson.annotation.JsonCreator;+import com.fasterxml.jackson.annotation.JsonProperty;+public class GeofenceDefinition {protected String id;@@ -28,7 +31,8 @@ public class GeofenceDefinition {protected String httpMethod;protected String url;- public GeofenceDefinition(String id, double lat, double lng, int radius, String httpMethod, String url) {+ @JsonCreator+ public GeofenceDefinition(@JsonProperty("id") String id, @JsonProperty("lat") double lat, @JsonProperty("lng") double lng, @JsonProperty("radius") int radius, @JsonProperty("httpMethod") String httpMethod, @JsonProperty("url") String url) {this.id = id;this.lat = lat;this.lng = lng;diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovyindex 92fdd2c8a..98a9c4e71 100644--- a/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy+++ b/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy@@ -99,9 +99,8 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai)then: "result should match"- assets.length == 2+ assets.length == 1assets[0].id == managerDemoSetup.smartHomeId- assets[1].id == managerDemoSetup.consolesIdwhen: "the child assets of an asset in a foreign realm are retrieved"assets = assetResource.queryAssets(null,@@ -427,12 +426,11 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraidef assets = assetResource.getCurrentUserAssets(null)then: "result should match"- assets.length == 2+ assets.length == 1assets[0].id == managerDemoSetup.smartHomeId// Assets should not be completely loadedassets[0].path == nullassets[0].attributesList.size() == 0- assets[1].id == managerDemoSetup.consolesIdwhen: "the root assets of a foreign realm are retrieved"assets = assetResource.queryAssets(null,@@ -451,11 +449,9 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai)then: "result should match"- assets.length == 2+ assets.length == 1assets[0].id == managerDemoSetup.smartHomeIdassets[0].realmId == keycloakDemoSetup.customerATenant.id- assets[1].id == managerDemoSetup.consolesId- assets[1].realmId == keycloakDemoSetup.customerATenant.idwhen: "the root assets of the given realm are retrieved"assets = assetResource.queryAssets(null,@@ -574,7 +570,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraidef assets = assetResource.getCurrentUserAssets(null)then: "result should match"- assets.length == 6+ assets.length == 5Asset apartment1 = assets[0]apartment1.id == managerDemoSetup.apartment1Idapartment1.name == "Apartment 1"@@ -601,10 +597,6 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraiapartment2.id == managerDemoSetup.apartment2Idapartment2.name == "Apartment 2"- Asset console = assets[5]- console.id == managerDemoSetup.consoleId- console.name == "Demo Console"-when: "the root assets of a foreign realm are retrieved"assets = assetResource.queryAssets(null,new AssetQuery()diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovyindex 61aa35e60..fcaac31aa 100644--- a/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy+++ b/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy@@ -96,7 +96,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {)then: "only the users assets should be retrieved"- assets.size() == 6+ assets.size() == 5assets.get(0).id == managerDemoSetup.apartment1Idassets.get(1).id == managerDemoSetup.apartment1LivingroomIdassets.get(1).getAttributesList().size() == 9@@ -108,7 +108,6 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {assets.get(2).id == managerDemoSetup.apartment1KitchenIdassets.get(3).id == managerDemoSetup.apartment1HallwayIdassets.get(4).id == managerDemoSetup.apartment2Id- assets.get(5).id == managerDemoSetup.consoleIdwhen: "a user filtering query is executed that returns only IDs, names and attribute names and limits to protected attributes and meta"assets = assetStorageService.findAll(@@ -118,7 +117,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {)then: "only the users assets should be retrieved"- assets.size() == 6+ assets.size() == 5assets.get(0).id == managerDemoSetup.apartment1Idassets.get(1).id == managerDemoSetup.apartment1LivingroomIdassets.get(1).getAttributesList().size() == 5@@ -130,7 +129,6 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {assets.get(2).id == managerDemoSetup.apartment1KitchenIdassets.get(3).id == managerDemoSetup.apartment1HallwayIdassets.get(4).id == managerDemoSetup.apartment2Id- assets.get(5).id == managerDemoSetup.consoleIdwhen: "a query is executed that returns a protected attribute without any other meta items"assets = assetStorageService.findAll(@@ -400,7 +398,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {)then: "result should match"- assets.size() == 6+ assets.size() == 5assets.get(0).id == managerDemoSetup.apartment1Idassets.get(1).id == managerDemoSetup.apartment1LivingroomIdassets.get(1).getAttributesList().size() == 5@@ -411,7 +409,6 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {assets.get(2).id == managerDemoSetup.apartment1KitchenIdassets.get(3).id == managerDemoSetup.apartment1HallwayIdassets.get(4).id == managerDemoSetup.apartment2Id- assets.get(5).id == managerDemoSetup.consoleIdwhen: "a query is executed"assets = assetStorageService.findAll(diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetUserLinkingTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetUserLinkingTest.groovyindex ce60734ef..1e147bc2a 100644--- a/test/src/test/groovy/org/openremote/test/assets/AssetUserLinkingTest.groovy+++ b/test/src/test/groovy/org/openremote/test/assets/AssetUserLinkingTest.groovy@@ -1,7 +1,6 @@package org.openremote.test.assetsimport org.openremote.container.timer.TimerService-import org.openremote.manager.asset.console.ConsoleResourceImplimport org.openremote.manager.security.ManagerIdentityServiceimport org.openremote.manager.setup.SetupServiceimport org.openremote.manager.setup.builtin.KeycloakDemoSetup@@ -52,7 +51,7 @@ class AssetUserLinkingTest extends Specification implements ManagerContainerTraidef userAssets = assetResource.getUserAssetLinks(null, keycloakDemoSetup.customerATenant.id, null, null)then: "result should match"- userAssets.length == 6+ userAssets.length == 5userAssets.any {it.id.realmId == keycloakDemoSetup.customerATenant.id &&it.id.userId == keycloakDemoSetup.testuser3Id &&@@ -93,20 +92,12 @@ class AssetUserLinkingTest extends Specification implements ManagerContainerTraiit.parentAssetName == "Smart Home" &&it.userFullName == "testuser3 (Testuserfirst Testuserlast)"}- userAssets.any {- it.id.realmId == keycloakDemoSetup.customerATenant.id &&- it.id.userId == keycloakDemoSetup.testuser3Id &&- it.id.assetId == managerDemoSetup.consoleId &&- it.assetName == "Demo Console" &&- it.parentAssetName == ConsoleResourceImpl.CONSOLE_PARENT_ASSET_NAME &&- it.userFullName == "testuser3 (Testuserfirst Testuserlast)"- }when: "all user assets are retrieved of a realm and user"userAssets = assetResource.getUserAssetLinks(null, keycloakDemoSetup.customerATenant.id, keycloakDemoSetup.testuser3Id, null)then: "result should match"- userAssets.length == 6+ userAssets.length == 5when: "the realm and user don't match"assetResource.getUserAssetLinks(null, keycloakDemoSetup.customerBTenant.id, keycloakDemoSetup.testuser3Id, null)diff --git a/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy b/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovyindex a3cea61e1..093875c90 100644--- a/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy+++ b/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy@@ -1,9 +1,10 @@package org.openremote.test.console-import org.junit.Ignore+import com.google.firebase.messaging.Messageimport org.openremote.container.util.UniqueIdentifierGeneratorimport org.openremote.manager.asset.AssetStorageService-import org.openremote.manager.asset.console.ConsoleResourceImpl+import org.openremote.manager.notification.FCMDeliveryService+import org.openremote.manager.notification.NotificationServiceimport org.openremote.manager.rules.RulesEngineimport org.openremote.manager.rules.RulesServiceimport org.openremote.manager.rules.RulesetStorageService@@ -12,271 +13,132 @@ import org.openremote.manager.setup.SetupServiceimport org.openremote.manager.setup.builtin.KeycloakDemoSetupimport org.openremote.manager.setup.builtin.ManagerDemoSetupimport org.openremote.model.asset.Asset-import org.openremote.model.asset.AssetAttribute-import org.openremote.model.asset.AssetMeta+import org.openremote.model.asset.AssetResource+import org.openremote.model.asset.BaseAssetQueryimport org.openremote.model.attribute.AttributeType-import org.openremote.model.attribute.MetaItemimport org.openremote.model.console.ConsoleConfigurationimport org.openremote.model.console.ConsoleProvider+import org.openremote.model.console.ConsoleRegistrationimport org.openremote.model.console.ConsoleResource-import org.openremote.model.rules.AssetRuleset-import org.openremote.model.rules.GlobalRuleset-import org.openremote.model.rules.Ruleset-import org.openremote.model.util.TextUtil+import org.openremote.model.geo.GeoJSONPoint+import org.openremote.model.rules.*import org.openremote.model.value.ObjectValueimport org.openremote.model.value.Valuesimport org.openremote.test.ManagerContainerTrait-import org.openremote.test.rules.BasicRulesImportimport spock.lang.Specificationimport spock.util.concurrent.PollingConditionsimport javax.ws.rs.WebApplicationExceptionimport static org.openremote.manager.rules.RulesetDeployment.Status.DEPLOYED-import static org.openremote.manager.setup.builtin.ManagerDemoSetup.DEMO_RULE_STATES_APARTMENT_2-import static org.openremote.manager.setup.builtin.ManagerDemoSetup.DEMO_RULE_STATES_APARTMENT_3import static org.openremote.manager.setup.builtin.ManagerDemoSetup.DEMO_RULE_STATES_CUSTOMER_A-import static org.openremote.manager.setup.builtin.ManagerDemoSetup.DEMO_RULE_STATES_GLOBAL-import static org.openremote.manager.setup.builtin.ManagerDemoSetup.DEMO_RULE_STATES_SMART_OFFICE+import static org.openremote.manager.setup.builtin.ManagerDemoSetup.SMART_HOME_LOCATIONimport static org.openremote.model.Constants.KEYCLOAK_CLIENT_ID-import static org.openremote.model.Constants.MASTER_REALMimport static org.openremote.model.asset.AssetMeta.RULE_STATE-import static org.openremote.model.asset.AssetType.CONSOLE+import static org.openremote.model.util.TextUtil.isNullOrEmptyimport static org.openremote.model.value.Values.parseclass ConsoleTest extends Specification implements ManagerContainerTrait {- @Ignore- def "Check basic geofence provider functionality"() {+ def "Check full console behaviour"() {given: "expected conditions"def conditions = new PollingConditions(timeout: 10, initialDelay: 0.5, delay: 0.5)- and: "the container is started"+ and: "the server container is started"def serverPort = findEphemeralPort()- RulesService.GEOFENCE_INIT_DEBOUNCE_MILLIS = 500+ ORConsoleGeofenceAssetAdapter.NOTIFY_ASSETS_DEBOUNCE_MILLIS = 100def container = startContainer(defaultConfig(serverPort), defaultServices())- def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)+ def assetStorageService = container.getService(AssetStorageService.class)def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)+ def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def rulesService = container.getService(RulesService.class)def rulesetStorageService = container.getService(RulesetStorageService.class)- def assetStorageService = container.getService(AssetStorageService.class)def geofenceAdapter = (ORConsoleGeofenceAssetAdapter) rulesService.geofenceAssetAdapters.find {it.name == "ORConsole" }- and: "some test rulesets have been imported"- def rulesImport = new BasicRulesImport(rulesetStorageService, keycloakDemoSetup, managerDemoSetup)-- expect: "the rules engines to be ready"- conditions.eventually {- rulesImport.assertEnginesReady(rulesService, keycloakDemoSetup, managerDemoSetup)- }-- and: "the demo attributes marked with RULE_STATE = true meta should be inserted into the engines"- conditions.eventually {- assert rulesService.assetStates.size() == DEMO_RULE_STATES_GLOBAL- assert rulesImport.globalEngine.assetStates.size() == DEMO_RULE_STATES_GLOBAL- assert rulesImport.masterEngine.assetStates.size() == DEMO_RULE_STATES_SMART_OFFICE- assert rulesImport.customerAEngine.assetStates.size() == DEMO_RULE_STATES_CUSTOMER_A- assert rulesImport.apartment2Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_2- assert rulesImport.apartment3Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_3- }-- and: "the geofence adapter should have been initialised with the demo consoles location predicate"- conditions.eventually {- def geofences = rulesService.getAssetGeofences(managerDemoSetup.consoleId)- assert geofences.size() == 1- assert geofences[0].radius == 100- assert geofences[0].lat == 50- assert geofences[0].lng == 100- assert geofences[0].id == managerDemoSetup.consoleId + "_-174661203"- assert geofences[0].url == "/master/asset/public/${managerDemoSetup.consoleId}/updateLocation"- }-- when: "another console asset is added with its location attribute marked as RULE_STATE and it has a CONSOLE_PROVIDER_GEOFENCE attribute"- Asset console2 = ConsoleConfiguration.initConsoleConfiguration(- new Asset("Demo Android Console 2", CONSOLE),- "Demo Android Console",- "1.0",- "Android 7.1.2",- new HashMap<String, ConsoleProvider>() {-- {- put("geofence", new ConsoleProvider(- ORConsoleGeofenceAssetAdapter.NAME,- true,- false,- false,- null- ))- }- })- .addAttributes(- new AssetAttribute(AttributeType.LOCATION.getName(),- AttributeType.LOCATION.getType())- .setMeta(new MetaItem(RULE_STATE))- )- console2.setParentId(managerDemoSetup.lobbyId)- console2 = assetStorageService.merge(console2)- def console2Id = console2.getId()-- then: "the geofence adapter should be notified of the new console asset with the existing location predicate"- conditions.eventually {- def geofences = rulesService.getAssetGeofences(console2Id)- assert geofences.size() == 1- assert geofences[0].radius == 100- assert geofences[0].lat == 50- assert geofences[0].lng == 100- assert geofences[0].id == console2Id + "_-174661203"- assert geofences[0].url == "/master/asset/public/${console2Id}/updateLocation"- }-- when: "a new ruleset is deployed with multiple location predicate rules (including a duplicate and a rectangular predicate) on the lobby asset"- def lobbyRuleset = new AssetRuleset(- "Lobby location predicates",- managerDemoSetup.lobbyId,- getClass().getResource("/org/openremote/test/rules/BasicLocationPredicate2.groovy").text,- Ruleset.Lang.GROOVY- )- rulesetStorageService.merge(lobbyRuleset)- RulesEngine lobbyEngine = null-- then: "the new rule engine should be created and be running"- conditions.eventually {- lobbyEngine = rulesService.assetEngines.get(managerDemoSetup.lobbyId)- assert lobbyEngine != null- assert lobbyEngine.isRunning()- assert lobbyEngine.deployments.size() == 1- assert lobbyEngine.deployments.values().any({- it.name == "Lobby location predicates" && it.status == DEPLOYED- })- }-- then: "the geofence adapter should have been notified of the new radial location predicates for the console assets (but shouldn't contain the rectangular or duplicate predicates)"- conditions.eventually {- def console1Geofences = rulesService.getAssetGeofences(managerDemoSetup.consoleId)- def console2Geofences = rulesService.getAssetGeofences(console2Id)- assert console1Geofences.size() == 1- assert console2Geofences.size() == 2- assert console1Geofences[0].radius == 100- assert console1Geofences[0].lat == 50- assert console1Geofences[0].lng == 100- assert console1Geofences[0].id == managerDemoSetup.consoleId + "_-174661203"- assert console1Geofences[0].url == "/master/asset/public/${managerDemoSetup.consoleId}/updateLocation"-- def console2Geofence1 = console2Geofences.find {- it.radius == 100 &&- it.lat == 50 &&- it.lng == 100 &&- it.id == console2Id + "_-174661203" &&- it.url == "/master/asset/public/${console2Id}/updateLocation"- }- assert console2Geofence1 != null-- def console2Geofence2 = console2Geofences.find {- it.radius == 50 &&- it.lat == 0 &&- it.lng == -60 &&- it.id == console2Id + "_-1397479941" &&- it.url == "/master/asset/public/${console2Id}/updateLocation"- }- assert console2Geofence2 != null- }-- when: "a location predicate ruleset is removed"- rulesetStorageService.delete(GlobalRuleset.class, rulesImport.globalRuleset3Id)-- then: "the geofence adapter should be notified and update to reflect the changes"- conditions.eventually {- def console1Geofences = rulesService.getAssetGeofences(managerDemoSetup.consoleId)- def console2Geofences = rulesService.getAssetGeofences(console2Id)- assert console1Geofences.size() == 0- assert console2Geofences.size() == 2-- def console2Geofence1 = console2Geofences.find {- it.radius == 100 &&- it.lat == 50 &&- it.lng == 100 &&- it.id == console2Id + "_-174661203" &&- it.url == "/master/asset/public/${console2Id}/updateLocation"+ and: "a mock FCM delivery service"+ List<Message> sentFcmMessages = []+ def mockFCMDeliveryService = Spy(FCMDeliveryService, constructorArgs: [container]) {+ // Assume valid+ isValid() >> {+ return true}- assert console2Geofence1 != null-- def console2Geofence2 = console2Geofences.find {- it.radius == 50 &&- it.lat == 0 &&- it.lng == -60 &&- it.id == console2Id + "_-1397479941" &&- it.url == "/master/asset/public/${console2Id}/updateLocation"+ // Always "deliver" to FCM+ sendMessage(_) >> {+ Message message ->+ sentFcmMessages.add(message)+ return true}- assert console2Geofence2 != null}+ def notificationService = container.getService(NotificationService)+ notificationService.fcmDeliveryService = mockFCMDeliveryService+ Asset testUser3Console1, testUser3Console2, anonymousConsole1++ and: "the demo location predicate console rules are loaded"+ Ruleset ruleset = new TenantRuleset(+ "Demo Customer A - Console Location",+ keycloakDemoSetup.customerATenant.id,+ getClass().getResource("/demo/rules/DemoConsoleLocation.groovy").text,+ Ruleset.Lang.GROOVY+ )+ rulesetStorageService.merge(ruleset)- when: "the RULE_STATE meta is removed from the second console asset's location attribute"- console2.getAttribute(AttributeType.LOCATION.getName()).get().getMeta().removeIf({it.name.orElse(null) == AssetMeta.RULE_STATE.urn})- console2 = assetStorageService.merge(console2)-- then: "the geofence adapter should be notified that the console asset no longer has any rules with location predicates"+ expect: "the rule engine to become available and be running"conditions.eventually {- def console2Geofences = rulesService.getAssetGeofences(console2Id)- assert console2Geofences.size() == 0- assert geofenceAdapter.assetLocationPredicatesMap.isEmpty()+ def customerAEngine = rulesService.tenantEngines.get(keycloakDemoSetup.customerATenant.id)+ assert customerAEngine != null+ assert customerAEngine.isRunning()+ assert customerAEngine.assetStates.size() == DEMO_RULE_STATES_CUSTOMER_A}- cleanup: "the server should be stopped"- stopContainer(container)- }-- @Ignore- def "Check full console behaviour"() {- given: "the server container is started"- def serverPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), defaultServices())- def assetStorageService = container.getService(AssetStorageService.class)- def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)- def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)-- and: "an authenticated admin user"+ and: "an authenticated user"def accessToken = authenticate(container,- MASTER_REALM,+ keycloakDemoSetup.customerATenant.realm,KEYCLOAK_CLIENT_ID,- "testuser1",- "testuser1"+ "testuser3",+ "testuser3").token- and: "the console resource"- def consoleResource = getClientTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(ConsoleResource.class)-- when: "a new console registers"- def console = ConsoleConfiguration.initConsoleConfiguration(- new Asset("Test Android Console", CONSOLE),- "Test Android Console",- "1.0",- "Android 7.1.2",- new HashMap<String, ConsoleProvider>() {- {- put("geofence", new ConsoleProvider(- ORConsoleGeofenceAssetAdapter.NAME,- true,- false,- false,- null- ))- put("push", new ConsoleProvider(- "ORConsole",- true,- true,- false,- (ObjectValue)parse("{token: \"23123213ad2313b0897efd\"}").orElse(null)- ))- }- })- def returnedConsole = consoleResource.register(null, console)- def consoleId = returnedConsole.getId()-- then: "the returned console should have an id and match what was sent"- assert ConsoleConfiguration.getConsoleName(console).orElse(null) == "Test Android Console"+ and: "authenticated and anonymous console, rules and asset resources"+ def authenticatedConsoleResource = getClientTarget(serverUri(serverPort), keycloakDemoSetup.customerATenant.realm, accessToken).proxy(ConsoleResource.class)+ def authenticatedRulesResource = getClientTarget(serverUri(serverPort), keycloakDemoSetup.customerATenant.realm, accessToken).proxy(RulesResource.class)+ def authenticatedAssetResource = getClientTarget(serverUri(serverPort), keycloakDemoSetup.customerATenant.realm, accessToken).proxy(AssetResource.class)+ def anonymousConsoleResource = getClientTarget(serverUri(serverPort), keycloakDemoSetup.customerATenant.realm).proxy(ConsoleResource.class)+ def anonymousRulesResource = getClientTarget(serverUri(serverPort), keycloakDemoSetup.customerATenant.realm).proxy(RulesResource.class)+ def anonymousAssetResource = getClientTarget(serverUri(serverPort), keycloakDemoSetup.customerATenant.realm).proxy(AssetResource.class)++ when: "a console registers with an authenticated user"+ def consoleRegistration = new ConsoleRegistration(null,+ "Test Console",+ "1.0",+ "Android 7.0",+ new HashMap<String, ConsoleProvider>() {+ {+ put("geofence", new ConsoleProvider(+ ORConsoleGeofenceAssetAdapter.NAME,+ true,+ false,+ false,+ null+ ))+ put("push", new ConsoleProvider(+ "fcm",+ true,+ true,+ false,+ (ObjectValue)parse("{token: \"23123213ad2313b0897efd\"}").orElse(null)+ ))+ }+ })+ def returnedConsoleRegistration = authenticatedConsoleResource.register(null, consoleRegistration)+ def consoleId = returnedConsoleRegistration.getId()+ def console = assetStorageService.find(consoleId, true)++ then: "the console asset should have been created and be correctly configured"+ assert console != null+ assert ConsoleConfiguration.getConsoleName(console).orElse(null) == "Test Console"assert ConsoleConfiguration.getConsoleVersion(console).orElse(null) == "1.0"- assert ConsoleConfiguration.getConsolePlatform(console).orElse(null) == "Android 7.1.2"+ assert ConsoleConfiguration.getConsolePlatform(console).orElse(null) == "Android 7.0"def consoleGeofenceProvider = ConsoleConfiguration.getConsoleProvider(console, "geofence").orElse(null)def consolePushProvider = ConsoleConfiguration.getConsoleProvider(console, "push").orElse(null)assert consoleGeofenceProvider != null@@ -286,110 +148,406 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {assert !consoleGeofenceProvider.disabledassert consoleGeofenceProvider.data == nullassert consolePushProvider != null- assert consolePushProvider.version == "ORConsole"+ assert consolePushProvider.version == "fcm"assert consolePushProvider.requiresPermissionassert consolePushProvider.hasPermissionassert !consolePushProvider.disabledassert consolePushProvider.data.get("token").flatMap{Values.getString(it)}.orElse(null) == "23123213ad2313b0897efd"- assert !TextUtil.isNullOrEmpty(returnedConsole.getId())- assert returnedConsole.getParentId() == ConsoleResourceImpl.consoleParentAssetIdGenerator(MASTER_REALM)- assert returnedConsole.name == console.name- assert ConsoleConfiguration.getConsoleName(returnedConsole).orElse(null) == ConsoleConfiguration.getConsoleName(console).orElse(null)- assert ConsoleConfiguration.getConsoleVersion(returnedConsole).orElse(null) == ConsoleConfiguration.getConsoleVersion(console).orElse(null)- assert ConsoleConfiguration.getConsolePlatform(returnedConsole).orElse(null) == ConsoleConfiguration.getConsolePlatform(console).orElse(null)- def returnedConsoleGeofenceProvider = ConsoleConfiguration.getConsoleProvider(returnedConsole, "geofence").orElse(null)- def returnedConsolePushProvider = ConsoleConfiguration.getConsoleProvider(returnedConsole, "push").orElse(null)- assert returnedConsoleGeofenceProvider != null- assert returnedConsoleGeofenceProvider.version == ORConsoleGeofenceAssetAdapter.NAME- assert returnedConsoleGeofenceProvider.requiresPermission- assert !returnedConsoleGeofenceProvider.hasPermission- assert !returnedConsoleGeofenceProvider.disabled- assert returnedConsoleGeofenceProvider.data == null- assert returnedConsolePushProvider != null- assert returnedConsolePushProvider.version == "ORConsole"- assert returnedConsolePushProvider.requiresPermission- assert returnedConsolePushProvider.hasPermission- assert !returnedConsolePushProvider.disabled- assert returnedConsolePushProvider.data.get("token").flatMap{Values.getString(it)}.orElse(null) == "23123213ad2313b0897efd"-and: "the console should have been linked to the authenticated user"- def userAssets = assetStorageService.findUserAssets(MASTER_REALM, keycloakDemoSetup.testuser1Id, consoleId)+ def userAssets = assetStorageService.findUserAssets(keycloakDemoSetup.customerATenant.id, keycloakDemoSetup.testuser3Id, consoleId)assert userAssets.size() == 1- assert userAssets.get(0).assetName == "Test Android Console"+ assert userAssets.get(0).assetName == "Test Console"- when: "the console is modified and registration is updated"- returnedConsoleGeofenceProvider.hasPermission = true- ConsoleConfiguration.addOrReplaceConsoleProvider(returnedConsole, "geofence", returnedConsoleGeofenceProvider)- ConsoleConfiguration.addOrReplaceConsoleProvider(returnedConsole, "test", new ConsoleProvider(+ when: "the console registration is updated"+ returnedConsoleRegistration.providers.get("geofence").hasPermission = true+ returnedConsoleRegistration.providers.put("test", new ConsoleProvider("Test 1.0",false,false,true,null))- returnedConsole = consoleResource.register(null, returnedConsole)+ returnedConsoleRegistration = authenticatedConsoleResource.register(null, returnedConsoleRegistration)+ console = assetStorageService.find(consoleId, true)+ testUser3Console1 = console+ consoleGeofenceProvider = ConsoleConfiguration.getConsoleProvider(console, "geofence").orElse(null)+ consolePushProvider = ConsoleConfiguration.getConsoleProvider(console, "push").orElse(null)then: "the returned console should contain the updated data and have the same id"- assert returnedConsole.getId() == consoleId- def returnedConsoleTestProvider = ConsoleConfiguration.getConsoleProvider(returnedConsole, "test").orElse(null)- assert returnedConsoleTestProvider != null- assert returnedConsoleTestProvider.version == "Test 1.0"- assert !returnedConsoleTestProvider.requiresPermission- assert !returnedConsoleTestProvider.hasPermission- assert returnedConsoleTestProvider.disabled- assert returnedConsoleTestProvider.data == null+ assert returnedConsoleRegistration.getId() == consoleId+ assert console != null+ def consoleTestProvider = ConsoleConfiguration.getConsoleProvider(console, "test").orElse(null)+ assert consoleGeofenceProvider != null+ assert consoleGeofenceProvider.version == ORConsoleGeofenceAssetAdapter.NAME+ assert consoleGeofenceProvider.requiresPermission+ assert consoleGeofenceProvider.hasPermission+ assert !consoleGeofenceProvider.disabled+ assert consoleGeofenceProvider.data == null+ assert consolePushProvider != null+ assert consolePushProvider.version == "fcm"+ assert consolePushProvider.requiresPermission+ assert consolePushProvider.hasPermission+ assert !consolePushProvider.disabled+ assert consolePushProvider.data.get("token").flatMap{Values.getString(it)}.orElse(null) == "23123213ad2313b0897efd"+ assert consoleTestProvider != null+ assert consoleTestProvider.version == "Test 1.0"+ assert !consoleTestProvider.requiresPermission+ assert !consoleTestProvider.hasPermission+ assert consoleTestProvider.disabled+ assert consoleTestProvider.data == null++ when: "the console registration is updated anonymously"+ returnedConsoleRegistration.providers.get("test").disabled = false+ returnedConsoleRegistration = anonymousConsoleResource.register(null, returnedConsoleRegistration)+ console = assetStorageService.find(consoleId, true)+ consoleTestProvider = ConsoleConfiguration.getConsoleProvider(console, "test").orElse(null)++ then: "the result should be a forbidden request"+ WebApplicationException ex = thrown()+ ex.response.status == 403++ and: "the console should not have been updated"+ assert consoleTestProvider != null+ assert consoleTestProvider.disabledwhen: "a console registers with the id of another existing asset"- returnedConsole.setId(managerDemoSetup.thingId)- returnedConsole = consoleResource.register(null, returnedConsole)+ consoleRegistration.setId(managerDemoSetup.thingId)+ authenticatedConsoleResource.register(null, consoleRegistration)then: "the result should be bad request"- WebApplicationException ex = thrown()+ ex = thrown()ex.response.status == 400when: "a console registers with an id that doesn't exist"def unusedId = UniqueIdentifierGenerator.generateId("UnusedConsoleId")- returnedConsole.setId(unusedId)- returnedConsole = consoleResource.register(null, returnedConsole)- returnedConsoleGeofenceProvider = ConsoleConfiguration.getConsoleProvider(returnedConsole, "geofence").orElse(null)- returnedConsolePushProvider = ConsoleConfiguration.getConsoleProvider(returnedConsole, "push").orElse(null)- returnedConsoleTestProvider = ConsoleConfiguration.getConsoleProvider(returnedConsole, "test").orElse(null)+ consoleRegistration.setId(unusedId)+ authenticatedConsoleResource.register(null, consoleRegistration)+ console = assetStorageService.find(unusedId, true)+ testUser3Console2 = console+ consoleGeofenceProvider = ConsoleConfiguration.getConsoleProvider(console, "geofence").orElse(null)+ consolePushProvider = ConsoleConfiguration.getConsoleProvider(console, "push").orElse(null)then: "the console should be registered successfully and the returned console should match the supplied console"- assert unusedId.equals(returnedConsole.getId())- assert returnedConsole.name == console.name- assert ConsoleConfiguration.getConsoleName(returnedConsole).orElse(null) == ConsoleConfiguration.getConsoleName(console).orElse(null)- assert ConsoleConfiguration.getConsoleVersion(returnedConsole).orElse(null) == ConsoleConfiguration.getConsoleVersion(console).orElse(null)- assert ConsoleConfiguration.getConsolePlatform(returnedConsole).orElse(null) == ConsoleConfiguration.getConsolePlatform(console).orElse(null)- assert returnedConsoleGeofenceProvider != null- assert returnedConsoleGeofenceProvider.version == ORConsoleGeofenceAssetAdapter.NAME- assert returnedConsoleGeofenceProvider.requiresPermission- assert returnedConsoleGeofenceProvider.hasPermission- assert !returnedConsoleGeofenceProvider.disabled- assert returnedConsoleGeofenceProvider.data == null- assert returnedConsolePushProvider != null- assert returnedConsolePushProvider.version == "ORConsole"- assert returnedConsolePushProvider.requiresPermission- assert returnedConsolePushProvider.hasPermission- assert !returnedConsolePushProvider.disabled- assert returnedConsolePushProvider.data.get("token").flatMap{Values.getString(it)}.orElse(null) == "23123213ad2313b0897efd"- assert returnedConsoleTestProvider != null- assert returnedConsoleTestProvider.version == "Test 1.0"- assert !returnedConsoleTestProvider.requiresPermission- assert !returnedConsoleTestProvider.hasPermission- assert returnedConsoleTestProvider.disabled- assert returnedConsoleTestProvider.data == null-- when: "an invalid console is registered"- returnedConsole.removeAttribute(AttributeType.CONSOLE_NAME)- returnedConsole.setId(null)- returnedConsole = consoleResource.register(null, returnedConsole)+ assert console != null+ assert ConsoleConfiguration.getConsoleName(console).orElse(null) == "Test Console"+ assert ConsoleConfiguration.getConsoleVersion(console).orElse(null) == "1.0"+ assert ConsoleConfiguration.getConsolePlatform(console).orElse(null) == "Android 7.0"+ assert consoleGeofenceProvider != null+ assert consoleGeofenceProvider.version == ORConsoleGeofenceAssetAdapter.NAME+ assert consoleGeofenceProvider.requiresPermission+ assert !consoleGeofenceProvider.hasPermission+ assert !consoleGeofenceProvider.disabled+ assert consoleGeofenceProvider.data == null+ assert consolePushProvider != null+ assert consolePushProvider.version == "fcm"+ assert consolePushProvider.requiresPermission+ assert consolePushProvider.hasPermission+ assert !consolePushProvider.disabled+ assert consolePushProvider.data.get("token").flatMap{Values.getString(it)}.orElse(null) == "23123213ad2313b0897efd"++ when: "an invalid console registration is registered"+ def invalidRegistration = new ConsoleRegistration(null, null, "1.0", null, null)+ authenticatedConsoleResource.register(null, invalidRegistration)then: "the result should be bad request"ex = thrown()ex.response.status == 400+ when: "a console is registered anonymously"+ consoleRegistration.id = null+ returnedConsoleRegistration = anonymousConsoleResource.register(null, consoleRegistration)+ consoleId = returnedConsoleRegistration.getId()+ console = assetStorageService.find(consoleId, true)+ anonymousConsole1 = console+ consoleGeofenceProvider = ConsoleConfiguration.getConsoleProvider(console, "geofence").orElse(null)+ consolePushProvider = ConsoleConfiguration.getConsoleProvider(console, "push").orElse(null)+ userAssets = assetStorageService.findUserAssets(null, null, consoleId)++ then: "the console asset should have been created and be correctly configured"+ assert !isNullOrEmpty(consoleId)+ assert console != null+ assert ConsoleConfiguration.getConsoleName(console).orElse(null) == "Test Console"+ assert ConsoleConfiguration.getConsoleVersion(console).orElse(null) == "1.0"+ assert ConsoleConfiguration.getConsolePlatform(console).orElse(null) == "Android 7.0"+ assert consoleGeofenceProvider != null+ assert consoleGeofenceProvider.version == ORConsoleGeofenceAssetAdapter.NAME+ assert consoleGeofenceProvider.requiresPermission+ assert !consoleGeofenceProvider.hasPermission+ assert !consoleGeofenceProvider.disabled+ assert consoleGeofenceProvider.data == null+ assert consolePushProvider != null+ assert consolePushProvider.version == "fcm"+ assert consolePushProvider.requiresPermission+ assert consolePushProvider.hasPermission+ assert !consolePushProvider.disabled+ assert consolePushProvider.data.get("token").flatMap{Values.getString(it)}.orElse(null) == "23123213ad2313b0897efd"++ and: "the console should not have been linked to any users"+ assert userAssets.isEmpty()++ ////////////////////////////////////////////////////+ // LOCATION PREDICATE AND ALERT NOTIFICATION TESTS+ ////////////////////////////////////////////////////++ when: "an authenticated user updates the location of a linked console"+ authenticatedAssetResource.writeAttributeValue(null, testUser3Console1.id, AttributeType.LOCATION.name, new GeoJSONPoint(0d, 0d, 0d).toValue().toJson())++ then: "the consoles location should have been updated"+ conditions.eventually {+ def asset = assetStorageService.find(testUser3Console1.id, true)+ assert asset != null+ def assetLocation = asset.getAttribute(AttributeType.LOCATION.name).flatMap { it.value }.flatMap { GeoJSONPoint.fromValue(it) }.orElse(null)+ assert assetLocation != null+ assert assetLocation.x == 0d+ assert assetLocation.y == 0d+ assert assetLocation.z == 0d+ }++ when: "an anonymous user updates the location of a console linked to users"+ anonymousAssetResource.writeAttributeValue(null, testUser3Console1.id, AttributeType.LOCATION.name, new GeoJSONPoint(0d, 0d, 0d).toValue().toJson())++ then: "the result should be forbidden"+ ex = thrown()+ ex.response.status == 403++ when: "a console's location is updated to be at the smart home"+ authenticatedAssetResource.writeAttributeValue(null, testUser3Console2.id, AttributeType.LOCATION.name, SMART_HOME_LOCATION.toValue().toJson())+ long timestamp = Long.MAX_VALUE++ then: "a welcome home alert should be sent to the console"+ conditions.eventually {+ assert sentFcmMessages.size() == 1+ def asset = assetStorageService.find(testUser3Console2.id, true)+ assert asset != null+ timestamp = asset.getAttribute(AttributeType.LOCATION.name).flatMap { it.valueTimestamp }.orElse(Long.MAX_VALUE)+ }++ when: "a console's location is updated to be at the smart home again"+ authenticatedAssetResource.writeAttributeValue(null, testUser3Console2.id, AttributeType.LOCATION.name, SMART_HOME_LOCATION.toValue().toJson())++ then: "no more alerts should have been sent"+ conditions.eventually {+ def asset = assetStorageService.find(testUser3Console2.id, true)+ assert asset != null+ assert asset.getAttribute(AttributeType.LOCATION.name).flatMap { it.valueTimestamp }.orElse(Long.MIN_VALUE) > timestamp+ timestamp = asset.getAttribute(AttributeType.LOCATION.name).flatMap { it.valueTimestamp }.orElse(Long.MIN_VALUE)+ assert sentFcmMessages.size() == 1+ }++ when: "a console's location is updated to be null"+ authenticatedAssetResource.writeAttributeValue(null, testUser3Console2.id, AttributeType.LOCATION.name, "null")++ then: "no more alerts should have been sent and the welcome reset rule should have fired on the tenant rule engine"+ conditions.eventually {+ def asset = assetStorageService.find(testUser3Console2.id, true)+ assert asset != null+ assert asset.getAttribute(AttributeType.LOCATION.name).flatMap { it.valueTimestamp }.orElse(Long.MIN_VALUE) > timestamp+ assert sentFcmMessages.size() == 1+ def customerAEngine = rulesService.tenantEngines.get(keycloakDemoSetup.customerATenant.id)+ assert customerAEngine != null+ assert customerAEngine.isRunning()+ assert !customerAEngine.facts.getOptional("welcomeHome_${testUser3Console2.id}").isPresent()+ }++ when: "a console's location is updated to be at the smart home again"+ authenticatedAssetResource.writeAttributeValue(null, testUser3Console2.id, AttributeType.LOCATION.name, SMART_HOME_LOCATION.toValue().toJson())++ then: "another alert should have been sent"+ conditions.eventually {+ assert sentFcmMessages.size() == 2+ }++ ///////////////////////////////////////+ // GEOFENCE PROVIDER TESTS+ ///////////////////////////////////////++ when: "the geofences of a user linked console are requested by the authenticated user"+ def geofences = authenticatedRulesResource.getAssetGeofences(null, testUser3Console1.id)+ def expectedLocationPredicate = new BaseAssetQuery.RadialLocationPredicate(100, SMART_HOME_LOCATION.y, SMART_HOME_LOCATION.x)++ then: "the welcome home geofence should be retrieved"+ assert expectedLocationPredicate.centrePoint.size() == 2+ assert expectedLocationPredicate.centrePoint[0] == expectedLocationPredicate.lng+ assert expectedLocationPredicate.centrePoint[1] == expectedLocationPredicate.lat+ assert geofences.size() == 1+ assert geofences[0].id == testUser3Console1.id + "_" + Integer.toString(expectedLocationPredicate.hashCode())+ assert geofences[0].lat == expectedLocationPredicate.lat+ assert geofences[0].lng == expectedLocationPredicate.lng+ assert geofences[0].radius == expectedLocationPredicate.radius+ assert geofences[0].httpMethod == ORConsoleGeofenceAssetAdapter.HTTP_METHOD+ assert geofences[0].url == String.format(ORConsoleGeofenceAssetAdapter.LOCATION_URL_FORMAT_TEMPLATE, testUser3Console1.id)++ when: "an anonymous user tries to retrieve the geofences of a console linked to users"+ geofences = anonymousRulesResource.getAssetGeofences(null, testUser3Console1.id)++ then: "the result should be a forbidden request"+ ex = thrown()+ ex.response.status == 403++ when: "the geofences of testUser3Console2 are retrieved"+ geofences = authenticatedRulesResource.getAssetGeofences(null, testUser3Console2.id)++ then: "the welcome home geofence should be retrieved"+ assert geofences.size() == 1+ assert geofences[0].id == testUser3Console2.id + "_" + Integer.toString(expectedLocationPredicate.hashCode())+ assert geofences[0].lat == expectedLocationPredicate.lat+ assert geofences[0].lng == expectedLocationPredicate.lng+ assert geofences[0].radius == expectedLocationPredicate.radius+ assert geofences[0].httpMethod == ORConsoleGeofenceAssetAdapter.HTTP_METHOD+ assert geofences[0].url == String.format(ORConsoleGeofenceAssetAdapter.LOCATION_URL_FORMAT_TEMPLATE, testUser3Console2.id)++ when: "the geofences of anonymousConsole1 are retrieved"+ geofences = anonymousRulesResource.getAssetGeofences(null, anonymousConsole1.id)++ then: "the welcome home geofence should be retrieved"+ assert geofences.size() == 1+ assert geofences[0].id == anonymousConsole1.id + "_" + Integer.toString(expectedLocationPredicate.hashCode())+ assert geofences[0].lat == expectedLocationPredicate.lat+ assert geofences[0].lng == expectedLocationPredicate.lng+ assert geofences[0].radius == expectedLocationPredicate.radius+ assert geofences[0].httpMethod == ORConsoleGeofenceAssetAdapter.HTTP_METHOD+ assert geofences[0].url == String.format(ORConsoleGeofenceAssetAdapter.LOCATION_URL_FORMAT_TEMPLATE, anonymousConsole1.id)++ when: "the geofences of a non-existent console are retrieved"+ geofences = anonymousRulesResource.getAssetGeofences(null, UniqueIdentifierGenerator.generateId("nonExistentConsole"))++ then: "an empty array should be returned"+ assert geofences.size() == 0++ when: "a console is deleted"+ assetStorageService.delete(testUser3Console2.id)++ then: "the deleted console should be removed from ORConsoleGeofenceAssetAdapter"+ conditions.eventually {+ assert !geofenceAdapter.consoleIdRealmMap.containsKey(testUser3Console2.id)+ }++ then: "no geofences should be returned for this deleted console"+ conditions.eventually {+ geofences = anonymousRulesResource.getAssetGeofences(null, testUser3Console2.id)+ assert geofences.size() == 0+ }++ when: "a new ruleset is deployed on the console parent asset with multiple location predicate rules (including a duplicate and a rectangular predicate)"+ def newRuleset = new AssetRuleset(+ "Console test location predicates",+ testUser3Console1.parentId,+ getClass().getResource("/org/openremote/test/rules/BasicLocationPredicates.groovy").text,+ Ruleset.Lang.GROOVY+ )+ newRuleset = rulesetStorageService.merge(newRuleset)+ RulesEngine consoleParentEngine = null+ def newLocationPredicate = new BaseAssetQuery.RadialLocationPredicate(50, 0, -60)++ then: "the new rule engine should be created and be running"+ conditions.eventually {+ consoleParentEngine = rulesService.assetEngines.get(testUser3Console1.parentId)+ assert consoleParentEngine != null+ assert consoleParentEngine.isRunning()+ assert consoleParentEngine.deployments.size() == 1+ assert consoleParentEngine.deployments.values().any({+ it.name == "Console test location predicates" && it.status == DEPLOYED+ })+ }++ then: "a push notification should have been sent to the two remaining consoles telling them to refresh their geofences"+ conditions.eventually {+ assert sentFcmMessages.size() == 4+ assert sentFcmMessages[2].data.get("action") == "GEOFENCE_REFRESH"+ assert sentFcmMessages[3].data.get("action") == "GEOFENCE_REFRESH"+ }++ then: "the geofences of testUser3Console1 should contain the welcome home geofence and new radial geofence (but not the rectangular and duplicate predicates)"+ conditions.eventually {+ geofences = authenticatedRulesResource.getAssetGeofences(null, testUser3Console1.id)+ assert geofences.size() == 2+ def geofence1 = geofences.find { it.id == testUser3Console1.id + "_" + Integer.toString(+ expectedLocationPredicate.hashCode())}+ def geofence2 = geofences.find { it.id == testUser3Console1.id + "_" + Integer.toString(+ newLocationPredicate.hashCode())}+ assert geofence1 != null && geofence2 != null+ assert geofence1.lat == expectedLocationPredicate.lat+ assert geofence1.lng == expectedLocationPredicate.lng+ assert geofence1.radius == expectedLocationPredicate.radius+ assert geofence1.httpMethod == ORConsoleGeofenceAssetAdapter.HTTP_METHOD+ assert geofence1.url == String.format(+ ORConsoleGeofenceAssetAdapter.LOCATION_URL_FORMAT_TEMPLATE,+ testUser3Console1.id)+ assert geofence2.lat == newLocationPredicate.lat+ assert geofence2.lng == newLocationPredicate.lng+ assert geofence2.radius == newLocationPredicate.radius+ assert geofence2.httpMethod == ORConsoleGeofenceAssetAdapter.HTTP_METHOD+ assert geofence2.url == String.format(+ ORConsoleGeofenceAssetAdapter.LOCATION_URL_FORMAT_TEMPLATE,+ testUser3Console1.id)+ }++ when: "an existing ruleset containing a radial location predicate is updated"+ newRuleset.rules = getClass().getResource("/org/openremote/test/rules/BasicLocationPredicates2.groovy").text+ newRuleset = rulesetStorageService.merge(newRuleset)+ newLocationPredicate = new BaseAssetQuery.RadialLocationPredicate(150, 10, 40)++ then: "a push notification should have been sent to the two remaining consoles telling them to refresh their geofences"+ conditions.eventually {+ assert sentFcmMessages.size() == 6+ assert sentFcmMessages[4].data.get("action") == "GEOFENCE_REFRESH"+ assert sentFcmMessages[5].data.get("action") == "GEOFENCE_REFRESH"+ }++ then: "the geofences of testUser3Console1 should still contain two geofences but the location of the second should have been updated"+ conditions.eventually {+ geofences = authenticatedRulesResource.getAssetGeofences(null, testUser3Console1.id)+ assert geofences.size() == 2+ def geofence1 = geofences.find { it.id == testUser3Console1.id + "_" + Integer.toString(+ expectedLocationPredicate.hashCode())}+ def geofence2 = geofences.find { it.id == testUser3Console1.id + "_" + Integer.toString(+ newLocationPredicate.hashCode())}+ assert geofence1 != null && geofence2 != null+ assert geofence1.lat == expectedLocationPredicate.lat+ assert geofence1.lng == expectedLocationPredicate.lng+ assert geofence1.radius == expectedLocationPredicate.radius+ assert geofence1.httpMethod == ORConsoleGeofenceAssetAdapter.HTTP_METHOD+ assert geofence1.url == String.format(+ ORConsoleGeofenceAssetAdapter.LOCATION_URL_FORMAT_TEMPLATE,+ testUser3Console1.id)+ assert geofence2.lat == newLocationPredicate.lat+ assert geofence2.lng == newLocationPredicate.lng+ assert geofence2.radius == newLocationPredicate.radius+ assert geofence2.httpMethod == ORConsoleGeofenceAssetAdapter.HTTP_METHOD+ assert geofence2.url == String.format(+ ORConsoleGeofenceAssetAdapter.LOCATION_URL_FORMAT_TEMPLATE,+ testUser3Console1.id)+ }++ when: "a location predicate ruleset is removed"+ rulesetStorageService.delete(AssetRuleset.class, newRuleset.id)++ then: "only the welcome home geofence should remain"+ conditions.eventually {+ geofences = authenticatedRulesResource.getAssetGeofences(null, testUser3Console1.id)+ assert geofences.size() == 1+ assert geofences[0].id == testUser3Console1.id + "_" + Integer.toString(+ expectedLocationPredicate.hashCode())+ assert geofences[0].lat == expectedLocationPredicate.lat+ assert geofences[0].lng == expectedLocationPredicate.lng+ assert geofences[0].radius == expectedLocationPredicate.radius+ assert geofences[0].httpMethod == ORConsoleGeofenceAssetAdapter.HTTP_METHOD+ assert geofences[0].url == String.format(+ ORConsoleGeofenceAssetAdapter.LOCATION_URL_FORMAT_TEMPLATE,+ testUser3Console1.id)+ }++ when: "the RULE_STATE meta is removed from a console's location attribute"+ testUser3Console1.getAttribute(AttributeType.LOCATION.getName()).get().getMeta().removeIf({it.name.orElse(null) == RULE_STATE.urn})+ testUser3Console1 = assetStorageService.merge(testUser3Console1)++ then: "no geofences should remain for this console"+ conditions.eventually {+ geofences = authenticatedRulesResource.getAssetGeofences(null, testUser3Console1.id)+ assert geofences.size() == 0+ }+cleanup: "the server should be stopped"stopContainer(container)}diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovyindex bb33e42f5..115f89cbe 100644--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovy@@ -66,8 +66,7 @@ class BasicRulesDeploymentTest extends Specification implements ManagerContainerconditions.eventually {assert rulesService.globalEngine != nullassert rulesService.globalEngine.isRunning()- assert rulesService.globalEngine.deployments.size() == 3- assert rulesService.globalEngine.deployments.values().any({ it.name == "Location predicate demo rules" && it.status == DEPLOYED})+ assert rulesService.globalEngine.deployments.size() == 2assert rulesService.globalEngine.deployments.values().any({ it.name == "Some global demo rules" && it.status == DEPLOYED})assert rulesService.globalEngine.deployments.values().any({ it.name == "Some more global rules" && it.status == DEPLOYED})}@@ -164,11 +163,10 @@ class BasicRulesDeploymentTest extends Specification implements ManagerContainerthen: "the global rules engine should not run and the rule engine status should indicate the issue"conditions.eventually {- assert rulesService.globalEngine.deployments.size() == 4+ assert rulesService.globalEngine.deployments.size() == 3assert rulesService.globalEngine.running == falseassert rulesService.globalEngine.isError()assert rulesService.globalEngine.error instanceof RuntimeException- assert rulesService.globalEngine.deployments.values().any({ it.name == "Location predicate demo rules" && it.status == READY})assert rulesService.globalEngine.deployments.values().any({ it.name == "Some global demo rules" && it.status == READY})assert rulesService.globalEngine.deployments.values().any({ it.name == "Some more global rules" && it.status == READY})assert rulesService.globalEngine.deployments.values().any({ it.name == "Some broken global rules" && it.status == COMPILATION_ERROR})@@ -179,10 +177,9 @@ class BasicRulesDeploymentTest extends Specification implements ManagerContainerthen: "the global rules engine should restart"conditions.eventually {- assert rulesService.globalEngine.deployments.size() == 3+ assert rulesService.globalEngine.deployments.size() == 2assert rulesService.globalEngine.running == trueassert rulesService.globalEngine.isError() == false- assert rulesService.globalEngine.deployments.values().any({ it.name == "Location predicate demo rules" && it.status == DEPLOYED})assert rulesService.globalEngine.deployments.values().any({ it.name == "Some global demo rules" && it.status == DEPLOYED })assert rulesService.globalEngine.deployments.values().any({ it.name == "Some more global rules" && it.status == DEPLOYED })}diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesImport.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesImport.groovyindex 5410c2009..e9aa34f8b 100644--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesImport.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesImport.groovy@@ -17,7 +17,6 @@ class BasicRulesImport {final Long globalRulesetIdfinal Long globalRuleset2Id- final Long globalRuleset3Idfinal Long masterRulesetIdfinal Long customerARulesetIdfinal Long customerBRulesetId@@ -51,13 +50,6 @@ class BasicRulesImport {ruleset.setEnabled(false)globalRuleset2Id = rulesetStorageService.merge(ruleset).id- ruleset = new GlobalRuleset(- "Location predicate demo rules",- getClass().getResource("/org/openremote/test/rules/BasicLocationPredicate.groovy").text,- GROOVY- )- globalRuleset3Id = rulesetStorageService.merge(ruleset).id-ruleset = new TenantRuleset("Some master tenant demo rules",keycloakDemoSetup.masterTenant.id,@@ -117,9 +109,8 @@ class BasicRulesImport {globalEngine.disableTemporaryFactExpiration = trueassert globalEngine != nullassert globalEngine.isRunning()- assert globalEngine.deployments.size() == 2+ assert globalEngine.deployments.size() == 1assert globalEngine.deployments.values().any { it -> it.name == "Some global demo rules" && it.status == DEPLOYED }- assert globalEngine.deployments.values().any { it -> it.name == "Location predicate demo rules" && it.status == DEPLOYED }assert rulesService.tenantEngines.size() == 2masterEngine = rulesService.tenantEngines.get(keycloakDemoSetup.masterTenant.id)diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovyindex 272595829..f788d45ff 100644--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovy@@ -58,7 +58,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainerdef ruleDefinitions = rulesetResource.getGlobalRulesets(null)then: "result should match"- ruleDefinitions.length == 3+ ruleDefinitions.length == 2ruleDefinitions[0].name == "Some global demo rules"ruleDefinitions[0].lang == GROOVYruleDefinitions[0].rules == null // Don't retrieve the (large) rules data when getting a list of rule definitions@@ -92,7 +92,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainerwhen: "global ruleset is created"def globalRuleset = new GlobalRuleset("Test global definition", "SomeRulesCode", GROOVY)rulesetResource.createGlobalRuleset(null, globalRuleset)- def rulesetId = rulesetResource.getGlobalRulesets(null)[3].id+ def rulesetId = rulesetResource.getGlobalRulesets(null)[2].idglobalRuleset = rulesetResource.getGlobalRuleset(null, rulesetId)def lastModified = globalRuleset.lastModifieddiff --git a/test/src/test/resources/org/openremote/test/rules/BasicLocationPredicate.groovy b/test/src/test/resources/org/openremote/test/rules/BasicLocationPredicate.groovydeleted file mode 100644index 21695abb1..000000000--- a/test/src/test/resources/org/openremote/test/rules/BasicLocationPredicate.groovy+++ /dev/null@@ -1,19 +0,0 @@-package org.openremote.test.rules--import org.openremote.manager.rules.RulesBuilder-import org.openremote.model.asset.AssetQuery-import org.openremote.model.asset.BaseAssetQuery--RulesBuilder rules = binding.rules--rules.add()- .name("Radial location predicate")- .when(- { facts ->- facts.matchFirstAssetState(new AssetQuery().location(new BaseAssetQuery.RadialLocationPredicate(100, 50, 100))).isPresent() &&- !facts.matchFirst("Location").isPresent()- })- .then(- { facts ->- facts.put("RadialLocation", "fired")- })diff --git a/test/src/test/resources/org/openremote/test/rules/BasicLocationPredicate2.groovy b/test/src/test/resources/org/openremote/test/rules/BasicLocationPredicates.groovysimilarity index 75%rename from test/src/test/resources/org/openremote/test/rules/BasicLocationPredicate2.groovyrename to test/src/test/resources/org/openremote/test/rules/BasicLocationPredicates.groovyindex 7b8e849c8..1ff8f3e64 100644--- a/test/src/test/resources/org/openremote/test/rules/BasicLocationPredicate2.groovy+++ b/test/src/test/resources/org/openremote/test/rules/BasicLocationPredicates.groovy@@ -1,6 +1,7 @@package org.openremote.test.rulesimport org.openremote.manager.rules.RulesBuilder+import org.openremote.manager.setup.builtin.ManagerDemoSetupimport org.openremote.model.asset.AssetQueryimport org.openremote.model.asset.BaseAssetQuery@@ -11,7 +12,7 @@ rules.add().when({ facts ->facts.matchFirstAssetState(new AssetQuery().location(new BaseAssetQuery.RadialLocationPredicate(50, 0, -60))).isPresent() &&- !facts.matchFirst("RadialLocation").isPresent()+ !facts.matchFirst("RadialLocation2").isPresent()}).then({ facts ->@@ -22,12 +23,12 @@ rules.add().name("Duplicate radial location predicate").when({ facts ->- facts.matchFirstAssetState(new AssetQuery().location(new BaseAssetQuery.RadialLocationPredicate(100, 50, 100))).isPresent() &&- !facts.matchFirst("Location").isPresent()+ facts.matchFirstAssetState(new AssetQuery().location(new BaseAssetQuery.RadialLocationPredicate(100, ManagerDemoSetup.SMART_HOME_LOCATION.y, ManagerDemoSetup.SMART_HOME_LOCATION.x))).isPresent() &&+ !facts.matchFirst("DuplicateLocation").isPresent()}).then({ facts ->- facts.put("Location", "fired")+ facts.put("DuplicateLocation", "fired")})rules.add()diff --git a/test/src/test/resources/org/openremote/test/rules/BasicLocationPredicates2.groovy b/test/src/test/resources/org/openremote/test/rules/BasicLocationPredicates2.groovynew file mode 100644index 000000000..84c2907be--- /dev/null+++ b/test/src/test/resources/org/openremote/test/rules/BasicLocationPredicates2.groovy@@ -0,0 +1,44 @@+package org.openremote.test.rules++import org.openremote.manager.rules.RulesBuilder+import org.openremote.manager.setup.builtin.ManagerDemoSetup+import org.openremote.model.asset.AssetQuery+import org.openremote.model.asset.BaseAssetQuery++RulesBuilder rules = binding.rules++rules.add()+ .name("Another radial location predicate")+ .when(+ { facts ->+ facts.matchFirstAssetState(new AssetQuery().location(new BaseAssetQuery.RadialLocationPredicate(150, 10, 40))).isPresent() &&+ !facts.matchFirst("RadialLocation2").isPresent()+ })+ .then(+ { facts ->+ facts.put("RadialLocation2", "fired")+ })++rules.add()+ .name("Duplicate radial location predicate")+ .when(+ { facts ->+ facts.matchFirstAssetState(new AssetQuery().location(new BaseAssetQuery.RadialLocationPredicate(100, ManagerDemoSetup.SMART_HOME_LOCATION.y, ManagerDemoSetup.SMART_HOME_LOCATION.x))).isPresent() &&+ !facts.matchFirst("Location").isPresent()+ })+ .then(+ { facts ->+ facts.put("DuplicateLocation", "fired")+ })++rules.add()+ .name("Rectangular location predicate")+ .when(+ { facts ->+ facts.matchFirstAssetState(new AssetQuery().location(new BaseAssetQuery.RectangularLocationPredicate(0, 50, 50, 100))).isPresent() &&+ !facts.matchFirst("RectLocation").isPresent()+ })+ .then(+ { facts ->+ facts.put("RectLocation", "fired")+ })