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
Fixed missing files (renamed AttributeValue AttributeType at the same time) Geofence updates and console WIP
Rich Turneraaa981b068af
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java b/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.javaindex 1bdde0caa..72fe54d59 100644--- a/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java+++ b/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java@@ -605,8 +605,8 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResourtry {Asset asset = get(requestParams, assetId);- AssetAttribute locationAttribute = asset.getAttribute(AttributeValue.LOCATION.getName())- .orElse(AssetAttribute.createWithDescriptor(AttributeValue.LOCATION));+ AssetAttribute locationAttribute = asset.getAttribute(AttributeType.LOCATION.getName())+ .orElse(AssetAttribute.createWithDescriptor(AttributeType.LOCATION));ObjectValue currentCoordinates = locationAttribute.getValueAsObject().orElse(Values.createObject());ArrayValue arrayValue = location.getObjectValue().getArray("coordinates").orElseThrow(() -> new IllegalStateException("location doesn't contain 'coordinates' key"));@@ -633,8 +633,8 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResourAsset asset = result[0];//TODO do we need a PUBLIC_WRITE metaitem?- AssetAttribute locationAttribute = asset.getAttribute(AttributeValue.LOCATION.getName())- .orElse(AssetAttribute.createWithDescriptor(AttributeValue.LOCATION));+ AssetAttribute locationAttribute = asset.getAttribute(AttributeType.LOCATION.getName())+ .orElse(AssetAttribute.createWithDescriptor(AttributeType.LOCATION));ObjectValue currentCoordinates = locationAttribute.getValueAsObject().orElse(Values.createObject());ArrayValue arrayValue = location.getObjectValue().getArray("coordinates").orElseThrow(() -> new IllegalStateException("location doesn't contain 'coordinates' key"));diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.javaindex ae7cdbddd..2584dbe97 100644--- a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java+++ b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java@@ -44,7 +44,7 @@ import org.openremote.manager.security.UserConfiguration;import org.openremote.model.Constants;import org.openremote.model.ValidationFailure;import org.openremote.model.asset.*;-import org.openremote.model.attribute.AttributeValue;+import org.openremote.model.attribute.AttributeType;import org.openremote.model.attribute.AttributeEvent;import org.openremote.model.calendar.CalendarEvent;import org.openremote.model.calendar.RecurrenceRule;@@ -1176,6 +1176,15 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic}break;}+ } else if (attributePredicate.value instanceof AssetQuery.ObjectValueKeyPredicate) {+ ObjectValueKeyPredicate keyPredicate = (ObjectValueKeyPredicate)attributePredicate.value;+ if (keyPredicate.negated) {+ attributeBuilder.append(" and NOT(AX.VALUE #> '{value}' ?? ? ) ");+ } else {+ attributeBuilder.append(" and AX.VALUE #> '{value}' ?? ? ");+ }+ final int pos = binders.size() + 1;+ binders.add(st -> st.setString(pos, keyPredicate.key));}}@@ -1324,8 +1333,8 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicStream<AssetAttribute> oldAttributes = attributesFromJson(persistenceEvent.getPreviousState("attributes"), asset.getId());Stream<AssetAttribute> currentAttributes = attributesFromJson(persistenceEvent.getCurrentState("attributes"), asset.getId());- Optional<AssetAttribute> oldLocation = oldAttributes.filter(assetAttribute -> assetAttribute.name.equals(AttributeValue.LOCATION.getName())).findFirst();- Optional<AssetAttribute> currentLocation = currentAttributes.filter(assetAttribute -> assetAttribute.name.equals(AttributeValue.LOCATION.getName())).findFirst();+ Optional<AssetAttribute> oldLocation = oldAttributes.filter(assetAttribute -> assetAttribute.name.equals(AttributeType.LOCATION.getName())).findFirst();+ Optional<AssetAttribute> currentLocation = currentAttributes.filter(assetAttribute -> assetAttribute.name.equals(AttributeType.LOCATION.getName())).findFirst();if (!(!oldLocation.isPresent() && !currentLocation.isPresent())) {if (!oldLocation.isPresent() || !currentLocation.isPresent() || !oldLocation.get().equals(currentLocation.get())) {diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.javaindex 3e5dd38d3..5833adc8c 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java@@ -51,16 +51,16 @@ public class RulesEngine<T extends Ruleset> {*/public static final class AssetStateLocationPredicates {- protected final AssetState assetState;+ protected final String assetId;protected final Set<BaseAssetQuery.LocationPredicate> locationPredicates;- public AssetStateLocationPredicates(AssetState assetState, Set<BaseAssetQuery.LocationPredicate> locationPredicates) {- this.assetState = assetState;+ public AssetStateLocationPredicates(String assetId, Set<BaseAssetQuery.LocationPredicate> locationPredicates) {+ this.assetId = assetId;this.locationPredicates = locationPredicates;}- public AssetState getAssetState() {- return assetState;+ public String getAssetId() {+ return assetId;}public Set<BaseAssetQuery.LocationPredicate> getLocationPredicates() {@@ -178,7 +178,8 @@ public class RulesEngine<T extends Ruleset> {}/**- * @return <code>true</code> if all rulesets are {@link RulesetDeployment.Status#DEPLOYED} and this engine can be started.+ * @return <code>true</code> if all rulesets are {@link RulesetDeployment.Status#DEPLOYED} and this engine can be+ * started.*/public boolean isDeployed() {return deployments.values().stream().allMatch(rd -> rd.getStatus() == DEPLOYED);@@ -319,7 +320,7 @@ public class RulesEngine<T extends Ruleset> {}),TemporaryFact.GUARANTEED_MIN_EXPIRATION_MILLIS- );+ );}});}@@ -432,7 +433,7 @@ public class RulesEngine<T extends Ruleset> {deployments.values().stream().map(RulesetDeployment::toString).toArray(String[]::new)- );+ );}protected void printSessionStats() {@@ -444,11 +445,11 @@ public class RulesEngine<T extends Ruleset> {long temporaryFactsCount = facts.getTemporaryFacts().count();long total = assetStateFacts.size() + assetEventFacts.size() + namedFacts.size() + anonFacts.size();STATS_LOG.info("On " + this + ", in memory facts are Total: " + total- + ", AssetState: " + assetStateFacts.size()- + ", AssetEvent: " + assetEventFacts.size()- + ", Named: " + namedFacts.size()- + ", Anonymous: " + anonFacts.size()- + ", Temporary: " + temporaryFactsCount);+ + ", AssetState: " + assetStateFacts.size()+ + ", AssetEvent: " + assetEventFacts.size()+ + ", Named: " + namedFacts.size()+ + ", Anonymous: " + anonFacts.size()+ + ", Temporary: " + temporaryFactsCount);// Additional details if FINEST is enabledif (STATS_LOG.isLoggable(Level.FINEST)) {diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java b/manager/src/main/java/org/openremote/manager/rules/RulesFacts.javaindex 04d881281..d100124a0 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java@@ -66,7 +66,7 @@ public class RulesFacts extends Facts implements RuleListener {protected int triggerCount;protected boolean trackLocationRules;- protected Map<AssetState, Set<BaseAssetQuery.LocationPredicate>> assetStateLocationPredicateMap = null;+ protected Map<String, Set<BaseAssetQuery.LocationPredicate>> assetStateLocationPredicateMap = null;public RulesFacts(Assets assetsFacade, Object loggingContext, Logger logger) {this.assetsFacade = assetsFacade;@@ -85,7 +85,7 @@ public class RulesFacts extends Facts implements RuleListener {protected List<RulesEngine.AssetStateLocationPredicates> stopTrackingLocationRules() {trackLocationRules = false;- Map<AssetState, Set<BaseAssetQuery.LocationPredicate>> assetStateLocationPredicateMap = this.assetStateLocationPredicateMap;+ Map<String, Set<BaseAssetQuery.LocationPredicate>> assetStateLocationPredicateMap = this.assetStateLocationPredicateMap;this.assetStateLocationPredicateMap = null;return assetStateLocationPredicateMap.entrySet().stream().map(assetStateSetEntry ->@@ -434,7 +434,7 @@ public class RulesFacts extends Facts implements RuleListener {// TODO: Use static reference to well known location attribute when it is implementedCollection<AssetState> locationAssetStates = getAssetStates().stream().filter(assetState -> assetState.getAttributeName().equalsIgnoreCase("location")).collect(Collectors.toSet());assetStateLocationPredicateMap = new HashMap<>(locationAssetStates.size());- locationAssetStates.forEach(assetState -> assetStateLocationPredicateMap.put(assetState, new HashSet<>()));+ locationAssetStates.forEach(assetState -> assetStateLocationPredicateMap.put(assetState.getId(), new HashSet<>()));}assetStateLocationPredicateMap.forEach((assetState, locationPredicates) -> locationPredicates.add(assetQuery.location));diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesResourceImpl.java b/manager/src/main/java/org/openremote/manager/rules/RulesResourceImpl.javaindex b72a1e86a..af17b5391 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesResourceImpl.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesResourceImpl.java@@ -26,7 +26,7 @@ import org.openremote.manager.web.ManagerWebResource;import org.openremote.model.asset.Asset;import org.openremote.model.asset.AssetQuery;import org.openremote.model.asset.BaseAssetQuery;-import org.openremote.model.attribute.AttributeValue;+import org.openremote.model.asset.UserAsset;import org.openremote.model.http.RequestParams;import org.openremote.model.rules.AssetRuleset;import org.openremote.model.rules.GlobalRuleset;@@ -308,18 +308,23 @@ public class RulesResourceImpl extends ManagerWebResource implements RulesResourif (asset == null)return new GeofenceDefinition[0];+ // If asset is linked to users then only those users can get the geofences for it+ List<UserAsset> userAssetLinks = assetStorageService.findUserAssets(asset.getRealmId(), null, assetId);++ // If not linked to users check if asset is marked as public read+ // TODO: Change for public write when implemented+ if (userAssetLinks.isEmpty() && !asset.isAccessPublicRead()) {+ throw new WebApplicationException(Response.Status.FORBIDDEN);+ }+if (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(AttributeValue.CONSOLE_PROVIDER_GEOFENCE.getName()).get().isAccessPublicRead()) {+ // Check asset is linked to authenticated user or super user is logged in+ if (!isSuperUser() || userAssetLinks.stream().noneMatch(userAssetLink -> userAssetLink.getId().getUserId().equals(getUserId()))) {throw new WebApplicationException(Response.Status.FORBIDDEN);}+ }+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 cea4faafa..e124563c3 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesService.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesService.java@@ -35,7 +35,6 @@ 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.AttributeValue;import org.openremote.model.attribute.AttributeEvent.Source;import org.openremote.model.rules.*;import org.openremote.model.rules.geofence.GeofenceDefinition;@@ -90,14 +89,15 @@ public class RulesService extends RouteBuilder implements ContainerService, Assepublic 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;+ protected static List<GeofenceAssetAdapter> geofenceAssetAdapters;static {- geofenceAssetAdapters = new HashMap<>();+ geofenceAssetAdapters = new ArrayList<>();ServiceLoader.load(GeofenceAssetAdapter.class).forEach(geofenceAssetAdapter -> {LOG.fine("Adding GeofenceAssetAdapter: " + geofenceAssetAdapter.getClass().getName());- geofenceAssetAdapters.put(geofenceAssetAdapter.getName(), geofenceAssetAdapter);+ geofenceAssetAdapters.add(geofenceAssetAdapter);});+ geofenceAssetAdapters.sort(Comparator.comparingInt(GeofenceAssetAdapter::getPriority).reversed());}protected final Map<String, RulesEngine<TenantRuleset>> tenantEngines = new HashMap<>();@@ -112,10 +112,9 @@ public class RulesService extends RouteBuilder implements ContainerService, Asseprotected AssetProcessingService assetProcessingService;protected RulesEngine<GlobalRuleset> globalEngine;protected String[] activeTenantIds;- 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 Set<String> assetsWithModifiedLocationPredicates = new HashSet<>();protected ScheduledFuture scheduledGeofenceProcessor;protected boolean firstGeofenceProcessorRun = true;// Keep global list of asset states that have been pushed to any engines@@ -134,8 +133,16 @@ public class RulesService extends RouteBuilder implements ContainerService, AssenotificationService = container.getService(NotificationService.class);assetStorageService = container.getService(AssetStorageService.class);assetProcessingService = container.getService(AssetProcessingService.class);- container.getService(MessageBrokerSetupService.class).getContext().addRoutes(this);+ // Init geofence adapters before registering this services camel routes; this allows adapters to know about+ // asset persistence changes before the rule engines are updated.+ for (GeofenceAssetAdapter geofenceAssetAdapter : geofenceAssetAdapters) {+ if (geofenceAssetAdapter instanceof ContainerService) {+ ((ContainerService)geofenceAssetAdapter).init(container);+ }+ }++ container.getService(MessageBrokerSetupService.class).getContext().addRoutes(this);configEventExpires = getString(container.getConfig(), RULE_EVENT_EXPIRES, RULE_EVENT_EXPIRES_DEFAULT);}@@ -179,20 +186,11 @@ public class RulesService extends RouteBuilder implements ContainerService, AsseLOG.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,- AttributeValue.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)));+ for (GeofenceAssetAdapter geofenceAssetAdapter : geofenceAssetAdapters) {+ if (geofenceAssetAdapter instanceof ContainerService) {+ ((ContainerService)geofenceAssetAdapter).start(container);+ }+ }}LOG.info("Deploying global rulesets");@@ -205,7 +203,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse.filter(rd ->Arrays.stream(activeTenantIds).anyMatch(tenantId -> rd.getRealmId().equals(tenantId))- ).forEach(this::deployTenantRuleset);+ ).forEach(this::deployTenantRuleset);LOG.info("Deploying asset rulesets");// Group by asset ID then tenant and check tenant is enabled@@ -229,6 +227,16 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse@Overridepublic void stop(Container container) throws Exception {withLock(getClass().getSimpleName() + "::stop", () -> {+ for (GeofenceAssetAdapter geofenceAssetAdapter : geofenceAssetAdapters) {+ if (geofenceAssetAdapter instanceof ContainerService) {+ try {+ ((ContainerService)geofenceAssetAdapter).stop(container);+ } catch (Exception e) {+ LOG.log(SEVERE, "Exception thrown whilst stopping geofence adapter", e);+ }+ }+ }+// TODO: Do rule engines need to be stopped on shutdownassetEngines.forEach((assetId, rulesEngine) -> rulesEngine.stop(true));assetEngines.clear();@@ -255,7 +263,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Assenew AssetState(asset, attribute, source),false, // Don't skip the error check on the rules engines!attribute.isRuleEvent() // If it's not a rule event, fire immediately- );+ );}// Then as asset event (if there wasn't an error), this will also fire the rules engines@@ -263,7 +271,7 @@ public class RulesService extends RouteBuilder implements ContainerService, AsseinsertAssetEvent(new AssetState(asset, attribute, source),attribute.getRuleEventExpires().orElse(configEventExpires)- );+ );}return false;@@ -271,13 +279,15 @@ public class RulesService extends RouteBuilder implements ContainerService, Assepublic GeofenceDefinition[] getAssetGeofences(String assetId) {return withLockReturning(getClass().getSimpleName() + "::getAssetGeofences", () -> {- GeofenceAssetAdapter geofenceAssetAdapter = assetIdGeofenceAdapterMap.get(assetId);- if (geofenceAssetAdapter == null) {- return new GeofenceDefinition[0];+ for (GeofenceAssetAdapter geofenceAdapter : geofenceAssetAdapters) {+ GeofenceDefinition[] geofences = geofenceAdapter.getAssetGeofences(assetId);+ if (geofences != null) {+ return geofences;+ }}- return geofenceAssetAdapter.getAssetGeofences(assetId);+ return new GeofenceDefinition[0];});}@@ -308,7 +318,7 @@ public class RulesService extends RouteBuilder implements ContainerService, AsseassetEngines.entrySet().removeIf(entry ->entry.getValue().getId().getRealmId().map(id -> id.equals(tenant.getId())).orElse(false)- );+ );} else {// Create tenant rules engines for this tenant if it has any rulesets@@ -330,8 +340,6 @@ 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:@@ -372,13 +380,13 @@ public class RulesService extends RouteBuilder implements ContainerService, AsseattributesFromJson((ObjectValue) persistenceEvent.getPreviousState()[attributesIndex],asset.getId()- ).filter(AssetAttribute::isRuleState).collect(Collectors.toList());+ ).filter(AssetAttribute::isRuleState).collect(Collectors.toList());List<AssetAttribute> newRuleStateAttributes =attributesFromJson((ObjectValue) persistenceEvent.getCurrentState()[attributesIndex],asset.getId()- ).filter(AssetAttribute::isRuleState).collect(Collectors.toList());+ ).filter(AssetAttribute::isRuleState).collect(Collectors.toList());// Retract facts for attributes that are obsoletegetAddedOrModifiedAttributes(newRuleStateAttributes,@@ -418,32 +426,6 @@ 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:-- if (geofenceAdapterName.isPresent()) {- assetIdGeofenceAdapterMap.put(asset.getId(), geofenceAssetAdapters.get(geofenceAdapterName.get()));- } else {- 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()) {@@ -580,7 +562,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse.stream().map(es ->new Pair<>(assetStorageService.find(es.getKey(), true), es.getValue())- )+ ).filter(assetAndRules -> assetAndRules.key != null).collect(Collectors.groupingBy(assetAndRules -> assetAndRules.key.getRealmId())).entrySet()@@ -749,12 +731,12 @@ public class RulesService extends RouteBuilder implements ContainerService, Assenew AssetQuery.AttributeMetaPredicate(AssetMeta.RULE_STATE,new AssetQuery.BooleanPredicate(true))- ));+ ));return assets.stream().map((Asset asset) ->new Pair<>(asset, asset.getAttributesStream().filter(AssetAttribute::isRuleState))- );+ );}/**@@ -765,15 +747,15 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse*/protected void onEngineLocationRulesChanged(RulesEngine rulesEngine, List<RulesEngine.AssetStateLocationPredicates> newEngineAssetStateLocationPredicates) {withLock(getClass().getSimpleName() + "::onEngineLocationRulesChanged", () -> {- int initialModifiedCount = modifiedAssetLocationPredicates.size();+ int initialModifiedCount = assetsWithModifiedLocationPredicates.size();if (newEngineAssetStateLocationPredicates == null) {engineAssetLocationPredicateMap.computeIfPresent(rulesEngine,(re, existingAssetStateLocationPredicates) -> {// All location predicates have been removed so record each asset state as modified- modifiedAssetLocationPredicates.addAll(+ assetsWithModifiedLocationPredicates.addAll(existingAssetStateLocationPredicates.stream().map(- RulesEngine.AssetStateLocationPredicates::getAssetState).collect(+ RulesEngine.AssetStateLocationPredicates::getAssetId).collect(Collectors.toList()));// Remove this engine from the mapreturn null;@@ -785,9 +767,9 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse// for any removed asset statesif (existingEngineAssetStateLocationPredicates == null) {// All asset states are new so record them all as modified- modifiedAssetLocationPredicates.addAll(+ assetsWithModifiedLocationPredicates.addAll(newEngineAssetStateLocationPredicates.stream().map(- RulesEngine.AssetStateLocationPredicates::getAssetState).collect(+ RulesEngine.AssetStateLocationPredicates::getAssetId).collect(Collectors.toList()));} else {// Find obsolete and modified asset states@@ -796,21 +778,21 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse// Check if there are no longer any location predicates for this assetOptional<RulesEngine.AssetStateLocationPredicates> newAssetStateLocationPredicates = newEngineAssetStateLocationPredicates.stream().filter(assetStateLocationPredicates ->- assetStateLocationPredicates.assetState.equals(- existingAssetStateLocationPredicates.getAssetState()))+ assetStateLocationPredicates.getAssetId().equals(+ existingAssetStateLocationPredicates.getAssetId())).findFirst();if (newAssetStateLocationPredicates.isPresent()) {// Compare existing and new location predicate sets if there is any change then record itif (!newAssetStateLocationPredicates.get().getLocationPredicates().equals(existingAssetStateLocationPredicates.getLocationPredicates())) {- modifiedAssetLocationPredicates.add(- existingAssetStateLocationPredicates.getAssetState());+ assetsWithModifiedLocationPredicates.add(+ existingAssetStateLocationPredicates.getAssetId());}} else {// This means that there are no longer any location predicates so old ones are obsolete- modifiedAssetLocationPredicates.add(- existingAssetStateLocationPredicates.getAssetState());+ assetsWithModifiedLocationPredicates.add(+ existingAssetStateLocationPredicates.getAssetId());}});@@ -819,13 +801,13 @@ public class RulesService extends RouteBuilder implements ContainerService, AssenewAssetStateLocationPredicates -> {boolean isNewAssetState = existingEngineAssetStateLocationPredicates.stream().noneMatch(assetStateLocationPredicates ->- assetStateLocationPredicates.assetState.equals(- newAssetStateLocationPredicates.getAssetState()));+ assetStateLocationPredicates.getAssetId().equals(+ newAssetStateLocationPredicates.getAssetId()));if (isNewAssetState) {// This means that all predicates for this asset are new- modifiedAssetLocationPredicates.add(- newAssetStateLocationPredicates.getAssetState());+ assetsWithModifiedLocationPredicates.add(+ newAssetStateLocationPredicates.getAssetId());}});}@@ -833,7 +815,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse});}- if (modifiedAssetLocationPredicates.size() != initialModifiedCount) {+ if (assetsWithModifiedLocationPredicates.size() != initialModifiedCount) {if (scheduledGeofenceProcessor != null) {scheduledGeofenceProcessor.cancel(false);}@@ -848,47 +830,47 @@ public class RulesService extends RouteBuilder implements ContainerService, Asseboolean isFirstRun = firstGeofenceProcessorRun;firstGeofenceProcessorRun = false;- // Group changed geofences by adaptertry {- 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);- }- );+ // Find all location predicates associated with modified assets and pass through to the geofence adapters+ List<RulesEngine.AssetStateLocationPredicates> assetLocationPredicates = new ArrayList<>(+ assetsWithModifiedLocationPredicates.size());++ assetsWithModifiedLocationPredicates.forEach(assetId -> {++ RulesEngine.AssetStateLocationPredicates locationPredicates = new RulesEngine.AssetStateLocationPredicates(+ assetId,+ new HashSet<>());++ engineAssetLocationPredicateMap.forEach((rulesEngine, engineAssetStateLocationPredicates) ->+ engineAssetStateLocationPredicates.stream().filter(+ assetStateLocationPredicates ->+ assetStateLocationPredicates.getAssetId().equals(+ assetId))+ .findFirst()+ .ifPresent(+ assetStateLocationPredicate -> {+ locationPredicates.getLocationPredicates().addAll(+ assetStateLocationPredicate.getLocationPredicates());+ }));++ assetLocationPredicates.add(locationPredicates);+ });++ for (GeofenceAssetAdapter geofenceAssetAdapter : geofenceAssetAdapters) {+ LOG.info("Passing modified geofences to adapter: " + geofenceAssetAdapter.getName());+ geofenceAssetAdapter.processLocationPredicates(assetLocationPredicates, isFirstRun);++ if (assetLocationPredicates.isEmpty()) {+ LOG.info("All modified geofences handled");+ break;+ }+ }+} catch (Exception e) {LOG.log(SEVERE, "Exception thrown by geofence adapter whilst processing location predicates", e);} finally {// Clear modified assets ready for next batch- modifiedAssetLocationPredicates.clear();+ assetsWithModifiedLocationPredicates.clear();scheduledGeofenceProcessor = null;}});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 ba15eadee..85bdf4c9b 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,18 +19,12 @@*/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.attribute.AttributeValue;import org.openremote.model.rules.geofence.GeofenceDefinition;import java.util.List;-import java.util.Optional;/*** Defines an adapter that can take a collection of {@link BaseAssetQuery.LocationPredicate} that apply to a given@@ -53,45 +47,34 @@ import java.util.Optional;* geofence)</li>* </ul>*/-public abstract class GeofenceAssetAdapter implements ContainerService {+public interface GeofenceAssetAdapter {- public static Optional<String> getAssetGeofenceAdapterName(Asset asset) {- return asset.getAttribute(AttributeValue.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 {-- }+ /**+ * Adapters with a higher priority are called first+ */+ int getPriority();/*** Get the name of this adapter*/- public abstract String getName();+ String getName();/*** The initialising flag is used to indicate that the system is just initialising and the adapter is being made* aware of existing {@link BaseAssetQuery.LocationPredicate}s; generally adapters should use this to initialise* 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).+ * <p>+ * If an adapter handles the location predicates for a particular asset then the adapter should remove that item+ * from the list to prevent other adapters from also handling it. If an {@link RulesEngine.AssetStateLocationPredicates#getLocationPredicates()}+ * is empty then it means there are no longer any location predicates associated with that asset*/- public abstract void processLocationPredicates(List<RulesEngine.AssetStateLocationPredicates> modifiedAssetLocationPredicates,- boolean initialising);+ void processLocationPredicates(List<RulesEngine.AssetStateLocationPredicates> modifiedAssetLocationPredicates,+ boolean initialising);/**- * Called to return the active geofences for the specified {@link Asset}.+ * Called to return the active geofences for the specified {@link Asset}; if this adapter supports the requested+ * asset then it should return a non null value to prevent the request from being sent to other geofence adapters.*/- public abstract GeofenceDefinition[] getAssetGeofences(String assetId);+ 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.javaindex c0e4f9731..5ae61c5a9 100644--- a/manager/src/main/java/org/openremote/manager/rules/geofence/ORConsoleGeofenceAssetAdapter.java+++ b/manager/src/main/java/org/openremote/manager/rules/geofence/ORConsoleGeofenceAssetAdapter.java@@ -19,42 +19,96 @@*/package org.openremote.manager.rules.geofence;+import org.apache.camel.builder.RouteBuilder;import org.openremote.container.Container;+import org.openremote.container.ContainerService;+import org.openremote.container.message.MessageBrokerSetupService;+import org.openremote.container.persistence.PersistenceEvent;+import org.openremote.manager.asset.AssetStorageService;import org.openremote.manager.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.Asset;+import org.openremote.model.asset.AssetQuery;import org.openremote.model.asset.BaseAssetQuery;-import org.openremote.model.attribute.AttributeValue;-import org.openremote.model.rules.AssetState;+import org.openremote.model.attribute.AttributeType;+import org.openremote.model.console.ConsoleConfigration;+import org.openremote.model.console.ConsoleProvider;import org.openremote.model.rules.geofence.GeofenceDefinition;import java.util.*;+import java.util.stream.Collectors;++import static org.openremote.container.concurrent.GlobalLock.withLock;+import static org.openremote.container.persistence.PersistenceEvent.*;+import static org.openremote.model.asset.AssetType.CONSOLE;/*** 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 AttributeValue#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 class ORConsoleGeofenceAssetAdapter extends RouteBuilder implements GeofenceAssetAdapter, ContainerService {public static final String NAME = "ORConsole";public static final String LOCATION_POST_URL_FORMAT_TEMPLATE = "/%1$s/asset/public/%2$s/updateLocation";protected Map<String, RulesEngine.AssetStateLocationPredicates> assetLocationPredicatesMap = new HashMap<>();protected NotificationService notificationService;+ protected AssetStorageService assetStorageService;+ protected Map<String, String> consoleIdRealmMap;+@Overridepublic void init(Container container) throws Exception {- super.init(container);+ this.assetStorageService = container.getService(AssetStorageService.class);this.notificationService = container.getService(NotificationService.class);++ container.getService(MessageBrokerSetupService.class).getContext().addRoutes(this);+ }++ @Override+ public void start(Container container) throws Exception {++ // Find all console assets that use this adapter+ // TODO: Add AssetQuery support for arbitrary property path amd value (e.g. geofence.version == "ORConsole")+ consoleIdRealmMap = assetStorageService.findAll(+ new AssetQuery()+ .select(new BaseAssetQuery.Select(BaseAssetQuery.Include.ALL_EXCEPT_PATH,+ false,+ AttributeType.CONSOLE_PROVIDERS.getName()))+ .attributeValue(AttributeType.CONSOLE_PROVIDERS.getName(),+ new BaseAssetQuery.ObjectValueKeyPredicate("geofence")))+ .stream()+ .filter(ORConsoleGeofenceAssetAdapter::isLinkedToORConsoleGeofenceAdapter)+ .collect(Collectors.toMap(Asset::getId, Asset::getRealmId));+ }++ @Override+ public void stop(Container container) throws Exception {++ }++ @Override+ public void configure() throws Exception {++ // If any console asset was modified in the database, detect geofence provider changes+ from(PERSISTENCE_TOPIC)+ .routeId("ORConsoleGeofenceAdapterAssetChanges")+ .filter(isPersistenceEventForEntityType(Asset.class))+ .process(exchange -> {+ if (isPersistenceEventForAssetType(CONSOLE).matches(exchange)) {+ PersistenceEvent persistenceEvent = exchange.getIn().getBody(PersistenceEvent.class);+ final Asset console = (Asset) persistenceEvent.getEntity();+ processConsoleAssetChange(console, persistenceEvent);+ }+ });+ }++ @Override+ public int getPriority() {+ return 0;}@Override@@ -65,53 +119,72 @@ public class ORConsoleGeofenceAssetAdapter extends GeofenceAssetAdapter {@Overridepublic void processLocationPredicates(List<RulesEngine.AssetStateLocationPredicates> modifiedAssetLocationPredicates, boolean initialising) {- modifiedAssetLocationPredicates.forEach(assetStateLocationPredicates -> {- assetStateLocationPredicates- .getLocationPredicates()- .removeIf(locationPredicate ->- !(locationPredicate instanceof BaseAssetQuery.RadialLocationPredicate));-- if (!initialising) {- Set<AssetState> notifyAssets = new HashSet<>(modifiedAssetLocationPredicates.size());-- RulesEngine.AssetStateLocationPredicates existingPredicates = assetLocationPredicatesMap.get(- assetStateLocationPredicates.getAssetState().getId());- if ((existingPredicates == null || existingPredicates.getLocationPredicates().isEmpty()) && !assetStateLocationPredicates.getLocationPredicates().isEmpty()) {- // We're not comparing before and after state as RulesService has done that although it could be- // that rectangular location predicates have changed but this will do for now- notifyAssets.add(assetStateLocationPredicates.getAssetState());+ Set<String> notifyAssets = new HashSet<>(modifiedAssetLocationPredicates.size());++ modifiedAssetLocationPredicates.removeIf(assetStateLocationPredicates -> {+ boolean remove = consoleIdRealmMap.containsKey(assetStateLocationPredicates.getAssetId());++ if (remove) {+ assetStateLocationPredicates+ .getLocationPredicates()+ .removeIf(locationPredicate ->+ !(locationPredicate instanceof BaseAssetQuery.RadialLocationPredicate));++ if (!initialising) {++ RulesEngine.AssetStateLocationPredicates existingPredicates = assetLocationPredicatesMap.get(+ assetStateLocationPredicates.getAssetId());+ if ((existingPredicates == null || existingPredicates.getLocationPredicates().isEmpty()) && !assetStateLocationPredicates.getLocationPredicates().isEmpty()) {+ // We're not comparing before and after state as RulesService has done that although it could be+ // that rectangular location predicates have changed but this will do for now+ notifyAssets.add(assetStateLocationPredicates.getAssetId());+ }}- notifyAssets.forEach(assetState -> notifyAssetGeofencesChanged(assetState.getId()));+ if (assetStateLocationPredicates.getLocationPredicates().isEmpty()) {+ assetLocationPredicatesMap.remove(assetStateLocationPredicates.getAssetId());+ } else {+ assetLocationPredicatesMap.put(assetStateLocationPredicates.getAssetId(),+ assetStateLocationPredicates);+ }}- if (assetStateLocationPredicates.getLocationPredicates().isEmpty()) {- assetLocationPredicatesMap.remove(assetStateLocationPredicates.getAssetState().getId());- } else {- assetLocationPredicatesMap.put(assetStateLocationPredicates.getAssetState().getId(),- assetStateLocationPredicates);- }+ return remove;});++ notifyAssets.forEach(this::notifyAssetGeofencesChanged);}@Overridepublic GeofenceDefinition[] getAssetGeofences(String assetId) {+ String realm = consoleIdRealmMap.get(assetId);++ if (realm == null) {+ // Asset not supported by this adapter+ return null;+ }+RulesEngine.AssetStateLocationPredicates assetStateLocationPredicates = assetLocationPredicatesMap.get(assetId);+if (assetStateLocationPredicates == null) {+ // No geofences exist for this assetreturn new GeofenceDefinition[0];}return assetStateLocationPredicates.getLocationPredicates().stream().map(locationPredicate ->- locationPredicateToGeofenceDefinition(assetStateLocationPredicates.getAssetState(),+ locationPredicateToGeofenceDefinition(assetStateLocationPredicates.getAssetId(),+ realm,locationPredicate)).toArray(GeofenceDefinition[]::new);}- protected GeofenceDefinition locationPredicateToGeofenceDefinition(AssetState assetState, BaseAssetQuery.LocationPredicate locationPredicate) {+ protected GeofenceDefinition locationPredicateToGeofenceDefinition(String assetId, String realm, BaseAssetQuery.LocationPredicate locationPredicate) {BaseAssetQuery.RadialLocationPredicate radialLocationPredicate = (BaseAssetQuery.RadialLocationPredicate) locationPredicate;- String id = assetState.getId() + "_" + Integer.toString(radialLocationPredicate.hashCode());- String postUrl = String.format(LOCATION_POST_URL_FORMAT_TEMPLATE, assetState.getTenantRealm(), assetState.getId());+ String id = assetId + "_" + Integer.toString(radialLocationPredicate.hashCode());+ String postUrl = String.format(LOCATION_POST_URL_FORMAT_TEMPLATE,+ realm,+ assetId);return new GeofenceDefinition(id,radialLocationPredicate.getLat(),radialLocationPredicate.getLng(),@@ -123,4 +196,31 @@ public class ORConsoleGeofenceAssetAdapter extends GeofenceAssetAdapter {// TODO: implement geofence push notification// notificationService.findDeviceToken(assetId);}++ protected void processConsoleAssetChange(Asset asset, PersistenceEvent persistenceEvent) {++ withLock(getClass().getSimpleName() + "::processAssetChange", () -> {+ switch (persistenceEvent.getCause()) {++ case INSERT:+ case UPDATE:++ if (isLinkedToORConsoleGeofenceAdapter(asset)) {+ consoleIdRealmMap.put(asset.getId(), asset.getRealmId());+ } else {+ consoleIdRealmMap.remove(asset.getId());+ }+ break;+ case DELETE:++ consoleIdRealmMap.remove(asset.getId());+ break;+ }+ });+ }++ protected static boolean isLinkedToORConsoleGeofenceAdapter(Asset asset) {+ return ConsoleConfigration.getConsoleProvider(asset, "geofence")+ .map(ConsoleProvider::getVersion).map(NAME::equals).orElse(false);+ }}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 97ae85542..e1ba87dfc 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@@ -21,9 +21,15 @@ package org.openremote.manager.setup.builtin;import org.openremote.agent.protocol.simulator.SimulatorProtocol;import org.openremote.container.Container;+import org.openremote.manager.rules.geofence.ORConsoleGeofenceAssetAdapter;import org.openremote.manager.setup.AbstractManagerSetup;-import org.openremote.model.asset.*;+import org.openremote.model.asset.Asset;+import org.openremote.model.asset.AssetAttribute;+import org.openremote.model.asset.AssetMeta;+import org.openremote.model.asset.UserAsset;import org.openremote.model.attribute.*;+import org.openremote.model.console.ConsoleConfigration;+import org.openremote.model.console.ConsoleProvider;import org.openremote.model.security.Tenant;import org.openremote.model.simulator.element.ColorSimulatorElement;import org.openremote.model.simulator.element.NumberSimulatorElement;@@ -35,6 +41,7 @@ import java.time.LocalDateTime;import java.time.ZoneId;import java.time.ZonedDateTime;import java.util.Arrays;+import java.util.HashMap;import java.util.List;import static org.openremote.model.asset.AssetMeta.*;@@ -103,7 +110,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {smartOffice.setName("Smart Office");smartOffice.setType(BUILDING);List<AssetAttribute> smartOfficeAttributes = Arrays.asList(- AssetAttribute.createWithDescriptor(AttributeValue.LOCATION, locationValue),+ AssetAttribute.createWithDescriptor(AttributeType.LOCATION, locationValue),new AssetAttribute("geoStreet", STRING, Values.create("Torenallee 20")).setMeta(new MetaItem(LABEL, Values.create("Street")),@@ -131,12 +138,12 @@ public class ManagerDemoSetup extends AbstractManagerSetup {smartOfficeId = smartOffice.getId();Asset groundFloor = new Asset("Ground Floor", FLOOR, smartOffice)- .addAttributes(AssetAttribute.createWithDescriptor(AttributeValue.LOCATION, locationValue));+ .addAttributes(AssetAttribute.createWithDescriptor(AttributeType.LOCATION, locationValue));groundFloor = assetStorageService.merge(groundFloor);groundFloorId = groundFloor.getId();Asset lobby = new Asset("Lobby", ROOM, groundFloor)- .addAttributes(AssetAttribute.createWithDescriptor(AttributeValue.LOCATION, locationValue));+ .addAttributes(AssetAttribute.createWithDescriptor(AttributeType.LOCATION, locationValue));lobby.addAttributes(new AssetAttribute("lobbyLocations", AttributeValueType.ARRAY));@@ -146,7 +153,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {Asset agent = new Asset("Demo Agent", AGENT, lobby);agent.addAttributes(- AssetAttribute.createWithDescriptor(AttributeValue.LOCATION, locationValue),+ AssetAttribute.createWithDescriptor(AttributeType.LOCATION, locationValue),initProtocolConfiguration(new AssetAttribute(agentProtocolConfigName), SimulatorProtocol.PROTOCOL_NAME).addMeta(new MetaItem(@@ -163,7 +170,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {agentId = agent.getId();Asset thing = new Asset("Demo Thing", THING, agent)- .addAttributes(AssetAttribute.createWithDescriptor(AttributeValue.LOCATION, locationValue)+ .addAttributes(AssetAttribute.createWithDescriptor(AttributeType.LOCATION, locationValue).setMeta(new MetaItem(RULE_STATE, Values.create(true))));thing.addAttributes(new AssetAttribute(thingLightToggleAttributeName, BOOLEAN, Values.create(true))@@ -365,7 +372,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {smartHome.setName("Smart Home");smartHome.setType(BUILDING);smartHome.addAttributes(- AssetAttribute.createWithDescriptor(AttributeValue.LOCATION, locationValueA),+ AssetAttribute.createWithDescriptor(AttributeType.LOCATION, locationValueA),new AssetAttribute("geoStreet", STRING, Values.create("Wilhelminaplein 21C")).setMeta(new MetaItem(LABEL, Values.create("Street")),@@ -392,7 +399,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {// The "Apartment 1" is the demo apartment with complex scenesAsset apartment1 = createDemoApartment(smartHome, "Apartment 1")- .addAttributes(AssetAttribute.createWithDescriptor(AttributeValue.LOCATION, locationValueA));+ .addAttributes(AssetAttribute.createWithDescriptor(AttributeType.LOCATION, locationValueA));apartment1 = assetStorageService.merge(apartment1);apartment1Id = apartment1.getId();@@ -411,7 +418,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {/* ############################ ROOMS ############################## */Asset apartment1Livingroom = createDemoApartmentRoom(apartment1, "Living Room")- .addAttributes(AssetAttribute.createWithDescriptor(AttributeValue.LOCATION, locationValueA));+ .addAttributes(AssetAttribute.createWithDescriptor(AttributeType.LOCATION, locationValueA));addDemoApartmentRoomMotionSensor(apartment1Livingroom, true, () -> new MetaItem[]{new MetaItem(AGENT_LINK, new AttributeRef(apartment1ServiceAgentId, "apartmentSimulator").toArrayValue()),new MetaItem(SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(NumberSimulatorElement.ELEMENT_NAME))@@ -437,7 +444,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {apartment1LivingroomId = apartment1Livingroom.getId();Asset apartment1Kitchen = createDemoApartmentRoom(apartment1, "Kitchen")- .addAttributes(AssetAttribute.createWithDescriptor(AttributeValue.LOCATION, locationValueA));+ .addAttributes(AssetAttribute.createWithDescriptor(AttributeType.LOCATION, locationValueA));addDemoApartmentRoomMotionSensor(apartment1Kitchen, true, () -> new MetaItem[]{new MetaItem(AGENT_LINK, new AttributeRef(apartment1ServiceAgentId, "apartmentSimulator").toArrayValue()),new MetaItem(SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(NumberSimulatorElement.ELEMENT_NAME))@@ -479,7 +486,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {apartment1KitchenId = apartment1Kitchen.getId();Asset apartment1Hallway = createDemoApartmentRoom(apartment1, "Hallway")- .addAttributes(AssetAttribute.createWithDescriptor(AttributeValue.LOCATION, locationValueA));+ .addAttributes(AssetAttribute.createWithDescriptor(AttributeType.LOCATION, locationValueA));addDemoApartmentRoomMotionSensor(apartment1Hallway, true, () -> new MetaItem[]{new MetaItem(AGENT_LINK, new AttributeRef(apartment1ServiceAgentId, "apartmentSimulator").toArrayValue()),new MetaItem(SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(NumberSimulatorElement.ELEMENT_NAME))@@ -505,7 +512,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {Asset demoApartmentSceneAgent = createDemoApartmentSceneAgent(apartment1, scenes, apartment1Livingroom, apartment1Kitchen, apartment1Hallway- ).addAttributes(AssetAttribute.createWithDescriptor(AttributeValue.LOCATION, locationValueA));+ ).addAttributes(AssetAttribute.createWithDescriptor(AttributeType.LOCATION, locationValueA));demoApartmentSceneAgent = assetStorageService.merge(demoApartmentSceneAgent);@@ -515,7 +522,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {Asset apartment2 = new Asset("Apartment 2", RESIDENCE, smartHome);apartment2.addAttributes(- AssetAttribute.createWithDescriptor(AttributeValue.LOCATION, locationValueA),+ AssetAttribute.createWithDescriptor(AttributeType.LOCATION, locationValueA),new AssetAttribute("allLightsOffSwitch", AttributeValueType.BOOLEAN, Values.create(true)).setMeta(new MetaItem(LABEL, Values.create("All Lights Off Switch")),@@ -529,7 +536,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {Asset apartment2Livingroom = new Asset("Living Room", ROOM, apartment2);apartment2Livingroom.addAttributes(- AssetAttribute.createWithDescriptor(AttributeValue.LOCATION, locationValueA),+ AssetAttribute.createWithDescriptor(AttributeType.LOCATION, locationValueA),new AssetAttribute("motionSensor", AttributeValueType.BOOLEAN, Values.create(false)).setMeta(new MetaItem(LABEL, Values.create("Motion Sensor")),@@ -575,7 +582,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {Asset apartment2Bathroom = new Asset("Bathroom", ROOM, apartment2);apartment2Bathroom.addAttributes(- AssetAttribute.createWithDescriptor(AttributeValue.LOCATION, locationValueA),+ AssetAttribute.createWithDescriptor(AttributeType.LOCATION, locationValueA),new AssetAttribute("motionSensor", AttributeValueType.BOOLEAN, Values.create(false)).setMeta(new MetaItem(LABEL, Values.create("Motion Sensor")),@@ -611,12 +618,12 @@ public class ManagerDemoSetup extends AbstractManagerSetup {apartment2BathroomId = apartment2Bathroom.getId();Asset apartment3 = new Asset("Apartment 3", RESIDENCE, smartHome)- .addAttributes(AssetAttribute.createWithDescriptor(AttributeValue.LOCATION, locationValueA));+ .addAttributes(AssetAttribute.createWithDescriptor(AttributeType.LOCATION, locationValueA));apartment3 = assetStorageService.merge(apartment3);apartment3Id = apartment3.getId();Asset apartment3Livingroom = new Asset("Living Room", ROOM, apartment3)- .addAttributes(AssetAttribute.createWithDescriptor(AttributeValue.LOCATION, locationValueA));+ .addAttributes(AssetAttribute.createWithDescriptor(AttributeType.LOCATION, locationValueA));apartment3Livingroom.addAttributes(new AssetAttribute("lightSwitch", AttributeValueType.BOOLEAN));@@ -624,17 +631,26 @@ public class ManagerDemoSetup extends AbstractManagerSetup {apartment3Livingroom = assetStorageService.merge(apartment3Livingroom);apartment3LivingroomId = apartment3Livingroom.getId();- Asset console = new Asset("Demo Android Console", CONSOLE, groundFloor)+ Asset console = ConsoleConfigration.initConsoleConfiguration(+ new Asset("Demo Android Console", CONSOLE, groundFloor),+ "Demo Android Console",+ "1.0",+ "Android 7.1.2",+ new HashMap<String, ConsoleProvider>() {+ {+ put("geofence", new ConsoleProvider(+ ORConsoleGeofenceAssetAdapter.NAME,+ true,+ false,+ false,+ null+ ));+ }+ }).addAttributes(- new AssetAttribute(AttributeValue.LOCATION.getName(),- AttributeValue.LOCATION.getType())- .setMeta(new MetaItem(RULE_STATE)),- new AssetAttribute(AttributeValue.CONSOLE_PROVIDER_GEOFENCE.getName(),- AttributeValue.CONSOLE_PROVIDER_GEOFENCE.getType())- .setMeta(- new MetaItem(GEOFENCE_ADAPTER, Values.create("ORConsole")),- new MetaItem(ACCESS_PUBLIC_READ)- )+ new AssetAttribute(AttributeType.LOCATION.getName(),+ AttributeType.LOCATION.getType())+ .setMeta(new MetaItem(RULE_STATE)));console = assetStorageService.merge(console);consoleId = console.getId();diff --git a/model/src/main/java/org/openremote/model/asset/Asset.java b/model/src/main/java/org/openremote/model/asset/Asset.javaindex 5ddd17f03..396d53b73 100644--- a/model/src/main/java/org/openremote/model/asset/Asset.java+++ b/model/src/main/java/org/openremote/model/asset/Asset.java@@ -23,7 +23,9 @@ import com.fasterxml.jackson.annotation.JsonIgnore;import org.hibernate.annotations.Check;import org.hibernate.annotations.Formula;import org.openremote.model.IdentifiableEntity;+import org.openremote.model.ValidationFailure;import org.openremote.model.attribute.Attribute;+import org.openremote.model.attribute.AttributeDescriptor;import org.openremote.model.geo.GeoJSON;import org.openremote.model.geo.GeoJSONFeature;import org.openremote.model.geo.GeoJSONPoint;@@ -48,7 +50,7 @@ import java.util.stream.Stream;import static org.openremote.model.Constants.PERSISTENCE_JSON_OBJECT_TYPE;import static org.openremote.model.Constants.PERSISTENCE_UNIQUE_ID_GENERATOR;import static org.openremote.model.asset.AssetAttribute.*;-import static org.openremote.model.attribute.AttributeValue.LOCATION;+import static org.openremote.model.attribute.AttributeType.LOCATION;// @formatter:off@@ -223,6 +225,11 @@ import static org.openremote.model.attribute.AttributeValue.LOCATION;@Check(constraints = "ID != PARENT_ID")public class Asset implements IdentifiableEntity {+ public enum AssetTypeFailureReason implements ValidationFailure.Reason {+ ASSET_TYPE_MISMATCH,+ ASSET_TYPE_NOT_SUPPORTED+ }+@Id@Column(name = "ID", length = 22, columnDefinition = "char(22)")@GeneratedValue(generator = PERSISTENCE_UNIQUE_ID_GENERATOR)@@ -563,6 +570,10 @@ public class Asset implements IdentifiableEntity {return attributes != null && attributes.hasKey(name);}+ public Optional<AssetAttribute> getAttribute(AttributeDescriptor descriptor) {+ return getAttribute(descriptor.getName());+ }+public Optional<AssetAttribute> getAttribute(String name) {return attributes == null ? Optional.empty() : attributes.getObject(name).flatMap(objectValue -> AssetAttribute.attributeFromJson(objectValue, id, name));diff --git a/model/src/main/java/org/openremote/model/asset/AssetMeta.java b/model/src/main/java/org/openremote/model/asset/AssetMeta.javaindex 48b096cce..72b4545ad 100644--- a/model/src/main/java/org/openremote/model/asset/AssetMeta.java+++ b/model/src/main/java/org/openremote/model/asset/AssetMeta.java@@ -351,17 +351,7 @@ public enum AssetMeta implements MetaItemDescriptor {null,null,Values.create(true),- true),-- GEOFENCE_ADAPTER(- ASSET_META_NAMESPACE + ":geofence:adapter",- new Access(false, true, true),- ValueType.STRING,- null,- null,- null,- false- );+ true);final protected String urn;final protected Access access;diff --git a/model/src/main/java/org/openremote/model/asset/BaseAssetQuery.java b/model/src/main/java/org/openremote/model/asset/BaseAssetQuery.javaindex d5dd0a96d..754d247b2 100644--- a/model/src/main/java/org/openremote/model/asset/BaseAssetQuery.java+++ b/model/src/main/java/org/openremote/model/asset/BaseAssetQuery.java@@ -547,6 +547,35 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {}}+ public static class ObjectValueKeyPredicate implements ValuePredicate<String> {++ public boolean negated;+ public String key;++ public ObjectValueKeyPredicate(String hasKey) {+ key = hasKey;+ }++ public ObjectValueKeyPredicate(String hasKey, boolean negate) {+ key = hasKey;+ negated = negate;+ }++ public ObjectValueKeyPredicate negate() {+ negated = !negated;+ return this;+ }++ @Override+ public ObjectValue toModelValue() {+ ObjectValue objectValue = Values.createObject();+ objectValue.put("predicateType", "ObjectValueKeyPredicate");+ objectValue.put("negated", Values.create(negated));+ objectValue.put("key", Values.create(key));+ return objectValue;+ }+ }+public static class ParentPredicate {public String id;diff --git a/model/src/main/java/org/openremote/model/asset/DefaultAssetModelProvider.java b/model/src/main/java/org/openremote/model/asset/DefaultAssetModelProvider.javaindex c96f94268..618612509 100644--- a/model/src/main/java/org/openremote/model/asset/DefaultAssetModelProvider.java+++ b/model/src/main/java/org/openremote/model/asset/DefaultAssetModelProvider.java@@ -20,7 +20,7 @@package org.openremote.model.asset;import org.openremote.model.attribute.AttributeDescriptor;-import org.openremote.model.attribute.AttributeValue;+import org.openremote.model.attribute.AttributeType;import org.openremote.model.attribute.MetaItemDescriptor;/**@@ -40,7 +40,7 @@ public class DefaultAssetModelProvider implements AssetModelProvider {@Overridepublic AttributeDescriptor[] getAttributeDescriptors() {- return AttributeValue.values();+ return AttributeType.values();}@Overridediff --git a/model/src/main/java/org/openremote/model/attribute/AttributeType.java b/model/src/main/java/org/openremote/model/attribute/AttributeType.javanew file mode 100644index 000000000..a397564ba--- /dev/null+++ b/model/src/main/java/org/openremote/model/attribute/AttributeType.java@@ -0,0 +1,78 @@+/*+ * 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.attribute;++import org.openremote.model.value.Value;++import java.util.Optional;++public enum AttributeType implements AttributeDescriptor {++ LOCATION("location", AttributeValueType.LOCATION),++ CONSOLE_NAME("consoleName", AttributeValueType.STRING),++ CONSOLE_VERSION("consoleVersion", AttributeValueType.STRING),++ CONSOLE_PLATFORM("consolePlatform", AttributeValueType.STRING),++ CONSOLE_PROVIDERS("consoleProviders", AttributeValueType.OBJECT);++ final protected String name;+ final protected AttributeValueType attributeValueType;+ final protected MetaItem[] defaultMetaItems;++ AttributeType(String name, AttributeValueType attributeValueType, MetaItem... defaultMetaItems) {+ this.name = name;+ this.attributeValueType = attributeValueType;+ 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();+ }++ @Override+ public String getName() {+ return name;+ }++ @Override+ public AttributeValueType getType() {+ return attributeValueType;+ }++ @Override+ public MetaItem[] getDefaultMetaItems() {+ return defaultMetaItems;+ }++ @Override+ public Value getDefaultValue() {+ return null;+ }+}diff --git a/model/src/main/java/org/openremote/model/attribute/AttributeValueType.java b/model/src/main/java/org/openremote/model/attribute/AttributeValueType.javanew file mode 100644index 000000000..30f4d4912--- /dev/null+++ b/model/src/main/java/org/openremote/model/attribute/AttributeValueType.java@@ -0,0 +1,276 @@+/*+ * 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.attribute;++import org.openremote.model.ValidationFailure;+import org.openremote.model.ValueHolder;+import org.openremote.model.asset.AssetMeta;+import org.openremote.model.value.Value;+import org.openremote.model.value.ValueType;+import org.openremote.model.value.Values;++import java.util.Optional;+import java.util.function.Function;++import static org.openremote.model.asset.AssetMeta.FORMAT;+import static org.openremote.model.attribute.AttributeValueType.AttributeValueTypeFailureReason.ATTRIBUTE_TYPE_VALUE_DOES_NOT_MATCH;++/**+ * The type of an {@link Attribute}, how its {@link Value} should be+ * interpreted when working with an attribute (e.g. when testing, rendering,+ * or editing the value).+ * <p>+ * Additional constraints and integrity rules upon attribute values can be declared by+ * adding arbitrary {@link Meta} to an {@link Attribute}.+ */+public enum AttributeValueType {++ STRING("file-text-o", ValueType.STRING, value -> Optional.empty()),++ NUMBER("hashtag", ValueType.NUMBER, value -> Optional.empty()),++ BOOLEAN("toggle-off", ValueType.BOOLEAN, value -> Optional.empty()),++ OBJECT("cubes", ValueType.OBJECT, value -> Optional.empty()),++ ARRAY("ellipsis-h", ValueType.ARRAY, value -> Optional.empty()),++ // TODO Implement "Saved Filter/Searches" properly, see AssetResourceImpl+ RULES_TEMPLATE_FILTER("filter", ValueType.ARRAY, value -> Optional.empty()),++ PERCENTAGE("percent", ValueType.NUMBER,+ value -> Values.getNumber(value)+ .filter(number -> number < 0 || number > 100)+ .map(number -> new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_PERCENTAGE_OUT_OF_RANGE)),+ new MetaItem(AssetMeta.RANGE_MIN, Values.create(0)),+ new MetaItem(AssetMeta.RANGE_MAX, Values.create(100)),+ new MetaItem(AssetMeta.FORMAT, Values.create("%3d %%"))+ ),++ TIMESTAMP_MILLIS("clock-o", ValueType.NUMBER, value -> Optional.empty(),+ new MetaItem(FORMAT, Values.create("%d ms"))+ ),++ TIMESTAMP_SECONDS("clock-o", ValueType.NUMBER, value -> Optional.empty(),+ new MetaItem(FORMAT, Values.create("%d s"))+ ),++ TIME_SECONDS("clock-o", ValueType.NUMBER, value -> Optional.empty(),+ new MetaItem(FORMAT, Values.create("%0.1f s"))+ ),++ TIME_MINUTES("clock-o", ValueType.NUMBER, value -> Optional.empty(),+ new MetaItem(FORMAT, Values.create("%0.1f min"))+ ),++ DATETIME("calendar", ValueType.STRING, value -> Optional.empty()),++ COLOR_RGB("paint-brush", ValueType.ARRAY, value -> Values.getArray(value)+ .filter(array -> array.length() != 3)+ .map(array -> new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_INVALID_COLOR_FORMAT))+ ),++ COLOR_ARGB("paint-brush", ValueType.ARRAY, value -> Values.getArray(value)+ .filter(array -> array.length() != 4)+ .map(array -> new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_INVALID_COLOR_FORMAT))+ ),++ COLOR_HEX("paint-brush", ValueType.STRING, value -> Values.getString(value)+ .filter(s -> !s.matches("[a-fA-F0-9]{6}"))+ .map(array -> new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_INVALID_COLOR_FORMAT))+ ),++ TEMPERATURE_CELCIUS("thermometer", ValueType.NUMBER, value -> Values.getNumber(value)+ .filter(n -> n < -273.15)+ .map(n -> new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_TEMPERATURE_OUT_OF_RANGE)),+ new MetaItem(FORMAT, Values.create("%0.1f C")+ )+ ),++ TEMPERATURE_KELVIN("thermometer", ValueType.NUMBER, value -> Values.getNumber(value)+ .filter(n -> n < 0)+ .map(n -> new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_TEMPERATURE_OUT_OF_RANGE))+ ),++ TEMPERATURE_FAHRENHEIT("thermometer", ValueType.NUMBER, value -> Values.getNumber(value)+ .filter(n -> n < -459.67)+ .map(n -> new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_TEMPERATURE_OUT_OF_RANGE))+ ),++ RAINFALL("tint", ValueType.NUMBER, value -> Optional.empty(),+ new MetaItem(FORMAT, Values.create("%0.1f mm/h"))+ ),++ BRIGHTNESS_LUX("sun-o", ValueType.NUMBER, value -> Optional.empty(),+ new MetaItem(FORMAT, Values.create("%d lx"))+ ),++ DISTANCE_M("arrows-h", ValueType.NUMBER, value -> Optional.empty(),+ new MetaItem(FORMAT, Values.create("%0.5f m"))+ ),++ DISTANCE_CM("arrows-h", ValueType.NUMBER, value -> Optional.empty(),+ new MetaItem(FORMAT, Values.create("%0.5f cm"))+ ),++ DISTANCE_MM("arrows-h", ValueType.NUMBER, value -> Optional.empty(),+ new MetaItem(FORMAT, Values.create("%0.5f mm"))+ ),++ DISTANCE_IN("arrows-h", ValueType.NUMBER, value -> Optional.empty(),+ new MetaItem(FORMAT, Values.create("%0.5f \""))+ ),++ DISTANCE_FT("arrows-h", ValueType.NUMBER, value -> Optional.empty(),+ new MetaItem(FORMAT, Values.create("%0.5f '"))+ ),++ DISTANCE_YARD("arrows-h", ValueType.NUMBER, value -> Optional.empty(),+ new MetaItem(FORMAT, Values.create("%0.5f yd"))+ ),++ SPEED_MS("rocket", ValueType.NUMBER, value -> Optional.empty(),+ new MetaItem(FORMAT, Values.create("%0.3f m/s"))+ ),++ SPEED_KPH("rocket", ValueType.NUMBER, value -> Optional.empty(),+ new MetaItem(FORMAT, Values.create("%0.1f km/h"))+ ),++ SPEED_MPH("rocket", ValueType.NUMBER, value -> Optional.empty(),+ new MetaItem(FORMAT, Values.create("%0.1f mi/h"))+ ),++ CO2_PPM("leaf", ValueType.NUMBER, value -> Optional.empty(),+ new MetaItem(FORMAT, Values.create("%4d ppm"))+ ),++ HUMIDITY_PERCENTAGE("tint", ValueType.NUMBER, value -> Values.getNumber(value)+ .filter(number -> number < 0 || number > 100)+ .map(number -> new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_PERCENTAGE_OUT_OF_RANGE)),+ new MetaItem(AssetMeta.RANGE_MIN, Values.create(0)),+ new MetaItem(AssetMeta.RANGE_MAX, Values.create(100)),+ new MetaItem(FORMAT, Values.create("%3d %%"))+ ),++ HUMIDITY_GPCM("tint", ValueType.NUMBER, value -> Optional.empty()),++ POWER_WATT("plug", ValueType.NUMBER, value -> Optional.empty(),+ new MetaItem(FORMAT, Values.create("%0.5f W"))+ ),++ POWER_KILOWATT("plug", ValueType.NUMBER, value -> Optional.empty(),+ new MetaItem(FORMAT, Values.create("%0.5f KW"))),++ POWER_MEGAWATT("plug", ValueType.NUMBER, value -> Optional.empty(),+ new MetaItem(FORMAT, Values.create("%0.5f MW"))),++ CHARGE_PERCENTAGE("battery-full", ValueType.NUMBER, value -> Values.getNumber(value)+ .filter(number -> number < 0 || number > 100)+ .map(number -> new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_PERCENTAGE_OUT_OF_RANGE)),+ new MetaItem(AssetMeta.RANGE_MIN, Values.create(0)),+ new MetaItem(AssetMeta.RANGE_MAX, Values.create(100)),+ new MetaItem(FORMAT, Values.create("%3d %%"))+ ),++ CHARGE_KWH("battery-full", ValueType.NUMBER, value -> Optional.empty(),+ new MetaItem(FORMAT, Values.create("%0.5f KWh"))),++ ENERGY_KWH("plug", ValueType.NUMBER, value -> Optional.empty(),+ new MetaItem(FORMAT, Values.create("%0.5f KWh"))+ ),++ ENERGY_JOULE("plug", ValueType.NUMBER, value -> Optional.empty(),+ new MetaItem(FORMAT, Values.create("%0.5f J"))+ ),++ ENERGY_MEGAJOULE("plug", ValueType.NUMBER, value -> Optional.empty(),+ new MetaItem(FORMAT, Values.create("%0.5f MJ"))),++ FLOW_LPM("tachometer", ValueType.NUMBER, value -> Optional.empty(),+ new MetaItem(FORMAT, Values.create("%0.5f l/m"))+ ),++ FLOW_CMPS("tachometer", ValueType.NUMBER, value -> Optional.empty(),+ new MetaItem(FORMAT, Values.create("%0.5f m³/s"))+ ),++ FLOW_SCCM("tachometer", ValueType.NUMBER, value -> Optional.empty(),+ new MetaItem(FORMAT, Values.create("%0.5f cm³/m"))+ ),++ FLOW_CFPS("tachometer", ValueType.NUMBER, value -> Optional.empty(),+ new MetaItem(FORMAT, Values.create("%0.5f cfs"))+ ),++ FLOW_GPM("tachometer", ValueType.NUMBER, value -> Optional.empty(),+ new MetaItem(FORMAT, Values.create("%0.5f gpm"))+ ),++ DIRECTION_DECIMAL_DEGREES("compass", ValueType.NUMBER, value -> Optional.empty(),+ new MetaItem(FORMAT, Values.create("%0.1f deg"))+ ),++ LOCATION("map-marker", ValueType.OBJECT, value -> Values.getObject(value)+ .filter(object -> !object.hasKey("latitude") || !object.hasKey("longitude"))+ .map(object -> new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_INVALID))+ );++ public static final String DEFAULT_ICON = "circle-thin";++ public enum AttributeValueTypeFailureReason implements ValidationFailure.Reason {+ ATTRIBUTE_TYPE_VALUE_DOES_NOT_MATCH+ }++ final protected String icon;+ final protected ValueType valueType;+ final protected Function<Value, Optional<ValidationFailure>> validator;+ final protected MetaItem[] defaultMetaItems;++ AttributeValueType(String icon, ValueType valueType, Function<Value, Optional<ValidationFailure>> validator, MetaItem... defaultMetaItems) {+ this.icon = icon;+ this.valueType = valueType;+ this.validator = value -> {+ // Always perform some basic validation+ if (value != null && getValueType() != value.getType())+ return Optional.of(new ValidationFailure(ATTRIBUTE_TYPE_VALUE_DOES_NOT_MATCH, getValueType().name()));++ // Custom attribute type validation+ return validator.apply(value);+ };+ this.defaultMetaItems = defaultMetaItems;+ }++ public String getIcon() {+ return icon;+ }++ public ValueType getValueType() {+ return valueType;+ }++ public MetaItem[] getDefaultMetaItems() {+ return defaultMetaItems;+ }++ public Optional<ValidationFailure> isValidValue(Value value) {+ return validator.apply(value);+ }+}\ No newline at end of filediff --git a/model/src/main/java/org/openremote/model/console/ConsoleConfigration.java b/model/src/main/java/org/openremote/model/console/ConsoleConfigration.javanew file mode 100644index 000000000..cc6a0b0b1--- /dev/null+++ b/model/src/main/java/org/openremote/model/console/ConsoleConfigration.java@@ -0,0 +1,212 @@+/*+ * 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.console;++import org.openremote.model.AbstractValueHolder;+import org.openremote.model.ValidationFailure;+import org.openremote.model.asset.Asset;+import org.openremote.model.asset.AssetAttribute;+import org.openremote.model.asset.AssetType;+import org.openremote.model.attribute.AttributeType;+import org.openremote.model.attribute.AttributeValidationResult;+import org.openremote.model.util.Pair;+import org.openremote.model.util.TextUtil;+import org.openremote.model.value.ObjectValue;+import org.openremote.model.value.Value;+import org.openremote.model.value.Values;++import java.util.Map;+import java.util.Objects;+import java.util.Optional;+import java.util.stream.Collectors;++public final class ConsoleConfigration {++ public enum ValidationFailureReason implements ValidationFailure.Reason {+ NAME_MISSING_OR_INVALID,+ VERSION_MISSING_OR_INVALID,+ PLATFORM_MISSING_OR_INVALID,+ PROVIDERS_INVALID+ }++ private ConsoleConfigration() {}++ public static Asset initConsoleConfiguration(Asset asset, String name, String version, String platform, Map<String, ConsoleProvider> providerMap) {+ if (!isConsole(asset)) {+ throw new IllegalArgumentException("Asset must be of type console");+ }+ TextUtil.requireNonNullAndNonEmpty(name);+ TextUtil.requireNonNullAndNonEmpty(version);+ TextUtil.requireNonNullAndNonEmpty(platform);++ setConsoleName(asset, name);+ setConsoleVersion(asset, version);+ setConsolePlatform(asset, platform);+ setConsolProviders(asset, providerMap);++ return asset;+ }++ public static boolean isConsole(Asset asset) {+ return asset != null && asset.getWellKnownType() == AssetType.CONSOLE;+ }++ public static boolean validateConsoleConfiguration(Asset asset, AttributeValidationResult result) {+ boolean valid = isConsole(asset);++ if (!valid) {+ if (result != null) {+ result.addAttributeFailure(new ValidationFailure(Asset.AssetTypeFailureReason.ASSET_TYPE_MISMATCH));+ }+ return false;+ }++ if (!getConsoleName(asset).isPresent()) {+ if (result != null) {+ result.addAttributeFailure(new ValidationFailure(ValidationFailureReason.NAME_MISSING_OR_INVALID));+ }+ valid = false;+ }++ if (!getConsoleVersion(asset).isPresent()) {+ if (result != null) {+ result.addAttributeFailure(new ValidationFailure(ValidationFailureReason.VERSION_MISSING_OR_INVALID));+ }+ valid = false;+ }++ if (!getConsolePlatform(asset).isPresent()) {+ if (result != null) {+ result.addAttributeFailure(new ValidationFailure(ValidationFailureReason.PLATFORM_MISSING_OR_INVALID));+ }+ valid = false;+ }++ Value providerValue = asset.getAttribute(AttributeType.CONSOLE_PROVIDERS.getName()).flatMap(AbstractValueHolder::getValue).orElse(null);++ if (providerValue != null && !getConsoleProviders(asset).isPresent()) {+ if (result != null) {+ result.addAttributeFailure(new ValidationFailure(ValidationFailureReason.PROVIDERS_INVALID));+ }+ valid = false;+ }++ return valid;+ }++ public static Optional<String> getConsoleName(Asset asset) {+ return asset == null ? Optional.empty() : asset.getAttribute(AttributeType.CONSOLE_NAME).flatMap(AbstractValueHolder::getValueAsString);+ }++ public static Asset setConsoleName(Asset asset, String name) {+ Objects.requireNonNull(asset);+ TextUtil.requireNonNullAndNonEmpty(name);+ asset.replaceAttribute(AssetAttribute.createWithDescriptor(AttributeType.CONSOLE_NAME,+ Values.create(name)));+ return asset;+ }++ public static Optional<String> getConsoleVersion(Asset asset) {+ return asset == null ? Optional.empty() : asset.getAttribute(AttributeType.CONSOLE_VERSION).flatMap(AbstractValueHolder::getValueAsString);+ }++ public static Asset setConsoleVersion(Asset asset, String version) {+ Objects.requireNonNull(asset);+ TextUtil.requireNonNullAndNonEmpty(version);+ asset.replaceAttribute(AssetAttribute.createWithDescriptor(AttributeType.CONSOLE_VERSION,+ Values.create(version)));+ return asset;+ }++ public static Optional<String> getConsolePlatform(Asset asset) {+ return asset == null ? Optional.empty() : asset.getAttribute(AttributeType.CONSOLE_PLATFORM).flatMap(AbstractValueHolder::getValueAsString);+ }++ public static Asset setConsolePlatform(Asset asset, String platform) {+ Objects.requireNonNull(asset);+ TextUtil.requireNonNullAndNonEmpty(platform);+ asset.replaceAttribute(AssetAttribute.createWithDescriptor(AttributeType.CONSOLE_PLATFORM,+ Values.create(platform)));+ return asset;+ }++ public static Optional<Map<String, ConsoleProvider>> getConsoleProviders(Asset asset) {+ return asset == null ? Optional.empty() : asset.getAttribute(AttributeType.CONSOLE_VERSION).flatMap(ConsoleConfigration::getConsoleProviders);+ }++ public static Optional<ConsoleProvider> getConsoleProvider(Asset asset, String providerName) {+ return asset == null || TextUtil.isNullOrEmpty(providerName) ? Optional.empty() :+ asset.getAttribute(AttributeType.CONSOLE_PROVIDERS)+ .flatMap(AbstractValueHolder::getValueAsObject)+ .flatMap(obj -> obj.getObject(providerName))+ .flatMap(ConsoleProvider::fromValue);+ }++ public static Asset setConsolProviders(Asset asset, Map<String, ConsoleProvider> consoleProviderMap) {+ Objects.requireNonNull(asset);+ if (consoleProviderMap == null || consoleProviderMap.isEmpty()) {+ asset.removeAttribute(AttributeType.CONSOLE_PROVIDERS.getName());+ return asset;+ }++ asset.replaceAttribute(AssetAttribute.createWithDescriptor(AttributeType.CONSOLE_PROVIDERS,+ ConsoleProvider.toValue(consoleProviderMap)));+ return asset;+ }++ public static void addOrReplaceConsoleProvider(Asset asset, String name, ConsoleProvider consoleProvider) {+ Objects.requireNonNull(asset);+ TextUtil.requireNonNullAndNonEmpty(name);+ AssetAttribute providerAttribute = asset.getAttribute(AttributeType.CONSOLE_PROVIDERS).orElseGet(() -> {+ AssetAttribute attr = AssetAttribute.createWithDescriptor(AttributeType.CONSOLE_PROVIDERS, Values.createObject());+ asset.addAttributes(attr);+ return attr;+ });+ ObjectValue providerObj = Values.getObject(providerAttribute.getValue().orElseGet(() -> {+ Value val = Values.createObject();+ providerAttribute.setValue(val);+ return val;+ })).orElseThrow(() ->+ new IllegalStateException("Console provider attribute value is not an object")+ );++ if (consoleProvider == null) {+ providerObj.remove(name);+ if (!providerObj.hasKeys()) {+ asset.removeAttribute(AttributeType.CONSOLE_PROVIDERS.getName());+ }+ } else {+ providerObj.put(name, consoleProvider.toValue());+ }+ }++ public static Optional<Map<String, ConsoleProvider>> getConsoleProviders(AssetAttribute attribute) {+ if (attribute == null || !AttributeType.CONSOLE_PROVIDERS.getName().equals(attribute.getName().orElse(null))) {+ return Optional.empty();+ }++ return attribute.getValueAsObject().map(obj ->+ obj.stream()+ .map(providerNameValuePair ->+ new Pair<>(providerNameValuePair.key, ConsoleProvider.fromValue(providerNameValuePair.value).orElse(null)))+ .filter(pair -> pair.value != null)+ .collect(Collectors.toMap(pair -> pair.key, pair -> pair.value)));+ }+}diff --git a/model/src/main/java/org/openremote/model/console/ConsoleProvider.java b/model/src/main/java/org/openremote/model/console/ConsoleProvider.javanew file mode 100644index 000000000..b91530707--- /dev/null+++ b/model/src/main/java/org/openremote/model/console/ConsoleProvider.java@@ -0,0 +1,115 @@+/*+ * 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.console;++import com.fasterxml.jackson.annotation.JsonCreator;+import com.fasterxml.jackson.annotation.JsonProperty;+import org.openremote.model.value.ObjectValue;+import org.openremote.model.value.Value;+import org.openremote.model.value.Values;++import java.util.Map;+import java.util.Optional;++public class ConsoleProvider {+ protected String version;+ protected boolean requiresPermission;+ protected boolean hasPermission;+ protected boolean disabled;+ protected ObjectValue data;++ @JsonCreator+ public ConsoleProvider(@JsonProperty("version") String version,+ @JsonProperty("requiresPermission") boolean requiresPermission,+ @JsonProperty("hasPermission") boolean hasPermission,+ @JsonProperty("disabled") boolean disabled,+ @JsonProperty("data") ObjectValue data) {+ this.version = version;+ this.requiresPermission = requiresPermission;+ this.hasPermission = hasPermission;+ this.disabled = disabled;+ this.data = data;+ }++ public String getVersion() {+ return version;+ }++ public boolean isRequiresPermission() {+ return requiresPermission;+ }++ public boolean isHasPermission() {+ return hasPermission;+ }++ public boolean isDisabled() {+ return disabled;+ }++ public ObjectValue getData() {+ return data;+ }++ public static Optional<ConsoleProvider> fromValue(Value value) {+ return Values.getObject(value).flatMap(obj -> {+ Optional<String> version = obj.getString("version");+ Optional<Boolean> requiresPermission = obj.getBoolean("requiresPermission");+ if (!version.isPresent() || !requiresPermission.isPresent()) {+ return Optional.empty();+ }++ boolean hasPermission = obj.getBoolean("hasPermission").orElse(!requiresPermission.get());+ boolean disabled = obj.getBoolean("disabled").orElse(false);+ ObjectValue data = obj.getObject("data").orElse(null);++ return Optional.of(new ConsoleProvider(version.get(), requiresPermission.get(), hasPermission, disabled, data));+ });+ }++ public Value toValue() {+ ObjectValue obj = Values.createObject();+ obj.put("version", getVersion());+ obj.put("requiresPermission", isRequiresPermission());+ obj.put("hasPermission", isHasPermission());+ if (data != null) {+ obj.put("data", getData());+ }++ return obj;+ }++ public static Value toValue(ConsoleProvider provider) {+ return provider.toValue();+ }++ public static Value toValue(Map<String, ConsoleProvider> providerMap) {+ if (providerMap == null || providerMap.isEmpty()) {+ return null;+ }++ ObjectValue obj = Values.createObject();+ providerMap.forEach((providerName, provider) ->+ obj.put(providerName, provider.toValue())+ );++ return obj;+ }+}diff --git a/model/src/main/java/org/openremote/model/console/ConsoleRegistration.java b/model/src/main/java/org/openremote/model/console/ConsoleRegistration.javanew file mode 100644index 000000000..05c87e806--- /dev/null+++ b/model/src/main/java/org/openremote/model/console/ConsoleRegistration.java@@ -0,0 +1,37 @@+/*+ * 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.console;++import com.fasterxml.jackson.annotation.JsonCreator;+import com.fasterxml.jackson.annotation.JsonProperty;++public class ConsoleRegistration {++ protected String id;++ @JsonCreator+ public ConsoleRegistration(@JsonProperty("id") String id) {+ this.id = id;+ }++ public String getId() {+ return id;+ }+}diff --git a/model/src/main/java/org/openremote/model/console/ConsoleResource.java b/model/src/main/java/org/openremote/model/console/ConsoleResource.javanew file mode 100644index 000000000..e4213072b--- /dev/null+++ b/model/src/main/java/org/openremote/model/console/ConsoleResource.java@@ -0,0 +1,51 @@+/*+ * 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.console;++import jsinterop.annotations.JsType;+import org.openremote.model.asset.AssetType;+import org.openremote.model.http.RequestParams;+import org.openremote.model.http.SuccessStatusCode;++import javax.ws.rs.BeanParam;+import javax.ws.rs.Consumes;+import javax.ws.rs.POST;+import javax.ws.rs.Path;++import static javax.ws.rs.core.MediaType.APPLICATION_JSON;++@Path("console")+@JsType(isNative = true)+public interface ConsoleResource {++ /**+ * Creates or updates the registration for the specified console; if the {@link ConsoleConfigration} contains an ID+ * then it is an update operation otherwise it is a create operation, in both cases a {@link ConsoleRegistration} is+ * returned which contains the {@link ConsoleConfigration#getId()} value.+ * <p>+ * The console definition is converted to an asset of type {@link AssetType#CONSOLE}+ */+ @POST+ @Path("register")+ @SuccessStatusCode(204)+ @Consumes(APPLICATION_JSON)+ @SuppressWarnings("unusable-by-js")+ ConsoleRegistration register(@BeanParam RequestParams requestParams, ConsoleConfigration consoleDefinition);+}diff --git a/model/src/main/java/org/openremote/model/rules/RulesResource.java b/model/src/main/java/org/openremote/model/rules/RulesResource.javaindex a1e95793c..82aba4b09 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,6 @@package org.openremote.model.rules;import jsinterop.annotations.JsType;-import org.openremote.model.asset.AssetMeta;-import org.openremote.model.attribute.AttributeValue;import org.openremote.model.http.RequestParams;import org.openremote.model.http.SuccessStatusCode;import org.openremote.model.rules.geofence.GeofenceDefinition;@@ -232,11 +230,8 @@ public interface RulesResource {/*** 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 AttributeValue#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.+ * must have public read enabled. 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}")diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovyindex ab030d265..3f7e753cc 100644--- a/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy+++ b/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy@@ -13,7 +13,7 @@ import org.openremote.model.asset.AssetMetaimport org.openremote.model.asset.AssetQueryimport org.openremote.model.asset.AssetTypeimport org.openremote.model.asset.CalendarEventConfiguration-import org.openremote.model.attribute.AttributeValue+import org.openremote.model.attribute.AttributeTypeimport org.openremote.model.calendar.CalendarEventimport org.openremote.model.calendar.RecurrenceRuleimport org.openremote.model.value.Values@@ -672,7 +672,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {when: "one of the assets in the region is moved"def lobby = assetStorageService.find(managerDemoSetup.lobbyId, true)- lobby.replaceAttribute(createWithDescriptor(AttributeValue.LOCATION, Values.createObject().put("latitude", 51.44593d).put("longitude", 5.46108d)))+ lobby.replaceAttribute(createWithDescriptor(AttributeType.LOCATION, Values.createObject().put("latitude", 51.44593d).put("longitude", 5.46108d)))lobby = assetStorageService.merge(lobby)then: "the system should settle down"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.groovyindex 99a431046..e407d007a 100644--- a/test/src/test/groovy/org/openremote/test/rules/geofence/BasicGeofenceProcessingTest.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/geofence/BasicGeofenceProcessingTest.groovy@@ -1,6 +1,5 @@package org.openremote.test.rules.geofence-import org.openremote.manager.asset.AssetProcessingServiceimport org.openremote.manager.asset.AssetStorageServiceimport org.openremote.manager.rules.RulesEngineimport org.openremote.manager.rules.RulesService@@ -12,12 +11,13 @@ import org.openremote.manager.setup.builtin.ManagerDemoSetupimport org.openremote.model.asset.Assetimport org.openremote.model.asset.AssetAttributeimport org.openremote.model.asset.AssetMeta-import org.openremote.model.attribute.AttributeValue+import org.openremote.model.attribute.AttributeTypeimport org.openremote.model.attribute.MetaItem+import org.openremote.model.console.ConsoleConfigration+import org.openremote.model.console.ConsoleProviderimport org.openremote.model.rules.AssetRulesetimport org.openremote.model.rules.GlobalRulesetimport org.openremote.model.rules.Ruleset-import org.openremote.model.value.Valuesimport org.openremote.test.ManagerContainerTraitimport org.openremote.test.rules.BasicRulesImportimport spock.lang.Specification@@ -25,7 +25,7 @@ import spock.util.concurrent.PollingConditionsimport static org.openremote.manager.rules.RulesetDeployment.Status.DEPLOYEDimport static org.openremote.manager.setup.builtin.ManagerDemoSetup.*-import static org.openremote.model.asset.AssetMeta.*+import static org.openremote.model.asset.AssetMeta.RULE_STATEimport static org.openremote.model.asset.AssetType.CONSOLEclass BasicGeofenceProcessingTest extends Specification implements ManagerContainerTrait {@@ -43,8 +43,7 @@ class BasicGeofenceProcessingTest extends Specification implements ManagerContaidef 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")+ def geofenceAdapter = (ORConsoleGeofenceAssetAdapter) rulesService.geofenceAssetAdapters.find {it.name == "ORConsole" }and: "some test rulesets have been imported"def rulesImport = new BasicRulesImport(rulesetStorageService, keycloakDemoSetup, managerDemoSetup)@@ -66,7 +65,7 @@ class BasicGeofenceProcessingTest extends Specification implements ManagerContaiand: "the geofence adapter should have been initialised with the demo consoles location predicate"conditions.eventually {- def geofences = geofenceAdapter.getAssetGeofences(managerDemoSetup.consoleId)+ def geofences = rulesService.getAssetGeofences(managerDemoSetup.consoleId)assert geofences.size() == 1assert geofences[0].radius == 100assert geofences[0].lat == 50@@ -76,17 +75,27 @@ class BasicGeofenceProcessingTest extends Specification implements ManagerContai}when: "another console asset is added with its location attribute marked as RULE_STATE and it has a CONSOLE_PROVIDER_GEOFENCE attribute"- Asset console2 = new Asset("Demo Android Console 2", CONSOLE)- .addAttributes(- new AssetAttribute(AttributeValue.LOCATION.getName(),- AttributeValue.LOCATION.getType())- .setMeta(new MetaItem(RULE_STATE)),- new AssetAttribute(AttributeValue.CONSOLE_PROVIDER_GEOFENCE.getName(),- AttributeValue.CONSOLE_PROVIDER_GEOFENCE.getType())- .setMeta(- new MetaItem(GEOFENCE_ADAPTER, Values.create("ORConsole")),- new MetaItem(ACCESS_PUBLIC_READ)- )+ Asset console2 = ConsoleConfigration.initConsoleConfiguration(+ new Asset("Demo Android Console 2", CONSOLE),+ "Demo Android Console",+ "1.0",+ "Android 7.1.2",+ new HashMap<String, ConsoleProvider>() {++ {+ put("geofence", new ConsoleProvider(+ ORConsoleGeofenceAssetAdapter.NAME,+ true,+ false,+ false,+ null+ ))+ }+ })+ .addAttributes(+ new AssetAttribute(AttributeType.LOCATION.getName(),+ AttributeType.LOCATION.getType())+ .setMeta(new MetaItem(RULE_STATE)))console2.setParentId(managerDemoSetup.lobbyId)console2 = assetStorageService.merge(console2)@@ -94,7 +103,7 @@ class BasicGeofenceProcessingTest extends Specification implements ManagerContaithen: "the geofence adapter should be notified of the new console asset with the existing location predicate"conditions.eventually {- def geofences = geofenceAdapter.getAssetGeofences(console2Id)+ def geofences = rulesService.getAssetGeofences(console2Id)assert geofences.size() == 1assert geofences[0].radius == 100assert geofences[0].lat == 50@@ -126,8 +135,8 @@ class BasicGeofenceProcessingTest extends Specification implements ManagerContaithen: "the geofence adapter should have been notified of the new radial location predicates for the console assets (but shouldn't contain the rectangular or duplicate predicates)"conditions.eventually {- def console1Geofences = geofenceAdapter.getAssetGeofences(managerDemoSetup.consoleId)- def console2Geofences = geofenceAdapter.getAssetGeofences(console2Id)+ def console1Geofences = rulesService.getAssetGeofences(managerDemoSetup.consoleId)+ def console2Geofences = rulesService.getAssetGeofences(console2Id)assert console1Geofences.size() == 1assert console2Geofences.size() == 2assert console1Geofences[0].radius == 100@@ -138,31 +147,30 @@ class BasicGeofenceProcessingTest extends Specification implements ManagerContaidef console2Geofence1 = console2Geofences.find {it.radius == 100 &&- it.lat == 50 &&- it.lng == 100 &&- it.id == console2Id + "_-174661203" &&- it.postUrl == "/master/asset/public/${console2Id}/updateLocation"+ it.lat == 50 &&+ it.lng == 100 &&+ it.id == console2Id + "_-174661203" &&+ it.postUrl == "/master/asset/public/${console2Id}/updateLocation"}assert console2Geofence1 != nulldef console2Geofence2 = console2Geofences.find {it.radius == 50 &&- it.lat == 0 &&- it.lng == -60 &&- it.id == console2Id + "_-1397479941" &&- it.postUrl == "/master/asset/public/${console2Id}/updateLocation"+ it.lat == 0 &&+ it.lng == -60 &&+ it.id == console2Id + "_-1397479941" &&+ it.postUrl == "/master/asset/public/${console2Id}/updateLocation"}assert console2Geofence2 != null}-when: "a location predicate ruleset is removed"rulesetStorageService.delete(GlobalRuleset.class, rulesImport.globalRuleset3Id)then: "the geofence adapter should be notified and update to reflect the changes"conditions.eventually {- def console1Geofences = geofenceAdapter.getAssetGeofences(managerDemoSetup.consoleId)- def console2Geofences = geofenceAdapter.getAssetGeofences(console2Id)+ def console1Geofences = rulesService.getAssetGeofences(managerDemoSetup.consoleId)+ def console2Geofences = rulesService.getAssetGeofences(console2Id)assert console1Geofences.size() == 0assert console2Geofences.size() == 2@@ -186,12 +194,12 @@ class BasicGeofenceProcessingTest extends Specification implements ManagerContai}when: "the RULE_STATE meta is removed from the second console asset's location attribute"- console2.getAttribute(AttributeValue.LOCATION.getName()).get().getMeta().removeIf({it.name.orElse(null) == AssetMeta.RULE_STATE.urn})+ console2.getAttribute(AttributeType.LOCATION.getName()).get().getMeta().removeIf({it.name.orElse(null) == AssetMeta.RULE_STATE.urn})console2 = assetStorageService.merge(console2)then: "the geofence adapter should be notified that the console asset no longer has any rules with location predicates"conditions.eventually {- def console2Geofences = geofenceAdapter.getAssetGeofences(console2Id)+ def console2Geofences = rulesService.getAssetGeofences(console2Id)assert console2Geofences.size() == 0assert geofenceAdapter.assetLocationPredicatesMap.isEmpty()}