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
Added AssetQuery support for location and calendar event
Rich Turner8ffd2ca18351
diff --git a/gradle.properties b/gradle.propertiesindex 31f671f7f..3e68f7e3a 100644--- a/gradle.properties+++ b/gradle.properties@@ -40,4 +40,5 @@ nrjavaserialVersion = 3.13.0saxonHEVersion = 9.8.0-3jmxtermVersion = 1.0.0nettyVersion = 4.1.19.Final-flywaydbVersion = 4.2.0\ No newline at end of file+flywaydbVersion = 4.2.0+ical4jVersion = 2.1.5\ No newline at end of filediff --git a/manager/build.gradle b/manager/build.gradleindex b2c9a6a62..bad7ac18f 100644--- a/manager/build.gradle+++ b/manager/build.gradle@@ -11,6 +11,8 @@ dependencies {compile resolveProject(":model")compile "org.xerial:sqlite-jdbc:$sqliteVersion"++ compile "org.mnode.ical4j:ical4j:$ical4jVersion"}jar {diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.javaindex 8c2b0d276..8ca0f5203 100644--- a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java+++ b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java@@ -20,6 +20,13 @@package org.openremote.manager.asset;import com.vividsolutions.jts.geom.Point;+import net.fortuna.ical4j.filter.PeriodRule;+import net.fortuna.ical4j.model.DateTime;+import net.fortuna.ical4j.model.Dur;+import net.fortuna.ical4j.model.Period;+import net.fortuna.ical4j.model.Recur;+import net.fortuna.ical4j.model.component.VEvent;+import net.fortuna.ical4j.model.property.RRule;import org.apache.camel.builder.RouteBuilder;import org.hibernate.Session;import org.hibernate.jdbc.AbstractReturningWork;@@ -39,6 +46,8 @@ import org.openremote.model.Constants;import org.openremote.model.ValidationFailure;import org.openremote.model.asset.*;import org.openremote.model.attribute.AttributeEvent;+import org.openremote.model.calendar.CalendarEvent;+import org.openremote.model.calendar.RecurrenceRule;import org.openremote.model.event.shared.TenantFilter;import org.openremote.model.security.ClientRole;import org.openremote.model.security.User;@@ -99,15 +108,13 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicidentityService = container.getService(ManagerIdentityService.class);clientEventService = container.getService(ClientEventService.class);- clientEventService.addSubscriptionAuthorizer((auth, subscription) -> {- if (!subscription.isEventType(AssetTreeModifiedEvent.class) && !subscription.isEventType(LocationEvent.class))- return false;- return identityService.getIdentityProvider().canSubscribeWith(- auth,- subscription.getFilter() instanceof TenantFilter ? ((TenantFilter) subscription.getFilter()) : null,- ClientRole.READ_ASSETS- );- });+ clientEventService.addSubscriptionAuthorizer((auth, subscription) ->+ (subscription.isEventType(AssetTreeModifiedEvent.class) || subscription.isEventType(LocationEvent.class))+ && identityService.getIdentityProvider().canSubscribeWith(+ auth,+ subscription.getFilter() instanceof TenantFilter ? ((TenantFilter) subscription.getFilter()) : null,+ ClientRole.READ_ASSETS)+ );container.getService(WebService.class).getApiSingletons().add(new AssetResourceImpl(@@ -528,8 +535,17 @@ public class AssetStorageService extends RouteBuilder implements ContainerServictry (ResultSet rs = st.executeQuery()) {List<ServerAsset> result = new ArrayList<>();- while (rs.next()) {- result.add(mapResultTuple(query, rs));+ if (query.calendarEventActive != null) {+ while (rs.next()) {+ ServerAsset asset = mapResultTuple(query, rs);+ if (calendarEventPredicateMatches(query.calendarEventActive, asset)) {+ result.add(asset);+ }+ }+ } else {+ while (rs.next()) {+ result.add(mapResultTuple(query, rs));+ }}return result;}@@ -575,7 +591,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicsb.append("select A.ID as ID, A.NAME as NAME, A.ACCESS_PUBLIC_READ as ACCESS_PUBLIC_READ");- if (query.orderBy != null || includeMainProperties) {+ if (query.orderBy != null || query.location != null || includeMainProperties) {sb.append(", A.CREATED_ON AS CREATED_ON, A.ASSET_TYPE AS ASSET_TYPE, A.PARENT_ID AS PARENT_ID, A.REALM_ID AS REALM_ID");}@@ -776,6 +792,31 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicbinders.add(st -> st.setString(pos, query.name.prepareValue()));}+ if (level == 1 && query.location != null) {+ if (query.location instanceof RadialLocationPredicate) {+ RadialLocationPredicate location = (RadialLocationPredicate)query.location;+ sb.append(" and ST_Distance_Sphere(A.LOCATION, ST_MakePoint(");+ sb.append(location.lng);+ sb.append(",");+ sb.append(location.lat);+ sb.append(location.negated ? ")) > " : ")) <= ");+ sb.append(location.radius);+ } else if (query.location instanceof RectangularLocationPredicate) {+ RectangularLocationPredicate location = (RectangularLocationPredicate)query.location;+ sb.append(location.negated ? " and NOT": " and");+ sb.append(" ST_Within(A.LOCATION,");+ sb.append("ST_MakeEnvelope(");+ sb.append(location.lngMin);+ sb.append(",");+ sb.append(location.latMin);+ sb.append(",");+ sb.append(location.lngMax);+ sb.append(",");+ sb.append(location.latMax);+ sb.append("))");+ }+ }+if (query.parent != null) {// Can only restrict recursive query parent by asset typeif (level == 1 && query.parent.id != null) {@@ -1191,6 +1232,40 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic.map(Optional::get).toArray(AttributeEvent[]::new));}+ protected static boolean calendarEventPredicateMatches(CalendarEventActivePredicate eventActivePredicate, Asset asset) {+ return CalendarEventConfiguration.getCalendarEvent(asset)+ .map(calendarEvent -> calendarEventActiveOn(calendarEvent, new Date(1000L*eventActivePredicate.when)))+ .orElse(true);+ }++ protected static boolean calendarEventActiveOn(CalendarEvent calendarEvent, Date when) {+ if (calendarEvent.getRecurrence() == null) {+ return (!when.before(calendarEvent.getStart()) && !when.after(calendarEvent.getEnd()));+ }++ RecurrenceRule recurrenceRule = calendarEvent.getRecurrence();+ Recur recurrence;++ if (recurrenceRule.getCount() != null) {+ recurrence = new Recur(recurrenceRule.getFrequency().name(), recurrenceRule.getCount());+ } else {+ recurrence = new Recur(recurrenceRule.getFrequency().name(),+ new net.fortuna.ical4j.model.Date(recurrenceRule.getUntil()));+ }++ if (recurrenceRule.getInterval() != null) {+ recurrence.setInterval(recurrenceRule.getInterval());+ }++ RRule rRule = new RRule(recurrence);+ VEvent vEvent = new VEvent(new DateTime(calendarEvent.getStart()),+ new DateTime(calendarEvent.getEnd()), "");+ vEvent.getProperties().add(rRule);+ Period period = new Period(new DateTime(when), new Dur(0,0,1,0));+ PeriodRule periodRule = new PeriodRule(period);+ return periodRule.evaluate(vEvent);+ }+public String toString() {return getClass().getSimpleName() + "{" +'}';diff --git a/model/src/main/java/org/openremote/model/asset/BaseAssetQuery.java b/model/src/main/java/org/openremote/model/asset/BaseAssetQuery.javaindex bfe54a19b..bf8f92322 100644--- a/model/src/main/java/org/openremote/model/asset/BaseAssetQuery.java+++ b/model/src/main/java/org/openremote/model/asset/BaseAssetQuery.java@@ -19,6 +19,8 @@*/package org.openremote.model.asset;+import com.fasterxml.jackson.annotation.JsonCreator;+import com.fasterxml.jackson.annotation.JsonProperty;import com.fasterxml.jackson.annotation.JsonSubTypes;import com.fasterxml.jackson.annotation.JsonTypeInfo;import org.openremote.model.attribute.AttributeRef;@@ -623,6 +625,69 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {}}+ public static class CalendarEventActivePredicate {++ @JsonProperty("timestamp")+ public long timestampSeconds;++ @JsonCreator+ public CalendarEventActivePredicate(@JsonProperty("timestamp") long timestampSeconds) {+ this.timestampSeconds = timestampSeconds;+ }+ }++ @JsonSubTypes({+ @JsonSubTypes.Type(value = RadialLocationPredicate.class, name = "radial"),+ @JsonSubTypes.Type(value = BooleanPredicate.class, name = "rect")+ })+ @JsonTypeInfo(+ use = JsonTypeInfo.Id.NAME,+ include = JsonTypeInfo.As.PROPERTY,+ property = "predicateType"+ )+ public static class LocationPredicate {+ }++ public static class RadialLocationPredicate extends LocationPredicate {++ public boolean negated;+ public int radius;+ public double lat;+ public double lng;++ public RadialLocationPredicate(int radius, double lat, double lng) {+ this.radius = radius;+ this.lat = lat;+ this.lng = lng;+ }++ public RadialLocationPredicate negate() {+ negated = true;+ return this;+ }+ }++ public static class RectangularLocationPredicate extends LocationPredicate {++ public boolean negated;+ public double latMin;+ public double lngMin;+ public double latMax;+ public double lngMax;++ public RectangularLocationPredicate(double latMin, double lngMin, double latMax, double lngMax) {+ this.latMin = latMin;+ this.lngMin = lngMin;+ this.latMax = latMax;+ this.lngMax = lngMax;+ }++ public RectangularLocationPredicate negate() {+ negated = true;+ return this;+ }+ }+public static class OrderBy {public enum Property {@@ -680,6 +745,8 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {public StringPredicate type;public AttributePredicate[] attribute;public AttributeMetaPredicate[] attributeMeta;+ public CalendarEventActivePredicate calendarEventActive;+ public LocationPredicate location;// Orderingpublic OrderBy orderBy;@@ -805,6 +872,26 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {return (CHILD) this;}+ /**+ * Will filter out assets that have a {@link CalendarEventConfiguration} attribute that results in the event+ * not being 'active/in progress' at the specified time. Assets without a {@link CalendarEventConfiguration}+ * attribute are assumed to always be in progress (i.e. will always pass this check).+ * <p>+ * <b>+ * NOTE: This predicate is applied in memory and the results should be limited as much as possible by applying+ * other predicates to the query to avoid performance issues.+ * </b>+ */+ public CHILD calendarEventActive(long timestampSeconds) {+ calendarEventActive = new CalendarEventActivePredicate(timestampSeconds);+ return (CHILD) this;+ }++ public CHILD location(LocationPredicate locationPredicate) {+ this.location = locationPredicate;+ return (CHILD) this;+ }+@Overridepublic String toString() {return getClass().getSimpleName() + "{" +diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovyindex 939efb5e8..caa35337b 100644--- a/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy+++ b/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy@@ -1,7 +1,10 @@package org.openremote.test.assets+import com.vividsolutions.jts.geom.Coordinate+import com.vividsolutions.jts.geom.GeometryFactoryimport org.openremote.container.Containerimport org.openremote.container.persistence.PersistenceService+import org.openremote.manager.asset.AssetProcessingServiceimport org.openremote.manager.asset.AssetStorageServiceimport org.openremote.manager.asset.ServerAssetimport org.openremote.manager.setup.SetupService@@ -10,9 +13,13 @@ import org.openremote.manager.setup.builtin.ManagerDemoSetupimport org.openremote.model.asset.AssetMetaimport org.openremote.model.asset.AssetQueryimport org.openremote.model.asset.AssetType+import org.openremote.model.asset.CalendarEventConfiguration+import org.openremote.model.calendar.CalendarEvent+import org.openremote.model.calendar.RecurrenceRuleimport org.openremote.test.ManagerContainerTraitimport spock.lang.Sharedimport spock.lang.Specification+import spock.util.concurrent.PollingConditionsimport javax.persistence.EntityManagerimport java.util.function.Function@@ -35,6 +42,8 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {@Sharedstatic AssetStorageService assetStorageService@Shared+ static AssetProcessingService assetProcessingService+ @Sharedstatic PersistenceService persistenceServicedef setupSpec() {@@ -44,6 +53,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)assetStorageService = container.getService(AssetStorageService.class)+ assetProcessingService = container.getService(AssetProcessingService.class)persistenceService = container.getService(PersistenceService.class)}@@ -644,4 +654,218 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {assert asset.getAttribute("co2Level").get().valueAsNumber.get() == 350}++ def "Location queries"() {++ given: "polling conditions"+ def conditions = new PollingConditions(timeout: 10, delay: 1)++ when: "a location filtering query is executed"+ def assets = assetStorageService.findAll(+ new AssetQuery()+ .select(new Select(Include.ONLY_ID_AND_NAME))+ .location(new RadialLocationPredicate(10, 51.44541688237109d, 5.460315214821094d))+ .tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.id))+ .orderBy(new OrderBy(NAME))+ )++ then: "assets in the queried region should be retrieved"+ assets.size() == 5+ assets[0].id == managerDemoSetup.agentId+ assets[0].name == "Demo Agent"+ assets[1].id == managerDemoSetup.thingId+ assets[1].name == "Demo Thing"+ assets[2].id == managerDemoSetup.groundFloorId+ assets[2].name == "Ground Floor"+ assets[3].id == managerDemoSetup.lobbyId+ assets[3].name == "Lobby"+ assets[4].id == managerDemoSetup.smartOfficeId+ assets[4].name == "Smart Office"++ when: "one of the assets in the region is moved"+ def lobby = assetStorageService.find(managerDemoSetup.lobbyId, true)+ lobby.setLocation(new GeometryFactory().createPoint(new Coordinate(5.46108d, 51.44593d)))+ lobby = assetStorageService.merge(lobby)++ then: "the system should settle down"+ conditions.eventually {+ assert noEventProcessedIn(assetProcessingService, 100)+ }++ when: "the same query is run again"+ assets = assetStorageService.findAll(+ new AssetQuery()+ .select(new Select(Include.ONLY_ID_AND_NAME))+ .location(new RadialLocationPredicate(10, 51.44541688237109d, 5.460315214821094d))+ .tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.id))+ .orderBy(new OrderBy(NAME))+ )++ then: "the moved asset should not be included"+ assets.size() == 4+ !assets.any {it.name == "Lobby"}++ when: "a rectangular region is used that includes previous assets and moved asset"+ assets = assetStorageService.findAll(+ new AssetQuery()+ .select(new Select(Include.ONLY_ID_AND_NAME))+ .location(new RectangularLocationPredicate(51.44540d, 5.46031d, 51.44594d, 5.46110d))+ .tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.id))+ .orderBy(new OrderBy(NAME))+ )++ then: "all 5 assets should be returned"+ assets.size() == 5+ assets[0].id == managerDemoSetup.agentId+ assets[0].name == "Demo Agent"+ assets[1].id == managerDemoSetup.thingId+ assets[1].name == "Demo Thing"+ assets[2].id == managerDemoSetup.groundFloorId+ assets[2].name == "Ground Floor"+ assets[3].id == managerDemoSetup.lobbyId+ assets[3].name == "Lobby"+ assets[4].id == managerDemoSetup.smartOfficeId+ assets[4].name == "Smart Office"++ when: "a rectangular region is used that doesn't cover any assets"+ assets = assetStorageService.findAll(+ new AssetQuery()+ .select(new Select(Include.ONLY_ID_AND_NAME))+ .location(new RectangularLocationPredicate(51.44542d, 5.46032d, 51.44590d, 5.46100d))+ .tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.id))+ .orderBy(new OrderBy(NAME))+ )++ then: "no assets should be returned"+ assets.size() == 0++ when: "the same region is used but negated"+ assets = assetStorageService.findAll(+ new AssetQuery()+ .select(new Select(Include.ONLY_ID_AND_NAME))+ .location(new RectangularLocationPredicate(51.44542d, 5.46032d, 51.44590d, 5.46100d).negate())+ .tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.id))+ .orderBy(new OrderBy(NAME))+ )++ then: "all 5 realm assets should be returned"+ assets.size() == 5+ assets[0].id == managerDemoSetup.agentId+ assets[0].name == "Demo Agent"+ assets[1].id == managerDemoSetup.thingId+ assets[1].name == "Demo Thing"+ assets[2].id == managerDemoSetup.groundFloorId+ assets[2].name == "Ground Floor"+ assets[3].id == managerDemoSetup.lobbyId+ assets[3].name == "Lobby"+ assets[4].id == managerDemoSetup.smartOfficeId+ assets[4].name == "Smart Office"+ }++ def "Calendar queries"() {+ given: "polling conditions"+ def conditions = new PollingConditions(timeout: 10, delay: 1)++ when: "an asset is given a calendar event configuration attribute"+ def lobby = assetStorageService.find(managerDemoSetup.lobbyId, true)+ def calendar = Calendar.getInstance(Locale.ROOT);+ calendar.setTimeInMillis(1517151600000) // 28/01/2018 @ 3:00pm (UTC)+ def start = calendar.getTime()+ calendar.add(Calendar.HOUR, 2)+ def end = calendar.getTime()+ def recur = new RecurrenceRule(RecurrenceRule.Frequency.DAILY, 2, 5)++ lobby.addAttributes(+ CalendarEventConfiguration.toAttribute(new CalendarEvent(start, end, recur))+ )+ lobby = assetStorageService.merge(lobby)++ then: "the system should settle down"+ conditions.eventually {+ assert noEventProcessedIn(assetProcessingService, 100)+ }++ when: "a calendar event filtering query is executed for the correct date and time of the event"+ def assets = assetStorageService.findAll(+ new AssetQuery()+ .select(new Select(Include.ALL_EXCEPT_PATH)) // Need attributes to do calendar filtering+ .tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.id))+ .calendarEventActive(1517155200) // 28/01/2018 @ 4:00pm (UTC)+ .orderBy(new OrderBy(NAME))+ )++ then: "all 5 realm assets should be returned"+ assets.size() == 5+ assets[0].id == managerDemoSetup.agentId+ assets[0].name == "Demo Agent"+ assets[1].id == managerDemoSetup.thingId+ assets[1].name == "Demo Thing"+ assets[2].id == managerDemoSetup.groundFloorId+ assets[2].name == "Ground Floor"+ assets[3].id == managerDemoSetup.lobbyId+ assets[3].name == "Lobby"+ assets[4].id == managerDemoSetup.smartOfficeId+ assets[4].name == "Smart Office"++ when: "a calendar event filtering query is executed for future event on a correct day but wrong time"+ assets = assetStorageService.findAll(+ new AssetQuery()+ .select(new Select(Include.ALL_EXCEPT_PATH))+ .tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.id))+ .calendarEventActive(1517335200) // 30/01/2018 @ 6:00pm (UTC)+ .orderBy(new OrderBy(NAME))+ )++ then: "the calendar event asset should not be included"+ assets.size() == 4+ !assets.any {it.name == "Lobby"}++ when: "a calendar event filtering query is executed for a future event on a wrong day but correct time"+ assets = assetStorageService.findAll(+ new AssetQuery()+ .select(new Select(Include.ALL_EXCEPT_PATH))+ .tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.id))+ .calendarEventActive(1517238600) // 29/01/2018 @ 3:10pm (UTC)+ .orderBy(new OrderBy(NAME))+ )++ then: "the calendar event asset should not be included"+ assets.size() == 4+ !assets.any {it.name == "Lobby"}++ when: "a calendar event filtering query is executed inside a valid future event date and time"+ assets = assetStorageService.findAll(+ new AssetQuery()+ .select(new Select(Include.ALL_EXCEPT_PATH)) // Need attributes to do calendar filtering+ .tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.id))+ .calendarEventActive(1517849400) // 05/02/2018 @ 4:50pm (UTC))+ .orderBy(new OrderBy(NAME))+ )++ then: "all 5 realm assets should be returned"+ assets.size() == 5+ assets[0].id == managerDemoSetup.agentId+ assets[0].name == "Demo Agent"+ assets[1].id == managerDemoSetup.thingId+ assets[1].name == "Demo Thing"+ assets[2].id == managerDemoSetup.groundFloorId+ assets[2].name == "Ground Floor"+ assets[3].id == managerDemoSetup.lobbyId+ assets[3].name == "Lobby"+ assets[4].id == managerDemoSetup.smartOfficeId+ assets[4].name == "Smart Office"++ when: "a calendar event filtering query is executed for some time after the last occurrence"+ assets = assetStorageService.findAll(+ new AssetQuery()+ .select(new Select(Include.ALL_EXCEPT_PATH))+ .tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.id))+ .calendarEventActive(1518017520) // 02/07/2018 @ 3:32pm (UTC)+ .orderBy(new OrderBy(NAME))+ )++ then: "the calendar event asset should not be included"+ assets.size() == 4+ !assets.any {it.name == "Lobby"}+ }}