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
ORConsole GeofenceAssetAdapter implemented and AssetType CONSOLE added (Testing WIP)
Rich Turnerdfd8b22f11f0
diff --git a/container/src/main/java/org/openremote/container/web/WebResource.java b/container/src/main/java/org/openremote/container/web/WebResource.javaindex 98b504585..1b47bf6ef 100644--- a/container/src/main/java/org/openremote/container/web/WebResource.java+++ b/container/src/main/java/org/openremote/container/web/WebResource.java@@ -21,15 +21,14 @@ package org.openremote.container.web;import org.keycloak.KeycloakPrincipal;import org.openremote.container.Container;+import org.openremote.container.security.AuthContext;import org.openremote.container.security.basic.BasicAuthContext;import org.openremote.container.security.keycloak.AccessTokenAuthContext;-import org.openremote.container.security.AuthContext;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.ws.rs.WebApplicationException;import javax.ws.rs.core.*;-import java.security.Principal;import static javax.ws.rs.core.Response.Status.FORBIDDEN;@@ -71,6 +70,10 @@ public class WebResource implements AuthContext {return request.getHeader(WebService.REQUEST_HEADER_REALM);}+ public boolean isAuthenticated() {+ return securityContext.getUserPrincipal() != null;+ }+@SuppressWarnings("unchecked")public AuthContext getAuthContext() {// The securityContext is a thread-local proxy, careful when/how you call itdiff --git a/manager/src/main/java/org/openremote/manager/rules/RulesResourceImpl.java b/manager/src/main/java/org/openremote/manager/rules/RulesResourceImpl.javaindex 07c569c05..c01974b2b 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesResourceImpl.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesResourceImpl.java@@ -23,13 +23,17 @@ import org.openremote.container.timer.TimerService;import org.openremote.manager.asset.AssetStorageService;import org.openremote.manager.security.ManagerIdentityService;import org.openremote.manager.web.ManagerWebResource;-import org.openremote.model.rules.RulesResource;-import org.openremote.model.security.Tenant;import org.openremote.model.asset.Asset;+import org.openremote.model.asset.AssetQuery;+import org.openremote.model.asset.BaseAssetQuery;+import org.openremote.model.attribute.AttributeDescriptorImpl;import org.openremote.model.http.RequestParams;import org.openremote.model.rules.AssetRuleset;import org.openremote.model.rules.GlobalRuleset;+import org.openremote.model.rules.RulesResource;import org.openremote.model.rules.TenantRuleset;+import org.openremote.model.rules.geofence.GeofenceDefinition;+import org.openremote.model.security.Tenant;import javax.ws.rs.BeanParam;import javax.ws.rs.WebApplicationException;@@ -46,14 +50,17 @@ public class RulesResourceImpl extends ManagerWebResource implements RulesResourfinal protected RulesetStorageService rulesetStorageService;final protected AssetStorageService assetStorageService;+ final protected RulesService rulesService;public RulesResourceImpl(TimerService timerService,ManagerIdentityService identityService,RulesetStorageService rulesetStorageService,- AssetStorageService assetStorageService) {+ AssetStorageService assetStorageService,+ RulesService rulesService) {super(timerService, identityService);this.rulesetStorageService = rulesetStorageService;this.assetStorageService = assetStorageService;+ this.rulesService = rulesService;}/* ################################################################################################# */@@ -264,7 +271,8 @@ public class RulesResourceImpl extends ManagerWebResource implements RulesResourthrow new WebApplicationException("Requested ID and ruleset ID don't match", BAD_REQUEST);}if (!existingRuleset.getAssetId().equals(ruleset.getAssetId())) {- throw new WebApplicationException("Can't update asset ID, delete and create the ruleset to reassign", BAD_REQUEST);+ throw new WebApplicationException("Can't update asset ID, delete and create the ruleset to reassign",+ BAD_REQUEST);}rulesetStorageService.merge(ruleset);}@@ -288,4 +296,31 @@ public class RulesResourceImpl extends ManagerWebResource implements RulesResourrulesetStorageService.delete(AssetRuleset.class, id);}+ @Override+ public GeofenceDefinition[] getAssetGeofences(String assetId) {+ Asset asset;++ asset = assetStorageService.find(+ new AssetQuery()+ .select(new BaseAssetQuery.Select(BaseAssetQuery.Include.ONLY_ID_AND_NAME))+ .id(assetId));++ if (asset == null)+ return new GeofenceDefinition[0];++ if (isAuthenticated()) {+ if (!isRealmAccessibleByUser(asset.getTenantRealm())) {+ throw new WebApplicationException(Response.Status.FORBIDDEN);+ }+ if (isRestrictedUser() && !assetStorageService.isUserAsset(getUserId(), assetId)) {+ throw new WebApplicationException(Response.Status.FORBIDDEN);+ }+ } else //noinspection ConstantConditions+ if (!asset.getAttribute(AttributeDescriptorImpl.CONSOLE_PROVIDER_GEOFENCE.getName()).get().isAccessPublicRead()) {+ throw new WebApplicationException(Response.Status.FORBIDDEN);+ }++ return rulesService.getAssetGeofences(assetId);+ }+}diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesService.java b/manager/src/main/java/org/openremote/manager/rules/RulesService.javaindex 74ae9d704..58ecf1b69 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesService.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesService.java@@ -26,14 +26,19 @@ import org.openremote.container.message.MessageBrokerSetupService;import org.openremote.container.persistence.PersistenceEvent;import org.openremote.container.persistence.PersistenceService;import org.openremote.container.timer.TimerService;-import org.openremote.manager.asset.*;+import org.openremote.manager.asset.AssetProcessingException;+import org.openremote.manager.asset.AssetProcessingService;+import org.openremote.manager.asset.AssetStorageService;+import org.openremote.manager.asset.AssetUpdateProcessor;import org.openremote.manager.concurrent.ManagerExecutorService;import org.openremote.manager.notification.NotificationService;import org.openremote.manager.rules.geofence.GeofenceAssetAdapter;import org.openremote.manager.security.ManagerIdentityService;import org.openremote.model.asset.*;+import org.openremote.model.attribute.AttributeDescriptorImpl;import org.openremote.model.attribute.AttributeEvent.Source;import org.openremote.model.rules.*;+import org.openremote.model.rules.geofence.GeofenceDefinition;import org.openremote.model.security.Tenant;import org.openremote.model.util.Pair;import org.openremote.model.value.ObjectValue;@@ -80,12 +85,22 @@ import static org.openremote.model.asset.AssetAttribute.getAddedOrModifiedAttrib*/public class RulesService extends RouteBuilder implements ContainerService, AssetUpdateProcessor {- private static final Logger LOG = Logger.getLogger(RulesService.class.getName());-public static final String RULE_EVENT_EXPIRES = "RULE_EVENT_EXPIRES";public static final String RULE_EVENT_EXPIRES_DEFAULT = "1h";+ private static final Logger LOG = Logger.getLogger(RulesService.class.getName());public static int GEOFENCE_PROCESSING_DEBOUNCE_MILLIS = 10000;+ protected static Map<String, GeofenceAssetAdapter> geofenceAssetAdapters;++ static {+ geofenceAssetAdapters = new HashMap<>();+ ServiceLoader.load(GeofenceAssetAdapter.class).forEach(geofenceAssetAdapter -> {+ LOG.fine("Adding GeofenceAssetAdapter: " + geofenceAssetAdapter.getClass().getName());+ geofenceAssetAdapters.put(geofenceAssetAdapter.getName(), geofenceAssetAdapter);+ });+ }+ protected final Map<String, RulesEngine<TenantRuleset>> tenantEngines = new HashMap<>();+ protected final Map<String, RulesEngine<AssetRuleset>> assetEngines = new HashMap<>();protected TimerService timerService;protected ManagerExecutorService executorService;protected PersistenceService persistenceService;@@ -94,24 +109,18 @@ public class RulesService extends RouteBuilder implements ContainerService, Asseprotected AssetStorageService assetStorageService;protected NotificationService notificationService;protected AssetProcessingService assetProcessingService;-protected RulesEngine<GlobalRuleset> globalEngine;- protected final Map<String, RulesEngine<TenantRuleset>> tenantEngines = new HashMap<>();- protected final Map<String, RulesEngine<AssetRuleset>> assetEngines = new HashMap<>();protected String[] activeTenantIds;-- protected Collection<GeofenceAssetAdapter> geofenceAssetAdapters;+ protected Map<String, GeofenceAssetAdapter> assetIdGeofenceAdapterMap;protected BiConsumer<RulesEngine, List<RulesEngine.AssetStateLocationPredicates>> locationPredicateRulesConsumer;protected Map<RulesEngine, List<RulesEngine.AssetStateLocationPredicates>> engineAssetLocationPredicateMap = new HashMap<>();protected Set<AssetState> modifiedAssetLocationPredicates = new HashSet<>();protected ScheduledFuture scheduledGeofenceProcessor;protected boolean firstGeofenceProcessorRun = true;-// Keep global list of asset states that have been pushed to any engines// The objects are already in memory inside the rule engines but keeping them// here means we can quickly insert facts into newly started enginesprotected Set<AssetState> assetStates = new HashSet<>();-protected String configEventExpires;@Override@@ -164,13 +173,25 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse@Overridepublic void start(Container container) throws Exception {- geofenceAssetAdapters = container.getServices(GeofenceAssetAdapter.class)- .stream()- .sorted(Comparator.comparingInt(GeofenceAssetAdapter::getPriority).reversed())- .collect(Collectors.toSet());+if (!geofenceAssetAdapters.isEmpty()) {LOG.info("GeoefenceAssetAdapters found: " + geofenceAssetAdapters.size());locationPredicateRulesConsumer = this::onEngineLocationRulesChanged;++ // Find all assets that link to geofence adapters and store them in a hashmap+ assetIdGeofenceAdapterMap = assetStorageService.findAll(+ new AssetQuery()+ .select(new BaseAssetQuery.Select(BaseAssetQuery.Include.ALL_EXCEPT_PATH,+ false,+ AttributeDescriptorImpl.CONSOLE_PROVIDER_GEOFENCE.getName()))+ .attributeMeta(+ new AssetQuery.AttributeMetaPredicate(+ AssetMeta.GEOFENCE_ADAPTER)+ ))+ .stream()+ .collect(Collectors.toMap(Asset::getId,+ asset -> GeofenceAssetAdapter.getAssetGeofenceAdapterName(asset).map(+ adapterName -> geofenceAssetAdapters.get(adapterName)).orElse(null)));}LOG.info("Deploying global rulesets");@@ -247,6 +268,18 @@ public class RulesService extends RouteBuilder implements ContainerService, Assereturn false;}+ public GeofenceDefinition[] getAssetGeofences(String assetId) {+ return withLockReturning(getClass().getSimpleName() + "::getAssetGeofences", () -> {+ GeofenceAssetAdapter geofenceAssetAdapter = assetIdGeofenceAdapterMap.get(assetId);++ if (geofenceAssetAdapter == null) {+ return new GeofenceDefinition[0];+ }++ return geofenceAssetAdapter.getAssetGeofences(assetId);+ });+ }+protected void processTenantChange(Tenant tenant, PersistenceEvent.Cause cause) {withLock(getClass().getSimpleName() + "::processTenantChange", () -> {// Check if enabled status has changed@@ -296,6 +329,8 @@ public class RulesService extends RouteBuilder implements ContainerService, AsseBiFunction<Asset, AssetAttribute, AssetState> buildAssetState = (loadedAsset, attribute) ->new AssetState(loadedAsset, attribute.deepCopy(), Source.INTERNAL);+ processAssetGeofenceChange(asset, persistenceEvent);+switch (persistenceEvent.getCause()) {case INSERT:@@ -305,6 +340,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse// Build an update with a fully loaded assetruleStateAttributes.forEach(attribute -> {+ // TODO: Why is the asset loaded for each attribute?Asset loadedAsset = assetStorageService.find(asset.getId(), true);// If the asset is now gone it was deleted immediately after being inserted, nothing more to doif (loadedAsset == null)@@ -381,6 +417,31 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse});}+ protected void processAssetGeofenceChange(Asset asset, PersistenceEvent persistenceEvent) {+ if (geofenceAssetAdapters.isEmpty()) {+ return;+ }++ Optional<String> geofenceAdapterName = GeofenceAssetAdapter.getAssetGeofenceAdapterName(asset);++ switch (persistenceEvent.getCause()) {++ case INSERT:+ case UPDATE:++ geofenceAdapterName+ .map(name -> assetIdGeofenceAdapterMap.put(asset.getId(), geofenceAssetAdapters.get(name)))+ .orElseGet(() -> assetIdGeofenceAdapterMap.remove(asset.getId()));++ break;+ case DELETE:++ assetIdGeofenceAdapterMap.remove(asset.getId());++ break;+ }+ }+protected void processRulesetChange(Ruleset ruleset, PersistenceEvent.Cause cause) {withLock(getClass().getSimpleName() + "::processRulesetChange", () -> {if (cause == PersistenceEvent.Cause.DELETE || !ruleset.isEnabled()) {@@ -709,56 +770,65 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse(re, existingAssetStateLocationPredicates) -> {// All location predicates have been removed so record each asset state as modifiedmodifiedAssetLocationPredicates.addAll(- existingAssetStateLocationPredicates.stream().map(RulesEngine.AssetStateLocationPredicates::getAssetState).collect(Collectors.toList()));+ existingAssetStateLocationPredicates.stream().map(+ RulesEngine.AssetStateLocationPredicates::getAssetState).collect(+ Collectors.toList()));// Remove this engine from the mapreturn null;});} else {- engineAssetLocationPredicateMap.compute(rulesEngine, (re, existingEngineAssetStateLocationPredicates) -> {- // Check if this not the first time this engine has been seen with location predicates so we can check- // for any removed asset states- if (existingEngineAssetStateLocationPredicates == null) {- // All asset states are new so record them all as modified- modifiedAssetLocationPredicates.addAll(newEngineAssetStateLocationPredicates.stream().map(RulesEngine.AssetStateLocationPredicates::getAssetState).collect(Collectors.toList()));- } else {- // Find obsolete and modified asset states- existingEngineAssetStateLocationPredicates.forEach(existingAssetStateLocationPredicates -> {- // Check if there are no longer any location predicates for this asset- Optional<RulesEngine.AssetStateLocationPredicates> newAssetStateLocationPredicates = newEngineAssetStateLocationPredicates.stream()- .filter(assetStateLocationPredicates ->- assetStateLocationPredicates.assetState.equals(- existingAssetStateLocationPredicates.getAssetState()))- .findFirst();-- if (newAssetStateLocationPredicates.isPresent()) {- // Compare existing and new location predicate sets if there is any change then record it- if (!newAssetStateLocationPredicates.get().getLocationPredicates().equals(- existingAssetStateLocationPredicates.getLocationPredicates())) {- modifiedAssetLocationPredicates.add(- existingAssetStateLocationPredicates.getAssetState());- }- } else {- // This means that there are no longer any location predicates so old ones are obsolete- modifiedAssetLocationPredicates.add(- existingAssetStateLocationPredicates.getAssetState());- }- });-- // Check for asset states in the new map but not in the old one- newEngineAssetStateLocationPredicates.forEach(newAssetStateLocationPredicates -> {- boolean isNewAssetState = existingEngineAssetStateLocationPredicates.stream()- .noneMatch(assetStateLocationPredicates ->- assetStateLocationPredicates.assetState.equals(- newAssetStateLocationPredicates.getAssetState()));-- if (isNewAssetState) {- // This means that all predicates for this asset are new- modifiedAssetLocationPredicates.add(newAssetStateLocationPredicates.getAssetState());- }- });- }- return newEngineAssetStateLocationPredicates;- });+ engineAssetLocationPredicateMap.compute(rulesEngine,+ (re, existingEngineAssetStateLocationPredicates) -> {+ // Check if this not the first time this engine has been seen with location predicates so we can check+ // for any removed asset states+ if (existingEngineAssetStateLocationPredicates == null) {+ // All asset states are new so record them all as modified+ modifiedAssetLocationPredicates.addAll(+ newEngineAssetStateLocationPredicates.stream().map(+ RulesEngine.AssetStateLocationPredicates::getAssetState).collect(+ Collectors.toList()));+ } else {+ // Find obsolete and modified asset states+ existingEngineAssetStateLocationPredicates.forEach(+ existingAssetStateLocationPredicates -> {+ // Check if there are no longer any location predicates for this asset+ Optional<RulesEngine.AssetStateLocationPredicates> newAssetStateLocationPredicates = newEngineAssetStateLocationPredicates.stream()+ .filter(assetStateLocationPredicates ->+ assetStateLocationPredicates.assetState.equals(+ existingAssetStateLocationPredicates.getAssetState()))+ .findFirst();++ if (newAssetStateLocationPredicates.isPresent()) {+ // Compare existing and new location predicate sets if there is any change then record it+ if (!newAssetStateLocationPredicates.get().getLocationPredicates().equals(+ existingAssetStateLocationPredicates.getLocationPredicates())) {+ modifiedAssetLocationPredicates.add(+ existingAssetStateLocationPredicates.getAssetState());+ }+ } else {+ // This means that there are no longer any location predicates so old ones are obsolete+ modifiedAssetLocationPredicates.add(+ existingAssetStateLocationPredicates.getAssetState());+ }+ });++ // Check for asset states in the new map but not in the old one+ newEngineAssetStateLocationPredicates.forEach(+ newAssetStateLocationPredicates -> {+ boolean isNewAssetState = existingEngineAssetStateLocationPredicates.stream()+ .noneMatch(assetStateLocationPredicates ->+ assetStateLocationPredicates.assetState.equals(+ newAssetStateLocationPredicates.getAssetState()));++ if (isNewAssetState) {+ // This means that all predicates for this asset are new+ modifiedAssetLocationPredicates.add(+ newAssetStateLocationPredicates.getAssetState());+ }+ });+ }+ return newEngineAssetStateLocationPredicates;+ });}if (modifiedAssetLocationPredicates.size() != initialModifiedCount) {@@ -776,35 +846,47 @@ public class RulesService extends RouteBuilder implements ContainerService, Asseboolean isFirstRun = firstGeofenceProcessorRun;firstGeofenceProcessorRun = false;- // Find all location predicates associated with modified asset states and pass through to geofence adapters- List<RulesEngine.AssetStateLocationPredicates> assetLocationPredicates = new ArrayList<>(- modifiedAssetLocationPredicates.size());-- modifiedAssetLocationPredicates.forEach(assetState -> {- RulesEngine.AssetStateLocationPredicates locationPredicates = new RulesEngine.AssetStateLocationPredicates(assetState, new HashSet<>());- engineAssetLocationPredicateMap.forEach((rulesEngine, engineAssetStateLocationPredicates) ->- engineAssetStateLocationPredicates.stream().filter(assetStateLocationPredicates ->- assetStateLocationPredicates.assetState.equals(- assetState))- .findFirst()- .ifPresent(assetStateLocationPredicate -> {- locationPredicates.getLocationPredicates().addAll(- assetStateLocationPredicate.getLocationPredicates());- }));-- assetLocationPredicates.add(locationPredicates);- });-- // Clear modified assets ready for next batch- modifiedAssetLocationPredicates.clear();- scheduledGeofenceProcessor = null;-- List<RulesEngine.AssetStateLocationPredicates> unmodifiableAssetStateLocationPredicates =- Collections.unmodifiableList(assetLocationPredicates);+ // Group changed geofences by adapter+ try {+ modifiedAssetLocationPredicates.stream()+ .filter(assetState -> assetIdGeofenceAdapterMap.get(assetState.getId()) != null)+ .collect(Collectors.groupingBy(assetState -> assetIdGeofenceAdapterMap.get(assetState.getId())))+ .forEach((geofenceAdapter, assetStates) -> {++ // Find all location predicates associated with modified asset states and pass through to the geofence adapter+ List<RulesEngine.AssetStateLocationPredicates> assetLocationPredicates = new ArrayList<>(+ assetStates.size());++ assetStates.forEach(+ assetState -> {+ RulesEngine.AssetStateLocationPredicates locationPredicates = new RulesEngine.AssetStateLocationPredicates(+ assetState,+ new HashSet<>());+ engineAssetLocationPredicateMap.forEach((rulesEngine, engineAssetStateLocationPredicates) ->+ engineAssetStateLocationPredicates.stream().filter(+ assetStateLocationPredicates ->+ assetStateLocationPredicates.assetState.equals(+ assetState))+ .findFirst()+ .ifPresent(+ assetStateLocationPredicate -> {+ locationPredicates.getLocationPredicates().addAll(+ assetStateLocationPredicate.getLocationPredicates());+ }));++ assetLocationPredicates.add(locationPredicates);+ }+ );++ LOG.info("Processing asset geofence updates for adapter '" + geofenceAdapter.getName() + "': asset count=" + assetLocationPredicates.size());+ geofenceAdapter.processLocationPredicates(assetLocationPredicates, isFirstRun);+ }+ );- LOG.info("Processing asset geofence updates: asset count=" + assetLocationPredicates.size());- for (GeofenceAssetAdapter geofenceAssetAdapter : geofenceAssetAdapters) {- geofenceAssetAdapter.processLocationPredicates(unmodifiableAssetStateLocationPredicates, isFirstRun);+ } finally {+ // Clear modified assets ready for next batch+ modifiedAssetLocationPredicates.clear();+ scheduledGeofenceProcessor = null;}});}diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesetStorageService.java b/manager/src/main/java/org/openremote/manager/rules/RulesetStorageService.javaindex c7ea38e1b..73e736113 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesetStorageService.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesetStorageService.java@@ -48,7 +48,8 @@ public class RulesetStorageService implements ContainerService {container.getService(TimerService.class),container.getService(ManagerIdentityService.class),this,- container.getService(AssetStorageService.class)+ container.getService(AssetStorageService.class),+ container.getService(RulesService.class)));}@@ -63,55 +64,53 @@ public class RulesetStorageService implements ContainerService {}/**- * The {@link Ruleset#rules} property is not populated for this query to avoid- * loading multiple large strings.+ * The {@link Ruleset#rules} property is not populated for this query to avoid loading multiple large strings.*/public List<GlobalRuleset> findGlobalRulesets() {return persistenceService.doReturningTransaction(entityManager ->- entityManager.createQuery(- "select new org.openremote.model.rules.GlobalRuleset(" +- "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.lang" +- ") " +- "from GlobalRuleset rs " +- "order by rs.createdOn asc",- GlobalRuleset.class- ).getResultList()+ entityManager.createQuery(+ "select new org.openremote.model.rules.GlobalRuleset(" ++ "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.lang" ++ ") " ++ "from GlobalRuleset rs " ++ "order by rs.createdOn asc",+ GlobalRuleset.class+ ).getResultList());}/**- * The {@link Ruleset#rules} property is not populated for this query to avoid- * loading multiple large strings.+ * The {@link Ruleset#rules} property is not populated for this query to avoid loading multiple large strings.*/public List<TenantRuleset> findTenantRulesets(String realmId) {return persistenceService.doReturningTransaction(entityManager ->- entityManager.createQuery(- "select new org.openremote.model.rules.TenantRuleset(" +- "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.realmId, rs.lang" +- ") " +- "from TenantRuleset rs " +- "where rs.realmId = :realmId " +- "order by rs.createdOn asc",- TenantRuleset.class- ).setParameter("realmId", realmId).getResultList()+ entityManager.createQuery(+ "select new org.openremote.model.rules.TenantRuleset(" ++ "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.realmId, rs.lang" ++ ") " ++ "from TenantRuleset rs " ++ "where rs.realmId = :realmId " ++ "order by rs.createdOn asc",+ TenantRuleset.class+ ).setParameter("realmId", realmId).getResultList());}/**- * The {@link Ruleset#rules} property is not populated for this query to avoid- * loading multiple large strings.+ * The {@link Ruleset#rules} property is not populated for this query to avoid loading multiple large strings.*/public List<AssetRuleset> findAssetRulesets(String realmId, String assetId) {return persistenceService.doReturningTransaction(entityManager ->- entityManager.createQuery(- "select new org.openremote.model.rules.AssetRuleset(" +- "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.assetId, rs.lang" +- ") " +- "from AssetRuleset rs, Asset a " +- "where rs.assetId = :assetId and rs.assetId = a.id and a.realmId = :realmId " +- "order by rs.createdOn asc",- AssetRuleset.class- ).setParameter("realmId", realmId).setParameter("assetId", assetId).getResultList()+ entityManager.createQuery(+ "select new org.openremote.model.rules.AssetRuleset(" ++ "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.assetId, rs.lang" ++ ") " ++ "from AssetRuleset rs, Asset a " ++ "where rs.assetId = :assetId and rs.assetId = a.id and a.realmId = :realmId " ++ "order by rs.createdOn asc",+ AssetRuleset.class+ ).setParameter("realmId", realmId).setParameter("assetId",+ assetId).getResultList());}@@ -120,14 +119,14 @@ public class RulesetStorageService implements ContainerService {*/public List<GlobalRuleset> findEnabledGlobalRulesets() {return persistenceService.doReturningTransaction(entityManager ->- entityManager.createQuery(- "select new org.openremote.model.rules.GlobalRuleset(" +- "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.rules, rs.lang" +- ") " +- "from GlobalRuleset rs " +- "where rs.enabled = true",- GlobalRuleset.class- ).getResultList()+ entityManager.createQuery(+ "select new org.openremote.model.rules.GlobalRuleset(" ++ "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.rules, rs.lang" ++ ") " ++ "from GlobalRuleset rs " ++ "where rs.enabled = true",+ GlobalRuleset.class+ ).getResultList());}@@ -136,14 +135,14 @@ public class RulesetStorageService implements ContainerService {*/public List<TenantRuleset> findEnabledTenantRulesets() {return persistenceService.doReturningTransaction(entityManager ->- entityManager.createQuery(- "select new org.openremote.model.rules.TenantRuleset(" +- "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.rules, rs.lang, rs.realmId" +- ") " +- "from TenantRuleset rs " +- "where rs.enabled = true",- TenantRuleset.class- ).getResultList()+ entityManager.createQuery(+ "select new org.openremote.model.rules.TenantRuleset(" ++ "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.rules, rs.lang, rs.realmId" ++ ") " ++ "from TenantRuleset rs " ++ "where rs.enabled = true",+ TenantRuleset.class+ ).getResultList());}@@ -152,14 +151,14 @@ public class RulesetStorageService implements ContainerService {*/public List<TenantRuleset> findEnabledTenantRulesets(String realmId) {return persistenceService.doReturningTransaction(entityManager ->- entityManager.createQuery(- "select new org.openremote.model.rules.TenantRuleset(" +- "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.rules, rs.lang, rs.realmId" +- ") " +- "from TenantRuleset rs " +- "where rs.enabled = true and rs.realmId = :realmId",- TenantRuleset.class- ).setParameter("realmId", realmId).getResultList()+ entityManager.createQuery(+ "select new org.openremote.model.rules.TenantRuleset(" ++ "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.rules, rs.lang, rs.realmId" ++ ") " ++ "from TenantRuleset rs " ++ "where rs.enabled = true and rs.realmId = :realmId",+ TenantRuleset.class+ ).setParameter("realmId", realmId).getResultList());}@@ -168,15 +167,15 @@ public class RulesetStorageService implements ContainerService {*/public List<AssetRuleset> findEnabledAssetRulesets() {return persistenceService.doReturningTransaction(entityManager ->- entityManager.createQuery(- "select new org.openremote.model.rules.AssetRuleset(" +- "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.rules, rs.lang, rs.assetId, a.realmId" +- ") " +- "from AssetRuleset rs, Asset a " +- "where rs.assetId = a.id " +- "and rs.enabled = true ",- AssetRuleset.class- ).getResultList()+ entityManager.createQuery(+ "select new org.openremote.model.rules.AssetRuleset(" ++ "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.rules, rs.lang, rs.assetId, a.realmId" ++ ") " ++ "from AssetRuleset rs, Asset a " ++ "where rs.assetId = a.id " ++ "and rs.enabled = true ",+ AssetRuleset.class+ ).getResultList());}@@ -185,18 +184,18 @@ public class RulesetStorageService implements ContainerService {*/public AssetRuleset findEnabledAssetRuleset(Long id) {return persistenceService.doReturningTransaction(entityManager -> {- List<AssetRuleset> result = entityManager.createQuery(- "select new org.openremote.model.rules.AssetRuleset(" +- "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.rules, rs.lang, rs.assetId, a.realmId" +- ") " +- "from AssetRuleset rs, Asset a " +- "where rs.assetId = a.id " +- "and rs.id = :id " +- "and rs.enabled = true ",- AssetRuleset.class- ).setParameter("id", id).getResultList();- return result.size() > 0 ? result.get(0) : null;- }+ List<AssetRuleset> result = entityManager.createQuery(+ "select new org.openremote.model.rules.AssetRuleset(" ++ "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.rules, rs.lang, rs.assetId, a.realmId" ++ ") " ++ "from AssetRuleset rs, Asset a " ++ "where rs.assetId = a.id " ++ "and rs.id = :id " ++ "and rs.enabled = true ",+ AssetRuleset.class+ ).setParameter("id", id).getResultList();+ return result.size() > 0 ? result.get(0) : null;+ });}@@ -205,15 +204,15 @@ public class RulesetStorageService implements ContainerService {*/public List<AssetRuleset> findEnabledAssetRulesets(String realmId) {return persistenceService.doReturningTransaction(entityManager ->- entityManager.createQuery(- "select new org.openremote.model.rules.AssetRuleset(" +- "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.rules, rs.lang, rs.assetId, a.realmId" +- ") " +- "from AssetRuleset rs, Asset a " +- "where rs.assetId = a.id and a.realmId = :realmId " +- "and rs.enabled = true",- AssetRuleset.class- ).setParameter("realmId", realmId).getResultList()+ entityManager.createQuery(+ "select new org.openremote.model.rules.AssetRuleset(" ++ "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.rules, rs.lang, rs.assetId, a.realmId" ++ ") " ++ "from AssetRuleset rs, Asset a " ++ "where rs.assetId = a.id and a.realmId = :realmId " ++ "and rs.enabled = true",+ AssetRuleset.class+ ).setParameter("realmId", realmId).getResultList());}@@ -223,7 +222,7 @@ public class RulesetStorageService implements ContainerService {public <T extends Ruleset> T merge(T ruleset) {return persistenceService.doReturningTransaction(entityManager ->- entityManager.merge(ruleset)+ entityManager.merge(ruleset));}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 284a971b4..562444884 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@@ -19,31 +19,30 @@*/package org.openremote.manager.rules.geofence;+import org.openremote.container.Container;import org.openremote.container.ContainerService;import org.openremote.manager.rules.RulesEngine;+import org.openremote.model.AbstractValueHolder;import org.openremote.model.asset.Asset;+import org.openremote.model.asset.AssetMeta;import org.openremote.model.asset.BaseAssetQuery;-import org.openremote.model.rules.AssetState;+import org.openremote.model.attribute.AttributeDescriptorImpl;+import org.openremote.model.rules.geofence.GeofenceDefinition;import java.util.List;-import java.util.Map;-import java.util.Set;+import java.util.Optional;/*** Defines an adapter that can take a collection of {@link BaseAssetQuery.LocationPredicate} that apply to a given* {@link Asset} and can convert the {@link BaseAssetQuery.LocationPredicate}s into Geofences that can be implemented by* the asset(s) itself.* <p>- * The adapter is notified when the {@link BaseAssetQuery.LocationPredicate}s {@link Asset} map changes; if a map entry- * contains a null or empty collection of {@link BaseAssetQuery.LocationPredicate}s then it means that there are no- * longer any associated with that {@link Asset} so the adapter should clear any that already exist on that {@link- * Asset}, it is the adapters job to maintain state if required (see initialising flag on {@link+ * The adapter is notified when the {@link Asset}s {@link RulesEngine.AssetStateLocationPredicates} change; if the+ * {@link RulesEngine.AssetStateLocationPredicates#getLocationPredicates()} is null or empty then it means that there+ * are no longer any associated with that {@link Asset} so the adapter should clear any that already exist on that+ * {@link Asset}, it is the adapters job to maintain state if required (see initialising flag on {@link* #processLocationPredicates}).* <p>- * When an adapter consumes a {@link BaseAssetQuery.LocationPredicate} for an {@link Asset} then it should remove that- * value from the collection (the map entry cannot be removed so adapters must only modify the entry collection value).- * This means that the next adapter won't be able to consume the same {@link BaseAssetQuery.LocationPredicate}.- * <p>* How the gefences are implemented and 'pushed' to the {@link Asset}s is up to the adapter but when a geofence is* triggered on an asset then the asset should update its own location by posting to the asset/location endpoint, the* location value sent should be as follows:@@ -54,14 +53,33 @@ import java.util.Set;* geofence)</li>* </ul>*/-public interface GeofenceAssetAdapter extends ContainerService {+public abstract class GeofenceAssetAdapter implements ContainerService {++ public static Optional<String> getAssetGeofenceAdapterName(Asset asset) {+ return asset.getAttribute(AttributeDescriptorImpl.CONSOLE_PROVIDER_GEOFENCE.getName())+ .flatMap(attr -> attr.getMetaItem(AssetMeta.GEOFENCE_ADAPTER))+ .flatMap(AbstractValueHolder::getValueAsString);+ }++ @Override+ public void init(Container container) throws Exception {++ }++ @Override+ public void start(Container container) throws Exception {++ }++ @Override+ public void stop(Container container) throws Exception {++ }/**- * An integer indicating where this adapter should be placed in the adapter chain; adapters are ordered by priority- * so a higher priority means the adapter will be called sooner (i.e. it will have a chance to consume {@link- * BaseAssetQuery.LocationPredicate}s before adapters with a lower priority).+ * Get the name of this adapter*/- int getPriority();+ public abstract String getName();/*** The initialising flag is used to indicate that the system is just initialising and the adapter is being made@@ -69,6 +87,11 @@ public interface GeofenceAssetAdapter extends ContainerService {* their own state rather than 'pushing' geofences to the asset(s) it can be assumed that they were previously sent,* hence adapters should be more concerned with delta changes (but this is really up to the adapter).*/- void processLocationPredicates(List<RulesEngine.AssetStateLocationPredicates> assetLocationPredicates,- boolean initialising);+ public abstract void processLocationPredicates(List<RulesEngine.AssetStateLocationPredicates> modifiedAssetLocationPredicates,+ boolean initialising);++ /**+ * Called to return the active geofences for the specified {@link Asset}.+ */+ public abstract GeofenceDefinition[] getAssetGeofences(String assetId);}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.javanew file mode 100644index 000000000..2890f7a8c--- /dev/null+++ b/manager/src/main/java/org/openremote/manager/rules/geofence/ORConsoleGeofenceAssetAdapter.java@@ -0,0 +1,121 @@+/*+ * 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.geofence;++import org.openremote.container.Container;+import org.openremote.manager.notification.NotificationService;+import org.openremote.manager.rules.RulesEngine;+import org.openremote.model.asset.AssetMeta;+import org.openremote.model.asset.AssetType;+import org.openremote.model.asset.BaseAssetQuery;+import org.openremote.model.attribute.AttributeDescriptorImpl;+import org.openremote.model.rules.AssetState;+import org.openremote.model.rules.geofence.GeofenceDefinition;++import java.util.*;++/**+ * This implementation is for handling geofences on console assets that support the OR Console Geofence Provider (i.e.+ * Android and iOS Consoles):+ * <ul>+ * <li>Asset type: {@link AssetType#CONSOLE}</li>+ * <li>Has the required {@link AttributeDescriptorImpl#CONSOLE_PROVIDER_GEOFENCE} attribute with an+ * {@link AssetMeta#GEOFENCE_ADAPTER} with a value of "ORConsole"</li>+ * </ul>+ * <p>+ * This adapter utilises push notifications to notify assets when their geofences change; a data only (silent) push+ * notification is sent to affected consoles/assets. Consoles can also manually request their geofences (e.g. on+ * startup)+ */+public class ORConsoleGeofenceAssetAdapter extends GeofenceAssetAdapter {++ public static final String NAME = "ORConsole";+ public static final String POST_URL_TEMPLATE = "/asset/location/";+ protected Map<String, RulesEngine.AssetStateLocationPredicates> assetLocationPredicatesMap = new HashMap<>();+ protected NotificationService notificationService;++ @Override+ public void init(Container container) throws Exception {+ super.init(container);+ this.notificationService = container.getService(NotificationService.class);+ }++ @Override+ public String getName() {+ return NAME;+ }++ @Override+ public void processLocationPredicates(List<RulesEngine.AssetStateLocationPredicates> modifiedAssetLocationPredicates, boolean initialising) {++ Set<AssetState> notifyAssets = new HashSet<>(modifiedAssetLocationPredicates.size());++ modifiedAssetLocationPredicates.forEach(assetStateLocationPredicates -> {+ assetStateLocationPredicates+ .getLocationPredicates()+ .removeIf(locationPredicate ->+ !(locationPredicate instanceof BaseAssetQuery.RadialLocationPredicate));++ if (initialising) {+ assetLocationPredicatesMap.put(assetStateLocationPredicates.getAssetState().getId(),+ assetStateLocationPredicates);+ } else {+ RulesEngine.AssetStateLocationPredicates existingPredicates = assetLocationPredicatesMap.get(+ assetStateLocationPredicates.getAssetState().getId());+ if (!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.getAssetState());+ }+ }+ });++ notifyAssets.forEach(assetState -> notifyAssetGeofencesChanged(assetState.getId()));+ }++ @Override+ public GeofenceDefinition[] getAssetGeofences(String assetId) {+ RulesEngine.AssetStateLocationPredicates assetStateLocationPredicates = assetLocationPredicatesMap.get(assetId);+ if (assetStateLocationPredicates == null) {+ return new GeofenceDefinition[0];+ }++ return assetStateLocationPredicates.getLocationPredicates().stream()+ .map(locationPredicate ->+ locationPredicateToGeofenceDefinition(assetStateLocationPredicates.getAssetState(),+ locationPredicate))+ .toArray(GeofenceDefinition[]::new);+ }++ protected GeofenceDefinition locationPredicateToGeofenceDefinition(AssetState assetState, BaseAssetQuery.LocationPredicate locationPredicate) {+ BaseAssetQuery.RadialLocationPredicate radialLocationPredicate = (BaseAssetQuery.RadialLocationPredicate) locationPredicate;+ String id = assetState.getId() + "_" + Integer.toString(radialLocationPredicate.hashCode());+ String postUrl = "/" + assetState.getTenantRealm() + POST_URL_TEMPLATE + assetState.getId();+ return new GeofenceDefinition(id,+ radialLocationPredicate.getLat(),+ radialLocationPredicate.getLng(),+ radialLocationPredicate.getRadius(),+ postUrl);+ }++ protected void notifyAssetGeofencesChanged(String assetId) {+ // TODO: implement geofence push notification+ }+}diff --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 d32960fab..2145d5335 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@@ -47,8 +47,6 @@ import static org.openremote.model.attribute.AttributeType.*;public class ManagerDemoSetup extends AbstractManagerSetup {- final protected boolean importDemoScenes;-// Update these numbers whenever you change a RULE_STATE flag in test datapublic static final int DEMO_RULE_STATES_APARTMENT_1 = 37;public static final int DEMO_RULE_STATES_APARTMENT_2 = 11;@@ -56,21 +54,19 @@ public class ManagerDemoSetup extends AbstractManagerSetup {public static final int DEMO_RULE_STATES_SMART_OFFICE = 2;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;-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 final String agentProtocolConfigName = "simulator123";+ public final String thingLightToggleAttributeName = "light1Toggle";+ final protected boolean importDemoScenes;public String smartOfficeId;public String groundFloorId;public String lobbyId;public String agentId;- public final String agentProtocolConfigName = "simulator123";public String thingId;- public final String thingLightToggleAttributeName = "light1Toggle";public String smartHomeId;public String apartment1Id;public String apartment1ServiceAgentId;@@ -84,6 +80,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {public String apartment3LivingroomId;public String masterRealmId;public String customerARealmId;+ public String consoleId;public ManagerDemoSetup(Container container, boolean importDemoScenes) {super(container);@@ -101,7 +98,8 @@ public class ManagerDemoSetup extends AbstractManagerSetup {// ################################ Demo assets for 'master' realm ###################################- ObjectValue locationValue = Values.createObject().put("latitude", 51.44541688237109).put("longitude", 5.460315214821094);+ ObjectValue locationValue = Values.createObject().put("latitude", 51.44541688237109).put("longitude",+ 5.460315214821094);Asset smartOffice = new Asset();smartOffice.setRealmId(masterTenant.getId());@@ -169,7 +167,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {Asset thing = new Asset("Demo Thing", THING, agent).addAttributes(AssetAttribute.createWithDescriptor(AttributeDescriptorImpl.LOCATION, locationValue)- .setMeta(new MetaItem(RULE_STATE, Values.create(true))));+ .setMeta(new MetaItem(RULE_STATE, Values.create(true))));thing.addAttributes(new AssetAttribute(thingLightToggleAttributeName, BOOLEAN, Values.create(true)).setMeta(new Meta(@@ -191,67 +189,66 @@ public class ManagerDemoSetup extends AbstractManagerSetup {),new AssetAttribute("light1Dimmer", PERCENTAGE) // No initial value!.setMeta(new Meta(- new MetaItem(- LABEL,- Values.create("Light 1 Dimmer")),- new MetaItem(- DESCRIPTION,- Values.create("Dimmer for living room light")),- new MetaItem(- RANGE_MIN,- Values.create(0)),- new MetaItem(- RANGE_MAX,- Values.create(100)),- new MetaItem(- AGENT_LINK,- new AttributeRef(agent.getId(), agentProtocolConfigName).toArrayValue()),- new MetaItem(- SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(NumberSimulatorElement.ELEMENT_NAME_RANGE)),- new MetaItem(- SimulatorProtocol.CONFIG_MODE, Values.create(SimulatorProtocol.Mode.WRITE_THROUGH_DELAYED.toString()))- )+ new MetaItem(+ LABEL,+ Values.create("Light 1 Dimmer")),+ new MetaItem(+ DESCRIPTION,+ Values.create("Dimmer for living room light")),+ new MetaItem(+ RANGE_MIN,+ Values.create(0)),+ new MetaItem(+ RANGE_MAX,+ Values.create(100)),+ new MetaItem(+ AGENT_LINK,+ new AttributeRef(agent.getId(), agentProtocolConfigName).toArrayValue()),+ new MetaItem(+ SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(NumberSimulatorElement.ELEMENT_NAME_RANGE)),+ new MetaItem(+ SimulatorProtocol.CONFIG_MODE,+ Values.create(SimulatorProtocol.Mode.WRITE_THROUGH_DELAYED.toString()))+ )),new AssetAttribute("light1Color", COLOR_RGB, new ColorRGB(88, 123, 88).asArrayValue()).setMeta(new Meta(- new MetaItem(- LABEL,- Values.create("Light 1 Color")),- new MetaItem(- DESCRIPTION,- Values.create("Color of living room light")),- new MetaItem(- AGENT_LINK,- new AttributeRef(agent.getId(), agentProtocolConfigName).toArrayValue()),- new MetaItem(- SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(ColorSimulatorElement.ELEMENT_NAME))- )+ new MetaItem(+ LABEL,+ Values.create("Light 1 Color")),+ new MetaItem(+ DESCRIPTION,+ Values.create("Color of living room light")),+ new MetaItem(+ AGENT_LINK,+ new AttributeRef(agent.getId(), agentProtocolConfigName).toArrayValue()),+ new MetaItem(+ SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(ColorSimulatorElement.ELEMENT_NAME))+ )),new AssetAttribute("light1PowerConsumption", ENERGY_KWH, Values.create(12.345)).setMeta(new Meta(- new MetaItem(- LABEL,- Values.create("Light 1 Usage")),- new MetaItem(- DESCRIPTION,- Values.create("Total energy consumption of living room light")),- new MetaItem(- READ_ONLY,- Values.create(true)),- new MetaItem(- FORMAT,- Values.create("%3d kWh")),- new MetaItem(- AGENT_LINK,- new AttributeRef(agent.getId(), agentProtocolConfigName).toArrayValue()),- new MetaItem(- SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(NumberSimulatorElement.ELEMENT_NAME)),- new MetaItem(- STORE_DATA_POINTS, Values.create(true))- )- ),- new AssetAttribute("locations", ARRAY)- .setMeta(new MetaItem(RULE_STATE))+ new MetaItem(+ LABEL,+ Values.create("Light 1 Usage")),+ new MetaItem(+ DESCRIPTION,+ Values.create("Total energy consumption of living room light")),+ new MetaItem(+ READ_ONLY,+ Values.create(true)),+ new MetaItem(+ FORMAT,+ Values.create("%3d kWh")),+ new MetaItem(+ AGENT_LINK,+ new AttributeRef(agent.getId(), agentProtocolConfigName).toArrayValue()),+ new MetaItem(+ SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(NumberSimulatorElement.ELEMENT_NAME)),+ new MetaItem(+ STORE_DATA_POINTS, Values.create(true))+ )+ ));thing = assetStorageService.merge(thing);thingId = thing.getId();@@ -264,54 +261,102 @@ public class ManagerDemoSetup extends AbstractManagerSetup {.orElseThrow(() -> new RuntimeException("Invalid test data"));persistenceService.doTransaction(em -> {- assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);+ assetDatapointService.processAssetUpdate(em,+ finalThing,+ light1PowerConsumptionAttribute,+ AttributeEvent.Source.SENSOR);light1PowerConsumptionAttribute.setValue(Values.create(0.11), now.minusDays(80).toEpochSecond() * 1000);- assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);+ assetDatapointService.processAssetUpdate(em,+ finalThing,+ light1PowerConsumptionAttribute,+ AttributeEvent.Source.SENSOR);light1PowerConsumptionAttribute.setValue(Values.create(1.22), now.minusDays(40).toEpochSecond() * 1000);- assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);+ assetDatapointService.processAssetUpdate(em,+ finalThing,+ light1PowerConsumptionAttribute,+ AttributeEvent.Source.SENSOR);light1PowerConsumptionAttribute.setValue(Values.create(2.33), now.minusDays(20).toEpochSecond() * 1000);- assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);+ assetDatapointService.processAssetUpdate(em,+ finalThing,+ light1PowerConsumptionAttribute,+ AttributeEvent.Source.SENSOR);light1PowerConsumptionAttribute.setValue(Values.create(3.44), now.minusDays(10).toEpochSecond() * 1000);- assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);+ assetDatapointService.processAssetUpdate(em,+ finalThing,+ light1PowerConsumptionAttribute,+ AttributeEvent.Source.SENSOR);light1PowerConsumptionAttribute.setValue(Values.create(4.55), now.minusDays(8).toEpochSecond() * 1000);light1PowerConsumptionAttribute.setValue(Values.create(5.66), now.minusDays(6).toEpochSecond() * 1000);- assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);+ assetDatapointService.processAssetUpdate(em,+ finalThing,+ light1PowerConsumptionAttribute,+ AttributeEvent.Source.SENSOR);light1PowerConsumptionAttribute.setValue(Values.create(6.77), now.minusDays(3).toEpochSecond() * 1000);- assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);+ assetDatapointService.processAssetUpdate(em,+ finalThing,+ light1PowerConsumptionAttribute,+ AttributeEvent.Source.SENSOR);light1PowerConsumptionAttribute.setValue(Values.create(7.88), now.minusDays(1).toEpochSecond() * 1000);- assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);+ assetDatapointService.processAssetUpdate(em,+ finalThing,+ light1PowerConsumptionAttribute,+ AttributeEvent.Source.SENSOR);light1PowerConsumptionAttribute.setValue(Values.create(8.99), now.minusHours(10).toEpochSecond() * 1000);- assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);+ assetDatapointService.processAssetUpdate(em,+ finalThing,+ light1PowerConsumptionAttribute,+ AttributeEvent.Source.SENSOR);light1PowerConsumptionAttribute.setValue(Values.create(9.11), now.minusHours(5).toEpochSecond() * 1000);- assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);+ assetDatapointService.processAssetUpdate(em,+ finalThing,+ light1PowerConsumptionAttribute,+ AttributeEvent.Source.SENSOR);light1PowerConsumptionAttribute.setValue(Values.create(10.22), now.minusHours(2).toEpochSecond() * 1000);- assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);+ assetDatapointService.processAssetUpdate(em,+ finalThing,+ light1PowerConsumptionAttribute,+ AttributeEvent.Source.SENSOR);light1PowerConsumptionAttribute.setValue(Values.create(11.33), now.minusHours(1).toEpochSecond() * 1000);- assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);+ assetDatapointService.processAssetUpdate(em,+ finalThing,+ light1PowerConsumptionAttribute,+ AttributeEvent.Source.SENSOR);light1PowerConsumptionAttribute.setValue(Values.create(11.44), now.minusMinutes(30).toEpochSecond() * 1000);- assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);+ assetDatapointService.processAssetUpdate(em,+ finalThing,+ light1PowerConsumptionAttribute,+ AttributeEvent.Source.SENSOR);light1PowerConsumptionAttribute.setValue(Values.create(12.00), now.minusMinutes(5).toEpochSecond() * 1000);- assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);+ assetDatapointService.processAssetUpdate(em,+ finalThing,+ light1PowerConsumptionAttribute,+ AttributeEvent.Source.SENSOR);light1PowerConsumptionAttribute.setValue(Values.create(12.11), now.minusSeconds(5).toEpochSecond() * 1000);- assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);+ assetDatapointService.processAssetUpdate(em,+ finalThing,+ light1PowerConsumptionAttribute,+ AttributeEvent.Source.SENSOR);light1PowerConsumptionAttribute.setValue(Values.create(12.22), now.minusSeconds(1).toEpochSecond() * 1000);- assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);+ assetDatapointService.processAssetUpdate(em,+ finalThing,+ light1PowerConsumptionAttribute,+ AttributeEvent.Source.SENSOR);});// ################################ Demo assets for 'customerA' realm ###################################@@ -406,18 +451,27 @@ public class ManagerDemoSetup extends AbstractManagerSetup {switch (attributeIndex) {case 2:return new MetaItem[]{- new MetaItem(AssetMeta.AGENT_LINK, new AttributeRef(apartment1ServiceAgentId, "apartmentSimulator").toArrayValue()),- new MetaItem(SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(NumberSimulatorElement.ELEMENT_NAME))+ new MetaItem(AssetMeta.AGENT_LINK,+ new AttributeRef(apartment1ServiceAgentId,+ "apartmentSimulator").toArrayValue()),+ new MetaItem(SimulatorProtocol.SIMULATOR_ELEMENT,+ Values.create(NumberSimulatorElement.ELEMENT_NAME))};case 3:return new MetaItem[]{- new MetaItem(AssetMeta.AGENT_LINK, new AttributeRef(apartment1ServiceAgentId, "apartmentSimulator").toArrayValue()),- new MetaItem(SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(NumberSimulatorElement.ELEMENT_NAME))+ new MetaItem(AssetMeta.AGENT_LINK,+ new AttributeRef(apartment1ServiceAgentId,+ "apartmentSimulator").toArrayValue()),+ new MetaItem(SimulatorProtocol.SIMULATOR_ELEMENT,+ Values.create(NumberSimulatorElement.ELEMENT_NAME))};case 4:return new MetaItem[]{- new MetaItem(AssetMeta.AGENT_LINK, new AttributeRef(apartment1ServiceAgentId, "apartmentSimulator").toArrayValue()),- new MetaItem(SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(NumberSimulatorElement.ELEMENT_NAME))+ new MetaItem(AssetMeta.AGENT_LINK,+ new AttributeRef(apartment1ServiceAgentId,+ "apartmentSimulator").toArrayValue()),+ new MetaItem(SimulatorProtocol.SIMULATOR_ELEMENT,+ Values.create(NumberSimulatorElement.ELEMENT_NAME))};}return null;@@ -573,12 +627,37 @@ public class ManagerDemoSetup extends AbstractManagerSetup {apartment3Livingroom = assetStorageService.merge(apartment3Livingroom);apartment3LivingroomId = apartment3Livingroom.getId();+ Asset console = new Asset("Demo Android Console", CONSOLE, lobby)+ .addAttributes(+ new AssetAttribute(AttributeDescriptorImpl.LOCATION.getName(),+ AttributeDescriptorImpl.LOCATION.getType())+ .setMeta(new MetaItem(RULE_STATE)),+ new AssetAttribute(AttributeDescriptorImpl.CONSOLE_PROVIDER_GEOFENCE.getName(),+ AttributeDescriptorImpl.CONSOLE_PROVIDER_GEOFENCE.getType())+ .setMeta(+ new MetaItem(GEOFENCE_ADAPTER, Values.create("ORConsole")),+ new MetaItem(ACCESS_PUBLIC_READ)+ )+ );+ console = assetStorageService.merge(console);+ consoleId = console.getId();+// ################################ Link demo users and assets ###################################- assetStorageService.storeUserAsset(new UserAsset(keycloakDemoSetup.customerATenant.getId(), keycloakDemoSetup.testuser3Id, apartment1Id));- assetStorageService.storeUserAsset(new UserAsset(keycloakDemoSetup.customerATenant.getId(), keycloakDemoSetup.testuser3Id, apartment1LivingroomId));- assetStorageService.storeUserAsset(new UserAsset(keycloakDemoSetup.customerATenant.getId(), keycloakDemoSetup.testuser3Id, apartment1KitchenId));- assetStorageService.storeUserAsset(new UserAsset(keycloakDemoSetup.customerATenant.getId(), keycloakDemoSetup.testuser3Id, apartment1HallwayId));- assetStorageService.storeUserAsset(new UserAsset(keycloakDemoSetup.customerATenant.getId(), keycloakDemoSetup.testuser3Id, apartment2Id));+ assetStorageService.storeUserAsset(new UserAsset(keycloakDemoSetup.customerATenant.getId(),+ keycloakDemoSetup.testuser3Id,+ apartment1Id));+ assetStorageService.storeUserAsset(new UserAsset(keycloakDemoSetup.customerATenant.getId(),+ keycloakDemoSetup.testuser3Id,+ apartment1LivingroomId));+ assetStorageService.storeUserAsset(new UserAsset(keycloakDemoSetup.customerATenant.getId(),+ keycloakDemoSetup.testuser3Id,+ apartment1KitchenId));+ assetStorageService.storeUserAsset(new UserAsset(keycloakDemoSetup.customerATenant.getId(),+ keycloakDemoSetup.testuser3Id,+ apartment1HallwayId));+ assetStorageService.storeUserAsset(new UserAsset(keycloakDemoSetup.customerATenant.getId(),+ keycloakDemoSetup.testuser3Id,+ apartment2Id));}}\ No newline at end of filediff --git a/manager/src/main/resources/META-INF/services/org.openremote.manager.rules.geofence.GeofenceAssetAdapter b/manager/src/main/resources/META-INF/services/org.openremote.manager.rules.geofence.GeofenceAssetAdapternew file mode 100644index 000000000..af4a27928--- /dev/null+++ b/manager/src/main/resources/META-INF/services/org.openremote.manager.rules.geofence.GeofenceAssetAdapter@@ -0,0 +1 @@+org.openremote.manager.rules.geofence.ORConsoleGeofenceAssetAdapter\ No newline at end of filediff --git a/model/src/main/java/org/openremote/model/asset/AssetMeta.java b/model/src/main/java/org/openremote/model/asset/AssetMeta.javaindex d939f295b..48b096cce 100644--- a/model/src/main/java/org/openremote/model/asset/AssetMeta.java+++ b/model/src/main/java/org/openremote/model/asset/AssetMeta.java@@ -36,8 +36,8 @@ import static org.openremote.model.attribute.MetaItemDescriptor.Access.ACCESS_PRimport static org.openremote.model.util.TextUtil.REGEXP_PATTERN_DOUBLE;/**- * Asset attribute meta item name is an arbitrary string. It should be URI. This enum contains- * the well-known URIs for functionality we can depend on in our platform.+ * Asset attribute meta item name is an arbitrary string. It should be URI. This enum contains the well-known URIs for+ * functionality we can depend on in our platform.* <p>* A custom project can add its own asset meta items through {@link AssetModelProvider}.* <p>@@ -46,8 +46,8 @@ import static org.openremote.model.util.TextUtil.REGEXP_PATTERN_DOUBLE;public enum AssetMeta implements MetaItemDescriptor {/**- * Marks an attribute of an agent asset as a {@link org.openremote.model.asset.agent.ProtocolConfiguration}.- * The attribute value is a protocol URN.+ * Marks an attribute of an agent asset as a {@link org.openremote.model.asset.agent.ProtocolConfiguration}. The+ * attribute value is a protocol URN.*/PROTOCOL_CONFIGURATION(ASSET_META_NAMESPACE + ":protocolConfiguration",@@ -72,8 +72,9 @@ public enum AssetMeta implements MetaItemDescriptor {false,value ->Optional.ofNullable(AttributeRef.isAttributeRef(value)- ? null- : new ValidationFailure(META_ITEM_VALUE_MISMATCH, AttributeRef.class.getSimpleName()))+ ? null+ : new ValidationFailure(META_ITEM_VALUE_MISMATCH,+ AttributeRef.class.getSimpleName()))),/**@@ -90,8 +91,9 @@ public enum AssetMeta implements MetaItemDescriptor {false,value ->Optional.ofNullable(AttributeLink.isAttributeLink(value)- ? null- : new ValidationFailure(META_ITEM_VALUE_MISMATCH, AttributeLink.class.getSimpleName()))+ ? null+ : new ValidationFailure(META_ITEM_VALUE_MISMATCH,+ AttributeLink.class.getSimpleName()))),/**@@ -155,9 +157,9 @@ public enum AssetMeta implements MetaItemDescriptor {false),/**- * Marks the attribute as read-only for non-superuser clients. South-bound {@link AttributeEvent}s- * by regular or restricted users are ignored. North-bound {@link AttributeEvent}s made by protocols and- * rules engine are possible.+ * Marks the attribute as read-only for non-superuser clients. South-bound {@link AttributeEvent}s by regular or+ * restricted users are ignored. North-bound {@link AttributeEvent}s made by protocols and rules engine are+ * possible.*/READ_ONLY(ASSET_META_NAMESPACE + ":readOnly",@@ -169,8 +171,8 @@ public enum AssetMeta implements MetaItemDescriptor {true),/**- * Marks the attribute as readable by restricted clients and therefore users who are linked to- * the asset, see {@link UserAsset}.+ * Marks the attribute as readable by restricted clients and therefore users who are linked to the asset, see {@link+ * UserAsset}.*/ACCESS_RESTRICTED_READ(ASSET_META_NAMESPACE + ":accessRestrictedRead",@@ -182,8 +184,8 @@ public enum AssetMeta implements MetaItemDescriptor {true),/**- * Marks the attribute as writable by restricted clients and therefore users who are linked to- * the asset, see {@link UserAsset}.+ * Marks the attribute as writable by restricted clients and therefore users who are linked to the asset, see {@link+ * UserAsset}.*/ACCESS_RESTRICTED_WRITE(ASSET_META_NAMESPACE + ":accessRestrictedWrite",@@ -275,11 +277,11 @@ public enum AssetMeta implements MetaItemDescriptor {true),/**- * Should attribute writes be processed by the rules engines as {@link AssetState} facts,- * with a lifecycle that reflects the state of the asset attribute. Each attribute will have one- * fact at all times in rules memory. These state facts are kept in sync with asset changes: When- * the attribute is updated, the fact will be updated (replaced). If you want evaluate the change- * history of an attribute, you typically need to combine this with {@link #RULE_EVENT}.+ * Should attribute writes be processed by the rules engines as {@link AssetState} facts, with a lifecycle that+ * reflects the state of the asset attribute. Each attribute will have one fact at all times in rules memory. These+ * state facts are kept in sync with asset changes: When the attribute is updated, the fact will be updated+ * (replaced). If you want evaluate the change history of an attribute, you typically need to combine this with+ * {@link #RULE_EVENT}.*/RULE_STATE(ASSET_META_NAMESPACE + ":ruleState",@@ -291,11 +293,11 @@ public enum AssetMeta implements MetaItemDescriptor {true),/**- * Should attribute writes be processed by the rules engines as temporary facts. When an attribute- * is updated, the change will be inserted as a new {@link AssetState} temporary fact in rules engines.- * These facts expire automatically after a defined time, see {@link #RULE_EVENT_EXPIRES}. If you want- * to match (multiple) {@link AssetState}s for the same attribute over time, to evaluate the change- * history of an attribute, add this meta item.+ * Should attribute writes be processed by the rules engines as temporary facts. When an attribute is updated, the+ * change will be inserted as a new {@link AssetState} temporary fact in rules engines. These facts expire+ * automatically after a defined time, see {@link #RULE_EVENT_EXPIRES}. If you want to match (multiple) {@link+ * AssetState}s for the same attribute over time, to evaluate the change history of an attribute, add this meta+ * item.*/RULE_EVENT(ASSET_META_NAMESPACE + ":ruleEvent",@@ -307,11 +309,12 @@ public enum AssetMeta implements MetaItemDescriptor {true),/**- * Set maximum lifetime of {@link AssetState} temporary facts in rules, for example "1h30m5s". The rules- * engine will remove temporary {@link AssetState} facts if they are older than this value (using event- * source/value timestamp, not event processing time).+ * Set maximum lifetime of {@link AssetState} temporary facts in rules, for example "1h30m5s". The rules engine will+ * remove temporary {@link AssetState} facts if they are older than this value (using event source/value timestamp,+ * not event processing time).* <p>- * The default expiration for asset events can be configured with environment variable <code>RULE_EVENT_EXPIRES</code>.+ * The default expiration for asset events can be configured with environment variable+ * <code>RULE_EVENT_EXPIRES</code>.* <p>* Also see {@link TemporaryFact#GUARANTEED_MIN_EXPIRATION_MILLIS}.*/@@ -319,13 +322,15 @@ public enum AssetMeta implements MetaItemDescriptor {ASSET_META_NAMESPACE + ":ruleEventExpires",new Access(true, false, true),ValueType.STRING,- "^([+-])?((\\d+)[Dd])?\\s*((\\d+)[Hh])?\\s*((\\d+)[Mm])?\\s*((\\d+)[Ss])?\\s*((\\d+)([Mm][Ss])?)?$", // See TimeUtil+ "^([+-])?((\\d+)[Dd])?\\s*((\\d+)[Hh])?\\s*((\\d+)[Mm])?\\s*((\\d+)[Ss])?\\s*((\\d+)([Mm][Ss])?)?$",+ // See TimeUtilPatternFailure.DAYS_HOURS_MINS_SECONDS.name(),null,false),/**- * Disabled flag to be used by asset attributes that could require this functionality (e.g. {@link org.openremote.model.asset.agent.ProtocolConfiguration})+ * Disabled flag to be used by asset attributes that could require this functionality (e.g. {@link+ * org.openremote.model.asset.agent.ProtocolConfiguration})*/DISABLED(ASSET_META_NAMESPACE + ":disabled",@@ -346,7 +351,17 @@ public enum AssetMeta implements MetaItemDescriptor {null,null,Values.create(true),- true);+ true),++ GEOFENCE_ADAPTER(+ ASSET_META_NAMESPACE + ":geofence:adapter",+ new Access(false, true, true),+ ValueType.STRING,+ null,+ null,+ null,+ false+ );final protected String urn;final protected Access access;diff --git a/model/src/main/java/org/openremote/model/asset/AssetType.java b/model/src/main/java/org/openremote/model/asset/AssetType.javaindex c945aa89f..d91a4e5e9 100644--- a/model/src/main/java/org/openremote/model/asset/AssetType.java+++ b/model/src/main/java/org/openremote/model/asset/AssetType.java@@ -31,8 +31,8 @@ import static org.openremote.model.attribute.AttributeType.NUMBER;import static org.openremote.model.attribute.AttributeType.STRING;/**- * Asset type is an arbitrary string. It should be URI. This enum contains- * the well-known URIs for functionality we want to depend on in our platform.+ * Asset type is an arbitrary string. It should be URI. This enum contains the well-known URIs for functionality we want+ * to depend on in our platform.* <p>* TODO https://people.eecs.berkeley.edu/~arka/papers/buildsys2015_metadatasurvey.pdf*/@@ -41,32 +41,32 @@ public enum AssetType implements AssetTypeDescriptor {CUSTOM(null, "cube"),BUILDING(ASSET_NAMESPACE + ":building", "building",- new AssetAttribute("area", NUMBER)- .setMeta(- new MetaItem(LABEL, Values.create("Surface Area")),- new MetaItem(DESCRIPTION, Values.create("Floor area of building measured in m²")),- new MetaItem(ABOUT, Values.create("http://project-haystack.org/tag/area"))- ),- new AssetAttribute("geoStreet", STRING)- .setMeta(- new MetaItem(LABEL, Values.create("Street")),- new MetaItem(ABOUT, Values.create("http://project-haystack.org/tag/geoStreet"))- ),- new AssetAttribute("geoPostalCode", NUMBER)- .setMeta(- new MetaItem(LABEL, Values.create("Postal Code")),- new MetaItem(ABOUT, Values.create("http://project-haystack.org/tag/geoPostalCode"))- ),- new AssetAttribute("geoCity", STRING)- .setMeta(- new MetaItem(LABEL, Values.create("City")),- new MetaItem(ABOUT, Values.create("http://project-haystack.org/tag/geoCity"))- ),- new AssetAttribute("geoCountry", STRING)- .setMeta(- new MetaItem(LABEL, Values.create("Country")),- new MetaItem(ABOUT, Values.create("http://project-haystack.org/tag/geoCountry"))- )+ new AssetAttribute("area", NUMBER)+ .setMeta(+ new MetaItem(LABEL, Values.create("Surface Area")),+ new MetaItem(DESCRIPTION, Values.create("Floor area of building measured in m²")),+ new MetaItem(ABOUT, Values.create("http://project-haystack.org/tag/area"))+ ),+ new AssetAttribute("geoStreet", STRING)+ .setMeta(+ new MetaItem(LABEL, Values.create("Street")),+ new MetaItem(ABOUT, Values.create("http://project-haystack.org/tag/geoStreet"))+ ),+ new AssetAttribute("geoPostalCode", NUMBER)+ .setMeta(+ new MetaItem(LABEL, Values.create("Postal Code")),+ new MetaItem(ABOUT, Values.create("http://project-haystack.org/tag/geoPostalCode"))+ ),+ new AssetAttribute("geoCity", STRING)+ .setMeta(+ new MetaItem(LABEL, Values.create("City")),+ new MetaItem(ABOUT, Values.create("http://project-haystack.org/tag/geoCity"))+ ),+ new AssetAttribute("geoCountry", STRING)+ .setMeta(+ new MetaItem(LABEL, Values.create("Country")),+ new MetaItem(ABOUT, Values.create("http://project-haystack.org/tag/geoCountry"))+ )),FLOOR(ASSET_NAMESPACE + ":floor", "server"),@@ -77,6 +77,8 @@ public enum AssetType implements AssetTypeDescriptor {AGENT(ASSET_NAMESPACE + ":agent", "gears"),+ CONSOLE(ASSET_NAMESPACE + ":console", "mobile"),+THING(ASSET_NAMESPACE + ":thing", "gear");final protected String value;@@ -95,6 +97,30 @@ public enum AssetType implements AssetTypeDescriptor {this.defaultAttributes = defaultAttributes;}+ public static AssetTypeDescriptor[] valuesSorted() {+ List<AssetTypeDescriptor> list = new ArrayList<>(Arrays.asList(values()));++ list.sort(Comparator.comparing(AssetTypeDescriptor::getName));+ if (list.contains(CUSTOM)) {+ // CUSTOM should be first+ list.remove(CUSTOM);+ list.add(0, CUSTOM);+ }++ return list.toArray(new AssetTypeDescriptor[list.size()]);+ }++ public static Optional<AssetType> getByValue(String value) {+ if (value == null)+ return Optional.empty();++ for (AssetType assetType : values()) {+ if (value.equals(assetType.getValue()))+ return Optional.of(assetType);+ }+ return Optional.empty();+ }+@Overridepublic String getName() {return this.name();@@ -119,28 +145,4 @@ public enum AssetType implements AssetTypeDescriptor {public Stream<AssetAttribute> getDefaultAttributes() {return defaultAttributes != null ? Arrays.stream(defaultAttributes) : Stream.empty();}-- public static AssetTypeDescriptor[] valuesSorted() {- List<AssetTypeDescriptor> list = new ArrayList<>(Arrays.asList(values()));-- list.sort(Comparator.comparing(AssetTypeDescriptor::getName));- if (list.contains(CUSTOM)) {- // CUSTOM should be first- list.remove(CUSTOM);- list.add(0, CUSTOM);- }-- return list.toArray(new AssetTypeDescriptor[list.size()]);- }-- public static Optional<AssetType> getByValue(String value) {- if (value == null)- return Optional.empty();-- for (AssetType assetType : values()) {- if (value.equals(assetType.getValue()))- return Optional.of(assetType);- }- return Optional.empty();- }}diff --git a/model/src/main/java/org/openremote/model/asset/BaseAssetQuery.java b/model/src/main/java/org/openremote/model/asset/BaseAssetQuery.javaindex d874ad169..d5dd0a96d 100644--- a/model/src/main/java/org/openremote/model/asset/BaseAssetQuery.java+++ b/model/src/main/java/org/openremote/model/asset/BaseAssetQuery.java@@ -37,82 +37,6 @@ import java.util.Objects;@SuppressWarnings("unchecked")public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {- public static final ArrayValue queriesAsValue(BaseAssetQuery... queries) {- ArrayValue arrayValue = Values.createArray();-- for (BaseAssetQuery query : queries) {- ObjectValue objectValue = Values.createObject();- if (query.select != null) {- objectValue.put("select", query.select.toModelValue());- }- if (query.type != null) {- objectValue.put("type", query.type.toModelValue());- }- if (query.attribute != null && query.attribute.length > 0) {- ArrayValue attributeArray = Values.createArray();- for (AttributePredicate attributePredicate : query.attribute) {- attributeArray.add(attributePredicate.toModelValue());- }- objectValue.put("attribute", attributeArray);- }- arrayValue.add(objectValue);- }- return arrayValue;- }-- public static final AssetQuery objectValueAsQuery(ObjectValue objectValue) {- AssetQuery assetQuery = new AssetQuery();-- objectValue.getObject("select").ifPresent(selectValue -> {- assetQuery.select = Select.fromObjectValue(selectValue);- });-- objectValue.getObject("type").ifPresent(typeValue -> {- assetQuery.type = StringPredicate.fromObjectValue(typeValue);- });-- objectValue.getArray("attribute").ifPresent(attributeValue -> {- assetQuery.attribute = attributeValue.stream()- .map(val -> (ObjectValue) val)- .map(attributePredicateValue -> {- AttributePredicate attributePredicate = new AttributePredicate();-- attributePredicate.name = StringPredicate.fromObjectValue(attributePredicateValue- .getObject("name")- .orElseThrow(() -> new IllegalArgumentException("StringPredicate missing for name in AttributePredicate"))- );-- ObjectValue predicateValue = attributePredicateValue- .getObject("value")- .orElseThrow(() -> new IllegalArgumentException("value missing in AttributePredicate"));-- predicateValue.getString("predicateType").ifPresent(predicateType -> {- switch (predicateType) {- case "StringPredicate":- attributePredicate.value = StringPredicate.fromObjectValue(predicateValue);- break;- case "BooleanPredicate":- attributePredicate.value = BooleanPredicate.fromObjectValue(predicateValue);- break;- case "StringArrayPredicate":- attributePredicate.value = StringArrayPredicate.fromObjectValue(predicateValue);- break;- case "DateTimePredicate":- attributePredicate.value = DateTimePredicate.fromObjectValue(predicateValue);- break;- case "NumberPredicate":- attributePredicate.value = NumberPredicate.fromObjectValue(predicateValue);- break;- }- });- return attributePredicate;- })- .toArray(AttributePredicate[]::new);- });-- return assetQuery;- }-public enum Include {ALL_EXCEPT_PATH_AND_ATTRIBUTES,ALL_EXCEPT_PATH,@@ -128,7 +52,68 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {PUBLIC_READ}+ /**+ * String matching options+ */+ public enum Match {+ EXACT,+ NOT_EXACT,+ BEGIN,+ END,+ CONTAINS;++ public String prepare(String string) {+ if (string == null)+ return null;+ switch (this) {+ case BEGIN:+ return string + "%";+ case CONTAINS:+ return "%" + string + "%";+ case END:+ return "%" + string;+ }+ return string;+ }+ }++ /**+ * Binary operators+ */+ public enum Operator {+ EQUALS,+ NOT_EQUALS,+ GREATER_THAN,+ GREATER_EQUALS,+ LESS_THAN,+ LESS_EQUALS,+ BETWEEN+ }++ public enum NumberType {+ DOUBLE,+ INTEGER+ }++ @JsonSubTypes({+ @JsonSubTypes.Type(value = StringPredicate.class, name = "string"),+ @JsonSubTypes.Type(value = BooleanPredicate.class, name = "boolean"),+ @JsonSubTypes.Type(value = StringArrayPredicate.class, name = "string-array"),+ @JsonSubTypes.Type(value = DateTimePredicate.class, name = "datetime"),+ @JsonSubTypes.Type(value = NumberPredicate.class, name = "number")+ })+ @JsonTypeInfo(+ use = JsonTypeInfo.Id.NAME,+ include = JsonTypeInfo.As.PROPERTY,+ property = "predicateType"+ )+ public interface ValuePredicate<T> {++ ObjectValue toModelValue();+ }+public static class Select {+public Include include;public boolean recursive;public Access access;@@ -163,21 +148,6 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {this.attributeNames = attributeNames;}- public Select include(Include include) {- this.include = include;- return this;- }-- public Select filterAccess(Access access) {- this.access = access;- return this;- }-- public Select filterAttributes(String... attributeNames) {- this.attributeNames = attributeNames;- return this;- }-public static Select fromObjectValue(ObjectValue objectValue) {Select select = new Select();objectValue.getString("include").ifPresent(include -> {@@ -198,12 +168,28 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {return select;}+ public Select include(Include include) {+ this.include = include;+ return this;+ }++ public Select filterAccess(Access access) {+ this.access = access;+ return this;+ }++ public Select filterAttributes(String... attributeNames) {+ this.attributeNames = attributeNames;+ return this;+ }+public ObjectValue toModelValue() {ObjectValue objectValue = Values.createObject();objectValue.put("include", Values.create(include.toString()));objectValue.put("recursive", Values.create(recursive));objectValue.put("access", Values.create(access.toString()));- objectValue.put("attributeNames", Values.createArray().addAll(Arrays.stream(attributeNames).map(Values::create).toArray(Value[]::new)));+ objectValue.put("attributeNames",+ Values.createArray().addAll(Arrays.stream(attributeNames).map(Values::create).toArray(Value[]::new)));return objectValue;}@@ -218,66 +204,8 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {}}- /**- * String matching options- */- public enum Match {- EXACT,- NOT_EXACT,- BEGIN,- END,- CONTAINS;-- public String prepare(String string) {- if (string == null)- return null;- switch (this) {- case BEGIN:- return string + "%";- case CONTAINS:- return "%" + string + "%";- case END:- return "%" + string;- }- return string;- }- }-- /**- * Binary operators- */- public enum Operator {- EQUALS,- NOT_EQUALS,- GREATER_THAN,- GREATER_EQUALS,- LESS_THAN,- LESS_EQUALS,- BETWEEN- }-- public enum NumberType {- DOUBLE,- INTEGER- }-- @JsonSubTypes({- @JsonSubTypes.Type(value = StringPredicate.class, name = "string"),- @JsonSubTypes.Type(value = BooleanPredicate.class, name = "boolean"),- @JsonSubTypes.Type(value = StringArrayPredicate.class, name = "string-array"),- @JsonSubTypes.Type(value = DateTimePredicate.class, name = "datetime"),- @JsonSubTypes.Type(value = NumberPredicate.class, name = "number")- })- @JsonTypeInfo(- use = JsonTypeInfo.Id.NAME,- include = JsonTypeInfo.As.PROPERTY,- property = "predicateType"- )- public interface ValuePredicate<T> {- ObjectValue toModelValue();- }-public static class ValueNotEmptyPredicate implements ValuePredicate<Value> {+@Overridepublic ObjectValue toModelValue() {ObjectValue objectValue = Values.createObject();@@ -287,6 +215,7 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {}public static class StringPredicate implements ValuePredicate<String> {+public Match match = Match.EXACT;public boolean caseSensitive = true;public String value;@@ -309,6 +238,20 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {this.value = value;}+ public static StringPredicate fromObjectValue(ObjectValue objectValue) {+ StringPredicate stringPredicate = new StringPredicate();+ objectValue.getString("match").ifPresent(match -> {+ stringPredicate.match = Match.valueOf(match);+ });+ objectValue.getBoolean("caseSensitive").ifPresent(caseSensitive -> {+ stringPredicate.caseSensitive = caseSensitive;+ });+ objectValue.getString("value").ifPresent(value -> {+ stringPredicate.value = value;+ });+ return stringPredicate;+ }+public StringPredicate match(Match match) {this.match = match;return this;@@ -340,20 +283,6 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {return objectValue;}- public static StringPredicate fromObjectValue(ObjectValue objectValue) {- StringPredicate stringPredicate = new StringPredicate();- objectValue.getString("match").ifPresent(match -> {- stringPredicate.match = Match.valueOf(match);- });- objectValue.getBoolean("caseSensitive").ifPresent(caseSensitive -> {- stringPredicate.caseSensitive = caseSensitive;- });- objectValue.getString("value").ifPresent(value -> {- stringPredicate.value = value;- });- return stringPredicate;- }-@Overridepublic String toString() {return getClass().getSimpleName() + "{" +@@ -365,6 +294,7 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {}public static class BooleanPredicate implements ValuePredicate<Boolean> {+public boolean value;public BooleanPredicate() {@@ -374,6 +304,14 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {this.value = value;}+ public static BooleanPredicate fromObjectValue(ObjectValue objectValue) {+ BooleanPredicate booleanPredicate = new BooleanPredicate();+ booleanPredicate.value = objectValue+ .getBoolean("value")+ .orElseThrow(() -> new IllegalArgumentException("value missing for BooleanPredicate"));+ return booleanPredicate;+ }+public BooleanPredicate value(boolean value) {this.value = value;return this;@@ -393,17 +331,10 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {objectValue.put("value", Values.create(value));return objectValue;}-- public static BooleanPredicate fromObjectValue(ObjectValue objectValue) {- BooleanPredicate booleanPredicate = new BooleanPredicate();- booleanPredicate.value = objectValue- .getBoolean("value")- .orElseThrow(() -> new IllegalArgumentException("value missing for BooleanPredicate"));- return booleanPredicate;- }}public static class StringArrayPredicate implements ValuePredicate<String[]> {+public StringPredicate[] predicates = new StringPredicate[0];public StringArrayPredicate() {@@ -413,6 +344,18 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {this.predicates = predicates;}+ public static StringArrayPredicate fromObjectValue(ObjectValue objectValue) {+ StringArrayPredicate stringArrayPredicate = new StringArrayPredicate();+ objectValue.getArray("value").ifPresent(arrayValue -> {+ ;+ stringArrayPredicate.predicates = objectValue.stream()+ .map(val -> (ObjectValue) val)+ .map(StringPredicate::fromObjectValue)+ .toArray(StringPredicate[]::new);+ });+ return stringArrayPredicate;+ }+public StringArrayPredicate predicates(StringPredicate... predicates) {this.predicates = predicates;return this;@@ -430,18 +373,6 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {return objectValue;}- public static StringArrayPredicate fromObjectValue(ObjectValue objectValue) {- StringArrayPredicate stringArrayPredicate = new StringArrayPredicate();- objectValue.getArray("value").ifPresent(arrayValue -> {- ;- stringArrayPredicate.predicates = objectValue.stream()- .map(val -> (ObjectValue) val)- .map(StringPredicate::fromObjectValue)- .toArray(StringPredicate[]::new);- });- return stringArrayPredicate;- }-@Overridepublic String toString() {return getClass().getSimpleName() + "{" +@@ -451,6 +382,7 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {}public static class DateTimePredicate implements ValuePredicate<Long> {+public String value;public String rangeValue; // Used as upper bound when Operator.BETWEENpublic Operator operator = Operator.EQUALS;@@ -470,6 +402,24 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {this.rangeValue = rangeEnd;}+ public static DateTimePredicate fromObjectValue(ObjectValue objectValue) {+ DateTimePredicate dateTimePredicate = new DateTimePredicate();++ objectValue.getString("dateFormat").ifPresent(format -> {+ dateTimePredicate.dateFormat = format;+ });+ objectValue.getString("value").ifPresent(value -> {+ dateTimePredicate.value = value;+ });+ objectValue.getString("rangeValue").ifPresent(rangeValue -> {+ dateTimePredicate.rangeValue = rangeValue;+ });+ objectValue.getString("operator").ifPresent(operator -> {+ dateTimePredicate.operator = Operator.valueOf(operator);+ });+ return dateTimePredicate;+ }+public DateTimePredicate operator(Operator dateMatch) {this.operator = dateMatch;return this;@@ -501,24 +451,6 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {return objectValue;}- public static DateTimePredicate fromObjectValue(ObjectValue objectValue) {- DateTimePredicate dateTimePredicate = new DateTimePredicate();-- objectValue.getString("dateFormat").ifPresent(format -> {- dateTimePredicate.dateFormat = format;- });- objectValue.getString("value").ifPresent(value -> {- dateTimePredicate.value = value;- });- objectValue.getString("rangeValue").ifPresent(rangeValue -> {- dateTimePredicate.rangeValue = rangeValue;- });- objectValue.getString("operator").ifPresent(operator -> {- dateTimePredicate.operator = Operator.valueOf(operator);- });- return dateTimePredicate;- }-@Overridepublic String toString() {return getClass().getSimpleName() + "{" +@@ -531,6 +463,7 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {}public static class NumberPredicate implements ValuePredicate<Double> {+public double value;public double rangeValue; // Used as upper bound when Operator.BETWEENpublic Operator operator = Operator.EQUALS;@@ -559,6 +492,20 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {this.numberType = numberType;}+ public static NumberPredicate fromObjectValue(ObjectValue objectValue) {+ NumberPredicate numberPredicate = new NumberPredicate();+ objectValue.getNumber("value").ifPresent(value -> {+ numberPredicate.value = value;+ });+ objectValue.getNumber("rangeValue").ifPresent(rangeValue -> {+ numberPredicate.rangeValue = rangeValue;+ });+ objectValue.getString("operator").ifPresent(operator -> {+ numberPredicate.operator = Operator.valueOf(operator);+ });+ return numberPredicate;+ }+public NumberPredicate predicate(double predicate) {this.value = predicate;return this;@@ -598,23 +545,10 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {", numberType=" + numberType +'}';}-- public static NumberPredicate fromObjectValue(ObjectValue objectValue) {- NumberPredicate numberPredicate = new NumberPredicate();- objectValue.getNumber("value").ifPresent(value -> {- numberPredicate.value = value;- });- objectValue.getNumber("rangeValue").ifPresent(rangeValue -> {- numberPredicate.rangeValue = rangeValue;- });- objectValue.getString("operator").ifPresent(operator -> {- numberPredicate.operator = Operator.valueOf(operator);- });- return numberPredicate;- }}public static class ParentPredicate {+public String id;public String type;public boolean noParent;@@ -660,6 +594,7 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {}public static class PathPredicate {+public String[] path;public PathPredicate() {@@ -687,6 +622,7 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {}public static class TenantPredicate {+public String realmId;public String realm;@@ -717,6 +653,7 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {}public static class AttributePredicate {+public StringPredicate name;public ValuePredicate value;@@ -767,6 +704,7 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {}public static class AttributeMetaPredicate {+public StringPredicate itemNamePredicate;public ValuePredicate itemValuePredicate;@@ -883,6 +821,7 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {)public abstract static class LocationPredicate {+// TODO: switch return type to location objectpublic abstract double[] getCentrePoint();}@@ -917,6 +856,18 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {return this;}+ public int getRadius() {+ return radius;+ }++ public double getLat() {+ return lat;+ }++ public double getLng() {+ return lng;+ }+@Overridepublic boolean equals(Object o) {if (this == o) return true;@@ -935,7 +886,7 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {@Overridepublic double[] getCentrePoint() {- return new double[] {lng, lat};+ return new double[]{lng, lat};}}@@ -973,6 +924,22 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {return this;}+ public double getLatMin() {+ return latMin;+ }++ public double getLngMin() {+ return lngMin;+ }++ public double getLatMax() {+ return latMax;+ }++ public double getLngMax() {+ return lngMax;+ }+@Overridepublic boolean equals(Object o) {if (this == o) return true;@@ -992,9 +959,9 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {@Overridepublic double[] getCentrePoint() {- double x = (lngMin+lngMax)/2;- double y = (latMin+latMax)/2;- return new double[] {x,y};+ double x = (lngMin + lngMax) / 2;+ double y = (latMin + latMax) / 2;+ return new double[]{x, y};}}@@ -1041,10 +1008,8 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {'}';}}-// Projectionpublic Select select;-// Restriction predicatespublic String id;public StringPredicate name;@@ -1057,13 +1022,88 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {public AttributeMetaPredicate[] attributeMeta;public CalendarEventActivePredicate calendarEventActive;public LocationPredicate location;-// Orderingpublic OrderBy orderBy;-protected BaseAssetQuery() {}+ public static final ArrayValue queriesAsValue(BaseAssetQuery... queries) {+ ArrayValue arrayValue = Values.createArray();++ for (BaseAssetQuery query : queries) {+ ObjectValue objectValue = Values.createObject();+ if (query.select != null) {+ objectValue.put("select", query.select.toModelValue());+ }+ if (query.type != null) {+ objectValue.put("type", query.type.toModelValue());+ }+ if (query.attribute != null && query.attribute.length > 0) {+ ArrayValue attributeArray = Values.createArray();+ for (AttributePredicate attributePredicate : query.attribute) {+ attributeArray.add(attributePredicate.toModelValue());+ }+ objectValue.put("attribute", attributeArray);+ }+ arrayValue.add(objectValue);+ }+ return arrayValue;+ }++ public static final AssetQuery objectValueAsQuery(ObjectValue objectValue) {+ AssetQuery assetQuery = new AssetQuery();++ objectValue.getObject("select").ifPresent(selectValue -> {+ assetQuery.select = Select.fromObjectValue(selectValue);+ });++ objectValue.getObject("type").ifPresent(typeValue -> {+ assetQuery.type = StringPredicate.fromObjectValue(typeValue);+ });++ objectValue.getArray("attribute").ifPresent(attributeValue -> {+ assetQuery.attribute = attributeValue.stream()+ .map(val -> (ObjectValue) val)+ .map(attributePredicateValue -> {+ AttributePredicate attributePredicate = new AttributePredicate();++ attributePredicate.name = StringPredicate.fromObjectValue(attributePredicateValue+ .getObject("name")+ .orElseThrow(() -> new IllegalArgumentException(+ "StringPredicate missing for name in AttributePredicate"))+ );++ ObjectValue predicateValue = attributePredicateValue+ .getObject("value")+ .orElseThrow(() -> new IllegalArgumentException("value missing in AttributePredicate"));++ predicateValue.getString("predicateType").ifPresent(predicateType -> {+ switch (predicateType) {+ case "StringPredicate":+ attributePredicate.value = StringPredicate.fromObjectValue(predicateValue);+ break;+ case "BooleanPredicate":+ attributePredicate.value = BooleanPredicate.fromObjectValue(predicateValue);+ break;+ case "StringArrayPredicate":+ attributePredicate.value = StringArrayPredicate.fromObjectValue(predicateValue);+ break;+ case "DateTimePredicate":+ attributePredicate.value = DateTimePredicate.fromObjectValue(predicateValue);+ break;+ case "NumberPredicate":+ attributePredicate.value = NumberPredicate.fromObjectValue(predicateValue);+ break;+ }+ });+ return attributePredicate;+ })+ .toArray(AttributePredicate[]::new);+ });++ return assetQuery;+ }+public CHILD select(Select select) {if (select == null) {select = new Select();@@ -1187,13 +1227,13 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {}/**- * Will filter out assets that have a {@link CalendarEventConfiguration} attribute that results in the event- * not being 'active/in progress' at the specified time. Assets without a {@link CalendarEventConfiguration}- * attribute are assumed to always be in progress (i.e. will always pass this check).- * <p>+ * Will filter out assets that have a {@link CalendarEventConfiguration} attribute that results in the event not+ * being 'active/in progress' at the specified time. Assets without a {@link CalendarEventConfiguration} attribute+ * are assumed to always be in progress (i.e. will always pass this check).+ ** <b>- * NOTE: This predicate is applied in memory and the results should be limited as much as possible by applying- * other predicates to the query to avoid performance issues.+ * NOTE: This predicate is applied in memory and the results should be limited as much as possible by applying other+ * predicates to the query to avoid performance issues.* </b>*/public CHILD calendarEventActive(long timestampSeconds) {diff --git a/model/src/main/java/org/openremote/model/attribute/AttributeDescriptorImpl.java b/model/src/main/java/org/openremote/model/attribute/AttributeDescriptorImpl.javaindex 28306b7d5..745d7a2b0 100644--- a/model/src/main/java/org/openremote/model/attribute/AttributeDescriptorImpl.java+++ b/model/src/main/java/org/openremote/model/attribute/AttributeDescriptorImpl.java@@ -1,15 +1,12 @@package org.openremote.model.attribute;-import org.openremote.model.value.Value;-import org.openremote.model.value.Values;-import java.util.Optional;-import static org.openremote.model.asset.AssetMeta.RULE_STATE;-public enum AttributeDescriptorImpl implements AttributeDescriptor {- LOCATION("location", AttributeType.LOCATION);+ LOCATION("location", AttributeType.LOCATION),++ CONSOLE_PROVIDER_GEOFENCE("providerGeofence", AttributeType.OBJECT);final protected String name;final protected AttributeType attributeType;@@ -21,6 +18,17 @@ public enum AttributeDescriptorImpl implements AttributeDescriptor {this.defaultMetaItems = defaultMetaItems;}+ public static Optional<AttributeDescriptor> getByValue(String name) {+ if (name == null)+ return Optional.empty();++ for (AttributeDescriptor descriptor : values()) {+ if (name.equals(descriptor.getName()))+ return Optional.of(descriptor);+ }+ return Optional.empty();+ }+@Overridepublic String getName() {return name;@@ -32,18 +40,7 @@ public enum AttributeDescriptorImpl implements AttributeDescriptor {}@Override- public MetaItem[] getDefaultMetaItems(){+ public MetaItem[] getDefaultMetaItems() {return defaultMetaItems;}-- public static Optional<AttributeDescriptor> getByValue(String name) {- if (name == null)- return Optional.empty();-- for (AttributeDescriptor descriptor : values()) {- if (name.equals(descriptor.getName()))- return Optional.of(descriptor);- }- return Optional.empty();- }}diff --git a/model/src/main/java/org/openremote/model/rules/RulesResource.java b/model/src/main/java/org/openremote/model/rules/RulesResource.javaindex b8694ad24..44af35a77 100644--- a/model/src/main/java/org/openremote/model/rules/RulesResource.java+++ b/model/src/main/java/org/openremote/model/rules/RulesResource.java@@ -20,8 +20,11 @@package org.openremote.model.rules;import jsinterop.annotations.JsType;+import org.openremote.model.asset.AssetMeta;+import org.openremote.model.attribute.AttributeDescriptorImpl;import org.openremote.model.http.RequestParams;import org.openremote.model.http.SuccessStatusCode;+import org.openremote.model.rules.geofence.GeofenceDefinition;import javax.annotation.security.RolesAllowed;import javax.validation.Valid;@@ -34,8 +37,8 @@ import static javax.ws.rs.core.MediaType.APPLICATION_JSON;public interface RulesResource {/**- * Retrieve global rules. Only the superuser can perform this operation, a 403 status is- * returned if a regular user tries to access global rulesets.+ * Retrieve global rules. Only the superuser can perform this operation, a 403 status is returned if a regular user+ * tries to access global rulesets.*/@GET@Produces(APPLICATION_JSON)@@ -45,9 +48,9 @@ public interface RulesResource {GlobalRuleset[] getGlobalRulesets(@BeanParam RequestParams requestParams);/**- * Retrieve rules of a tenant. The superuser can retrieve rules of all realms, a 403 status- * is returned if a regular user tries to access rulesets outside of its authenticated realm.- * An empty result will be returned if the realm can not be found.+ * Retrieve rules of a tenant. The superuser can retrieve rules of all realms, a 403 status is returned if a regular+ * user tries to access rulesets outside of its authenticated realm. An empty result will be returned if the realm+ * can not be found.*/@GET@Path("tenant/for/{realmId}")@@ -58,10 +61,9 @@ public interface RulesResource {TenantRuleset[] getTenantRulesets(@BeanParam RequestParams requestParams, @PathParam("realmId") String realmId);/**- * Retrieve rules of an asset. The superuser can retrieve rules of all realms and assets, a 403 status- * is returned if a regular user tries to access ruleset outside of its authenticated realm, or- * if the user is restricted and the asset is not one of its linked assets. An empty result will be returned- * if the asset can not be found.+ * Retrieve rules of an asset. The superuser can retrieve rules of all realms and assets, a 403 status is returned+ * if a regular user tries to access ruleset outside of its authenticated realm, or if the user is restricted and+ * the asset is not one of its linked assets. An empty result will be returned if the asset can not be found.*/@GET@Path("asset/for/{assetId}")@@ -74,8 +76,8 @@ public interface RulesResource {/* ################################################################################################# *//**- * Create a global ruleset. Only the superuser can perform this operation, a 403 status is- * returned if a regular user tries to access global ruleset.+ * Create a global ruleset. Only the superuser can perform this operation, a 403 status is returned if a regular+ * user tries to access global ruleset.*/@POST@Consumes(APPLICATION_JSON)@@ -86,8 +88,8 @@ public interface RulesResource {void createGlobalRuleset(@BeanParam RequestParams requestParams, @Valid GlobalRuleset ruleset);/**- * Retrieve a global ruleset. Only the superuser can perform this operation, a 403 status is- * returned if a regular user tries to access global ruleset.+ * Retrieve a global ruleset. Only the superuser can perform this operation, a 403 status is returned if a regular+ * user tries to access global ruleset.*/@GET@Path("{id}")@@ -98,8 +100,8 @@ public interface RulesResource {GlobalRuleset getGlobalRuleset(@BeanParam RequestParams requestParams, @PathParam("id") Long id);/**- * Update a global rules ruleset. Only the superuser can perform this operation, a 403 status is- * returned if a regular user tries to access global ruleset.+ * Update a global rules ruleset. Only the superuser can perform this operation, a 403 status is returned if a+ * regular user tries to access global ruleset.*/@PUT@Path("{id}")@@ -110,8 +112,8 @@ public interface RulesResource {void updateGlobalRuleset(@BeanParam RequestParams requestParams, @PathParam("id") Long id, @Valid GlobalRuleset ruleset);/**- * Deletes a global ruleset. Only the superuser can perform this operation, a 403 status is- * returned if a regular user tries to access global ruleset.+ * Deletes a global ruleset. Only the superuser can perform this operation, a 403 status is returned if a regular+ * user tries to access global ruleset.*/@DELETE@Path("{id}")@@ -124,9 +126,8 @@ public interface RulesResource {/* ################################################################################################# *//**- * Create a tenant ruleset. The superuser can create rules in all realms, a 403 status- * is returned if a regular user tries to access ruleset outside of its authenticated realm,- * or if the user is restricted.+ * Create a tenant ruleset. The superuser can create rules in all realms, a 403 status is returned if a regular user+ * tries to access ruleset outside of its authenticated realm, or if the user is restricted.*/@POST@Path("tenant")@@ -138,9 +139,8 @@ public interface RulesResource {void createTenantRuleset(@BeanParam RequestParams requestParams, @Valid TenantRuleset ruleset);/**- * Retrieve a tenant ruleset. The superuser can retrieve rules of all realms, a 403 status- * is returned if a regular user tries to access ruleset outside of its authenticated realm, or- * if the user is restricted.+ * Retrieve a tenant ruleset. The superuser can retrieve rules of all realms, a 403 status is returned if a regular+ * user tries to access ruleset outside of its authenticated realm, or if the user is restricted.*/@GET@Path("tenant/{id}")@@ -151,9 +151,8 @@ public interface RulesResource {TenantRuleset getTenantRuleset(@BeanParam RequestParams requestParams, @PathParam("id") Long id);/**- * Update a tenant ruleset. The superuser can update rules of all realms, a 403 status- * is returned if a regular user tries to access rulesets outside of its authenticated realm,- * or if the user is restricted.+ * Update a tenant ruleset. The superuser can update rules of all realms, a 403 status is returned if a regular user+ * tries to access rulesets outside of its authenticated realm, or if the user is restricted.*/@PUT@Path("tenant/{id}")@@ -164,9 +163,8 @@ public interface RulesResource {void updateTenantRuleset(@BeanParam RequestParams requestParams, @PathParam("id") Long id, @Valid TenantRuleset ruleset);/**- * Delete a tenant ruleset. The superuser can delete rules of all realms, a 403 status- * is returned if a regular user tries to access rulesets outside of its authenticated realm,- * or if the user is restricted.+ * Delete a tenant ruleset. The superuser can delete rules of all realms, a 403 status is returned if a regular user+ * tries to access rulesets outside of its authenticated realm, or if the user is restricted.*/@DELETE@Path("tenant/{id}")@@ -179,9 +177,9 @@ public interface RulesResource {/* ################################################################################################# *//**- * Create an asset ruleset. The superuser can create rules for all assets, a 403 status- * is returned if a regular user tries to access ruleset outside of its authenticated realm,- * or if the user is restricted and does not have access to the asset.+ * Create an asset ruleset. The superuser can create rules for all assets, a 403 status is returned if a regular+ * user tries to access ruleset outside of its authenticated realm, or if the user is restricted and does not have+ * access to the asset.*/@POST@Path("asset")@@ -193,9 +191,9 @@ public interface RulesResource {void createAssetRuleset(@BeanParam RequestParams requestParams, @Valid AssetRuleset ruleset);/**- * Retrieve an asset ruleset. The superuser can retrieve rules of all assets, a 403 status- * is returned if a regular user tries to access ruleset outside of its authenticated realm, or- * if the user is restricted and does not have access to the asset.+ * Retrieve an asset ruleset. The superuser can retrieve rules of all assets, a 403 status is returned if a regular+ * user tries to access ruleset outside of its authenticated realm, or if the user is restricted and does not have+ * access to the asset.*/@GET@Path("asset/{id}")@@ -206,9 +204,9 @@ public interface RulesResource {AssetRuleset getAssetRuleset(@BeanParam RequestParams requestParams, @PathParam("id") Long id);/**- * Update an asset ruleset. The superuser can update rules of all assets, a 403 status- * is returned if a regular user tries to access ruleset outside of its authenticated realm,- * or if the user is restricted and does not have access to the asset.+ * Update an asset ruleset. The superuser can update rules of all assets, a 403 status is returned if a regular user+ * tries to access ruleset outside of its authenticated realm, or if the user is restricted and does not have access+ * to the asset.*/@PUT@Path("asset/{id}")@@ -219,9 +217,9 @@ public interface RulesResource {void updateAssetRuleset(@BeanParam RequestParams requestParams, @PathParam("id") Long id, @Valid AssetRuleset ruleset);/**- * Delete an asset ruleset. The superuser can delete rules of all assets, a 403 status- * is returned if a regular user tries to access ruleset outside of its authenticated realm,- * or if the user is restricted and does not have access to the asset.+ * Delete an asset ruleset. The superuser can delete rules of all assets, a 403 status is returned if a regular user+ * tries to access ruleset outside of its authenticated realm, or if the user is restricted and does not have access+ * to the asset.*/@DELETE@Path("asset/{id}")@@ -231,4 +229,19 @@ public interface RulesResource {@SuppressWarnings("unusable-by-js")void deleteAssetRuleset(@BeanParam RequestParams requestParams, @PathParam("id") Long id);++ /**+ * Get the geofences for the specified asset; if this method is accessed anonymously (public read) then the asset+ * must have public read enabled and the {@link AttributeDescriptorImpl#CONSOLE_PROVIDER_GEOFENCE} attribute must+ * have a {@link AssetMeta#ACCESS_PUBLIC_READ} meta item. Otherwise the asset must be linked to the logged in user.+ * If neither of these conditions are met then a 403 is returned.+ * <p>+ * The attribute must also have a valid {@link AssetMeta#GEOFENCE_ADAPTER}.+ */+ @GET+ @Path("geofences/{assetId}")+ @Produces(APPLICATION_JSON)+ @SuccessStatusCode(200)+ @SuppressWarnings("unusable-by-js")+ GeofenceDefinition[] getAssetGeofences(@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.javanew file mode 100644index 000000000..adbf4583b--- /dev/null+++ b/model/src/main/java/org/openremote/model/rules/geofence/GeofenceDefinition.java@@ -0,0 +1,57 @@+/*+ * 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.model.rules.geofence;++public class GeofenceDefinition {++ protected String id;+ protected double lat;+ protected double lng;+ protected int radius;+ protected String postUrl;++ public GeofenceDefinition(String id, double lat, double lng, int radius, String postUrl) {+ this.id = id;+ this.lat = lat;+ this.lng = lng;+ this.radius = radius;+ this.postUrl = postUrl;+ }++ public String getId() {+ return id;+ }++ public double getLat() {+ return lat;+ }++ public double getLng() {+ return lng;+ }++ public int getRadius() {+ return radius;+ }++ public String getPostUrl() {+ return postUrl;+ }+}diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovyindex f455c9d0d..c5f5442d1 100644--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy@@ -1,13 +1,10 @@package org.openremote.test.rules-import org.openremote.container.Containerimport org.openremote.manager.asset.AssetProcessingServiceimport org.openremote.manager.asset.AssetStorageService-import org.openremote.manager.rules.RulesEngineimport org.openremote.manager.rules.RulesServiceimport org.openremote.manager.rules.RulesetStorageService-import org.openremote.manager.rules.geofence.GeofenceAssetAdapterimport org.openremote.manager.setup.SetupServiceimport org.openremote.manager.setup.builtin.KeycloakDemoSetupimport org.openremote.manager.setup.builtin.ManagerDemoSetup@@ -15,14 +12,11 @@ import org.openremote.model.asset.Assetimport org.openremote.model.asset.AssetAttributeimport org.openremote.model.asset.AssetMetaimport org.openremote.model.asset.AssetType-import org.openremote.model.asset.BaseAssetQueryimport org.openremote.model.attribute.AttributeEventimport org.openremote.model.attribute.AttributeTypeimport org.openremote.model.attribute.Metaimport org.openremote.model.attribute.MetaItemimport org.openremote.model.rules.AssetRuleset-import org.openremote.model.rules.AssetState-import org.openremote.model.rules.GlobalRulesetimport org.openremote.model.rules.Rulesetimport org.openremote.model.rules.TenantRulesetimport org.openremote.model.value.Values@@ -70,7 +64,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerwhen: "an attribute event is pushed into the system for an attribute with RULE_STATE meta set to true"rulesImport.resetRulesFired()def apartment2LivingRoomPresenceDetectedChange = new AttributeEvent(- managerDemoSetup.apartment2LivingroomId, "presenceDetected", Values.create(true)+ managerDemoSetup.apartment2LivingroomId, "presenceDetected", Values.create(true))assetProcessingService.sendAttributeEvent(apartment2LivingRoomPresenceDetectedChange)@@ -89,7 +83,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerwhen: "an attribute event is pushed into the system for an attribute with no RULE_STATE meta"rulesImport.resetRulesFired()def apartment2LivingRoomWindowOpenChange = new AttributeEvent(- managerDemoSetup.apartment2LivingroomId, "windowOpen", Values.create(true)+ managerDemoSetup.apartment2LivingroomId, "windowOpen", Values.create(true))assetProcessingService.sendAttributeEvent(apartment2LivingRoomWindowOpenChange)@@ -135,10 +129,10 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerwhen: "a LHS filtering test rule definition is loaded into the smart home asset"def assetRuleset = new AssetRuleset(- "Some smart home asset rules",- managerDemoSetup.smartHomeId,- getClass().getResource("/org/openremote/test/rules/BasicSmartHomeMatchAllAssetStates.groovy").text,- Ruleset.Lang.GROOVY+ "Some smart home asset rules",+ managerDemoSetup.smartHomeId,+ getClass().getResource("/org/openremote/test/rules/BasicSmartHomeMatchAllAssetStates.groovy").text,+ Ruleset.Lang.GROOVY)rulesetStorageService.merge(assetRuleset)RulesEngine smartHomeEngine = null@@ -171,7 +165,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerwhen: "an attribute event occurs"rulesImport.resetRulesFired(smartHomeEngine)def apartment2LivingRoomPresenceDetectedChange = new AttributeEvent(- managerDemoSetup.apartment2LivingroomId, "presenceDetected", Values.create(true)+ managerDemoSetup.apartment2LivingroomId, "presenceDetected", Values.create(true))assetProcessingService.sendAttributeEvent(apartment2LivingRoomPresenceDetectedChange)@@ -219,11 +213,11 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerdef asset = new Asset("Kitchen", AssetType.ROOM, apartment2)asset.setRealmId(keycloakDemoSetup.customerATenant.getId())def attributes = [- new AssetAttribute("testString", AttributeType.STRING, Values.create("test"))- .setMeta(- new Meta(new MetaItem(AssetMeta.RULE_STATE, Values.create(true))- )+ new AssetAttribute("testString", AttributeType.STRING, Values.create("test"))+ .setMeta(+ new Meta(new MetaItem(AssetMeta.RULE_STATE, Values.create(true)))+ )]asset.setAttributes(attributes)asset = assetStorageService.merge(asset)@@ -250,11 +244,11 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerwhen: "the Kitchen room asset is modified to add a new attribute but RULE_STATE = true meta is not changed"rulesImport.resetRulesFired()attributes = [- new AssetAttribute("testString", AttributeType.STRING, Values.create("test"))- .setMeta(- new MetaItem(AssetMeta.RULE_STATE, Values.create(true))- ),- new AssetAttribute("testInteger", AttributeType.NUMBER, Values.create(0))+ new AssetAttribute("testString", AttributeType.STRING, Values.create("test"))+ .setMeta(+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))+ ),+ new AssetAttribute("testInteger", AttributeType.NUMBER, Values.create(0))]asset.setAttributes(attributes)asset = assetStorageService.merge(asset)@@ -276,11 +270,11 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerwhen: "the Kitchen room asset is modified to set the RULE_STATE to false"rulesImport.resetRulesFired()attributes = [- new AssetAttribute("testString", AttributeType.STRING, Values.create("test"))- .setMeta(- new MetaItem(AssetMeta.RULE_STATE, Values.create(false))- ),- new AssetAttribute("testInteger", AttributeType.NUMBER, Values.create(0))+ new AssetAttribute("testString", AttributeType.STRING, Values.create("test"))+ .setMeta(+ new MetaItem(AssetMeta.RULE_STATE, Values.create(false))+ ),+ new AssetAttribute("testInteger", AttributeType.NUMBER, Values.create(0))]asset.setAttributes(attributes)asset = assetStorageService.merge(asset)@@ -305,14 +299,14 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerwhen: "the Kitchen room asset is modified to set all attributes to RULE_STATE = true"rulesImport.resetRulesFired()attributes = [- new AssetAttribute("testString", AttributeType.STRING, Values.create("test"))- .setMeta(- new MetaItem(AssetMeta.RULE_STATE, Values.create(true))- ),- new AssetAttribute("testInteger", AttributeType.NUMBER, Values.create(0))- .setMeta(- new MetaItem(AssetMeta.RULE_STATE, Values.create(true))- )+ new AssetAttribute("testString", AttributeType.STRING, Values.create("test"))+ .setMeta(+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))+ ),+ new AssetAttribute("testInteger", AttributeType.NUMBER, Values.create(0))+ .setMeta(+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))+ )]asset.setAttributes(attributes)asset = assetStorageService.merge(asset)@@ -383,10 +377,10 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerwhen: "a broken RHS rule is loaded into the customerA engine"def ruleset = new TenantRuleset(- "Some broken test rules",- keycloakDemoSetup.customerATenant.id,- getClass().getResource("/org/openremote/test/rules/BasicBrokenRules.groovy").text,- Ruleset.Lang.GROOVY+ "Some broken test rules",+ keycloakDemoSetup.customerATenant.id,+ getClass().getResource("/org/openremote/test/rules/BasicBrokenRules.groovy").text,+ Ruleset.Lang.GROOVY)rulesetStorageService.merge(ruleset)@@ -404,7 +398,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerwhen: "an attribute event occurs"def apartment2LivingRoomPresenceDetectedChange = new AttributeEvent(- managerDemoSetup.apartment2LivingroomId, "presenceDetected", Values.create(true)+ managerDemoSetup.apartment2LivingroomId, "presenceDetected", Values.create(true))assetProcessingService.sendAttributeEvent(apartment2LivingRoomPresenceDetectedChange)@@ -418,173 +412,4 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainercleanup: "the server should be stopped"stopContainer(container)}-- def "Check tracking of location predicate rules"() {- given: "expected conditions"- def conditions = new PollingConditions(timeout: 10, initialDelay: 0.5, delay: 0.5)-- and: "a mock geofence adapter"- List<RulesEngine.AssetStateLocationPredicates> geofenceChanges = null- def geofenceInit = false;- def testGeofenceAdapter = new GeofenceAssetAdapter() {-- @Override- int getPriority() {- return Integer.MAX_VALUE- }-- @Override- void processLocationPredicates(List<RulesEngine.AssetStateLocationPredicates> assetLocationPredicates, boolean initialising) {- geofenceChanges = assetLocationPredicates- geofenceInit = initialising- }-- @Override- void init(Container container) throws Exception {-- }-- @Override- void start(Container container) throws Exception {-- }-- @Override- void stop(Container container) throws Exception {-- }- }-- and: "the container is started"- def serverPort = findEphemeralPort()- RulesService.GEOFENCE_PROCESSING_DEBOUNCE_MILLIS = 50- def container = startContainer(defaultConfig(serverPort), defaultServices(testGeofenceAdapter))- def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)- def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)- def rulesService = container.getService(RulesService.class)- def rulesetStorageService = container.getService(RulesetStorageService.class)- def assetStorageService = container.getService(AssetStorageService.class)- def assetProcessingService = container.getService(AssetProcessingService.class)-- 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 mock geofence adapter should have been initialised with the demo thing assets location predicate"- conditions.eventually {- assert geofenceChanges != null- assert geofenceInit- assert geofenceChanges.size() == 1- def thingGeofences = geofenceChanges.find({ it.assetState.id == managerDemoSetup.thingId }).locationPredicates- assert thingGeofences.size() == 1- BaseAssetQuery.RadialLocationPredicate locPredicate = thingGeofences.find { it instanceof BaseAssetQuery.RadialLocationPredicate && it.centrePoint[0] == 100 && it.centrePoint[1] == 50 && it.radius == 100 }- assert locPredicate != null- }-- when: "another asset's location attribute is marked as RULE_STATE"- def lobby = assetStorageService.find(managerDemoSetup.lobbyId, true)- lobby.getAttribute("location").get().addMeta(new MetaItem(AssetMeta.RULE_STATE))- lobby = assetStorageService.merge(lobby)-- then: "the mock geofence adapter should be notified of the new lobby asset with a location predicate"- conditions.eventually {- assert geofenceChanges != null- assert !geofenceInit- assert geofenceChanges.size() == 1- def lobbyGeofences = geofenceChanges.find({ it.assetState.id == managerDemoSetup.lobbyId }).locationPredicates- assert lobbyGeofences.size() == 1- BaseAssetQuery.RadialLocationPredicate locPredicate = lobbyGeofences.find { it instanceof BaseAssetQuery.RadialLocationPredicate && it.centrePoint[0] == 100 && it.centrePoint[1] == 50 && it.radius == 100 }- assert locPredicate != null- }-- when: "a new ruleset is deployed with multiple location predicate rules 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 mock geofence adapter should have been notified of the new location predicates for the demo thing and lobby assets"- conditions.eventually {- assert geofenceChanges != null- assert !geofenceInit- assert geofenceChanges.size() == 2- Set<BaseAssetQuery.LocationPredicate> thingGeofences = geofenceChanges.find{ it.assetState.id == managerDemoSetup.thingId }.locationPredicates- assert thingGeofences.size() == 3- BaseAssetQuery.RadialLocationPredicate rad1Predicate = thingGeofences.find { it instanceof BaseAssetQuery.RadialLocationPredicate && it.centrePoint[0] == 100 && it.centrePoint[1] == 50 && it.radius == 100 }- BaseAssetQuery.RadialLocationPredicate rad2Predicate = thingGeofences.find { it instanceof BaseAssetQuery.RadialLocationPredicate && it.centrePoint[0] == 50 && it.centrePoint[1] == 0 && it.radius == 200 }- BaseAssetQuery.RectangularLocationPredicate rect1Predicate = thingGeofences.find { it instanceof BaseAssetQuery.RectangularLocationPredicate && it.centrePoint[0] == 75 && it.centrePoint[1] == 25 && it.lngMax == 100 && it.latMax == 50 }- assert rad1Predicate != null- assert rad2Predicate != null- assert rect1Predicate != null- def lobbyGeofences = geofenceChanges.find({ it.assetState.id == managerDemoSetup.lobbyId }).locationPredicates- assert lobbyGeofences.size() == 3- assert lobbyGeofences.any { it == rad1Predicate }- assert lobbyGeofences.any { it == rad2Predicate }- assert lobbyGeofences.any { it == rect1Predicate }- }-- when: "a location predicate ruleset is removed"- rulesetStorageService.delete(GlobalRuleset.class, rulesImport.globalRuleset3Id)-- then: "the mock geofence adapter should be notified that the demo thing and lobby asset's rules with location predicates have changed"- conditions.eventually {- assert geofenceChanges != null- assert geofenceChanges.size() == 2- Set<BaseAssetQuery.LocationPredicate> thingGeofences = geofenceChanges.find{ it.assetState.id == managerDemoSetup.thingId }.locationPredicates- assert thingGeofences.size() == 2- BaseAssetQuery.RadialLocationPredicate rad2Predicate = thingGeofences.find { it instanceof BaseAssetQuery.RadialLocationPredicate && it.centrePoint[0] == 50 && it.centrePoint[1] == 0 && it.radius == 200 }- BaseAssetQuery.RectangularLocationPredicate rect1Predicate = thingGeofences.find { it instanceof BaseAssetQuery.RectangularLocationPredicate && it.centrePoint[0] == 75 && it.centrePoint[1] == 25 && it.lngMax == 100 && it.latMax == 50 }- assert rad2Predicate != null- assert rect1Predicate != null- def lobbyGeofences = geofenceChanges.find({ it.assetState.id == managerDemoSetup.lobbyId }).locationPredicates- assert lobbyGeofences.size() == 2- assert lobbyGeofences.any { it == rad2Predicate }- assert lobbyGeofences.any { it == rect1Predicate }- }-- when: "the RULE_STATE meta is removed from the lobby asset's location attribute"- lobby.getAttribute("location").get().getMeta().removeIf({ it.name.orElse(null) == AssetMeta.RULE_STATE.urn })- lobby = assetStorageService.merge(lobby)-- then: "the mock geofence adapter should be notified that the lobby asset no longer has any rules with location predicates"- conditions.eventually {- assert geofenceChanges != null- assert !geofenceInit- assert geofenceChanges.size() == 1- def lobbyGeofences = geofenceChanges.find({ it.assetState.id == managerDemoSetup.lobbyId }).locationPredicates- assert lobbyGeofences.size() == 0- }-- cleanup: "the server should be stopped"- stopContainer(container)- }}diff --git a/test/src/test/groovy/org/openremote/test/rules/geofence/BasicGeofenceProcessingTest.groovy b/test/src/test/groovy/org/openremote/test/rules/geofence/BasicGeofenceProcessingTest.groovynew file mode 100644index 000000000..495894237--- /dev/null+++ b/test/src/test/groovy/org/openremote/test/rules/geofence/BasicGeofenceProcessingTest.groovy@@ -0,0 +1,183 @@+package org.openremote.test.rules.geofence++import org.openremote.manager.asset.AssetProcessingService+import org.openremote.manager.asset.AssetStorageService+import org.openremote.manager.rules.RulesEngine+import org.openremote.manager.rules.RulesService+import org.openremote.manager.rules.RulesetStorageService+import org.openremote.manager.rules.geofence.ORConsoleGeofenceAssetAdapter+import org.openremote.manager.setup.SetupService+import org.openremote.manager.setup.builtin.KeycloakDemoSetup+import org.openremote.manager.setup.builtin.ManagerDemoSetup+import org.openremote.model.asset.AssetMeta+import org.openremote.model.asset.BaseAssetQuery+import org.openremote.model.attribute.MetaItem+import org.openremote.model.rules.AssetRuleset+import org.openremote.model.rules.GlobalRuleset+import org.openremote.model.rules.Ruleset+import org.openremote.test.ManagerContainerTrait+import org.openremote.test.rules.BasicRulesImport+import spock.lang.Ignore+import spock.lang.Specification+import spock.util.concurrent.PollingConditions++import static org.openremote.manager.rules.RulesetDeployment.Status.DEPLOYED+import static org.openremote.manager.setup.builtin.ManagerDemoSetup.*++class BasicGeofenceProcessingTest extends Specification implements ManagerContainerTrait {++ @Ignore+ def "Check tracking of location predicate rules"() {+ given: "expected conditions"+ def conditions = new PollingConditions(timeout: 10, initialDelay: 0.5, delay: 0.5)++ and: "the container is started"+ def serverPort = findEphemeralPort()+ RulesService.GEOFENCE_PROCESSING_DEBOUNCE_MILLIS = 50+ def container = startContainer(defaultConfig(serverPort), defaultServices())+ def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)+ def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)+ def rulesService = container.getService(RulesService.class)+ def rulesetStorageService = container.getService(RulesetStorageService.class)+ def assetStorageService = container.getService(AssetStorageService.class)+ def assetProcessingService = container.getService(AssetProcessingService.class)+ def geofenceAdapter = (ORConsoleGeofenceAssetAdapter) rulesService.geofenceAssetAdapters.get("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 = geofenceAdapter.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].postUrl == "/master/asset/location/" + managerDemoSetup.consoleId+ }++ when: "another asset's location attribute is marked as RULE_STATE"+ def lobby = assetStorageService.find(managerDemoSetup.lobbyId, true)+ lobby.getAttribute("location").get().addMeta(new MetaItem(AssetMeta.RULE_STATE))+ lobby = assetStorageService.merge(lobby)++ then: "the geofence adapter should be notified of the new lobby asset with a location predicate"+ conditions.eventually {+ assert geofenceChanges != null+ assert !geofenceInit+ assert geofenceChanges.size() == 1+ def lobbyGeofences = geofenceChanges.find({it.assetState.id == managerDemoSetup.lobbyId}).locationPredicates+ assert lobbyGeofences.size() == 1+ BaseAssetQuery.RadialLocationPredicate locPredicate = lobbyGeofences.find {+ it instanceof BaseAssetQuery.RadialLocationPredicate && it.centrePoint[0] == 100 && it.centrePoint[1] == 50 && it.radius == 100+ }+ assert locPredicate != null+ }++ when: "a new ruleset is deployed with multiple location predicate rules 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 mock geofence adapter should have been notified of the new location predicates for the demo thing and lobby assets"+ conditions.eventually {+ assert geofenceChanges != null+ assert !geofenceInit+ assert geofenceChanges.size() == 2+ Set<BaseAssetQuery.LocationPredicate> thingGeofences = geofenceChanges.find {+ it.assetState.id == managerDemoSetup.thingId+ }.locationPredicates+ assert thingGeofences.size() == 3+ BaseAssetQuery.RadialLocationPredicate rad1Predicate = thingGeofences.find {+ it instanceof BaseAssetQuery.RadialLocationPredicate && it.centrePoint[0] == 100 && it.centrePoint[1] == 50 && it.radius == 100+ }+ BaseAssetQuery.RadialLocationPredicate rad2Predicate = thingGeofences.find {+ it instanceof BaseAssetQuery.RadialLocationPredicate && it.centrePoint[0] == 50 && it.centrePoint[1] == 0 && it.radius == 200+ }+ BaseAssetQuery.RectangularLocationPredicate rect1Predicate = thingGeofences.find {+ it instanceof BaseAssetQuery.RectangularLocationPredicate && it.centrePoint[0] == 75 && it.centrePoint[1] == 25 && it.lngMax == 100 && it.latMax == 50+ }+ assert rad1Predicate != null+ assert rad2Predicate != null+ assert rect1Predicate != null+ def lobbyGeofences = geofenceChanges.find({it.assetState.id == managerDemoSetup.lobbyId}).locationPredicates+ assert lobbyGeofences.size() == 3+ assert lobbyGeofences.any {it == rad1Predicate}+ assert lobbyGeofences.any {it == rad2Predicate}+ assert lobbyGeofences.any {it == rect1Predicate}+ }++ when: "a location predicate ruleset is removed"+ rulesetStorageService.delete(GlobalRuleset.class, rulesImport.globalRuleset3Id)++ then: "the mock geofence adapter should be notified that the demo thing and lobby asset's rules with location predicates have changed"+ conditions.eventually {+ assert geofenceChanges != null+ assert geofenceChanges.size() == 2+ Set<BaseAssetQuery.LocationPredicate> thingGeofences = geofenceChanges.find {+ it.assetState.id == managerDemoSetup.thingId+ }.locationPredicates+ assert thingGeofences.size() == 2+ BaseAssetQuery.RadialLocationPredicate rad2Predicate = thingGeofences.find {+ it instanceof BaseAssetQuery.RadialLocationPredicate && it.centrePoint[0] == 50 && it.centrePoint[1] == 0 && it.radius == 200+ }+ BaseAssetQuery.RectangularLocationPredicate rect1Predicate = thingGeofences.find {+ it instanceof BaseAssetQuery.RectangularLocationPredicate && it.centrePoint[0] == 75 && it.centrePoint[1] == 25 && it.lngMax == 100 && it.latMax == 50+ }+ assert rad2Predicate != null+ assert rect1Predicate != null+ def lobbyGeofences = geofenceChanges.find({it.assetState.id == managerDemoSetup.lobbyId}).locationPredicates+ assert lobbyGeofences.size() == 2+ assert lobbyGeofences.any {it == rad2Predicate}+ assert lobbyGeofences.any {it == rect1Predicate}+ }++ when: "the RULE_STATE meta is removed from the lobby asset's location attribute"+ lobby.getAttribute("location").get().getMeta().removeIf({it.name.orElse(null) == AssetMeta.RULE_STATE.urn})+ lobby = assetStorageService.merge(lobby)++ then: "the mock geofence adapter should be notified that the lobby asset no longer has any rules with location predicates"+ conditions.eventually {+ assert geofenceChanges != null+ assert !geofenceInit+ assert geofenceChanges.size() == 1+ def lobbyGeofences = geofenceChanges.find({it.assetState.id == managerDemoSetup.lobbyId}).locationPredicates+ assert lobbyGeofences.size() == 0+ }++ cleanup: "the server should be stopped"+ stopContainer(container)+ }+}