Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

BREAKING CHANGE for rules and asset query: Cleanup of AssetQuery (merged NewAssetQuery), UserQuery, Assets facade and Users facade

Rich Turner95a902f761d9
diff --git a/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketClientProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketClientProtocol.java
index b2e47405f..3e4e56113 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketClientProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketClientProtocol.java
@@ -36,7 +36,7 @@ import org.openremote.model.asset.AssetAttribute;
import org.openremote.model.asset.agent.ConnectionStatus;
import org.openremote.model.asset.agent.ProtocolConfiguration;
import org.openremote.model.attribute.*;
-import org.openremote.model.query.BaseAssetQuery;
+import org.openremote.model.query.AssetQuery;
import org.openremote.model.query.filter.StringPredicate;
import org.openremote.model.syslog.SyslogCategory;
import org.openremote.model.util.Pair;
@@ -168,7 +168,7 @@ public class WebsocketClientProtocol extends AbstractProtocol {
PROTOCOL_NAME + ":messageMatchPredicate",
ACCESS_PRIVATE,
false,
- new StringPredicate(BaseAssetQuery.Match.EXACT, false, "").toModelValue());
+ new StringPredicate(AssetQuery.Match.EXACT, false, "").toModelValue());
public static final List<MetaItemDescriptor> ATTRIBUTE_META_ITEM_DESCRIPTORS = Arrays.asList(
META_ATTRIBUTE_MESSAGE_MATCH_FILTERS,
diff --git a/client/src/main/java/org/openremote/app/client/AppSecurity.java b/client/src/main/java/org/openremote/app/client/AppSecurity.java
index a2d2d80d2..fe7ca0a97 100644
--- a/client/src/main/java/org/openremote/app/client/AppSecurity.java
+++ b/client/src/main/java/org/openremote/app/client/AppSecurity.java
@@ -4,7 +4,7 @@ import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsProperty;
import jsinterop.annotations.JsType;
import org.openremote.model.http.RequestParams;
-import java.util.function.Consumer;
+import org.openremote.model.interop.Consumer;
import org.openremote.model.interop.Runnable;
/**
diff --git a/client/src/main/java/org/openremote/app/client/assets/asset/AssetEditActivity.java b/client/src/main/java/org/openremote/app/client/assets/asset/AssetEditActivity.java
index 55f9e1021..16d42436f 100644
--- a/client/src/main/java/org/openremote/app/client/assets/asset/AssetEditActivity.java
+++ b/client/src/main/java/org/openremote/app/client/assets/asset/AssetEditActivity.java
@@ -52,7 +52,6 @@ import org.openremote.model.query.filter.BooleanPredicate;
import org.openremote.model.query.filter.TenantPredicate;
import org.openremote.model.util.EnumUtil;
import org.openremote.model.util.Pair;
-import org.openremote.model.value.ObjectValue;
import org.openremote.model.value.Value;
import org.openremote.model.value.ValueType;
import org.openremote.model.value.Values;
@@ -67,6 +66,7 @@ import static org.openremote.model.asset.AssetType.CUSTOM;
import static org.openremote.model.attribute.Attribute.ATTRIBUTE_NAME_VALIDATOR;
import static org.openremote.model.attribute.Attribute.isAttributeNameEqualTo;
import static org.openremote.model.attribute.MetaItem.isMetaNameEqualTo;
+import static org.openremote.model.attribute.MetaItemType.LABEL;
import static org.openremote.model.util.TextUtil.isNullOrEmpty;
public class AssetEditActivity
@@ -362,9 +362,9 @@ public class AssetEditActivity
// Is it agent or attribute link?
if ((valueHolder instanceof MetaItem) && AgentLink.isAgentLink((MetaItem) valueHolder)) {
query = new AssetQuery()
- .select(new AssetQuery.Select(AssetQuery.Include.ONLY_ID_AND_NAME_AND_ATTRIBUTES))
+ .select(AssetQuery.Select.selectExcludePathAndParentAndRealm())
// Limit to agents
- .type(AssetType.AGENT);
+ .types(AssetType.AGENT);
// Retrieve agents in the same realm as the asset (if it has been assigned a realm otherwise
// the query will be automatically restricted to the logged in users realm)
@@ -379,7 +379,11 @@ public class AssetEditActivity
attributeFilter = ProtocolConfiguration::isProtocolConfiguration;
} else {
query = new AssetQuery()
- .select(new AssetQuery.Select(AssetQuery.Include.ONLY_ID_AND_NAME_AND_ATTRIBUTE_NAMES));
+ .select(AssetQuery.Select
+ .selectExcludeAll()
+ .excludeAttributes(false)
+ .excludeAttributeMeta(false)
+ .meta(LABEL));
// Limit to assets that have the same realm as the asset being edited (if it has been assigned a realm
// otherwise the query will be automatically restricted to the logged in users realm)
diff --git a/client/src/main/java/org/openremote/app/client/assets/browser/AssetBrowserPresenter.java b/client/src/main/java/org/openremote/app/client/assets/browser/AssetBrowserPresenter.java
index 8da45aa13..e3d1af7f3 100644
--- a/client/src/main/java/org/openremote/app/client/assets/browser/AssetBrowserPresenter.java
+++ b/client/src/main/java/org/openremote/app/client/assets/browser/AssetBrowserPresenter.java
@@ -258,12 +258,12 @@ public class AssetBrowserPresenter implements AssetBrowser.Presenter {
requestParams,
new AssetQuery()
.tenant(new TenantPredicate(parent.getId()))
- .parent(new ParentPredicate(true))
+ .parents(new ParentPredicate(true))
);
} else if (parent instanceof RootTreeNode) {
assetResource.getCurrentUserAssets(requestParams);
} else {
- assetResource.queryAssets(requestParams, new AssetQuery().parent(parent.getId()));
+ assetResource.queryAssets(requestParams, new AssetQuery().parents(parent.getId()));
}
},
200,
diff --git a/client/src/main/java/org/openremote/app/client/notifications/NotificationsActivity.java b/client/src/main/java/org/openremote/app/client/notifications/NotificationsActivity.java
index a3b2b507b..327d55d81 100644
--- a/client/src/main/java/org/openremote/app/client/notifications/NotificationsActivity.java
+++ b/client/src/main/java/org/openremote/app/client/notifications/NotificationsActivity.java
@@ -41,7 +41,7 @@ import org.openremote.model.event.bus.EventBus;
import org.openremote.model.event.bus.EventRegistration;
import org.openremote.model.notification.*;
import org.openremote.model.query.AssetQuery;
-import org.openremote.model.query.BaseAssetQuery;
+import org.openremote.model.query.AssetQuery;
import org.openremote.model.query.filter.TenantPredicate;
import org.openremote.model.security.Tenant;
import org.openremote.model.security.TenantResource;
@@ -399,8 +399,7 @@ public class NotificationsActivity extends AssetBrowsingActivity<NotificationsPl
assetQueryMapper,
requestParams -> assetResource.queryAssets(requestParams,
new AssetQuery()
- .select(new BaseAssetQuery
- .Select(BaseAssetQuery.Include.ONLY_ID_AND_NAME))
+ .select(AssetQuery.Select.selectExcludeAll())
.tenant(new TenantPredicate(realm))),
200,
assetConsumer::accept);
diff --git a/manager/src/main/java/org/openremote/manager/agent/AgentService.java b/manager/src/main/java/org/openremote/manager/agent/AgentService.java
index 1a94af03d..8c84af3ba 100644
--- a/manager/src/main/java/org/openremote/manager/agent/AgentService.java
+++ b/manager/src/main/java/org/openremote/manager/agent/AgentService.java
@@ -493,7 +493,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Asse
// Get all assets that have attributes that use this protocol configuration
List<Asset> assets = assetStorageService.findAll(
new AssetQuery()
- .select(new AssetQuery.Select(AssetQuery.Include.ALL))
+ .select(AssetQuery.Select.selectAll())
.attributeMeta(
new AttributeRefPredicate(
MetaItemType.AGENT_LINK,
@@ -523,7 +523,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Asse
// Get all assets that have attributes that use this protocol configuration
List<Asset> assets = assetStorageService.findAll(
new AssetQuery()
- .select(new AssetQuery.Select(AssetQuery.Include.ALL))
+ .select(AssetQuery.Select.selectAll())
.attributeMeta(
new AttributeRefPredicate(
MetaItemType.AGENT_LINK,
@@ -763,8 +763,8 @@ public class AgentService extends RouteBuilder implements ContainerService, Asse
return withLockReturning(getClass().getSimpleName() + "::getAgents", () -> {
if (agentMap == null) {
agentMap = assetStorageService.findAll(new AssetQuery()
- .select(new AssetQuery.Select(AssetQuery.Include.ALL))
- .type(AssetType.AGENT))
+ .select(AssetQuery.Select.selectAll())
+ .types(AssetType.AGENT))
.stream()
.collect(Collectors.toMap(Asset::getId, agent -> agent));
}
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetAttributeLinkingService.java b/manager/src/main/java/org/openremote/manager/asset/AssetAttributeLinkingService.java
index c2a25a873..64aa47de1 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetAttributeLinkingService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetAttributeLinkingService.java
@@ -39,7 +39,6 @@ import java.util.logging.Logger;
import static org.openremote.model.attribute.AttributeEvent.Source.ATTRIBUTE_LINKING_SERVICE;
import static org.openremote.model.attribute.MetaItem.isMetaNameEqualTo;
-import static org.openremote.model.query.AssetQuery.Include;
import static org.openremote.model.query.AssetQuery.Select;
/**
@@ -258,8 +257,8 @@ public class AssetAttributeLinkingService implements ContainerService, AssetUpda
Asset asset = assetStorageService.find(
em,
new AssetQuery()
- .id(attributeRef.getEntityId())
- .select(new Select(Include.ALL, false, attributeRef.getAttributeName()))
+ .ids(attributeRef.getEntityId())
+ .select(Select.selectAll().attributes(attributeRef.getAttributeName()))
);
AssetAttribute attribute = asset != null ? asset.getAttribute(attributeRef.getAttributeName()).orElse(null) : null;
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java b/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java
index b11619843..db68269a9 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java
@@ -198,7 +198,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
// Restricted users can only get events for their linked assets
if (!assetStorageService.isUserAsset(auth.getUserId(), assetId))
return false;
- // TODO Restricted clients should only receive events for RESTRICTED_READ attributes!
+ // TODO Restricted clients should only receive events for PROTECTED attributes!
} else {
// Regular users can only get events for assets in their realm
if (!asset.getRealm().equals(auth.getAuthenticatedRealm()))
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java b/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java
index f526b221b..f5df3378b 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java
@@ -24,11 +24,14 @@ import org.openremote.container.timer.TimerService;
import org.openremote.manager.security.ManagerIdentityService;
import org.openremote.manager.web.ManagerWebResource;
import org.openremote.model.Constants;
-import org.openremote.model.asset.*;
+import org.openremote.model.asset.Asset;
+import org.openremote.model.asset.AssetAttribute;
+import org.openremote.model.asset.AssetResource;
+import org.openremote.model.asset.UserAsset;
import org.openremote.model.attribute.*;
import org.openremote.model.http.RequestParams;
import org.openremote.model.query.AssetQuery;
-import org.openremote.model.query.BaseAssetQuery.Select;
+import org.openremote.model.query.AssetQuery.Select;
import org.openremote.model.query.filter.ParentPredicate;
import org.openremote.model.query.filter.TenantPredicate;
import org.openremote.model.security.Tenant;
@@ -48,8 +51,8 @@ import java.util.logging.Logger;
import static javax.ws.rs.core.Response.Status.*;
import static org.openremote.container.Container.JSON;
import static org.openremote.model.attribute.AttributeEvent.Source.CLIENT;
+import static org.openremote.model.attribute.MetaItemType.ACCESS_RESTRICTED_READ;
import static org.openremote.model.query.AssetQuery.Access;
-import static org.openremote.model.query.AssetQuery.Include;
import static org.openremote.model.util.TextUtil.isNullOrEmpty;
public class AssetResourceImpl extends ManagerWebResource implements AssetResource {
@@ -79,16 +82,16 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
if (!isRestrictedUser()) {
List<Asset> result = assetStorageService.findAll(
new AssetQuery()
- .parent(new ParentPredicate(true))
+ .parents(new ParentPredicate(true))
.tenant(new TenantPredicate(getAuthenticatedRealm()))
);
return result.toArray(new Asset[result.size()]);
}
List<Asset> assets = assetStorageService.findAll(
- new AssetQuery().select(
- new Select(Include.ALL_EXCEPT_PATH_AND_ATTRIBUTES, Access.RESTRICTED_READ)
- ).userId(getUserId())
+ new AssetQuery()
+ .select(Select.selectExcludePathAndAttributes().meta(ACCESS_RESTRICTED_READ))
+ .userIds(getUserId())
);
// Filter assets that might have been moved into a different realm and can no longer be accessed by user
@@ -203,7 +206,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
if (!assetStorageService.isUserAsset(getUserId(), assetId)) {
throw new WebApplicationException(FORBIDDEN);
}
- asset = assetStorageService.find(assetId, loadComplete, Access.RESTRICTED_READ);
+ asset = assetStorageService.find(assetId, loadComplete, Access.PROTECTED);
} else {
asset = assetStorageService.find(assetId, loadComplete);
}
@@ -309,7 +312,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
// An attribute added by a restricted user must be readable by restricted users
if (!updatedAttribute.isAccessRestrictedRead()) {
- updatedAttribute.addMeta(new MetaItem(MetaItemType.ACCESS_RESTRICTED_READ, Values.create(true)));
+ updatedAttribute.addMeta(new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)));
}
// An attribute added by a restricted user must be writable by restricted users
@@ -532,13 +535,11 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
if (isRestrictedUser()) {
// A restricted user can only query linked assets
- query = query.userId(getUserId());
+ query = query.userIds(getUserId());
// A restricted user may not query private asset data, only restricted or public
- if (query.select == null)
- query.select = new Select();
- if (query.select.access == null || query.select.access == Access.PRIVATE_READ)
- query.select.filterAccess(Access.RESTRICTED_READ);
+ if (query.access == null || query.access == Access.PRIVATE)
+ query.access(Access.PROTECTED);
}
Tenant tenant = query.tenant != null
@@ -556,7 +557,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
}
// This replicates behaviour of old getRoot and getChildren methods
- if (!isSuperUser() || query.parent == null || query.parent.noParent) {
+ if (!isSuperUser()) {
query.tenant(new TenantPredicate(tenant.getRealm()));
}
@@ -589,10 +590,10 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
}
// Force public access filter on query
- if (query.select == null) {
- query.select(new Select().filterAccess(Access.PUBLIC_READ));
+ if (query.access == null) {
+ query.access(Access.PUBLIC);
} else {
- query.select.filterAccess(Access.PUBLIC_READ);
+ query.access(Access.PUBLIC);
}
try {
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
index 7d8e86b18..03f649097 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
@@ -53,7 +53,7 @@ import org.openremote.model.calendar.RecurrenceRule;
import org.openremote.model.event.TriggeredEventSubscription;
import org.openremote.model.event.shared.TenantFilter;
import org.openremote.model.query.AssetQuery;
-import org.openremote.model.query.BaseAssetQuery;
+import org.openremote.model.query.LogicGroup;
import org.openremote.model.query.filter.*;
import org.openremote.model.security.ClientRole;
import org.openremote.model.security.User;
@@ -75,6 +75,7 @@ import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
+import java.util.stream.IntStream;
import static java.util.stream.Collectors.joining;
import static org.openremote.container.persistence.PersistenceEvent.PERSISTENCE_TOPIC;
@@ -82,10 +83,10 @@ import static org.openremote.container.persistence.PersistenceEvent.isPersistenc
import static org.openremote.manager.event.ClientEventService.CLIENT_EVENT_TOPIC;
import static org.openremote.manager.event.ClientEventService.getSessionKey;
import static org.openremote.model.asset.AssetAttribute.*;
-import static org.openremote.model.query.BaseAssetQuery.*;
-import static org.openremote.model.query.BaseAssetQuery.Access.PRIVATE_READ;
-import static org.openremote.model.query.BaseAssetQuery.Access.RESTRICTED_READ;
-import static org.openremote.model.query.BaseAssetQuery.Include.*;
+import static org.openremote.model.attribute.MetaItemType.ACCESS_RESTRICTED_READ;
+import static org.openremote.model.query.AssetQuery.*;
+import static org.openremote.model.query.AssetQuery.Access.PRIVATE;
+import static org.openremote.model.query.AssetQuery.Access.PROTECTED;
import static org.openremote.model.util.TextUtil.isNullOrEmpty;
public class AssetStorageService extends RouteBuilder implements ContainerService {
@@ -120,6 +121,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
void acceptStatement(PreparedStatement st) throws SQLException;
}
+
private static final Logger LOG = Logger.getLogger(AssetStorageService.class.getName());
protected static String META_ITEM_RESTRICTED_READ_SQL_FRAGMENT;
protected static String META_ITEM_PUBLIC_READ_SQL_FRAGMENT;
@@ -130,9 +132,9 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
protected static boolean calendarEventPredicateMatches(CalendarEventActivePredicate eventActivePredicate, Asset asset) {
return CalendarEventConfiguration.getCalendarEvent(asset)
- .map(calendarEvent -> calendarEventActiveOn(calendarEvent,
- new Date(1000L * eventActivePredicate.timestampSeconds)))
- .orElse(true);
+ .map(calendarEvent -> calendarEventActiveOn(calendarEvent,
+ new Date(1000L * eventActivePredicate.timestampSeconds)))
+ .orElse(true);
}
protected static boolean calendarEventActiveOn(CalendarEvent calendarEvent, Date when) {
@@ -147,7 +149,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
recurrence = new Recur(recurrenceRule.getFrequency().name(), recurrenceRule.getCount());
} else if (recurrenceRule.getUntil() != null) {
recurrence = new Recur(recurrenceRule.getFrequency().name(),
- new net.fortuna.ical4j.model.Date(recurrenceRule.getUntil()));
+ new net.fortuna.ical4j.model.Date(recurrenceRule.getUntil()));
} else {
recurrence = new Recur(recurrenceRule.getFrequency().name(), null);
}
@@ -158,7 +160,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
RRule rRule = new RRule(recurrence);
VEvent vEvent = new VEvent(new DateTime(calendarEvent.getStart()),
- new DateTime(calendarEvent.getEnd()), "");
+ 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);
@@ -178,39 +180,39 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
clientEventService = container.getService(ClientEventService.class);
META_ITEM_RESTRICTED_READ_SQL_FRAGMENT =
- " ('" + Arrays.stream(AssetModelUtil.getMetaItemDescriptors()).filter(i -> i.getAccess().restrictedRead).map(MetaItemDescriptor::getUrn).collect(joining("','")) + "')";
+ " ('" + Arrays.stream(AssetModelUtil.getMetaItemDescriptors()).filter(i -> i.getAccess().restrictedRead).map(MetaItemDescriptor::getUrn).collect(joining("','")) + "')";
META_ITEM_PUBLIC_READ_SQL_FRAGMENT =
- " ('" + Arrays.stream(AssetModelUtil.getMetaItemDescriptors()).filter(i -> i.getAccess().publicRead).map(MetaItemDescriptor::getUrn).collect(joining("','")) + "')";
+ " ('" + Arrays.stream(AssetModelUtil.getMetaItemDescriptors()).filter(i -> i.getAccess().publicRead).map(MetaItemDescriptor::getUrn).collect(joining("','")) + "')";
clientEventService.addSubscriptionAuthorizer((auth, subscription) ->
- (subscription.isEventType(AssetTreeModifiedEvent.class))
- && identityService.getIdentityProvider().canSubscribeWith(
- auth,
- subscription.getFilter() instanceof TenantFilter ? ((TenantFilter) subscription.getFilter()) : null,
- ClientRole.READ_ASSETS)
+ (subscription.isEventType(AssetTreeModifiedEvent.class))
+ && identityService.getIdentityProvider().canSubscribeWith(
+ auth,
+ subscription.getFilter() instanceof TenantFilter ? ((TenantFilter) subscription.getFilter()) : null,
+ ClientRole.READ_ASSETS)
);
container.getService(ManagerWebService.class).getApiSingletons().add(
- new AssetModelResourceImpl(
- container.getService(TimerService.class),
- identityService
- )
+ new AssetModelResourceImpl(
+ container.getService(TimerService.class),
+ identityService
+ )
);
container.getService(ManagerWebService.class).getApiSingletons().add(
- new AssetResourceImpl(
- container.getService(TimerService.class),
- identityService,
- this,
- container.getService(MessageBrokerService.class)
- )
+ new AssetResourceImpl(
+ container.getService(TimerService.class),
+ identityService,
+ this,
+ container.getService(MessageBrokerService.class)
+ )
);
container.getService(ManagerWebService.class).getApiSingletons().add(
- new ConsoleResourceImpl(container.getService(TimerService.class),
- identityService,
- this)
+ new ConsoleResourceImpl(container.getService(TimerService.class),
+ identityService,
+ this)
);
container.getService(MessageBrokerSetupService.class).getContext().addRoutes(this);
@@ -230,53 +232,54 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
public void configure() throws Exception {
// If any asset was modified in the database, publish events
from(PERSISTENCE_TOPIC)
- .routeId("AssetPersistenceChanges")
- .filter(isPersistenceEventForEntityType(Asset.class))
- .process(exchange -> publishModificationEvents(exchange.getIn().getBody(PersistenceEvent.class)));
+ .routeId("AssetPersistenceChanges")
+ .filter(isPersistenceEventForEntityType(Asset.class))
+ .process(exchange -> publishModificationEvents(exchange.getIn().getBody(PersistenceEvent.class)));
// React if a client wants to read assets and attributes
from(CLIENT_EVENT_TOPIC)
- .routeId("FromClientReadRequests")
- .filter(exchange ->
- (exchange.getIn().getBody() instanceof ReadAssetAttributesEvent) || (exchange.getIn().getBody() instanceof ReadAssetEvent))
- .process(exchange -> {
- ReadAssetEvent event = exchange.getIn().getBody(ReadAssetEvent.class);
- LOG.fine("Handling from client: " + event);
- boolean isAttributeRead = event instanceof ReadAssetAttributesEvent;
+ .routeId("FromClientReadRequests")
+ .filter(exchange ->
+ (exchange.getIn().getBody() instanceof ReadAssetAttributesEvent) || (exchange.getIn().getBody() instanceof ReadAssetEvent))
+ .process(exchange -> {
+ ReadAssetEvent event = exchange.getIn().getBody(ReadAssetEvent.class);
+ LOG.fine("Handling from client: " + event);
+ boolean isAttributeRead = event instanceof ReadAssetAttributesEvent;
- if (event.getAssetId() == null || event.getAssetId().isEmpty())
- return;
+ if (event.getAssetId() == null || event.getAssetId().isEmpty())
+ return;
- String sessionKey = getSessionKey(exchange);
- AuthContext authContext = exchange.getIn().getHeader(Constants.AUTH_CONTEXT, AuthContext.class);
+ String sessionKey = getSessionKey(exchange);
+ AuthContext authContext = exchange.getIn().getHeader(Constants.AUTH_CONTEXT, AuthContext.class);
- // Superuser can get all, User must have role
- if (!authContext.isSuperUser() && !authContext.hasResourceRole(ClientRole.READ_ASSETS.getValue(), Constants.KEYCLOAK_CLIENT_ID)) {
- return;
- }
+ // Superuser can get all, User must have role
+ if (!authContext.isSuperUser() && !authContext.hasResourceRole(ClientRole.READ_ASSETS.getValue(), Constants.KEYCLOAK_CLIENT_ID)) {
+ return;
+ }
- Access access = authContext.isSuperUser() || !identityService.getIdentityProvider().isRestrictedUser(authContext.getUserId()) ? PRIVATE_READ : RESTRICTED_READ;
+ Access access = authContext.isSuperUser() || !identityService.getIdentityProvider().isRestrictedUser(authContext.getUserId()) ? PRIVATE : PROTECTED;
- Asset asset = find(
- new AssetQuery()
- .select(new Select(ALL, access))
- .id(event.getAssetId()));
+ Asset asset = find(
+ new AssetQuery()
+ .select(Select.selectAll())
+ .ids(event.getAssetId())
+ .access(access));
- if (asset != null) {
- if (isAttributeRead) {
- replyWithAttributeEvents(sessionKey, event.getSubscriptionId(), asset, ((ReadAssetAttributesEvent)event).getAttributeNames());
- } else {
- replyWithAssetEvent(sessionKey, event.getSubscriptionId(), asset);
- }
+ if (asset != null) {
+ if (isAttributeRead) {
+ replyWithAttributeEvents(sessionKey, event.getSubscriptionId(), asset, ((ReadAssetAttributesEvent) event).getAttributeNames());
+ } else {
+ replyWithAssetEvent(sessionKey, event.getSubscriptionId(), asset);
}
- });
+ }
+ });
}
public Asset find(String assetId) {
if (assetId == null)
throw new IllegalArgumentException("Can't query null asset identifier");
- return find(new AssetQuery().id(assetId));
+ return find(new AssetQuery().ids(assetId));
}
/**
@@ -285,14 +288,14 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
public Asset find(String assetId, boolean loadComplete) {
if (assetId == null)
throw new IllegalArgumentException("Can't query null asset identifier");
- return find(new AssetQuery().select(new Select(loadComplete ? ALL : ALL_EXCEPT_PATH_AND_ATTRIBUTES)).id(assetId));
+ return find(new AssetQuery().select(loadComplete ? Select.selectAll() : Select.selectExcludePathAndAttributes()).ids(assetId));
}
/**
* @param loadComplete If the whole asset data (including path and attributes) should be loaded.
*/
public Asset find(EntityManager em, String assetId, boolean loadComplete) {
- return find(em, assetId, loadComplete, PRIVATE_READ);
+ return find(em, assetId, loadComplete, PRIVATE);
}
/**
@@ -302,15 +305,19 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
public Asset find(String assetId, boolean loadComplete, Access access) {
if (assetId == null)
throw new IllegalArgumentException("Can't query null asset identifier");
- return find(new AssetQuery().select(new Select(loadComplete ? ALL : ALL_EXCEPT_PATH_AND_ATTRIBUTES, access)).id(
- assetId));
+ return find(new AssetQuery()
+ .select(loadComplete
+ ? Select.selectAll()
+ : Select.selectExcludePathAndAttributes())
+ .ids(assetId)
+ .access(access));
}
- public Asset find(BaseAssetQuery query) {
+ public Asset find(AssetQuery query) {
return persistenceService.doReturningTransaction(em -> find(em, query));
}
- public Asset find(EntityManager em, BaseAssetQuery query) {
+ public Asset find(EntityManager em, AssetQuery query) {
List<Asset> result = findAll(em, query);
if (result.size() == 0)
return null;
@@ -321,7 +328,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
}
- public List<Asset> findAll(BaseAssetQuery query) {
+ public List<Asset> findAll(AssetQuery query) {
return persistenceService.doReturningTransaction(em -> findAll(em, query));
}
@@ -332,9 +339,9 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
// TODO: Do this in a loop in reasonably sized batches
return persistenceService.doReturningTransaction(em -> {
List<Object[]> result = em.createQuery("select a.id, a.name from Asset a where a.id in :ids",
- Object[].class)
- .setParameter("ids", Arrays.asList(ids))
- .getResultList();
+ Object[].class)
+ .setParameter("ids", Arrays.asList(ids))
+ .getResultList();
List<String> names = new ArrayList<>();
for (String id : ids) {
for (Object[] tuple : result) {
@@ -472,7 +479,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
Asset asset = em.find(Asset.class, assetId);
if (asset != null) {
List<Asset> children = findAll(em, new AssetQuery()
- .parent(new ParentPredicate(asset.getId()))
+ .parents(new ParentPredicate(asset.getId()))
);
if (children.size() > 0)
return false;
@@ -494,12 +501,12 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
return persistenceService.doReturningTransaction(entityManager -> {
try {
String queryStr = TextUtil.isNullOrEmpty(userId) ?
- "select count(ua) from UserAsset ua where ua.id.assetId = :assetId" :
- "select count(ua) from UserAsset ua where ua.id.userId = :userId and ua.id.assetId = :assetId";
+ "select count(ua) from UserAsset ua where ua.id.assetId = :assetId" :
+ "select count(ua) from UserAsset ua where ua.id.userId = :userId and ua.id.assetId = :assetId";
TypedQuery<Long> query = entityManager.createQuery(
- queryStr,
- Long.class).setParameter("assetId", assetId);
+ queryStr,
+ Long.class).setParameter("assetId", assetId);
if (!TextUtil.isNullOrEmpty(userId)) {
query.setParameter("userId", userId);
@@ -519,11 +526,11 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
return persistenceService.doReturningTransaction(entityManager -> {
try {
return entityManager.createQuery(
- "select count(ua) from UserAsset ua where ua.id.userId in :userIds and ua.id.assetId = :assetId",
- Long.class)
- .setParameter("userIds", userIds)
- .setParameter("assetId", assetId)
- .getSingleResult() > 0;
+ "select count(ua) from UserAsset ua where ua.id.userId in :userIds and ua.id.assetId = :assetId",
+ Long.class)
+ .setParameter("userIds", userIds)
+ .setParameter("assetId", assetId)
+ .getSingleResult() > 0;
} catch (NoResultException ex) {
return false;
}
@@ -537,11 +544,11 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
return persistenceService.doReturningTransaction(entityManager -> {
try {
return entityManager.createQuery(
- "select count(ua) from UserAsset ua where ua.id.userId = :userId and ua.id.assetId in :assetIds",
- Long.class)
- .setParameter("userId", userId)
- .setParameter("assetIds", assetIds)
- .getSingleResult() == assetIds.size();
+ "select count(ua) from UserAsset ua where ua.id.userId = :userId and ua.id.assetId in :assetIds",
+ Long.class)
+ .setParameter("userId", userId)
+ .setParameter("assetIds", assetIds)
+ .getSingleResult() == assetIds.size();
} catch (NoResultException ex) {
return false;
}
@@ -565,11 +572,11 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
return persistenceService.doReturningTransaction(entityManager -> {
try {
return entityManager.createQuery(
- "select count(a) from Asset a where a.realm = :realm and a.id in :assetIds",
- Long.class)
- .setParameter("realm", realm)
- .setParameter("assetIds", assetIds)
- .getSingleResult() == assetIds.size();
+ "select count(a) from Asset a where a.realm = :realm and a.id in :assetIds",
+ Long.class)
+ .setParameter("realm", realm)
+ .setParameter("assetIds", assetIds)
+ .getSingleResult() == assetIds.size();
} catch (NoResultException ex) {
return false;
}
@@ -655,22 +662,23 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
if (assetId == null)
throw new IllegalArgumentException("Can't query null asset identifier");
return find(
- em,
- new AssetQuery().select(
- new Select(loadComplete ? ALL : ALL_EXCEPT_PATH_AND_ATTRIBUTES, access)
- ).id(assetId)
+ em,
+ new AssetQuery()
+ .select(loadComplete
+ ? Select.selectAll()
+ : Select.selectExcludePathAndAttributes())
+ .ids(assetId)
+ .access(access)
);
}
- protected List<Asset> findAll(EntityManager em, BaseAssetQuery query) {
+ protected List<Asset> findAll(EntityManager em, AssetQuery query) {
// Use a default projection if it's missing
if (query.select == null)
query.select = new Select();
- if (query.select.include == null)
- query.select.include = ALL_EXCEPT_PATH_AND_ATTRIBUTES;
- if (query.select.access == null)
- query.select.access = PRIVATE_READ;
+ if (query.access == null)
+ query.access = PRIVATE;
// Default to order by creation date if the query may return multiple results
if (query.orderBy == null && query.ids == null)
@@ -706,10 +714,10 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
});
}
- protected PreparedAssetQuery buildQuery(BaseAssetQuery query) {
+ protected PreparedAssetQuery buildQuery(AssetQuery query) {
LOG.fine("Building: " + query);
StringBuilder sb = new StringBuilder();
- boolean recursive = query.select.recursive;
+ boolean recursive = query.recursive;
List<ParameterBinder> binders = new ArrayList<>();
sb.append(buildSelectString(query, 1, binders));
sb.append(buildFromString(query, 1));
@@ -732,49 +740,40 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
return new PreparedAssetQuery(sb.toString(), binders);
}
- protected String buildSelectString(BaseAssetQuery query, int level, List<ParameterBinder> binders) {
+ protected String buildSelectString(AssetQuery query, int level, List<ParameterBinder> binders) {
// level = 1 is main query select
// level = 2 is union select
// level = 3 is CTE select
StringBuilder sb = new StringBuilder();
- AssetQuery.Include include = query.select.include;
- boolean recursive = query.select.recursive;
+ AssetQuery.Select select = query.select;
sb.append("select A.ID as ID, A.NAME as NAME, A.ACCESS_PUBLIC_READ as ACCESS_PUBLIC_READ");
- sb.append(
- ", A.CREATED_ON AS CREATED_ON, A.ASSET_TYPE AS ASSET_TYPE, A.PARENT_ID AS PARENT_ID, A.REALM AS REALM");
+ sb.append(", A.CREATED_ON AS CREATED_ON, A.ASSET_TYPE AS ASSET_TYPE, A.PARENT_ID AS PARENT_ID");
+ sb.append(", A.REALM AS REALM, A.OBJ_VERSION as OBJ_VERSION");
- if (include == AssetQuery.Include.ONLY_ID_AND_NAME) {
- return sb.toString();
+ if (!select.excludeParentInfo) {
+ sb.append(", P.NAME as PARENT_NAME, P.ASSET_TYPE as PARENT_TYPE");
}
- switch (include) {
- case ALL_EXCEPT_PATH_AND_ATTRIBUTES:
- case ALL_EXCEPT_ATTRIBUTES:
- case ALL_EXCEPT_PATH:
- case ALL:
- sb.append(", A.OBJ_VERSION as OBJ_VERSION");
- sb.append(", P.NAME as PARENT_NAME, P.ASSET_TYPE as PARENT_TYPE");
- if (!recursive || level == 3) {
- sb.append(", R.NAME as TENANT_NAME");
- }
- break;
+
+ if (!select.excludeRealm) {
+ if (!query.recursive || level == 3) {
+ sb.append(", R.NAME as TENANT_NAME");
+ }
}
- if (!recursive || level == 3) {
- if (include == ALL || include == ALL_EXCEPT_ATTRIBUTES) {
+ if (!query.recursive || level == 3) {
+ if (!select.excludePath) {
sb.append(", get_asset_tree_path(A.ID) as PATH");
} else {
sb.append(", NULL as PATH");
}
}
- if (include != ALL_EXCEPT_PATH_AND_ATTRIBUTES && include != ALL_EXCEPT_ATTRIBUTES) {
-
- if (recursive && level != 3) {
+ if (!select.excludeAttributes) {
+ if (query.recursive && level != 3) {
sb.append(", A.ATTRIBUTES as ATTRIBUTES");
} else {
- boolean namesOnly = include == AssetQuery.Include.ONLY_ID_AND_NAME_AND_ATTRIBUTE_NAMES;
- sb.append(buildAttributeSelect(query.select.attributeNames, query.select.access, namesOnly, binders));
+ sb.append(buildAttributeSelect(query, binders));
}
} else {
sb.append(", NULL as ATTRIBUTES");
@@ -783,37 +782,67 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
return sb.toString();
}
- protected String buildAttributeSelect(String[] attributeNames, Access access, boolean namesOnly, List<ParameterBinder> binders) {
- if (attributeNames == null && access == PRIVATE_READ && !namesOnly) {
+ protected String buildAttributeSelect(AssetQuery query, List<ParameterBinder> binders) {
+
+ Select select = query.select;
+ boolean hasMetaFilter = !select.excludeAttributeMeta && select.meta != null && select.meta.length > 0;
+ boolean fullyPopulateAttributes = !(select.excludeAttributeMeta || select.excludeAttributeValue || select.excludeAttributeTimestamp || select.meta != null);
+
+ if (select.attributes == null && query.access == PRIVATE && fullyPopulateAttributes) {
return ", A.ATTRIBUTES as ATTRIBUTES";
}
+ StringBuilder attributeBuilder = new StringBuilder();
+
+ if (select.excludeAttributeMeta) {
+ attributeBuilder.append(" - 'meta'");
+ }
+ if (select.excludeAttributeTimestamp) {
+ attributeBuilder.append(" - 'valueTimestamp'");
+ }
+ if (select.excludeAttributeValue) {
+ attributeBuilder.append(" - 'value'");
+ }
+ if (select.excludeAttributeType) {
+ attributeBuilder.append(" - 'type'");
+ }
+
StringBuilder sb = new StringBuilder();
sb.append(", (");
- if (namesOnly) {
- sb.append("select json_object_agg(AX.key, jsonb_set('{}'::jsonb, '{meta}', (");
- sb.append("select jsonb_agg(AM.VALUE)");
- sb.append(" from jsonb_array_elements(AX.VALUE #> '{meta}') as AM");
- sb.append(" where AM.VALUE #>> '{name}' = '");
- sb.append(MetaItemType.LABEL.getUrn());
- sb.append("'))) from jsonb_each(A.attributes) as AX");
- if (access != PRIVATE_READ) {
+ if (select.excludeAttributeMeta) {
+ sb.append("select json_object_agg(AX.key, AX.value");
+ sb.append(attributeBuilder);
+ sb.append(") from jsonb_each(A.attributes) as AX");
+ if (query.access != PRIVATE) {
// Use implicit inner join on meta array set to only select non-private attributes
sb.append(", jsonb_array_elements(AX.VALUE #> '{meta}') as AM");
}
- } else if (access != PRIVATE_READ) {
+ } else if (query.access != PRIVATE || hasMetaFilter) {
// Use sub-select for processing the attributes the meta inside each attribute is replaced with filtered meta
// (coalesce null to empty array because jsonb_set() with null will clear the whole object)
sb.append(
- "select json_object_agg(AX.key, jsonb_set(AX.value, '{meta}', coalesce(AMF.VALUE, jsonb_build_array()), false)) from jsonb_each(A.attributes) as AX");
+ "select json_object_agg(AX.key, jsonb_set(AX.value, '{meta}', coalesce(AMF.VALUE, jsonb_build_array()), false)) from jsonb_each(A.attributes) as AX");
// Use implicit inner join on meta array set to only select attributes with a non-private access meta item
sb.append(", jsonb_array_elements(AX.VALUE #> '{meta}') as AM");
// Use subquery to filter out meta items not marked as non-private access
sb.append(" INNER JOIN LATERAL (");
sb.append("select jsonb_agg(AM.value) AS VALUE from jsonb_array_elements(AX.VALUE #> '{meta}') as AM");
sb.append(" where AM.VALUE #>> '{name}' IN");
- sb.append(access == RESTRICTED_READ ? META_ITEM_RESTRICTED_READ_SQL_FRAGMENT : META_ITEM_PUBLIC_READ_SQL_FRAGMENT);
+
+ if (query.access != PRIVATE) {
+ sb.append(query.access == PROTECTED ? META_ITEM_RESTRICTED_READ_SQL_FRAGMENT : META_ITEM_PUBLIC_READ_SQL_FRAGMENT);
+ if (hasMetaFilter) {
+ sb.append(" AND AM.VALUE #>> '{name}' IN");
+ }
+ }
+
+ if (hasMetaFilter) {
+ sb.append(" ('");
+ sb.append(String.join("','", select.meta));
+ sb.append("')");
+ }
+
sb.append(") as AMF ON true");
} else {
sb.append("select json_object_agg(AX.key, AX.value) from jsonb_each(A.attributes) as AX");
@@ -821,36 +850,38 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
sb.append(" where true");
- if (attributeNames != null && attributeNames.length > 0) {
+ // Filter attributes
+ if (select.attributes != null && select.attributes.length > 0) {
sb.append(" AND AX.key IN (");
- for (int i = 0; i < attributeNames.length; i++) {
- sb.append(i == attributeNames.length - 1 ? "?" : "?,");
- final String attributeName = attributeNames[i];
+ for (int i = 0; i < select.attributes.length; i++) {
+ sb.append(i == select.attributes.length - 1 ? "?" : "?,");
+ final String attributeName = select.attributes[i];
final int pos = binders.size() + 1;
binders.add(st -> st.setString(pos, attributeName));
}
- sb.append(") ");
+ sb.append(")");
}
- if (access != PRIVATE_READ) {
+ if (query.access != PRIVATE) {
// Filter non-private access attributes
AttributeMetaPredicate accessPredicate =
- new AttributeMetaPredicate()
- .itemName(access == RESTRICTED_READ ? MetaItemType.ACCESS_RESTRICTED_READ : MetaItemType.ACCESS_PUBLIC_READ)
- .itemValue(new BooleanPredicate(true));
- sb.append(buildAttributeMetaFilter(accessPredicate, binders));
+ new AttributeMetaPredicate()
+ .itemName(query.access == PROTECTED ? ACCESS_RESTRICTED_READ : MetaItemType.ACCESS_PUBLIC_READ)
+ .itemValue(new BooleanPredicate(true));
+ sb.append(buildAttributeMetaFilter(binders, accessPredicate));
}
sb.append(") AS ATTRIBUTES");
return sb.toString();
}
- protected String buildFromString(BaseAssetQuery query, int level) {
+ protected String buildFromString(AssetQuery query, int level) {
// level = 1 is main query
// level = 2 is union
// level = 3 is CTE
StringBuilder sb = new StringBuilder();
- boolean recursive = query.select.recursive;
+ boolean recursive = query.recursive;
+ boolean includeRealmInfo = !query.select.excludeRealm;
if (level == 1) {
sb.append(" from ASSET A ");
@@ -861,20 +892,16 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
sb.append(" from top_level_assets A ");
}
- boolean includeRealmInfo = query.select.include != AssetQuery.Include.ONLY_ID_AND_NAME &&
- query.select.include != AssetQuery.Include.ONLY_ID_AND_NAME_AND_ATTRIBUTE_NAMES &&
- query.select.include != AssetQuery.Include.ONLY_ID_AND_NAME_AND_ATTRIBUTES;
-
if ((!recursive || level == 3) && (includeRealmInfo || query.tenant != null)) {
sb.append("join PUBLIC.REALM R on R.NAME = A.REALM ");
}
- if ((!recursive || level == 3) && query.ids == null && query.userId != null) {
+ if ((!recursive || level == 3) && query.ids == null && query.userIds != null && query.userIds.length > 0) {
sb.append("cross join USER_ASSET ua ");
}
if (level == 1) {
- if (query.parent != null && !query.parent.noParent && (query.parent.id != null || query.parent.type != null || query.parent.name != null)) {
+ if (hasParentConstraint(query.parents)) {
sb.append("cross join ASSET P ");
} else {
sb.append("left outer join ASSET P on A.PARENT_ID = P.ID ");
@@ -884,10 +911,20 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
return sb.toString();
}
- protected String buildOrderByString(BaseAssetQuery query) {
+ protected boolean hasParentConstraint(ParentPredicate[] parentPredicates) {
+ if (parentPredicates == null || parentPredicates.length == 0) {
+ return false;
+ }
+
+ return Arrays.stream(parentPredicates)
+ .anyMatch(p -> !p.noParent && (p.id != null || p.type != null || p.name != null));
+ }
+
+
+ protected String buildOrderByString(AssetQuery query) {
StringBuilder sb = new StringBuilder();
- if (query.ids != null && !query.select.recursive) {
+ if (query.ids != null && !query.recursive) {
return sb.toString();
}
@@ -917,75 +954,115 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
return sb.toString();
}
- protected String buildLimitString(BaseAssetQuery query) {
+ protected String buildLimitString(AssetQuery query) {
if (query.limit > 0) {
return " LIMIT " + query.limit;
}
return "";
}
- protected String buildWhereClause(BaseAssetQuery query, int level, List<ParameterBinder> binders) {
+ protected String buildWhereClause(AssetQuery query, int level, List<ParameterBinder> binders) {
// level = 1 is main query
// level = 2 is union
// level = 3 is CTE
StringBuilder sb = new StringBuilder();
- boolean recursive = query.select.recursive;
+ boolean recursive = query.recursive;
sb.append(" where true");
if (level == 2) {
return sb.toString();
}
- if (level == 1 && query.ids != null && !query.ids.isEmpty()) {
+ if (level == 1 && query.ids != null && query.ids.length > 0) {
sb.append(" and A.ID IN (?");
final int pos = binders.size() + 1;
- binders.add(st -> st.setString(pos, (String) query.ids.get(0)));
+ binders.add(st -> st.setString(pos, query.ids[0]));
- for (int i = 1; i < query.ids.size(); i++) {
+ for (int i = 1; i < query.ids.length; i++) {
sb.append(",?");
final int pos2 = binders.size() + 1;
final int index = i;
- binders.add(st -> st.setString(pos2, (String) query.ids.get(index)));
+ binders.add(st -> st.setString(pos2, query.ids[index]));
}
sb.append(")");
}
- if (level == 1 && query.name != null) {
- sb.append(query.name.caseSensitive ? " and A.NAME " : " and upper(A.NAME)");
- sb.append(buildMatchFilter(query.name));
- final int pos = binders.size() + 1;
- binders.add(st -> st.setString(pos, query.name.prepareValue()));
- }
+ if (level == 1 && query.names != null && query.names.length > 0) {
- if (query.parent != null) {
- if (level == 1 && query.parent.id != null) {
- sb.append(" and p.ID = a.PARENT_ID");
- sb.append(" and A.PARENT_ID = ?");
+ sb.append(" and (");
+ boolean isFirst = true;
+
+ for (StringPredicate pred : query.names) {
+ if (!isFirst) {
+ sb.append(" or ");
+ }
+ isFirst = false;
+ sb.append(pred.caseSensitive ? "A.NAME " : "upper(A.NAME)");
+ sb.append(buildMatchFilter(pred));
final int pos = binders.size() + 1;
- binders.add(st -> st.setString(pos, query.parent.id));
- } else if (level == 1 && query.parent.noParent) {
- sb.append(" and A.PARENT_ID is null");
- } else if (query.parent.type != null || query.parent.name != null) {
+ binders.add(st -> st.setString(pos, pred.prepareValue()));
+ }
+ sb.append(")");
+ }
- sb.append(" and p.ID = a.PARENT_ID");
+ if (query.parents != null && query.parents.length > 0) {
- if (query.parent.type != null) {
- sb.append(" and P.ASSET_TYPE = ?");
- final int pos = binders.size() + 1;
- binders.add(st -> st.setString(pos, query.parent.type));
+ sb.append(" and (");
+ boolean isFirst = true;
+
+ for (ParentPredicate pred : query.parents) {
+ if (!isFirst) {
+ sb.append(" or (");
+ } else {
+ sb.append("(");
}
- if (query.parent.name != null) {
- sb.append(" and P.NAME = ?");
+ isFirst = false;
+
+ if (level == 1 && pred.id != null) {
+ sb.append("p.ID = a.PARENT_ID");
+ sb.append(" and A.PARENT_ID = ?");
final int pos = binders.size() + 1;
- binders.add(st -> st.setString(pos, query.parent.name));
+ binders.add(st -> st.setString(pos, pred.id));
+ } else if (level == 1 && pred.noParent) {
+ sb.append("A.PARENT_ID is null");
+ } else if (pred.type != null || pred.name != null) {
+
+ sb.append("p.ID = a.PARENT_ID");
+
+ if (pred.type != null) {
+ sb.append(" and P.ASSET_TYPE = ?");
+ final int pos = binders.size() + 1;
+ binders.add(st -> st.setString(pos, pred.type));
+ }
+ if (pred.name != null) {
+ sb.append(" and P.NAME = ?");
+ final int pos = binders.size() + 1;
+ binders.add(st -> st.setString(pos, pred.name));
+ }
}
+
+ sb.append(")");
}
+
+ sb.append(")");
}
- if (level == 1 && query.path != null && query.path.hasPath()) {
- sb.append(" and ? <@ get_asset_tree_path(A.ID)");
- final int pos = binders.size() + 1;
- binders.add(st -> st.setArray(pos, st.getConnection().createArrayOf("text", query.path.path)));
+ if (level == 1 && hasPathConstraint(query.paths)) {
+ sb.append(" and (");
+ boolean isFirst = true;
+
+ for (PathPredicate pred : query.paths) {
+ if (!isFirst) {
+ sb.append(" or ");
+ }
+ isFirst = false;
+
+ sb.append("? <@ get_asset_tree_path(A.ID)");
+ final int pos = binders.size() + 1;
+ binders.add(st -> st.setArray(pos, st.getConnection().createArrayOf("text", pred.path)));
+ }
+
+ sb.append(")");
}
if (!recursive || level == 3) {
@@ -995,26 +1072,49 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
binders.add(st -> st.setString(pos, query.tenant.realm));
}
- if (query.ids == null && query.userId != null) {
- sb.append(" and ua.ASSET_ID = a.ID and ua.USER_ID = ?");
+ if (query.ids == null && query.userIds != null && query.userIds.length > 0) {
+ sb.append(" and ua.ASSET_ID = a.ID and ua.USER_ID IN (?");
final int pos = binders.size() + 1;
- binders.add(st -> st.setString(pos, query.userId));
+ binders.add(st -> st.setString(pos, query.userIds[0]));
+
+ for (int i = 1; i < query.userIds.length; i++) {
+ sb.append(",?");
+ final int pos2 = binders.size() + 1;
+ final int index = i;
+ binders.add(st -> st.setString(pos2, query.userIds[index]));
+ }
+ sb.append(")");
}
- if (level == 1 && query.select.access == Access.PUBLIC_READ) {
+ if (level == 1 && query.access == Access.PUBLIC) {
sb.append(" and A.ACCESS_PUBLIC_READ is true");
}
- if (query.type != null) {
- sb.append(query.type.caseSensitive ? " and A.ASSET_TYPE" : " and upper(A.ASSET_TYPE)");
- sb.append(buildMatchFilter(query.type));
- final int pos = binders.size() + 1;
- binders.add(st -> st.setString(pos, query.type.prepareValue()));
+ if (query.types != null && query.types.length > 0) {
+ sb.append(" and (");
+ boolean isFirst = true;
+
+ for (StringPredicate pred : query.types) {
+ if (!isFirst) {
+ sb.append(" or (");
+ } else {
+ sb.append("(");
+ }
+ isFirst = false;
+
+ sb.append(pred.caseSensitive ? "A.ASSET_TYPE" : " and upper(A.ASSET_TYPE)");
+ sb.append(buildMatchFilter(pred));
+ final int pos = binders.size() + 1;
+ binders.add(st -> st.setString(pos, pred.prepareValue()));
+ sb.append(")");
+ }
+
+ sb.append(")");
}
if (query.attributeMeta != null) {
for (AttributeMetaPredicate attributeMetaPredicate : query.attributeMeta) {
- String attributeMetaFilter = buildAttributeMetaFilter(attributeMetaPredicate, binders);
+ String attributeMetaFilter = buildAttributeMetaFilter(binders, attributeMetaPredicate);
if (attributeMetaFilter.length() > 0) {
sb.append(" and A.ID in (select A.ID from");
@@ -1027,68 +1127,121 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
}
}
- if (query.attribute != null) {
- for (AttributePredicate attributePredicate : query.attribute) {
- StringBuilder attributeFilterBuilder = new StringBuilder();
- attributeFilterBuilder.append(buildAttributeFilter(attributePredicate, binders));
+ if (query.attributes != null) {
+ sb.append(" and A.ID in (select A.ID from");
+ sb.append(" jsonb_each(A.ATTRIBUTES) as AX");
+ sb.append(" where true AND ");
+ addAttributePredicateGroupQuery(sb, binders, query.attributes);
+ sb.append(")");
+ }
+ }
+ return sb.toString();
+ }
+
+ protected void addAttributePredicateGroupQuery(StringBuilder sb, List<ParameterBinder> binders, LogicGroup<AttributePredicate> attributePredicateGroup) {
- if (attributeFilterBuilder.length() > 0) {
- sb.append(" and A.ID in (select A.ID from");
- sb.append(" jsonb_each(A.ATTRIBUTES) as AX");
- sb.append(" where true");
- sb.append(attributeFilterBuilder.toString());
- sb.append(")");
- }
+ LogicGroup.Operator operator = attributePredicateGroup.operator;
+
+ if (operator == null) {
+ operator = LogicGroup.Operator.OR;
+ }
+
+ sb.append("(");
+ boolean isFirst = true;
+
+ if (attributePredicateGroup.items != null) {
+ for (AttributePredicate attributePredicate : attributePredicateGroup.items) {
+
+ if (!isFirst) {
+ sb.append(operator == LogicGroup.Operator.OR ? " or " : " and ");
}
+ isFirst = false;
+
+ sb.append("(");
+ sb.append(buildAttributeFilter(attributePredicate, binders));
+ sb.append(")");
}
}
- return sb.toString();
+
+ if (attributePredicateGroup.groups != null) {
+ for (LogicGroup<AttributePredicate> group : attributePredicateGroup.groups) {
+ addAttributePredicateGroupQuery(sb, binders, group);
+ }
+ }
+ sb.append(")");
+ }
+
+ protected boolean hasPathConstraint(PathPredicate[] pathPredicates) {
+ if (pathPredicates == null || pathPredicates.length == 0) {
+ return false;
+ }
+
+ return Arrays.stream(pathPredicates).anyMatch(p -> p.path != null);
}
- protected String buildAttributeMetaFilter(AttributeMetaPredicate attributeMetaPredicate, List<ParameterBinder> binders) {
- StringBuilder attributeMetaBuilder = new StringBuilder();
+ protected String buildAttributeMetaFilter(List<ParameterBinder> binders, AttributeMetaPredicate...attributeMetaPredicates) {
+ StringBuilder sb = new StringBuilder();
+
+ if (attributeMetaPredicates == null || attributeMetaPredicates.length == 0) {
+ return "";
+ }
+
+ sb.append(" AND (");
+
+ boolean isFirst = true;
+ for (AttributeMetaPredicate attributeMetaPredicate : attributeMetaPredicates) {
- if (attributeMetaPredicate.itemNamePredicate != null) {
- attributeMetaBuilder.append(attributeMetaPredicate.itemNamePredicate.caseSensitive
+ if (!isFirst) {
+ sb.append(" OR (true");
+ } else {
+ sb.append("(true");
+ }
+ isFirst = false;
+
+ if (attributeMetaPredicate.itemNamePredicate != null) {
+ sb.append(attributeMetaPredicate.itemNamePredicate.caseSensitive
? " and AM.VALUE #>> '{name}'"
: " and upper(AM.VALUE #>> '{name}')"
- );
- attributeMetaBuilder.append(buildMatchFilter(attributeMetaPredicate.itemNamePredicate));
- final int pos = binders.size() + 1;
- binders.add(st -> st.setString(pos, attributeMetaPredicate.itemNamePredicate.prepareValue()));
- }
- if (attributeMetaPredicate.itemValuePredicate != null) {
- if (attributeMetaPredicate.itemValuePredicate instanceof StringPredicate) {
- StringPredicate stringPredicate = (StringPredicate) attributeMetaPredicate.itemValuePredicate;
- attributeMetaBuilder.append(stringPredicate.caseSensitive
+ );
+ sb.append(buildMatchFilter(attributeMetaPredicate.itemNamePredicate));
+ final int pos = binders.size() + 1;
+ binders.add(st -> st.setString(pos, attributeMetaPredicate.itemNamePredicate.prepareValue()));
+ }
+
+ if (attributeMetaPredicate.itemValuePredicate != null) {
+ if (attributeMetaPredicate.itemValuePredicate instanceof StringPredicate) {
+ StringPredicate stringPredicate = (StringPredicate) attributeMetaPredicate.itemValuePredicate;
+ sb.append(stringPredicate.caseSensitive
? " and AM.VALUE #>> '{value}'"
: " and upper(AM.VALUE #>> '{value}')"
- );
- attributeMetaBuilder.append(buildMatchFilter(stringPredicate));
+ );
+ sb.append(buildMatchFilter(stringPredicate));
- final int pos = binders.size() + 1;
- binders.add(st -> st.setString(pos, stringPredicate.prepareValue()));
- } else if (attributeMetaPredicate.itemValuePredicate instanceof BooleanPredicate) {
- BooleanPredicate booleanPredicate = (BooleanPredicate) attributeMetaPredicate.itemValuePredicate;
- attributeMetaBuilder.append(" and AM.VALUE #> '{value}' = to_jsonb(")
+ final int pos = binders.size() + 1;
+ binders.add(st -> st.setString(pos, stringPredicate.prepareValue()));
+ } else if (attributeMetaPredicate.itemValuePredicate instanceof BooleanPredicate) {
+ BooleanPredicate booleanPredicate = (BooleanPredicate) attributeMetaPredicate.itemValuePredicate;
+ sb.append(" and AM.VALUE #> '{value}' = to_jsonb(")
.append(booleanPredicate.value)
.append(")");
- } else if (attributeMetaPredicate.itemValuePredicate instanceof StringArrayPredicate) {
- StringArrayPredicate stringArrayPredicate = (StringArrayPredicate) attributeMetaPredicate.itemValuePredicate;
- for (int i = 0; i < stringArrayPredicate.predicates.length; i++) {
- StringPredicate stringPredicate = stringArrayPredicate.predicates[i];
- attributeMetaBuilder.append(stringPredicate.caseSensitive
+ } else if (attributeMetaPredicate.itemValuePredicate instanceof StringArrayPredicate) {
+ StringArrayPredicate stringArrayPredicate = (StringArrayPredicate) attributeMetaPredicate.itemValuePredicate;
+ for (int i = 0; i < stringArrayPredicate.predicates.length; i++) {
+ StringPredicate stringPredicate = stringArrayPredicate.predicates[i];
+ sb.append(stringPredicate.caseSensitive
? " and AM.VALUE #> '{value}' ->> " + i
: " and upper(AM.VALUE #> '{value}' ->> " + i + ")"
- );
- attributeMetaBuilder.append(buildMatchFilter(stringPredicate));
- final int pos = binders.size() + 1;
- binders.add(st -> st.setString(pos, stringPredicate.prepareValue()));
+ );
+ sb.append(buildMatchFilter(stringPredicate));
+ final int pos = binders.size() + 1;
+ binders.add(st -> st.setString(pos, stringPredicate.prepareValue()));
+ }
}
}
+ sb.append(")");
}
-
- return attributeMetaBuilder.toString();
+ sb.append(")");
+ return sb.toString();
}
protected String buildAttributeFilter(AttributePredicate attributePredicate, List<ParameterBinder> binders) {
@@ -1096,8 +1249,8 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
if (attributePredicate.name != null) {
attributeBuilder.append(attributePredicate.name.caseSensitive
- ? " and AX.key"
- : " and upper(AX.key)"
+ ? "AX.key"
+ : "upper(AX.key)"
);
attributeBuilder.append(buildMatchFilter(attributePredicate.name));
@@ -1105,27 +1258,32 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
binders.add(st -> st.setString(pos, attributePredicate.name.prepareValue()));
}
if (attributePredicate.value != null) {
+
+ if (attributePredicate.name != null) {
+ attributeBuilder.append(" and ");
+ }
+
if (attributePredicate.value instanceof StringPredicate) {
StringPredicate stringPredicate = (StringPredicate) attributePredicate.value;
attributeBuilder.append(stringPredicate.caseSensitive
- ? " and AX.VALUE #>> '{value}'"
- : " and upper(AX.VALUE #>> '{value}')"
+ ? "AX.VALUE #>> '{value}'"
+ : "upper(AX.VALUE #>> '{value}')"
);
attributeBuilder.append(buildMatchFilter(stringPredicate));
final int pos = binders.size() + 1;
binders.add(st -> st.setString(pos, stringPredicate.prepareValue()));
} else if (attributePredicate.value instanceof BooleanPredicate) {
BooleanPredicate booleanPredicate = (BooleanPredicate) attributePredicate.value;
- attributeBuilder.append(" and AX.VALUE #> '{value}' = to_jsonb(")
- .append(booleanPredicate.value)
- .append(")");
+ attributeBuilder.append("AX.VALUE #> '{value}' = to_jsonb(")
+ .append(booleanPredicate.value)
+ .append(")");
} else if (attributePredicate.value instanceof StringArrayPredicate) {
StringArrayPredicate stringArrayPredicate = (StringArrayPredicate) attributePredicate.value;
for (int i = 0; i < stringArrayPredicate.predicates.length; i++) {
StringPredicate stringPredicate = stringArrayPredicate.predicates[i];
attributeBuilder.append(stringPredicate.caseSensitive
- ? " and AX.VALUE #> '{value}' ->> " + i
- : " and upper(AX.VALUE #> '{value}' ->> " + i + ")"
+ ? "AX.VALUE #> '{value}' ->> " + i
+ : "upper(AX.VALUE #> '{value}' ->> " + i + ")"
);
attributeBuilder.append(buildMatchFilter(stringPredicate));
final int pos = binders.size() + 1;
@@ -1133,7 +1291,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
}
} else if (attributePredicate.value instanceof DateTimePredicate) {
DateTimePredicate dateTimePredicate = (DateTimePredicate) attributePredicate.value;
- attributeBuilder.append(" and (AX.Value #>> '{value}')::timestamp");
+ attributeBuilder.append("(AX.Value #>> '{value}')::timestamp");
Pair<Long, Long> fromAndTo = AssetQueryPredicate.asFromAndTo(timerService.getCurrentTimeMillis(), dateTimePredicate);
@@ -1147,7 +1305,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
}
} else if (attributePredicate.value instanceof NumberPredicate) {
NumberPredicate numberPredicate = (NumberPredicate) attributePredicate.value;
- attributeBuilder.append(" and (AX.VALUE #>> '{value}')::numeric");
+ attributeBuilder.append("(AX.VALUE #>> '{value}')::numeric");
attributeBuilder.append(buildOperatorFilter(numberPredicate.operator, numberPredicate.negate));
final int pos = binders.size() + 1;
@@ -1171,24 +1329,24 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
} else if (attributePredicate.value instanceof ObjectValueKeyPredicate) {
ObjectValueKeyPredicate keyPredicate = (ObjectValueKeyPredicate) attributePredicate.value;
if (keyPredicate.negated) {
- attributeBuilder.append(" and NOT(AX.VALUE #> '{value}' ?? ? ) ");
+ attributeBuilder.append("NOT(AX.VALUE #> '{value}' ?? ? ) ");
} else {
- attributeBuilder.append(" and AX.VALUE #> '{value}' ?? ? ");
+ attributeBuilder.append("AX.VALUE #> '{value}' ?? ? ");
}
final int pos = binders.size() + 1;
binders.add(st -> st.setString(pos, keyPredicate.key));
} else if (attributePredicate.value instanceof ArrayPredicate) {
ArrayPredicate arrayPredicate = (ArrayPredicate) attributePredicate.value;
- attributeBuilder.append(" and 1=1");
+ attributeBuilder.append("true");
if (arrayPredicate.negated) {
attributeBuilder.append(" and NOT(");
}
if (arrayPredicate.value != null) {
if (arrayPredicate.index != null) {
- attributeBuilder.append(" and AX.VALUE -> ");
+ attributeBuilder.append("AX.VALUE -> ");
attributeBuilder.append(arrayPredicate.index);
} else {
- attributeBuilder.append(" and AX.VALUE");
+ attributeBuilder.append("AX.VALUE");
}
attributeBuilder.append(" @> ?");
final int pos = binders.size() + 1;
@@ -1220,7 +1378,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
} else if (attributePredicate.value instanceof GeofencePredicate) {
if (attributePredicate.value instanceof RadialGeofencePredicate) {
RadialGeofencePredicate location = (RadialGeofencePredicate) attributePredicate.value;
- attributeBuilder.append(" and ST_Distance_Sphere(ST_MakePoint(");
+ attributeBuilder.append("ST_Distance_Sphere(ST_MakePoint(");
attributeBuilder.append("(AX.VALUE #>> '{value,coordinates,0}')::numeric");
attributeBuilder.append(", (AX.VALUE #>> '{value,coordinates,1}')::numeric");
attributeBuilder.append("), ST_MakePoint(");
@@ -1231,7 +1389,9 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
attributeBuilder.append(location.radius);
} else if (attributePredicate.value instanceof RectangularGeofencePredicate) {
RectangularGeofencePredicate location = (RectangularGeofencePredicate) attributePredicate.value;
- attributeBuilder.append(location.negated ? " and NOT" : " and");
+ if (location.negated) {
+ attributeBuilder.append("NOT");
+ }
attributeBuilder.append(" ST_Within(ST_MakePoint(");
attributeBuilder.append("(AX.VALUE #>> '{value,coordinates,0}')::numeric");
attributeBuilder.append(", (AX.VALUE #>> '{value,coordinates,1}')::numeric");
@@ -1246,13 +1406,19 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
attributeBuilder.append(location.latMax);
attributeBuilder.append("))");
}
+ } else if (attributePredicate.value instanceof ValueNotEmptyPredicate) {
+ attributeBuilder.append("AX.VALUE ->> 'value' IS NOT NULL");
+ } else if (attributePredicate.value instanceof ValueEmptyPredicate) {
+ attributeBuilder.append("AX.VALUE ->> 'value' IS NULL");
+ } else {
+ throw new UnsupportedOperationException("Attribute value predicate is not supported: " + attributePredicate.value);
}
}
return attributeBuilder.toString();
}
- protected String buildOperatorFilter(BaseAssetQuery.Operator operator, boolean negate) {
+ protected String buildOperatorFilter(AssetQuery.Operator operator, boolean negate) {
switch (operator) {
case EQUALS:
if (negate) {
@@ -1306,56 +1472,60 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
}
}
- protected Asset mapResultTuple(BaseAssetQuery query, ResultSet rs) throws SQLException {
- switch (query.select.include) {
- case ONLY_ID_AND_NAME:
- case ONLY_ID_AND_NAME_AND_ATTRIBUTES:
- case ONLY_ID_AND_NAME_AND_ATTRIBUTE_NAMES:
- Asset asset = new Asset();
- asset.setId(rs.getString("ID"));
- asset.setType(rs.getString("ASSET_TYPE"));
- asset.setName(rs.getString("NAME"));
- asset.setAccessPublicRead(rs.getBoolean("ACCESS_PUBLIC_READ"));
- if (query.select.include != AssetQuery.Include.ONLY_ID_AND_NAME) {
- if (rs.getString("ATTRIBUTES") != null) {
- asset.setAttributes(Values.instance().<ObjectValue>parse(rs.getString("ATTRIBUTES")).orElse(null));
- }
- }
- return asset;
- default:
- Array path = rs.getArray("PATH");
- String attributes = rs.getString("ATTRIBUTES");
- return new Asset(
- rs.getString("ID"), rs.getLong("OBJ_VERSION"), rs.getTimestamp("CREATED_ON"), rs.getString("NAME"),
- rs.getString("ASSET_TYPE"), rs.getBoolean("ACCESS_PUBLIC_READ"),
- rs.getString("PARENT_ID"), rs.getString("PARENT_NAME"), rs.getString("PARENT_TYPE"),
- rs.getString("REALM"),
- path != null ? (String[]) path.getArray() : null,
- attributes != null && attributes.length() > 0 ? Values.instance().<ObjectValue>parse(attributes).orElse(
- null)
- : null);
+ protected Asset mapResultTuple(AssetQuery query, ResultSet rs) throws SQLException {
+ Asset asset = new Asset();
+ asset.setId(rs.getString("ID"));
+ asset.setType(rs.getString("ASSET_TYPE"));
+ asset.setName(rs.getString("NAME"));
+ asset.setVersion(rs.getLong("OBJ_VERSION"));
+ asset.setCreatedOn(rs.getTimestamp("CREATED_ON"));
+ asset.setAccessPublicRead(rs.getBoolean("ACCESS_PUBLIC_READ"));
+
+ if (!query.select.excludeParentInfo) {
+ asset.setParentId(rs.getString("PARENT_ID"));
+ asset.setParentName(rs.getString("PARENT_NAME"));
+ asset.setParentType(rs.getString("PARENT_TYPE"));
}
+
+ if (!query.select.excludeRealm) {
+ asset.setRealm(rs.getString("REALM"));
+ }
+
+ if (!query.select.excludeAttributes) {
+ if (rs.getString("ATTRIBUTES") != null) {
+ asset.setAttributes(Values.instance().<ObjectValue>parse(rs.getString("ATTRIBUTES")).orElse(null));
+ }
+ }
+
+ if (!query.select.excludePath) {
+ Array path = rs.getArray("PATH");
+ if (path != null) {
+ asset.setPath((String[]) path.getArray());
+ }
+ }
+
+ return asset;
}
public boolean storeAttributeValue(EntityManager em, String assetId, String attributeName, Value value, String timestamp) {
return em.unwrap(Session.class).doReturningWork(connection -> {
String update =
- "update ASSET" +
- " set ATTRIBUTES = jsonb_set(jsonb_set(ATTRIBUTES, ?, ?, true), ?, ?, true)" +
- " where ID = ? and ATTRIBUTES -> ? is not null";
+ "update ASSET" +
+ " set ATTRIBUTES = jsonb_set(jsonb_set(ATTRIBUTES, ?, ?, true), ?, ?, true)" +
+ " where ID = ? and ATTRIBUTES -> ? is not null";
try (PreparedStatement statement = connection.prepareStatement(update)) {
// Bind the value (and check we don't have a SQL injection hole in attribute name!)
if (!AssetAttribute.ATTRIBUTE_NAME_VALIDATOR.test(attributeName)) {
LOG.fine(
- "Invalid attribute name (must match '" + AssetAttribute.ATTRIBUTE_NAME_PATTERN + "'): " + attributeName
+ "Invalid attribute name (must match '" + AssetAttribute.ATTRIBUTE_NAME_PATTERN + "'): " + attributeName
);
return false;
}
Array attributeValuePath = connection.createArrayOf(
- "text",
- new String[]{attributeName, "value"}
+ "text",
+ new String[]{attributeName, "value"}
);
statement.setArray(1, attributeValuePath);
@@ -1367,8 +1537,8 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
// Bind the value timestamp
Array attributeValueTimestampPath = connection.createArrayOf(
- "text",
- new String[]{attributeName, "valueTimestamp"}
+ "text",
+ new String[]{attributeName, "valueTimestamp"}
);
statement.setArray(3, attributeValueTimestampPath);
PGobject pgJsonValueTimestamp = new PGobject();
@@ -1382,9 +1552,9 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
int updatedRows = statement.executeUpdate();
LOG.fine("Stored asset '" + assetId
- + "' attribute '" + attributeName
- + "' (affected rows: " + updatedRows + ") value: "
- + (value != null ? value.toJson() : "null"));
+ + "' attribute '" + attributeName
+ + "' (affected rows: " + updatedRows + ") value: "
+ + (value != null ? value.toJson() : "null"));
return updatedRows == 1;
}
});
@@ -1396,38 +1566,38 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
switch (persistenceEvent.getCause()) {
case CREATE:
// Fully load the asset (excluding attributes)
- Asset loadedAsset = find(new AssetQuery().select(new Select(ALL_EXCEPT_ATTRIBUTES)).id(asset.getId()));
+ Asset loadedAsset = find(new AssetQuery().select(Select.selectAll().excludeAttributes(true)).ids(asset.getId()));
clientEventService.publishEvent(
- new AssetEvent(AssetEvent.Cause.CREATE, loadedAsset, null)
+ new AssetEvent(AssetEvent.Cause.CREATE, loadedAsset, null)
);
clientEventService.publishEvent(
- new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(), asset.getRealm(), asset.getId())
+ new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(), asset.getRealm(), asset.getId())
);
if (asset.getParentId() != null) {
// Child asset created
clientEventService.publishEvent(
- new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(),
- asset.getRealm(),
- asset.getParentId(),
- true)
+ new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(),
+ asset.getRealm(),
+ asset.getParentId(),
+ true)
);
} else {
// Child asset created (root asset)
clientEventService.publishEvent(
- new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(), asset.getRealm(), true)
+ new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(), asset.getRealm(), true)
);
}
// Raise attribute event for each attribute
asset.getAttributesStream().forEach(newAttribute ->
- clientEventService.publishEvent(
- new AttributeEvent(asset.getId(),
- newAttribute.getNameOrThrow(),
- newAttribute.getValue().orElse(null),
- newAttribute.getValueTimestamp().orElse(timerService.getCurrentTimeMillis()))
- ));
+ clientEventService.publishEvent(
+ new AttributeEvent(asset.getId(),
+ newAttribute.getNameOrThrow(),
+ newAttribute.getValue().orElse(null),
+ newAttribute.getValueTimestamp().orElse(timerService.getCurrentTimeMillis()))
+ ));
break;
case UPDATE:
@@ -1442,10 +1612,10 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
}).toArray(String[]::new);
// Fully load the asset (excluding attributes)
- loadedAsset = find(new AssetQuery().select(new Select(ALL_EXCEPT_ATTRIBUTES)).id(asset.getId()));
+ loadedAsset = find(new AssetQuery().select(Select.selectAll().excludeAttributes(true)).ids(asset.getId()));
clientEventService.publishEvent(
- new AssetEvent(AssetEvent.Cause.UPDATE, loadedAsset, updatedProperties)
+ new AssetEvent(AssetEvent.Cause.UPDATE, loadedAsset, updatedProperties)
);
// Did the name change?
@@ -1453,9 +1623,9 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
String currentName = persistenceEvent.getCurrentState("name");
if (!Objects.equals(previousName, currentName)) {
clientEventService.publishEvent(
- new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(),
- asset.getRealm(),
- asset.getId())
+ new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(),
+ asset.getRealm(),
+ asset.getId())
);
break;
}
@@ -1465,9 +1635,9 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
String currentParentId = persistenceEvent.getCurrentState("parentId");
if (!Objects.equals(previousParentId, currentParentId)) {
clientEventService.publishEvent(
- new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(),
- asset.getRealm(),
- asset.getId())
+ new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(),
+ asset.getRealm(),
+ asset.getId())
);
break;
}
@@ -1477,54 +1647,54 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
String currentRealm = persistenceEvent.getCurrentState("realm");
if (!Objects.equals(previousRealm, currentRealm)) {
clientEventService.publishEvent(
- new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(),
- asset.getRealm(),
- asset.getId())
+ new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(),
+ asset.getRealm(),
+ asset.getId())
);
break;
}
// Did any attributes change if so raise attribute events on the event bus
List<AssetAttribute> oldAttributes = attributesFromJson(persistenceEvent.getPreviousState("attributes"),
- asset.getId()).collect(Collectors.toList());
+ asset.getId()).collect(Collectors.toList());
List<AssetAttribute> newAttributes = attributesFromJson(persistenceEvent.getCurrentState(
- "attributes"), asset.getId()).collect(Collectors.toList());
+ "attributes"), asset.getId()).collect(Collectors.toList());
// Get removed attributes and raise an attribute event with deleted flag in attribute state
getAddedAttributes(newAttributes, oldAttributes).forEach(obsoleteAttribute ->
- clientEventService.publishEvent(
- new AttributeEvent(asset.getId(), obsoleteAttribute.getNameOrThrow(), true)
- ));
+ clientEventService.publishEvent(
+ new AttributeEvent(asset.getId(), obsoleteAttribute.getNameOrThrow(), true)
+ ));
// Get new or modified attributes
getAddedOrModifiedAttributes(oldAttributes,
- newAttributes)
- .forEach(newOrModifiedAttribute ->
- clientEventService.publishEvent(
- new AttributeEvent(
- asset.getId(),
- newOrModifiedAttribute.getNameOrThrow(),
- newOrModifiedAttribute.getValue().orElse(null),
- newOrModifiedAttribute.getValueTimestamp().orElse(timerService.getCurrentTimeMillis()))
- ));
+ newAttributes)
+ .forEach(newOrModifiedAttribute ->
+ clientEventService.publishEvent(
+ new AttributeEvent(
+ asset.getId(),
+ newOrModifiedAttribute.getNameOrThrow(),
+ newOrModifiedAttribute.getValue().orElse(null),
+ newOrModifiedAttribute.getValueTimestamp().orElse(timerService.getCurrentTimeMillis()))
+ ));
break;
case DELETE:
clientEventService.publishEvent(
- new AssetEvent(AssetEvent.Cause.DELETE, asset, null)
+ new AssetEvent(AssetEvent.Cause.DELETE, asset, null)
);
clientEventService.publishEvent(
- new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(), asset.getRealm(), asset.getId())
+ new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(), asset.getRealm(), asset.getId())
);
// Raise attribute event with deleted flag for each attribute
attributesFromJson(persistenceEvent.getPreviousState("attributes"), asset.getId())
- .forEach(obsoleteAttribute ->
- clientEventService.publishEvent(
- new AttributeEvent(asset.getId(), obsoleteAttribute.getNameOrThrow(), true)
- ));
+ .forEach(obsoleteAttribute ->
+ clientEventService.publishEvent(
+ new AttributeEvent(asset.getId(), obsoleteAttribute.getNameOrThrow(), true)
+ ));
break;
}
@@ -1535,23 +1705,23 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
// Client may want to read a subset or all attributes of the asset
AttributeEvent[] events = asset.getAttributesStream()
- .filter(attribute -> names.isEmpty() || attribute.getName().filter(names::contains).isPresent())
- .map(AssetAttribute::getStateEvent)
- .filter(Optional::isPresent)
- .map(Optional::get)
- .toArray(AttributeEvent[]::new);
+ .filter(attribute -> names.isEmpty() || attribute.getName().filter(names::contains).isPresent())
+ .map(AssetAttribute::getStateEvent)
+ .filter(Optional::isPresent)
+ .map(Optional::get)
+ .toArray(AttributeEvent[]::new);
TriggeredEventSubscription triggeredEventSubscription = new TriggeredEventSubscription(events, subscriptionId);
clientEventService.sendToSession(sessionKey, triggeredEventSubscription);
}
protected void replyWithAssetEvent(String sessionKey, String subscriptionId, Asset asset) {
- AssetEvent event = new AssetEvent(AssetEvent.Cause.READ,asset, null);
- TriggeredEventSubscription triggeredEventSubscription = new TriggeredEventSubscription(new AssetEvent[] {event}, subscriptionId);
+ AssetEvent event = new AssetEvent(AssetEvent.Cause.READ, asset, null);
+ TriggeredEventSubscription triggeredEventSubscription = new TriggeredEventSubscription(new AssetEvent[]{event}, subscriptionId);
clientEventService.sendToSession(sessionKey, triggeredEventSubscription);
}
public String toString() {
return getClass().getSimpleName() + "{" +
- '}';
+ '}';
}
}
\ No newline at end of file
diff --git a/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointService.java b/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointService.java
index e4df5b9a8..e97c3bb88 100644
--- a/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointService.java
+++ b/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointService.java
@@ -22,7 +22,6 @@ import org.openremote.model.datapoint.Datapoint;
import org.openremote.model.datapoint.DatapointInterval;
import org.openremote.model.datapoint.NumberDatapoint;
import org.openremote.model.query.AssetQuery;
-import org.openremote.model.query.BaseAssetQuery;
import org.openremote.model.query.filter.AttributeMetaPredicate;
import org.openremote.model.value.Values;
import org.postgresql.util.PGInterval;
@@ -296,7 +295,7 @@ public class AssetDatapointService implements ContainerService, AssetUpdateProce
.attributeMeta(
new AttributeMetaPredicate(MetaItemType.DATA_POINTS_MAX_AGE_DAYS),
new AttributeMetaPredicate(MetaItemType.STORE_DATA_POINTS))
- .select(new BaseAssetQuery.Select(BaseAssetQuery.Include.ONLY_ID_AND_NAME_AND_ATTRIBUTES)));
+ .select(AssetQuery.Select.selectExcludePathAndParentAndRealm()));
List<AssetAttribute> attributes = assets.stream()
.map(asset -> asset
diff --git a/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.java b/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.java
index d946226e4..295945256 100644
--- a/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.java
+++ b/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.java
@@ -31,7 +31,6 @@ import org.openremote.model.notification.EmailNotificationMessage;
import org.openremote.model.notification.Notification;
import org.openremote.model.notification.NotificationSendResult;
import org.openremote.model.query.AssetQuery;
-import org.openremote.model.query.BaseAssetQuery;
import org.openremote.model.query.UserQuery;
import org.openremote.model.query.filter.*;
import org.openremote.model.security.User;
@@ -52,7 +51,6 @@ import java.util.stream.Collectors;
import static org.openremote.container.util.MapAccess.getBoolean;
import static org.openremote.container.util.MapAccess.getInteger;
import static org.openremote.model.Constants.*;
-import static org.openremote.model.query.BaseAssetQuery.Include.ONLY_ID_AND_NAME_AND_ATTRIBUTES;
public class EmailNotificationHandler implements NotificationHandler {
@@ -183,11 +181,9 @@ public class EmailNotificationHandler implements NotificationHandler {
// Find descendant assets with email attribute
List<Asset> assets = assetStorageService.findAll(
new AssetQuery()
- .select(new BaseAssetQuery.Select(
- ONLY_ID_AND_NAME_AND_ATTRIBUTES,
- false,
- AttributeType.EMAIL.getAttributeName()))
- .path(new PathPredicate(targetId))
+ .select(AssetQuery.Select.selectExcludePathAndParentAndRealm()
+ .attributes(AttributeType.EMAIL.getAttributeName()))
+ .paths(new PathPredicate(targetId))
.attributes(new AttributePredicate(
new StringPredicate(AttributeType.EMAIL.getAttributeName()),
new ValueNotEmptyPredicate())));
diff --git a/manager/src/main/java/org/openremote/manager/notification/NotificationResourceImpl.java b/manager/src/main/java/org/openremote/manager/notification/NotificationResourceImpl.java
index 29fea0c50..6097fd92c 100644
--- a/manager/src/main/java/org/openremote/manager/notification/NotificationResourceImpl.java
+++ b/manager/src/main/java/org/openremote/manager/notification/NotificationResourceImpl.java
@@ -29,7 +29,7 @@ import org.openremote.model.http.RequestParams;
import org.openremote.model.notification.Notification;
import org.openremote.model.notification.NotificationResource;
import org.openremote.model.notification.SentNotification;
-import org.openremote.model.query.BaseAssetQuery;
+import org.openremote.model.query.AssetQuery;
import org.openremote.model.value.Value;
import javax.ws.rs.WebApplicationException;
@@ -178,7 +178,7 @@ public class NotificationResourceImpl extends WebResource implements Notificatio
}
// Check asset is public read amd not linked to any users
- Asset asset = assetStorageService.find(sentNotification.getTargetId(), false, BaseAssetQuery.Access.PUBLIC_READ);
+ Asset asset = assetStorageService.find(sentNotification.getTargetId(), false, AssetQuery.Access.PUBLIC);
if (asset == null) {
LOG.fine("DENIED: Anonymous request to update a notification sent to an asset that doesn't exist or isn't public");
throw new WebApplicationException("Anonymous request can only update public assets not linked to a user", FORBIDDEN);
diff --git a/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java b/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java
index bbf8b134c..3c1cd6ce4 100644
--- a/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java
+++ b/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java
@@ -40,7 +40,6 @@ import org.openremote.model.notification.Notification;
import org.openremote.model.notification.NotificationSendResult;
import org.openremote.model.notification.PushNotificationMessage;
import org.openremote.model.query.AssetQuery;
-import org.openremote.model.query.BaseAssetQuery;
import org.openremote.model.query.filter.ObjectValueKeyPredicate;
import org.openremote.model.query.filter.PathPredicate;
import org.openremote.model.query.filter.TenantPredicate;
@@ -59,8 +58,6 @@ import static org.openremote.container.persistence.PersistenceEvent.*;
import static org.openremote.model.asset.AssetType.CONSOLE;
import static org.openremote.model.notification.PushNotificationMessage.TargetType.DEVICE;
import static org.openremote.model.notification.PushNotificationMessage.TargetType.TOPIC;
-import static org.openremote.model.query.BaseAssetQuery.Include.ONLY_ID_AND_NAME;
-import static org.openremote.model.query.BaseAssetQuery.Include.ONLY_ID_AND_NAME_AND_ATTRIBUTES;
public class PushNotificationHandler extends RouteBuilder implements NotificationHandler {
@@ -124,10 +121,9 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio
// Find all console assets that use this adapter
assetStorageService.findAll(
new AssetQuery()
- .select(new BaseAssetQuery.Select(BaseAssetQuery.Include.ALL_EXCEPT_PATH,
- false,
- AttributeType.CONSOLE_PROVIDERS.getAttributeName()))
- .type(CONSOLE)
+ .select(AssetQuery.Select.selectAll().excludePath(true)
+ .attributes(AttributeType.CONSOLE_PROVIDERS.getAttributeName()))
+ .types(CONSOLE)
.attributeValue(AttributeType.CONSOLE_PROVIDERS.getAttributeName(),
new ObjectValueKeyPredicate("push")))
.stream()
@@ -182,14 +178,14 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio
// Check if message is going to a topic if so then filter consoles subscribed to that topic
PushNotificationMessage pushMessage = (PushNotificationMessage) message;
- BaseAssetQuery.Select select;
+ AssetQuery.Select select;
boolean forTopic = pushMessage.getTargetType() == TOPIC;
List<Asset> mappedConsoles;
if (forTopic) {
- select = new BaseAssetQuery.Select(ONLY_ID_AND_NAME_AND_ATTRIBUTES, false, AttributeType.CONSOLE_PROVIDERS.getAttributeName());
+ select = AssetQuery.Select.selectExcludePathAndParentAndRealm().attributes(AttributeType.CONSOLE_PROVIDERS.getAttributeName());
} else {
- select = new BaseAssetQuery.Select(ONLY_ID_AND_NAME);
+ select = AssetQuery.Select.selectExcludeAll();
}
switch (targetType) {
@@ -200,7 +196,7 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio
new AssetQuery()
.select(select)
.tenant(new TenantPredicate(targetId))
- .type(AssetType.CONSOLE)
+ .types(AssetType.CONSOLE)
.attributeValue(AttributeType.CONSOLE_PROVIDERS.getAttributeName(),
new ObjectValueKeyPredicate(PushNotificationMessage.TYPE))
);
@@ -220,17 +216,17 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio
case USER:
// Get all console assets linked to the specified user
- List<String> ids = assetStorageService.findUserAssets(null, targetId, null)
+ String[] ids = assetStorageService.findUserAssets(null, targetId, null)
.stream()
- .map(userAsset -> userAsset.getId().getAssetId()).collect(Collectors.toList());
+ .map(userAsset -> userAsset.getId().getAssetId()).toArray(String[]::new);
- if (!ids.isEmpty()) {
+ if (ids.length > 0) {
mappedConsoles = assetStorageService.findAll(
new AssetQuery()
.select(select)
.ids(ids)
- .type(AssetType.CONSOLE)
+ .types(AssetType.CONSOLE)
.attributeValue(AttributeType.CONSOLE_PROVIDERS.getAttributeName(),
new ObjectValueKeyPredicate(PushNotificationMessage.TYPE))
);
@@ -254,8 +250,8 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio
mappedConsoles = assetStorageService.findAll(
new AssetQuery()
.select(select)
- .path(new PathPredicate(targetId))
- .type(AssetType.CONSOLE)
+ .paths(new PathPredicate(targetId))
+ .types(AssetType.CONSOLE)
.attributeValue(AttributeType.CONSOLE_PROVIDERS.getAttributeName(),
new ObjectValueKeyPredicate(PushNotificationMessage.TYPE))
);
diff --git a/manager/src/main/java/org/openremote/manager/rules/AssetQueryPredicate.java b/manager/src/main/java/org/openremote/manager/rules/AssetQueryPredicate.java
index deafd8d85..da7f6d512 100644
--- a/manager/src/main/java/org/openremote/manager/rules/AssetQueryPredicate.java
+++ b/manager/src/main/java/org/openremote/manager/rules/AssetQueryPredicate.java
@@ -27,13 +27,11 @@ import org.openremote.manager.asset.AssetStorageService;
import org.openremote.model.attribute.Meta;
import org.openremote.model.attribute.MetaItem;
import org.openremote.model.geo.GeoJSONPoint;
-import org.openremote.model.query.BaseAssetQuery;
-import org.openremote.model.query.BaseAssetQuery.NumberType;
-import org.openremote.model.query.NewAssetQuery;
+import org.openremote.model.query.AssetQuery;
+import org.openremote.model.query.AssetQuery.NumberType;
+import org.openremote.model.query.LogicGroup;
import org.openremote.model.query.filter.*;
import org.openremote.model.rules.AssetState;
-import org.openremote.model.rules.json.LogicGroup;
-import org.openremote.model.rules.json.RuleOperator;
import org.openremote.model.util.Pair;
import org.openremote.model.util.TimeUtil;
import org.openremote.model.value.ArrayValue;
@@ -48,33 +46,15 @@ import java.util.function.Supplier;
import java.util.stream.Collectors;
/**
- * Test an {@link AssetState} with a {@link BaseAssetQuery}.
+ * Test an {@link AssetState} with a {@link AssetQuery}.
*/
public class AssetQueryPredicate implements Predicate<AssetState> {
- final protected NewAssetQuery query;
+ final protected AssetQuery query;
final protected TimerService timerService;
final protected AssetStorageService assetStorageService;
- // TODO: Remove this ctor once asset queries merged
- @SuppressWarnings("unchecked")
- public AssetQueryPredicate(TimerService timerService, AssetStorageService assetStorageService, BaseAssetQuery query) {
- this.timerService = timerService;
- this.assetStorageService = assetStorageService;
- this.query = new NewAssetQuery();
- this.query.ids = query.ids != null ? (String[])query.ids.toArray(new String[0]) : null;
- this.query.names = query.name != null ? new StringPredicate[] {query.name} : null;
- this.query.parents = query.parent != null ? new ParentPredicate[] {query.parent} : null;
- this.query.paths = query.path != null ? new PathPredicate[] {query.path} : null;
- this.query.attributes = query.attribute != null ? new LogicGroup<>(RuleOperator.AND, query.attribute, null) : null;
- this.query.types = query.type != null ? new StringPredicate[] {query.type} : null;
- this.query.userIds = query.userId != null ? new String[] {query.userId} : null;
- this.query.tenant = query.tenant;
- this.query.orderBy = query.orderBy;
- this.query.limit = query.limit;
- }
-
- public AssetQueryPredicate(TimerService timerService, AssetStorageService assetStorageService, NewAssetQuery query) {
+ public AssetQueryPredicate(TimerService timerService, AssetStorageService assetStorageService, AssetQuery query) {
this.timerService = timerService;
this.assetStorageService = assetStorageService;
this.query = query;
@@ -499,7 +479,7 @@ public class AssetQueryPredicate implements Predicate<AssetState> {
return as -> true;
}
- RuleOperator operator = condition.operator == null ? RuleOperator.AND : condition.operator;
+ LogicGroup.Operator operator = condition.operator == null ? LogicGroup.Operator.AND : condition.operator;
List<Predicate<AssetState>> assetStatePredicates = new ArrayList<>();
@@ -530,7 +510,7 @@ public class AssetQueryPredicate implements Predicate<AssetState> {
&& (condition.groups == null || condition.groups.length == 0);
}
- protected static <T> Predicate<T> asPredicate(Collection<Predicate<T>> predicates, RuleOperator operator) {
+ protected static <T> Predicate<T> asPredicate(Collection<Predicate<T>> predicates, LogicGroup.Operator operator) {
return in -> {
boolean matched = false;
@@ -539,13 +519,13 @@ public class AssetQueryPredicate implements Predicate<AssetState> {
if (p.test(in)) {
matched = true;
- if (operator == RuleOperator.OR) {
+ if (operator == LogicGroup.Operator.OR) {
break;
}
} else {
matched = false;
- if (operator == RuleOperator.AND) {
+ if (operator == LogicGroup.Operator.AND) {
break;
}
}
@@ -567,7 +547,7 @@ public class AssetQueryPredicate implements Predicate<AssetState> {
from = ZonedDateTime.parse(dateTimePredicate.value).toInstant().toEpochMilli();
}
- if (dateTimePredicate.operator == BaseAssetQuery.Operator.BETWEEN) {
+ if (dateTimePredicate.operator == AssetQuery.Operator.BETWEEN) {
if (TimeUtil.isTimeDuration(dateTimePredicate.rangeValue)) {
to = currentMillis + TimeUtil.parseTimeDuration(dateTimePredicate.rangeValue);
} else {
diff --git a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java
index f5f7b8bb4..35ffcad89 100644
--- a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java
+++ b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java
@@ -24,15 +24,14 @@ import org.openremote.container.Container;
import org.openremote.container.timer.TimerService;
import org.openremote.manager.asset.AssetStorageService;
import org.openremote.manager.concurrent.ManagerExecutorService;
-import org.openremote.manager.rules.facade.AssetsFacade;
import org.openremote.manager.rules.facade.NotificationsFacade;
import org.openremote.model.asset.Asset;
import org.openremote.model.attribute.Attribute;
+import org.openremote.model.attribute.AttributeRef;
import org.openremote.model.attribute.AttributeValueDescriptor;
import org.openremote.model.notification.Notification;
import org.openremote.model.query.AssetQuery;
-import org.openremote.model.query.BaseAssetQuery;
-import org.openremote.model.query.NewAssetQuery;
+import org.openremote.model.query.LogicGroup;
import org.openremote.model.query.UserQuery;
import org.openremote.model.query.filter.AttributePredicate;
import org.openremote.model.query.filter.DateTimePredicate;
@@ -83,7 +82,7 @@ public class JsonRulesBuilder extends RulesBuilder {
final TimerService timerService;
boolean trackUnmatched;
- BaseAssetQuery.OrderBy orderBy;
+ AssetQuery.OrderBy orderBy;
int limit;
LogicGroup<AttributePredicate> attributePredicates = null;
Collection<Predicate<AssetState>> attributeAndedPredicates = null;
@@ -141,7 +140,7 @@ public class JsonRulesBuilder extends RulesBuilder {
if (attributePredicates != null && attributePredicates.items != null) {
// Note only supports a single level or logic group for attributes (i.e. cannot nest groups)
attributePredicates.groups = null;
- if (attributePredicates.operator == null || attributePredicates.operator == RuleOperator.AND) {
+ if (attributePredicates.operator == null || attributePredicates.operator == LogicGroup.Operator.AND) {
attributeAndedPredicates = Arrays.stream(attributePredicates.items)
.map(attributePredicate -> AssetQueryPredicate.asPredicate(timerService::getCurrentTimeMillis, attributePredicate))
.collect(Collectors.toList());
@@ -160,7 +159,7 @@ public class JsonRulesBuilder extends RulesBuilder {
if (ruleCondition.timer != null) {
unfilteredAssetStates = new HashSet<>(facts.getAssetStates());
} else if (ruleCondition.assets != null) {
- NewAssetQuery query = ruleCondition.assets;
+ AssetQuery query = ruleCondition.assets;
unfilteredAssetStates = facts.matchAssetState(query).collect(Collectors.toSet());
// Use this opportunity to notify RulesFacts about any location predicates
@@ -171,8 +170,7 @@ public class JsonRulesBuilder extends RulesBuilder {
isValid = checkRuleValidity(timerService.getCurrentTimeMillis(), ruleCondition.datetime);
}
if (isValid) {
- List<AttributePredicate> flattenedAttributePredicates = LogicGroup.flatten(Collections.singletonList(attributePredicates));
- facts.storeLocationPredicates(getLocationPredicates(flattenedAttributePredicates));
+ facts.storeLocationPredicates(getLocationPredicates(attributePredicates));
}
}
}
@@ -421,7 +419,6 @@ public class JsonRulesBuilder extends RulesBuilder {
final protected BiConsumer<Runnable, Long> scheduledActionConsumer;
final protected Map<String, RuleEvaluationResult> ruleEvaluationMap = new HashMap<>();
-
public JsonRulesBuilder(TimerService timerService, AssetStorageService assetStorageService, ManagerExecutorService executorService, Assets assetsFacade, Users usersFacade, NotificationsFacade notificationFacade, BiConsumer<Runnable, Long> scheduledActionConsumer) {
this.timerService = timerService;
this.assetStorageService = assetStorageService;
@@ -436,7 +433,7 @@ public class JsonRulesBuilder extends RulesBuilder {
ruleEvaluationMap.values().forEach(triggerStateMap -> triggerStateMap.conditionStateMap.values().forEach(ruleConditionState -> ruleConditionState.updateUnfilteredAssetStates(facts)));
}
- public JsonRulesBuilder add(Rule rule) {
+ public JsonRulesBuilder add(JsonRule rule) {
if (ruleEvaluationMap.containsKey(rule.name)) {
throw new IllegalArgumentException("Rules must have a unique name within a ruleset, rule name '" + rule.name + "' already used");
@@ -496,7 +493,7 @@ public class JsonRulesBuilder extends RulesBuilder {
}
}
- protected Condition buildLhsCondition(Rule rule, RuleEvaluationResult ruleEvaluationResult) {
+ protected Condition buildLhsCondition(JsonRule rule, RuleEvaluationResult ruleEvaluationResult) {
if (rule.when == null) {
return null;
}
@@ -514,7 +511,7 @@ public class JsonRulesBuilder extends RulesBuilder {
};
}
- protected Action buildRhsAction(Rule rule, RuleEvaluationResult ruleEvaluationResult) {
+ protected Action buildRhsAction(JsonRule rule, RuleEvaluationResult ruleEvaluationResult) {
if (rule.then == null) {
return null;
@@ -541,7 +538,7 @@ public class JsonRulesBuilder extends RulesBuilder {
};
}
- public static void executeRuleActions(Rule rule, RuleAction[] ruleActions, String actionsName, boolean useUnmatched, RulesFacts facts, Map<String, RuleTriggerState> triggerStateMap, Assets assetsFacade, Users usersFacade, NotificationsFacade notificationsFacade, TimerService timerService, AssetStorageService assetStorageService, BiConsumer<Runnable, Long> scheduledActionConsumer) {
+ public static void executeRuleActions(JsonRule rule, RuleAction[] ruleActions, String actionsName, boolean useUnmatched, RulesFacts facts, Map<String, RuleTriggerState> triggerStateMap, Assets assetsFacade, Users usersFacade, NotificationsFacade notificationsFacade, TimerService timerService, AssetStorageService assetStorageService, BiConsumer<Runnable, Long> scheduledActionConsumer) {
// Push rule trigger results into the trigger state for future runs and store timestamps where required
if (triggerStateMap != null) {
@@ -608,31 +605,16 @@ public class JsonRulesBuilder extends RulesBuilder {
}
protected static Collection<String> getUserIds(Users users, UserQuery userQuery) {
- return users.query()
- .tenant(userQuery.tenantPredicate)
- .assetPath(userQuery.pathPredicate)
- .asset(userQuery.assetPredicate)
- .limit(userQuery.limit)
- .getResults();
+ return users.getResults(userQuery).collect(Collectors.toList());
}
- protected static Collection<String> getAssetIds(Assets assets, NewAssetQuery newAssetQuery) {
- AssetQuery query = new AssetQuery();
- newAssetQueryToAssetQuery(newAssetQuery, query);
- return assets.query()
- .ids(query.ids)
- .name(query.name)
- .parent(query.parent)
- .path(query.path)
- .type(query.type)
- .attributes(query.attribute)
- .attributeMeta(query.attributeMeta)
- .stream()
- .map(Asset::getId)
- .collect(Collectors.toList());
+ protected static Collection<String> getAssetIds(Assets assets, AssetQuery assetQuery) {
+ return assets.getResults(assetQuery)
+ .map(Asset::getId)
+ .collect(Collectors.toList());
}
- protected static RuleActionExecution buildRuleActionExecution(Rule rule, RuleAction ruleAction, String actionsName, int index, boolean useUnmatched, RulesFacts facts, Map<String, RuleTriggerState> triggerStateMap, Assets assetsFacade, Users usersFacade, NotificationsFacade notificationsFacade, AssetStorageService assetStorageService) {
+ protected static RuleActionExecution buildRuleActionExecution(JsonRule rule, RuleAction ruleAction, String actionsName, int index, boolean useUnmatched, RulesFacts facts, Map<String, RuleTriggerState> triggerStateMap, Assets assetsFacade, Users usersFacade, NotificationsFacade notificationsFacade, AssetStorageService assetStorageService) {
if (ruleAction instanceof RuleActionNotification) {
RuleActionNotification notificationAction = (RuleActionNotification) ruleAction;
@@ -665,19 +647,22 @@ public class JsonRulesBuilder extends RulesBuilder {
RuleActionWriteAttribute attributeAction = (RuleActionWriteAttribute) ruleAction;
- if (!TextUtil.isNullOrEmpty(attributeAction.attributeName)) {
- Collection<String> ids = getRuleActionTargetIds(ruleAction.target, useUnmatched, triggerStateMap, assetsFacade, usersFacade);
+ if (TextUtil.isNullOrEmpty(attributeAction.attributeName)) {
+ log(Level.WARNING, "Attribute name is missing for rule action: " + rule.name + " '" + actionsName + "' action index " + index);
+ return null;
+ }
- if (ids == null || ids.isEmpty()) {
- log(Level.FINEST, "No targets for write attribute rule action so skipping: " + rule.name + " '" + actionsName + "' action index " + index);
- return null;
- }
+ Collection<String> ids = getRuleActionTargetIds(ruleAction.target, useUnmatched, triggerStateMap, assetsFacade, usersFacade);
- log(Level.FINE, "Writing attribute '" + attributeAction.attributeName + "' for " + ids.size() + " asset(s) for rule action: " + rule.name + " '" + actionsName + "' action index " + index);
- return new RuleActionExecution(() ->
- ids.forEach(id ->
- assetsFacade.dispatch(id, attributeAction.attributeName, attributeAction.value)), 0);
+ if (ids == null || ids.isEmpty()) {
+ log(Level.FINEST, "No targets for write attribute rule action so skipping: " + rule.name + " '" + actionsName + "' action index " + index);
+ return null;
}
+
+ log(Level.FINE, "Writing attribute '" + attributeAction.attributeName + "' for " + ids.size() + " asset(s) for rule action: " + rule.name + " '" + actionsName + "' action index " + index);
+ return new RuleActionExecution(() ->
+ ids.forEach(id ->
+ assetsFacade.dispatch(id, attributeAction.attributeName, attributeAction.value)), 0);
}
if (ruleAction instanceof RuleActionWait) {
@@ -697,160 +682,120 @@ public class JsonRulesBuilder extends RulesBuilder {
RuleActionUpdateAttribute attributeUpdateAction = (RuleActionUpdateAttribute) ruleAction;
- if (!TextUtil.isNullOrEmpty(attributeUpdateAction.attributeName)) {
+ if (TextUtil.isNullOrEmpty(attributeUpdateAction.attributeName)) {
+ log(Level.WARNING, "Attribute name is missing for rule action: " + rule.name + " '" + actionsName + "' action index " + index);
+ return null;
+ }
+
+ List<String> matchingAssetIds;
- Map<String, Pair<ValueType, Value>> assetAttributeValueMap = new HashMap<>();
- NewAssetQuery assetQuery = null;
+ if (ruleAction.target == null || ruleAction.target.assets == null) {
+ if (ruleAction.target != null && ruleAction.target.users != null) {
+ throw new IllegalStateException("Cannot use action type '" + RuleActionUpdateAttribute.class.getSimpleName() + "' with user target");
+ }
+ matchingAssetIds = new ArrayList<>(getRuleActionTargetIds(ruleAction.target, useUnmatched, triggerStateMap, assetsFacade, usersFacade));
+ } else {
+ matchingAssetIds = facts
+ .matchAssetState(ruleAction.target.assets)
+ .map(AssetState::getId)
+ .distinct()
+ .collect(Collectors.toList());
+ }
- if (ruleAction.target == null || ruleAction.target.assets == null) {
- Collection<String> assetIds = getRuleActionTargetIds(ruleAction.target, useUnmatched, triggerStateMap, assetsFacade, usersFacade);
+ if (matchingAssetIds.isEmpty()) {
+ log(Level.WARNING, "No assets matched to apply update attribute action to");
+ return null;
+ }
- // Try and find the current value within the asset states in memory to avoid a DB call when possible
- Collection<String> assetsToLookup = assetIds.stream().filter(assetId -> {
- Optional<AssetState> assetState = facts.getAssetStates()
+ // Look for the current value within the asset state facts (asset/attribute has to be in scope of this rule engine and have a rule state meta item)
+ List<AssetState> matchingAssetStates = matchingAssetIds
+ .stream()
+ .map(assetId ->
+ facts.getAssetStates()
.stream()
.filter(state -> state.getId().equals(assetId) && state.getAttributeName().equals(attributeUpdateAction.attributeName))
- .findFirst();
-
- if (assetState.isPresent()) {
- ValueType valueType = assetState.get().getValue().map(Value::getType).orElseGet(() -> assetState.get().getAttributeValueType() != null ? assetState.get().getAttributeValueType().getValueType() : null);
- if (!(valueType == ValueType.ARRAY || valueType == ValueType.OBJECT)) {
- log(Level.WARNING, "JSON Rule: Rule action target asset '" + assetState.get().getId() + "' cannot determine value type or incompatible value type for attribute: " + attributeUpdateAction.attributeName);
- } else {
- assetAttributeValueMap.put(assetState.get().getId(), new Pair<>(valueType, assetState.get().getValue().orElse(null)));
- }
- return false;
- }
- return true;
- }).collect(Collectors.toList());
+ .findFirst().orElseGet(() -> {
+ log(Level.WARNING, "Failed to find attribute in rule states for attribute update: " + new AttributeRef(assetId, attributeUpdateAction.attributeName));
+ return null;
+ }))
+ .filter(Objects::nonNull)
+ .collect(Collectors.toList());
- if (!assetsToLookup.isEmpty()) {
- assetQuery = new NewAssetQuery();
- assetQuery.ids = assetsToLookup.toArray(new String[0]);
- }
- } else {
- assetQuery = ruleAction.target.assets;
- }
+ if (matchingAssetStates.isEmpty()) {
+ log(Level.WARNING, "No asset states matched to apply update attribute action to");
+ return null;
+ }
- if (assetQuery != null) {
- Stream<Asset> assets = getRuleActionAssets(ruleAction.target, useUnmatched, triggerStateMap, assetsFacade, usersFacade, assetStorageService);
- assets.forEach(asset -> {
- Attribute attribute = asset.getAttribute(attributeUpdateAction.attributeName).orElse(null);
- if (attribute == null) {
- log(Level.WARNING, "JSON Rule: Rule action target asset '" + asset.getId() + "' doesn't have requested attribute: " + attributeUpdateAction.attributeName);
- } else {
- ValueType valueType = attribute.getValue().map(Value::getType).orElseGet(() -> attribute.getType().map(AttributeValueDescriptor::getValueType).orElse(null));
- if (!(valueType == ValueType.ARRAY || valueType == ValueType.OBJECT)) {
- log(Level.WARNING, "JSON Rule: Rule action target asset '" + asset.getId() + "' cannot determine value type or incompatible value type for attribute: " + attributeUpdateAction.attributeName);
- } else {
- assetAttributeValueMap.put(asset.getId(), new Pair<>(valueType, attribute.getValue().orElse(null)));
- }
- }
- });
- }
+ return new RuleActionExecution(() ->
- assetAttributeValueMap.keySet().removeIf(assetId -> {
- Pair<ValueType, Value> valueTypeValue = assetAttributeValueMap.get(assetId);
- return valueTypeValue.value == null
- && (attributeUpdateAction.updateAction == RuleActionUpdateAttribute.UpdateAction.DELETE
- || attributeUpdateAction.updateAction == RuleActionUpdateAttribute.UpdateAction.CLEAR);
- });
+ matchingAssetStates.forEach(assetState -> {
+ ValueType valueType = assetState.getValue().map(Value::getType).orElseGet(() -> assetState.getAttributeValueType() != null ? assetState.getAttributeValueType().getValueType() : null);
+ Value value = assetState.getValue().orElse(null);
- if (assetAttributeValueMap.isEmpty()) {
- return null;
- }
+ if (!(valueType == ValueType.ARRAY || valueType == ValueType.OBJECT)) {
+ log(Level.WARNING, "Rule action target asset cannot determine value type or incompatible value type for attribute: " + assetState);
+ } else {
- log(Level.FINE, "Updating attribute '" + attributeUpdateAction.attributeName + "' for " + assetAttributeValueMap.size() + " asset(s) for rule action: " + rule.name + " '" + actionsName + "' action index " + index);
- return new RuleActionExecution(() ->
- assetAttributeValueMap.forEach((id, valueAndType) -> {
- ValueType valueType = valueAndType.key;
- Value value = valueAndType.value;
-
- switch (attributeUpdateAction.updateAction) {
- case ADD:
- if (valueType.equals(ValueType.ARRAY)) {
- value = value == null ? Values.createArray() : value;
- ((ArrayValue) value).add(attributeUpdateAction.value);
+ switch (attributeUpdateAction.updateAction) {
+ case ADD:
+ if (valueType.equals(ValueType.ARRAY)) {
+ value = value == null ? Values.createArray() : value;
+ ((ArrayValue) value).add(attributeUpdateAction.value);
+ } else {
+ value = value == null ? Values.createObject() : value;
+ ((ObjectValue) value).put(attributeUpdateAction.key, attributeUpdateAction.value);
+ }
+ break;
+ case ADD_OR_REPLACE:
+ case REPLACE:
+ if (valueType.equals(ValueType.ARRAY)) {
+ value = value == null ? Values.createArray() : value;
+ ArrayValue arrayValue = (ArrayValue) value;
+
+ if (attributeUpdateAction.index != null && arrayValue.length() >= attributeUpdateAction.index) {
+ arrayValue.set(attributeUpdateAction.index, attributeUpdateAction.value);
} else {
- value = value == null ? Values.createObject() : value;
- ((ObjectValue) value).put(attributeUpdateAction.key, attributeUpdateAction.value);
+ arrayValue.add(attributeUpdateAction.value);
}
- break;
- case ADD_OR_REPLACE:
- case REPLACE:
- if (valueType.equals(ValueType.ARRAY)) {
- value = value == null ? Values.createArray() : value;
- ArrayValue arrayValue = (ArrayValue) value;
-
- if (attributeUpdateAction.index != null && arrayValue.length() >= attributeUpdateAction.index) {
- arrayValue.set(attributeUpdateAction.index, attributeUpdateAction.value);
- } else {
- arrayValue.add(attributeUpdateAction.value);
- }
+ } else {
+ value = value == null ? Values.createObject() : value;
+ if (!TextUtil.isNullOrEmpty(attributeUpdateAction.key)) {
+ ((ObjectValue) value).put(attributeUpdateAction.key, attributeUpdateAction.value);
} else {
- value = value == null ? Values.createObject() : value;
- if (!TextUtil.isNullOrEmpty(attributeUpdateAction.key)) {
- ((ObjectValue) value).put(attributeUpdateAction.key, attributeUpdateAction.value);
- } else {
- try {
- log(Level.WARNING, "JSON Rule: Rule action missing required 'key': " + Container.JSON.writeValueAsString(attributeUpdateAction));
- } catch (JsonProcessingException ignored) {
- }
+ try {
+ log(Level.WARNING, "JSON Rule: Rule action missing required 'key': " + Container.JSON.writeValueAsString(attributeUpdateAction));
+ } catch (JsonProcessingException ignored) {
}
}
- break;
- case DELETE:
- if (valueType.equals(ValueType.ARRAY)) {
- ((ArrayValue) value).remove(attributeUpdateAction.index);
- } else {
- ((ObjectValue) value).remove(attributeUpdateAction.key);
- }
- break;
- case CLEAR:
- if (valueType.equals(ValueType.ARRAY)) {
- value = Values.createArray();
- } else {
- value = Values.createObject();
}
- break;
- }
+ break;
+ case DELETE:
+ if (valueType.equals(ValueType.ARRAY)) {
+ ((ArrayValue) value).remove(attributeUpdateAction.index);
+ } else {
+ ((ObjectValue) value).remove(attributeUpdateAction.key);
+ }
+ break;
+ case CLEAR:
+ if (valueType.equals(ValueType.ARRAY)) {
+ value = Values.createArray();
+ } else {
+ value = Values.createObject();
+ }
+ break;
+ }
- assetsFacade.dispatch(id, attributeUpdateAction.attributeName, value);
- }), 0);
- }
+ log(Level.FINE, "Updating attribute for rule action: " + rule.name + " '" + actionsName + "' action index " + index + ": " + assetState);
+ assetsFacade.dispatch(assetState.getId(), attributeUpdateAction.attributeName, value);
+ }
+ }),
+ 0);
}
log(Level.FINE, "Unsupported rule action: " + rule.name + " '" + actionsName + "' action index " + index);
return null;
}
- protected static Stream<Asset> getRuleActionAssets(RuleActionTarget target, boolean useUnmatched, Map<String, RuleTriggerState> triggerStateMap, Assets assetsFacade, Users usersFacade, AssetStorageService assetStorageService) {
- AssetsFacade.RestrictedQuery query = assetsFacade.query();
-
- if (target == null || target.assets == null) {
- Collection<String> ids = getRuleActionTargetIds(target, useUnmatched, triggerStateMap, assetsFacade, usersFacade);
- if (ids.isEmpty()) {
- return Stream.empty();
- }
- query.ids(ids);
- } else {
- newAssetQueryToAssetQuery(target.assets, query);
- }
-
- query.select = new BaseAssetQuery.Select(BaseAssetQuery.Include.ONLY_ID_AND_NAME_AND_ATTRIBUTES);
- return assetStorageService.findAll(query).stream();
- }
-
- // TODO: This is a hack until AssetQuery and NewAssetQuery are merged
- protected static void newAssetQueryToAssetQuery(NewAssetQuery newQuery, BaseAssetQuery query) {
- query.ids(newQuery.ids)
- .name(newQuery.names != null && newQuery.names.length > 0 ? newQuery.names[0] : null)
- .parent(newQuery.parents != null && newQuery.parents.length > 0 ? newQuery.parents[0] : null)
- .path(newQuery.paths != null && newQuery.paths.length > 0 ? newQuery.paths[0] : null)
- .type(newQuery.types != null && newQuery.types.length > 0 ? newQuery.types[0] : null)
- .attributes(newQuery.attributes != null && newQuery.attributes.items != null ? newQuery.attributes.items : null);
- }
-
protected static Collection<String> getRuleActionTargetIds(RuleActionTarget target, boolean useUnmatched, Map<String, RuleTriggerState> triggerStateMap, Assets assetsFacade, Users usersFacade) {
if (target != null) {
if (!TextUtil.isNullOrEmpty(target.ruleConditionTag) && triggerStateMap != null) {
@@ -892,9 +837,9 @@ public class JsonRulesBuilder extends RulesBuilder {
return;
}
- RuleOperator operator = ruleConditionGroup.operator == null ? RuleOperator.AND : ruleConditionGroup.operator;
+ LogicGroup.Operator operator = ruleConditionGroup.operator == null ? LogicGroup.Operator.AND : ruleConditionGroup.operator;
- if (operator == RuleOperator.AND) {
+ if (operator == LogicGroup.Operator.AND) {
if (ruleConditionGroup.items != null) {
ruleEvaluationResult.thenMatched = Arrays.stream(ruleConditionGroup.items)
@@ -924,7 +869,7 @@ public class JsonRulesBuilder extends RulesBuilder {
}
}
- if (operator == RuleOperator.OR) {
+ if (operator == LogicGroup.Operator.OR) {
if (ruleConditionGroup.items != null) {
ruleEvaluationResult.thenMatched = Arrays.stream(ruleConditionGroup.items)
.map(ruleCondition -> ruleEvaluationResult.conditionStateMap.get(ruleCondition.tag))
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java b/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java
index c6cafb364..e225750ba 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java
@@ -27,14 +27,10 @@ import org.openremote.manager.asset.AssetStorageService;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeExecuteStatus;
import org.openremote.model.query.AssetQuery;
-import org.openremote.model.query.BaseAssetQuery;
-import org.openremote.model.query.NewAssetQuery;
-import org.openremote.model.query.filter.AttributePredicate;
import org.openremote.model.query.filter.GeofencePredicate;
import org.openremote.model.rules.AssetState;
import org.openremote.model.rules.Assets;
import org.openremote.model.rules.TemporaryFact;
-import org.openremote.model.rules.json.LogicGroup;
import org.openremote.model.util.TimeUtil;
import org.openremote.model.value.Value;
import org.openremote.model.value.Values;
@@ -432,20 +428,10 @@ public class RulesFacts extends Facts implements RuleListener {
return matchAssetState(assetQuery).findFirst();
}
- public Stream<AssetState> matchAssetState(NewAssetQuery assetQuery) {
- if (trackLocationRules && assetQuery.attributes != null) {
- List<AttributePredicate> attributePredicates = LogicGroup.flatten(Collections.singletonList(assetQuery.attributes));
- storeLocationPredicates(getLocationPredicates(attributePredicates));
- }
-
- Predicate<AssetState> p = new AssetQueryPredicate(timerService, assetStorageService, assetQuery);
- return matchAssetState(p);
- }
-
public Stream<AssetState> matchAssetState(AssetQuery assetQuery) {
- if (trackLocationRules && assetQuery.attribute != null && assetQuery.attribute.length > 0) {
- storeLocationPredicates(getLocationPredicates(Arrays.asList(assetQuery.attribute)));
+ if (trackLocationRules && assetQuery.attributes != null) {
+ storeLocationPredicates(getLocationPredicates(assetQuery.attributes));
}
Predicate<AssetState> p = new AssetQueryPredicate(timerService, assetStorageService, assetQuery);
@@ -593,7 +579,7 @@ public class RulesFacts extends Facts implements RuleListener {
return haveLog;
}
- public static Comparator<AssetState> asComparator(BaseAssetQuery.OrderBy orderBy) {
+ public static Comparator<AssetState> asComparator(AssetQuery.OrderBy orderBy) {
Function<AssetState, String> keyExtractor = AssetState::getName;
boolean reverse = orderBy.descending;
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesResourceImpl.java b/manager/src/main/java/org/openremote/manager/rules/RulesResourceImpl.java
index 7bc0a6e15..b363dde3f 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,6 @@ import org.openremote.manager.web.ManagerWebResource;
import org.openremote.model.Constants;
import org.openremote.model.asset.Asset;
import org.openremote.model.query.AssetQuery;
-import org.openremote.model.query.BaseAssetQuery;
import org.openremote.model.asset.UserAsset;
import org.openremote.model.http.RequestParams;
import org.openremote.model.rules.*;
@@ -394,8 +393,8 @@ public class RulesResourceImpl extends ManagerWebResource implements RulesResour
asset = assetStorageService.find(
new AssetQuery()
- .select(new BaseAssetQuery.Select(BaseAssetQuery.Include.ALL_EXCEPT_PATH_AND_ATTRIBUTES))
- .id(assetId));
+ .select(AssetQuery.Select.selectExcludePathAndAttributes())
+ .ids(assetId));
if (asset == null)
return new GeofenceDefinition[0];
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesService.java b/manager/src/main/java/org/openremote/manager/rules/RulesService.java
index 4585d0ac7..c2a72b2c2 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesService.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesService.java
@@ -754,7 +754,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse
protected Stream<Pair<Asset, Stream<AssetAttribute>>> findRuleStateAttributes() {
List<Asset> assets = assetStorageService.findAll(
new AssetQuery()
- .select(new AssetQuery.Select(AssetQuery.Include.ALL))
+ .select(AssetQuery.Select.selectAll())
.attributeMeta(
new AttributeMetaPredicate(
MetaItemType.RULE_STATE,
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java b/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java
index c6ba7fa4e..cf3b2343b 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java
@@ -35,6 +35,7 @@ import org.openremote.container.Container;
import org.openremote.container.timer.TimerService;
import org.openremote.manager.asset.AssetStorageService;
import org.openremote.manager.concurrent.ManagerExecutorService;
+import org.openremote.manager.rules.facade.AssetsFacade;
import org.openremote.manager.rules.facade.NotificationsFacade;
import org.openremote.model.rules.Assets;
import org.openremote.model.rules.Ruleset;
@@ -288,9 +289,9 @@ public class RulesetDeployment {
" \"org.openremote.model.rules\",\n" +
" \"org.openremote.model.query\"\n" +
");\n" +
- "var Match = Java.type(\"org.openremote.model.query.BaseAssetQuery$Match\");\n" +
- "var Operator = Java.type(\"org.openremote.model.query.BaseAssetQuery$Operator\");\n" +
- "var NumberType = Java.type(\"org.openremote.model.query.BaseAssetQuery$NumberType\");\n" +
+ "var Match = Java.type(\"org.openremote.model.query.AssetQuery$Match\");\n" +
+ "var Operator = Java.type(\"org.openremote.model.query.AssetQuery$Operator\");\n" +
+ "var NumberType = Java.type(\"org.openremote.model.query.AssetQuery$NumberType\");\n" +
"var StringPredicate = Java.type(\"org.openremote.model.query.filter.StringPredicate\");\n" +
"var BooleanPredicate = Java.type(\"org.openremote.model.query.filter.BooleanPredicate\");\n" +
"var StringArrayPredicate = Java.type(\"org.openremote.model.query.filter.StringArrayPredicate\");\n" +
diff --git a/manager/src/main/java/org/openremote/manager/rules/facade/AssetsFacade.java b/manager/src/main/java/org/openremote/manager/rules/facade/AssetsFacade.java
index c8b9413df..dd6e04e00 100644
--- a/manager/src/main/java/org/openremote/manager/rules/facade/AssetsFacade.java
+++ b/manager/src/main/java/org/openremote/manager/rules/facade/AssetsFacade.java
@@ -24,14 +24,17 @@ import org.openremote.manager.rules.RulesEngineId;
import org.openremote.model.asset.Asset;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeExecuteStatus;
-import org.openremote.model.query.BaseAssetQuery;
+import org.openremote.model.query.AssetQuery;
import org.openremote.model.query.filter.PathPredicate;
import org.openremote.model.query.filter.TenantPredicate;
-import org.openremote.model.rules.*;
+import org.openremote.model.rules.AssetRuleset;
+import org.openremote.model.rules.Assets;
+import org.openremote.model.rules.Ruleset;
+import org.openremote.model.rules.TenantRuleset;
import org.openremote.model.value.Value;
import org.openremote.model.value.Values;
-import java.util.Collections;
+import java.util.Arrays;
import java.util.function.Consumer;
import java.util.logging.Logger;
import java.util.stream.Stream;
@@ -43,135 +46,96 @@ public class AssetsFacade<T extends Ruleset> extends Assets {
private static final Logger LOG = Logger.getLogger(AssetsFacade.class.getName());
+ protected final RulesEngineId<T> rulesEngineId;
+ protected final AssetStorageService assetStorageService;
+ protected final Consumer<AttributeEvent> eventConsumer;
- public class AssetsRestrictedQueryFacade extends Assets.RestrictedQuery {
+ public AssetsFacade(RulesEngineId<T> rulesEngineId, AssetStorageService assetStorageService, Consumer<AttributeEvent> eventConsumer) {
+ this.rulesEngineId = rulesEngineId;
+ this.assetStorageService = assetStorageService;
+ this.eventConsumer = eventConsumer;
+ }
- public AssetsRestrictedQueryFacade() {
- if (TenantRuleset.class.isAssignableFrom(rulesEngineId.getScope())) {
- tenant = new TenantPredicate(
- rulesEngineId.getRealm().orElseThrow(() -> new IllegalArgumentException("Realm ID missing: " + rulesEngineId))
- );
- }
- if (AssetRuleset.class.isAssignableFrom(rulesEngineId.getScope())) {
- Asset restrictedAsset = assetStorageService.find(
- rulesEngineId.getAssetId().orElseThrow(() -> new IllegalStateException("Asset ID missing: " + rulesEngineId)),
- true);
-
- if (restrictedAsset == null) {
- throw new IllegalStateException("Asset is no longer available: " + rulesEngineId);
- }
- path = new PathPredicate(restrictedAsset.getPath());
+ @Override
+ public Stream<Asset> getResults(AssetQuery assetQuery) {
+
+ if (TenantRuleset.class.isAssignableFrom(rulesEngineId.getScope())) {
+ // Realm is restricted to rules
+ assetQuery.tenant = new TenantPredicate(
+ rulesEngineId.getRealm().orElseThrow(() -> new IllegalArgumentException("Realm missing: " + rulesEngineId))
+ );
+ } else if (AssetRuleset.class.isAssignableFrom(rulesEngineId.getScope())) {
+ // Realm is restricted to assets'
+ assetQuery.tenant = new TenantPredicate(
+ rulesEngineId.getRealm().orElseThrow(() -> new IllegalArgumentException("Realm missing: " + rulesEngineId))
+ );
+
+ Asset restrictedAsset = assetStorageService.find(
+ rulesEngineId.getAssetId().orElseThrow(() -> new IllegalStateException("Asset ID missing: " + rulesEngineId)),
+ true);
+
+ if (restrictedAsset == null) {
+ throw new IllegalStateException("Asset is no longer available: " + rulesEngineId);
}
+ assetQuery.paths(new PathPredicate(restrictedAsset.getPath()));
}
- @Override
- public Assets.RestrictedQuery select(Select select) {
- throw new IllegalArgumentException("Overriding query projection is not allowed in this rules scope");
- }
+ AssetQuery.Select oldValue = assetQuery.select;
- @Override
- public Assets.RestrictedQuery id(String id) {
- throw new IllegalArgumentException("Overriding query restriction is not allowed in this rules scope");
- }
-
- @Override
- public Assets.RestrictedQuery tenant(TenantPredicate tenantPredicate) {
- if (GlobalRuleset.class.isAssignableFrom(rulesEngineId.getScope()))
- return super.tenant(tenantPredicate);
- throw new IllegalArgumentException("Overriding query restriction is not allowed in this rules scope");
- }
-
- @Override
- public Assets.RestrictedQuery userId(String userId) {
- throw new IllegalArgumentException("Overriding query restriction is not allowed in this rules scope");
- }
+ if (assetQuery.select == null)
+ assetQuery.select = new AssetQuery.Select();
- @Override
- public Assets.RestrictedQuery orderBy(OrderBy orderBy) {
- throw new IllegalArgumentException("Overriding query result order is not allowed in this rules scope");
- }
+ assetQuery.select = AssetQuery.Select.selectExcludeAll();
- @Override
- public Asset getResult() {
- // TODO: 'Security' checks must be done here as AssetQuery fields can easily be set by a rule
- return assetStorageService.find(this);
- }
-
- @Override
- public Stream<Asset> stream() {
- // TODO: 'Security' checks must be done here as AssetQuery fields can easily be set by a rule
-
- if (this.select == null)
- this.select = new Select();
- Include oldValue = this.select.include;
- this.select.include = Include.ONLY_ID_AND_NAME;
- try {
- return assetStorageService.findAll(this).stream();
- } finally {
- this.select.include = oldValue;
- }
+ try {
+ return assetStorageService.findAll(assetQuery).stream();
+ } finally {
+ assetQuery.select = oldValue;
}
}
- protected final RulesEngineId<T> rulesEngineId;
- protected final AssetStorageService assetStorageService;
- protected final Consumer<AttributeEvent> eventConsumer;
+ public AssetsFacade<T> dispatch(AttributeEvent... events) {
+ if (events == null || events.length == 0)
+ return this;
- public AssetsFacade(RulesEngineId<T> rulesEngineId, AssetStorageService assetStorageService, Consumer<AttributeEvent> eventConsumer) {
- this.rulesEngineId = rulesEngineId;
- this.assetStorageService = assetStorageService;
- this.eventConsumer = eventConsumer;
- }
+ // Check if the asset ID of every event can be found with the default security of this facade
+ String[] ids = Arrays.stream(events).map(AttributeEvent::getEntityId).toArray(String[]::new);
- @Override
- public Assets.RestrictedQuery query() {
- return new AssetsRestrictedQueryFacade();
- }
+ AssetQuery query = new AssetQuery().ids(ids);
+ long count = this.getResults(query).count();
- @Override
- public Assets dispatch(AttributeEvent... events) {
- if (events == null)
+ if (ids.length != count) {
+ LOG.warning("Access to asset(s) not allowed for this rule engine scope " + rulesEngineId + " for asset IDs: " + String.join(", ", ids));
return this;
+ }
+
for (AttributeEvent event : events) {
- // Check if the asset ID of the event can be found with the default query of this facade
- BaseAssetQuery<RestrictedQuery> checkQuery = query();
- checkQuery.ids = Collections.singletonList(event.getEntityId()); // Set directly on field, as modifying query restrictions is not allowed
- if (assetStorageService.find(checkQuery) == null) {
- LOG.warning("Access to asset not allowed for this rule engine scope " + rulesEngineId + " for event: " + event);
- continue;
- }
eventConsumer.accept(event);
}
return this;
}
- @Override
- public Assets dispatch(String assetId, String attributeName, Value value) {
+ public AssetsFacade<T> dispatch(String assetId, String attributeName, Value value) {
return dispatch(new AttributeEvent(assetId, attributeName, value));
}
- @Override
- public Assets dispatch(String assetId, String attributeName, String value) {
+ public AssetsFacade<T> dispatch(String assetId, String attributeName, String value) {
return dispatch(assetId, attributeName, Values.create(value));
}
- @Override
- public Assets dispatch(String assetId, String attributeName, double value) {
+ public AssetsFacade<T> dispatch(String assetId, String attributeName, double value) {
return dispatch(assetId, attributeName, Values.create(value));
}
- @Override
- public Assets dispatch(String assetId, String attributeName, boolean value) {
+ public AssetsFacade<T> dispatch(String assetId, String attributeName, boolean value) {
return dispatch(assetId, attributeName, Values.create(value));
}
- @Override
- public Assets dispatch(String assetId, String attributeName, AttributeExecuteStatus status) {
+ public AssetsFacade<T> dispatch(String assetId, String attributeName, AttributeExecuteStatus status) {
return dispatch(assetId, attributeName, status.asValue());
}
- @Override
- public Assets dispatch(String assetId, String attributeName) {
+ public AssetsFacade<T> dispatch(String assetId, String attributeName) {
return dispatch(new AttributeEvent(assetId, attributeName));
}
}
diff --git a/manager/src/main/java/org/openremote/manager/rules/facade/UsersFacade.java b/manager/src/main/java/org/openremote/manager/rules/facade/UsersFacade.java
index 857dc54ec..55da88dcc 100644
--- a/manager/src/main/java/org/openremote/manager/rules/facade/UsersFacade.java
+++ b/manager/src/main/java/org/openremote/manager/rules/facade/UsersFacade.java
@@ -23,6 +23,7 @@ import org.openremote.manager.asset.AssetStorageService;
import org.openremote.manager.notification.NotificationService;
import org.openremote.manager.rules.RulesEngineId;
import org.openremote.manager.security.ManagerIdentityService;
+import org.openremote.model.query.UserQuery;
import org.openremote.model.query.filter.PathPredicate;
import org.openremote.model.query.filter.TenantPredicate;
import org.openremote.model.query.filter.UserAssetPredicate;
@@ -45,58 +46,6 @@ public class UsersFacade<T extends Ruleset> extends Users {
protected final NotificationService notificationService;
protected final ManagerIdentityService identityService;
- public class UsersResctrictedQueryFacade extends Users.RestrictedQuery {
-
- @Override
- public Users.RestrictedQuery tenant(TenantPredicate tenantPredicate) {
- if (GlobalRuleset.class.isAssignableFrom(rulesEngineId.getScope()))
- return super.tenant(tenantPredicate);
- throw new IllegalArgumentException("Overriding query restriction is not allowed in this rules scope");
- }
-
- @Override
- public List<String> getResults() {
- return stream().collect(Collectors.toList());
- }
-
- @Override
- public Stream<String> stream() {
- // Do security checks to ensure correct scoping
- // No restriction for global rulesets
- if (TenantRuleset.class.isAssignableFrom(rulesEngineId.getScope())) {
- // Restrict tenant
- tenantPredicate = new TenantPredicate(
- rulesEngineId.getRealm().orElseThrow(() -> new IllegalArgumentException("Realm ID missing: " + rulesEngineId))
- );
- } else if (AssetRuleset.class.isAssignableFrom(rulesEngineId.getScope())) {
- tenantPredicate = null;
- String assetId = rulesEngineId.getAssetId().orElseThrow(() -> new IllegalArgumentException("Asset ID missing: " + rulesEngineId));
-
- // Asset must be this engines asset or a child
- if (assetPredicate != null) {
- if (assetId.equals(assetPredicate.id)) {
- pathPredicate = null;
- } else {
- pathPredicate = new PathPredicate(rulesEngineId.getAssetId().orElseThrow(IllegalArgumentException::new));
- }
- } else if (pathPredicate != null) {
- // Path must contain this engines asset ID
- List<String> path = new ArrayList<>(Arrays.asList(pathPredicate.path));
- if (!path.contains(assetId)) {
- path.add(assetId);
- pathPredicate.path = path.toArray(new String[pathPredicate.path.length + 1]);
- }
- } else {
- // Force scope to this asset
- assetPredicate = new UserAssetPredicate(assetId);
- }
- }
-
- return Arrays.stream(identityService.getIdentityProvider().getUsers(this))
- .map(User::getId);
- }
- }
-
public UsersFacade(RulesEngineId<T> rulesEngineId, AssetStorageService assetStorageService, NotificationService notificationService, ManagerIdentityService identityService) {
this.rulesEngineId = rulesEngineId;
this.assetStorageService = assetStorageService;
@@ -105,7 +54,40 @@ public class UsersFacade<T extends Ruleset> extends Users {
}
@Override
- public Users.RestrictedQuery query() {
- return new UsersResctrictedQueryFacade();
+ public Stream<String> getResults(UserQuery userQuery) {
+ // Do security checks to ensure correct scoping
+ // No restriction for global rulesets
+ if (TenantRuleset.class.isAssignableFrom(rulesEngineId.getScope())) {
+ // Restrict tenant
+ userQuery.tenantPredicate = new TenantPredicate(
+ rulesEngineId.getRealm().orElseThrow(() -> new IllegalArgumentException("Realm ID missing: " + rulesEngineId))
+ );
+ } else if (AssetRuleset.class.isAssignableFrom(rulesEngineId.getScope())) {
+ userQuery.tenantPredicate = null;
+ String assetId = rulesEngineId.getAssetId().orElseThrow(() -> new IllegalArgumentException("Asset ID missing: " + rulesEngineId));
+
+ // Asset must be this engines asset or a child
+ if (userQuery.assetPredicate != null) {
+ if (assetId.equals(userQuery.assetPredicate.id)) {
+ userQuery.pathPredicate = null;
+ } else {
+ userQuery.pathPredicate = new PathPredicate(rulesEngineId.getAssetId().orElseThrow(IllegalArgumentException::new));
+ }
+ } else if (userQuery.pathPredicate != null) {
+ // Path must contain this engines asset ID
+ List<String> path = new ArrayList<>(Arrays.asList(userQuery.pathPredicate.path));
+ if (!path.contains(assetId)) {
+ path.add(assetId);
+ userQuery.pathPredicate.path = path.toArray(new String[userQuery.pathPredicate.path.length + 1]);
+ }
+ } else {
+ // Force scope to this asset
+ userQuery.assetPredicate = new UserAssetPredicate(assetId);
+ }
+ }
+
+ return Arrays.stream(identityService.getIdentityProvider().getUsers(userQuery))
+ .map(User::getId);
}
+
}
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.java
index b4beb5806..5a2c9d6fc 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
@@ -36,7 +36,6 @@ import org.openremote.model.console.ConsoleProvider;
import org.openremote.model.notification.Notification;
import org.openremote.model.notification.PushNotificationMessage;
import org.openremote.model.query.AssetQuery;
-import org.openremote.model.query.BaseAssetQuery;
import org.openremote.model.query.filter.GeofencePredicate;
import org.openremote.model.query.filter.ObjectValueKeyPredicate;
import org.openremote.model.query.filter.RadialGeofencePredicate;
@@ -103,10 +102,9 @@ public class ORConsoleGeofenceAssetAdapter extends RouteBuilder implements Geofe
assetStorageService.findAll(
new AssetQuery()
- .select(new BaseAssetQuery.Select(BaseAssetQuery.Include.ALL_EXCEPT_PATH,
- false,
- AttributeType.CONSOLE_PROVIDERS.getAttributeName()))
- .type(CONSOLE)
+ .select(AssetQuery.Select.selectAll().excludePath(true)
+ .attributes(AttributeType.CONSOLE_PROVIDERS.getAttributeName()))
+ .types(CONSOLE)
.attributeValue(AttributeType.CONSOLE_PROVIDERS.getAttributeName(),
new ObjectValueKeyPredicate("geofence")))
.stream()
diff --git a/manager/src/main/resources/demo/rules/DemoConsoleLocation.groovy b/manager/src/main/resources/demo/rules/DemoConsoleLocation.groovy
index a96003e2f..7a2ec9336 100644
--- a/manager/src/main/resources/demo/rules/DemoConsoleLocation.groovy
+++ b/manager/src/main/resources/demo/rules/DemoConsoleLocation.groovy
@@ -26,7 +26,7 @@ rules.add()
facts ->
def consoleIds = facts.matchAssetState(new AssetQuery()
- .type(AssetType.CONSOLE)
+ .types(AssetType.CONSOLE)
.attributes(new LocationAttributePredicate(
new RadialGeofencePredicate(100, ManagerDemoSetup.SMART_BUILDING_LOCATION.y, ManagerDemoSetup.SMART_BUILDING_LOCATION.x))))
.filter({ !facts.getOptional("welcomeHome" + "_${it.id}").isPresent() })
@@ -63,7 +63,7 @@ rules.add()
facts ->
def consoleIds = facts.matchAssetState(new AssetQuery()
- .type(AssetType.CONSOLE)
+ .types(AssetType.CONSOLE)
.attributeValue(AttributeType.LOCATION.attributeName, new ValueEmptyPredicate()))
.filter({ facts.getOptional("welcomeHome" + "_${it.id}").isPresent() })
.map({ it.id })
diff --git a/manager/src/main/resources/demo/rules/DemoResidenceAllLightsOff.js b/manager/src/main/resources/demo/rules/DemoResidenceAllLightsOff.js
index 52d8eb377..e3af86aa5 100644
--- a/manager/src/main/resources/demo/rules/DemoResidenceAllLightsOff.js
+++ b/manager/src/main/resources/demo/rules/DemoResidenceAllLightsOff.js
@@ -4,7 +4,7 @@ rules = [{
var roomWithLightOn = facts.matchFirstAssetState( // Find asset state
new AssetQuery()
- .type(AssetType.ROOM) // for a room
+ .types(AssetType.ROOM) // for a room
.attributeValue("lightSwitch", true) // where the light switch is on
);
@@ -14,8 +14,8 @@ rules = [{
var residenceWithLightOff = facts.matchFirstAssetEvent( // Find asset event
new AssetQuery()
- .type(AssetType.RESIDENCE) // for a residence
- .id(room.parentId) // that is the parent asset of the room
+ .types(AssetType.RESIDENCE) // for a residence
+ .ids(room.parentId) // that is the parent asset of the room
.attributeValue("allLightsOffSwitch", true) // where the "all lights off" switch has been triggered
);
diff --git a/manager/src/main/resources/demo/rules/DemoResidenceAutoVentilation.groovy b/manager/src/main/resources/demo/rules/DemoResidenceAutoVentilation.groovy
index 90acbba29..4fa46868c 100644
--- a/manager/src/main/resources/demo/rules/DemoResidenceAutoVentilation.groovy
+++ b/manager/src/main/resources/demo/rules/DemoResidenceAutoVentilation.groovy
@@ -3,7 +3,7 @@ package demo.rules
import org.openremote.manager.rules.RulesBuilder
import org.openremote.manager.rules.RulesFacts
import org.openremote.model.query.AssetQuery
-import org.openremote.model.query.BaseAssetQuery.Operator
+import org.openremote.model.query.AssetQuery.Operator
import org.openremote.model.rules.AssetState
import java.util.logging.Logger
@@ -11,7 +11,7 @@ import java.util.stream.Stream
import static org.openremote.model.asset.AssetType.RESIDENCE
import static org.openremote.model.asset.AssetType.ROOM
-import static org.openremote.model.query.BaseAssetQuery.Operator.*
+import static org.openremote.model.query.AssetQuery.Operator.*
Logger LOG = binding.LOG
RulesBuilder rules = binding.rules
@@ -37,14 +37,14 @@ Closure<Stream<AssetState>> residenceWithVentilationAutoMatch =
{ RulesFacts facts, Operator operator, double ventilationLevelThreshold ->
// Any residence where auto ventilation is on
facts.matchAssetState(
- new AssetQuery().type(RESIDENCE).attributeValue("ventilationAuto", true)
+ new AssetQuery().types(RESIDENCE).attributeValue("ventilationAuto", true)
).filter { residenceWithVentilationAuto ->
// and ventilation level is above/below/equal/etc. threshold
if (operator == LESS_THAN) {
// Used to have an implicit "OR NULL" which has now been removed
def isNull = facts.matchFirstAssetState(
- new AssetQuery().id(residenceWithVentilationAuto.id).attributeName("ventilationLevel")
+ new AssetQuery().ids(residenceWithVentilationAuto.id).attributeName("ventilationLevel")
).map {!it.value.isPresent()}.orElse(false)
if (isNull) {
@@ -53,7 +53,7 @@ Closure<Stream<AssetState>> residenceWithVentilationAutoMatch =
}
return facts.matchFirstAssetState(
- new AssetQuery().id(residenceWithVentilationAuto.id)
+ new AssetQuery().ids(residenceWithVentilationAuto.id)
.attributeValue("ventilationLevel", operator, ventilationLevelThreshold)
).isPresent()
}
@@ -63,7 +63,7 @@ Closure<Boolean> roomThresholdMatch =
{ RulesFacts facts, AssetState residence, String attribute, boolean above, double threshold, String timeWindow ->
// Any room of the residence which has a level greater than zero
def roomWithMaxLevel = facts.matchAssetState(
- new AssetQuery().type(ROOM).parent(residence.id).attributeValue(attribute, GREATER_THAN, 0)
+ new AssetQuery().types(ROOM).parents(residence.id).attributeValue(attribute, GREATER_THAN, 0)
).max { roomA, roomB ->
// get the room with the highest level
Double.compare(roomA.valueAsNumber.orElse(0), roomB.valueAsNumber.orElse(0))
@@ -78,7 +78,7 @@ Closure<Boolean> roomThresholdMatch =
// and no level above/below threshold in the time window
facts.matchAssetEvent(
new AssetQuery()
- .id(roomAboveBelowThreshold.id)
+ .ids(roomAboveBelowThreshold.id)
.attributeValue(attribute, above ? LESS_EQUALS : GREATER_THAN, threshold)
).filter(facts.clock.last(timeWindow)).count() == 0
}.isPresent()
diff --git a/manager/src/main/resources/demo/rules/DemoResidenceNotifyAlarmTrigger.groovy b/manager/src/main/resources/demo/rules/DemoResidenceNotifyAlarmTrigger.groovy
index 6de41b7eb..fa63ad78a 100644
--- a/manager/src/main/resources/demo/rules/DemoResidenceNotifyAlarmTrigger.groovy
+++ b/manager/src/main/resources/demo/rules/DemoResidenceNotifyAlarmTrigger.groovy
@@ -8,12 +8,14 @@ import org.openremote.model.notification.PushNotificationAction
import org.openremote.model.notification.PushNotificationButton
import org.openremote.model.query.AssetQuery
import org.openremote.model.notification.PushNotificationMessage
+import org.openremote.model.query.UserQuery
import org.openremote.model.query.filter.UserAssetPredicate
import org.openremote.model.rules.Notifications
import org.openremote.model.rules.Users
import org.openremote.model.value.Values
import java.util.logging.Logger
+import java.util.stream.Collectors
import static org.openremote.model.asset.AssetType.RESIDENCE
import static org.openremote.model.asset.AssetType.ROOM
@@ -45,7 +47,7 @@ rules.add()
.when(
{ facts ->
facts.matchAssetState(
- new AssetQuery().type(RESIDENCE).attributeValue("alarmEnabled", true)
+ new AssetQuery().types(RESIDENCE).attributeValue("alarmEnabled", true)
).filter { residenceWithAlarmEnabled ->
!facts.matchFirst(AlarmTrigger) { alarmTrigger ->
alarmTrigger.residenceId == residenceWithAlarmEnabled.id
@@ -53,8 +55,8 @@ rules.add()
}.map { residenceWithoutAlarmTrigger ->
// Map to Optional<AssetState> of the "first" room in the residence with presence detected
facts.matchFirstAssetState(
- new AssetQuery().type(ROOM)
- .parent(residenceWithoutAlarmTrigger.id)
+ new AssetQuery().types(ROOM)
+ .parents(residenceWithoutAlarmTrigger.id)
.attributeValue("presenceDetected", true)
)
}.filter {
@@ -85,8 +87,8 @@ rules.add()
{ facts ->
facts.matchFirst(AlarmTrigger) { alarmTrigger ->
!facts.matchFirstAssetState(
- new AssetQuery().type(ROOM)
- .parent(alarmTrigger.residenceId)
+ new AssetQuery().types(ROOM)
+ .parents(alarmTrigger.residenceId)
.attributeValue("presenceDetected", true)
).isPresent()
}.map { alarmTrigger ->
@@ -107,8 +109,8 @@ rules.add()
{ facts ->
facts.matchFirst(AlarmTrigger) { alarmTrigger ->
facts.matchFirstAssetState(
- new AssetQuery().type(RESIDENCE)
- .id(alarmTrigger.residenceId)
+ new AssetQuery().types(RESIDENCE)
+ .ids(alarmTrigger.residenceId)
.attributeValue("alarmEnabled", false)
).isPresent()
}.map { alarmTrigger ->
@@ -127,7 +129,7 @@ rules.add()
.when(
{ facts ->
facts.matchAssetState(
- new AssetQuery().type(RESIDENCE).attributeValue("alarmEnabled", true)
+ new AssetQuery().types(RESIDENCE).attributeValue("alarmEnabled", true)
).map { residenceWithAlarmEnabled ->
facts.matchFirst(AlarmTrigger, { alarmTrigger ->
alarmTrigger.residenceId == residenceWithAlarmEnabled.id
@@ -149,10 +151,10 @@ rules.add()
AlarmTrigger alarmTrigger = facts.bound("alarmTrigger")
// Get users linked to this residence
- List<String> userIds = users
- .query()
+ UserQuery query = new UserQuery()
.asset(new UserAssetPredicate(alarmTrigger.residenceId))
- .getResults()
+
+ Collection<String> userIds = users.getResults(query).collect(Collectors.toList())
LOG.info("Alerting users of " + alarmTrigger + ": " + userIds)
@@ -183,7 +185,7 @@ rules.add()
.when(
{ facts ->
facts.matchAssetState(
- new AssetQuery().type(RESIDENCE).attributeValue("alarmEnabled", false)
+ new AssetQuery().types(RESIDENCE).attributeValue("alarmEnabled", false)
).map { residenceWithAlarmEnabled ->
facts.matchFirst(AlertSilence) { alertSilence ->
alertSilence.residenceId == residenceWithAlarmEnabled.id
diff --git a/manager/src/main/resources/demo/rules/DemoResidencePresenceDetection.groovy b/manager/src/main/resources/demo/rules/DemoResidencePresenceDetection.groovy
index 5391be812..909045d0b 100644
--- a/manager/src/main/resources/demo/rules/DemoResidencePresenceDetection.groovy
+++ b/manager/src/main/resources/demo/rules/DemoResidencePresenceDetection.groovy
@@ -18,8 +18,8 @@ import java.util.logging.Logger
import static org.openremote.model.asset.AssetType.RESIDENCE
import static org.openremote.model.asset.AssetType.ROOM
-import static org.openremote.model.query.BaseAssetQuery.Operator.GREATER_THAN
-import static org.openremote.model.query.BaseAssetQuery.Operator.LESS_THAN
+import static org.openremote.model.query.AssetQuery.Operator.GREATER_THAN
+import static org.openremote.model.query.AssetQuery.Operator.LESS_THAN
Logger LOG = binding.LOG
RulesBuilder rules = binding.rules
@@ -30,11 +30,11 @@ rules.add()
{ facts ->
// Any room where the presence detected flag is not set
facts.matchAssetState(
- new AssetQuery().type(ROOM).attributeValue("presenceDetected", false)
+ new AssetQuery().types(ROOM).attributeValue("presenceDetected", false)
).flatMap { roomWithoutPresence ->
// and the motion sensor has been triggered
facts.matchAssetState(
- new AssetQuery().id(roomWithoutPresence.id).attributeValue("motionSensor", GREATER_THAN, 0)
+ new AssetQuery().ids(roomWithoutPresence.id).attributeValue("motionSensor", GREATER_THAN, 0)
)
}.findFirst().map { roomWithMotionSensorTriggered ->
@@ -79,11 +79,11 @@ rules.add()
{ facts ->
// Any room where the presence detected flag is set
facts.matchAssetState(
- new AssetQuery().type(ROOM).attributeValue("presenceDetected", true)
+ new AssetQuery().types(ROOM).attributeValue("presenceDetected", true)
).flatMap { roomWithPresence ->
// and the motion sensor has not been triggered
facts.matchAssetState(
- new AssetQuery().id(roomWithPresence.id).attributeValue("motionSensor", LESS_THAN, 1)
+ new AssetQuery().ids(roomWithPresence.id).attributeValue("motionSensor", LESS_THAN, 1)
)
}.findFirst().map { roomWithoutMotionSensorTriggered ->
@@ -91,11 +91,11 @@ rules.add()
// and there is a CO2 sensor in the room
facts.matchFirstAssetState(
- new AssetQuery().id(roomWithoutMotionSensorTriggered.id).attributeName("co2Level")
+ new AssetQuery().ids(roomWithoutMotionSensorTriggered.id).attributeName("co2Level")
).map { co2Level ->
// and there are no sensor events
facts.matchAssetEvent(
- new AssetQuery().id(roomWithoutMotionSensorTriggered.id).attributeName("co2Level")
+ new AssetQuery().ids(roomWithoutMotionSensorTriggered.id).attributeName("co2Level")
).filter { coLevelFact ->
// with increasing values
coLevelFact.getFact().isValueGreaterThanOldValue()
@@ -118,16 +118,16 @@ rules.add()
{ facts ->
// Any room where the presence detected flag is set
facts.matchAssetState(
- new AssetQuery().type(ROOM).attributeValue("presenceDetected", true)
+ new AssetQuery().types(ROOM).attributeValue("presenceDetected", true)
).flatMap { roomWithPresence ->
// and the motion sensor has been triggered
facts.matchAssetState(
- new AssetQuery().id(roomWithPresence.id)
+ new AssetQuery().ids(roomWithPresence.id)
.attributeValue("motionSensor", GREATER_THAN, 0)
).flatMap { roomWithMotionSensorTriggered ->
// and the last presence detection timestamp is not set or is older than the motion sensor timestamp
facts.matchAssetState(
- new AssetQuery().id(roomWithMotionSensorTriggered.id)
+ new AssetQuery().ids(roomWithMotionSensorTriggered.id)
.attributeName("lastPresenceDetected")
).filter({
!it.value.isPresent() || it.valueAsNumber.get() < roomWithMotionSensorTriggered.timestamp
@@ -154,12 +154,12 @@ rules.add()
{ facts ->
// A room where the presence detected flag is set
facts.matchAssetState(
- new AssetQuery().type(ROOM).attributeValue("presenceDetected", true)
+ new AssetQuery().types(ROOM).attributeValue("presenceDetected", true)
).flatMap { roomWithPresence ->
// and a residence parent where the presence detected flag is not set
facts.matchAssetState(
- new AssetQuery().type(RESIDENCE)
- .id(roomWithPresence.parentId)
+ new AssetQuery().types(RESIDENCE)
+ .ids(roomWithPresence.parentId)
.attributeValue("presenceDetected", false)
)
}.findFirst().map { residenceWithoutPresence ->
@@ -180,11 +180,11 @@ rules.add()
{ facts ->
// A residence where the presence detected flag is set
facts.matchAssetState(
- new AssetQuery().type(RESIDENCE).attributeValue("presenceDetected", true)
+ new AssetQuery().types(RESIDENCE).attributeValue("presenceDetected", true)
).filter { residenceWithPresence ->
// and no room child of that residence has presence
facts.matchAssetState(
- new AssetQuery().type(ROOM).parent(residenceWithPresence.id)
+ new AssetQuery().types(ROOM).parents(residenceWithPresence.id)
.attributeValue("presenceDetected", true)
).count() == 0
}.findFirst().map { residenceWithPresence ->
diff --git a/manager/src/main/resources/demo/rules/DemoResidenceSmartSwitch.groovy b/manager/src/main/resources/demo/rules/DemoResidenceSmartSwitch.groovy
index c9abb751e..3800644b8 100644
--- a/manager/src/main/resources/demo/rules/DemoResidenceSmartSwitch.groovy
+++ b/manager/src/main/resources/demo/rules/DemoResidenceSmartSwitch.groovy
@@ -3,6 +3,8 @@ package demo.rules
import org.openremote.manager.rules.RulesBuilder
import org.openremote.manager.rules.RulesFacts
import org.openremote.model.query.AssetQuery
+import org.openremote.model.query.filter.AttributePredicate
+import org.openremote.model.query.filter.StringPredicate
import org.openremote.model.rules.AssetState
import org.openremote.model.value.Values
@@ -13,7 +15,7 @@ import java.util.logging.Logger
import java.util.stream.Stream
import static org.openremote.model.asset.AssetType.ROOM
-import static org.openremote.model.query.BaseAssetQuery.Match.BEGIN
+import static org.openremote.model.query.AssetQuery.Match.BEGIN
Logger LOG = binding.LOG
RulesBuilder rules = binding.rules
@@ -34,7 +36,7 @@ enum SmartSwitchMode {
Closure<Stream<AssetState>> smartSwitchAttributesMatch = { RulesFacts facts, SmartSwitchAttribute attribute ->
facts.matchAssetState(
- new AssetQuery().type(ROOM).attributeName(BEGIN, "smartSwitch" + attribute.name())
+ new AssetQuery().types(ROOM).attributes(new AttributePredicate(new StringPredicate(BEGIN, "smartSwitch" + attribute.name())))
)
}
@@ -44,7 +46,7 @@ Closure<Character> getSmartSwitchName = { AssetState attribute ->
Closure<Optional<AssetState>> smartSwitchAttributeMatch = { RulesFacts facts, AssetState smartSwitch, SmartSwitchAttribute attribute ->
facts.matchFirstAssetState(
- new AssetQuery().type(ROOM).attributeName("smartSwitch" + attribute.name() + getSmartSwitchName(smartSwitch))
+ new AssetQuery().types(ROOM).attributeName("smartSwitch" + attribute.name() + getSmartSwitchName(smartSwitch))
)
}
diff --git a/manager/src/main/resources/demo/rules/DemoResidenceVacationMode.groovy b/manager/src/main/resources/demo/rules/DemoResidenceVacationMode.groovy
index 5c2e93c40..27826c02e 100644
--- a/manager/src/main/resources/demo/rules/DemoResidenceVacationMode.groovy
+++ b/manager/src/main/resources/demo/rules/DemoResidenceVacationMode.groovy
@@ -3,14 +3,17 @@ package demo.rules
import groovy.transform.ToString
import org.openremote.manager.rules.RulesBuilder
import org.openremote.model.query.AssetQuery
+import org.openremote.model.query.filter.AttributePredicate
+import org.openremote.model.query.filter.StringPredicate
+import org.openremote.model.query.filter.ValueNotEmptyPredicate
import org.openremote.model.rules.AssetState
import org.openremote.model.rules.Assets
import java.util.logging.Logger
import static org.openremote.model.asset.AssetType.RESIDENCE
-import static org.openremote.model.query.BaseAssetQuery.Operator.GREATER_THAN
-import static org.openremote.model.query.BaseAssetQuery.Operator.LESS_EQUALS
+import static org.openremote.model.query.AssetQuery.Operator.GREATER_THAN
+import static org.openremote.model.query.AssetQuery.Operator.LESS_EQUALS
import static org.openremote.model.attribute.AttributeExecuteStatus.REQUEST_START
Logger LOG = binding.LOG
@@ -28,7 +31,7 @@ rules.add()
.when(
{ facts ->
facts.matchAssetState(
- new AssetQuery().type(RESIDENCE)
+ new AssetQuery().types(RESIDENCE)
.attributeValue("vacationUntil", GREATER_THAN, facts.clock.timestamp)
).filter { residenceWithVacationUntil ->
facts.match(VacationMode).noneMatch {
@@ -60,7 +63,7 @@ rules.add()
.when(
{ facts ->
facts.matchAssetState(
- new AssetQuery().type(RESIDENCE)
+ new AssetQuery().types(RESIDENCE)
.attributeValue("vacationUntil", LESS_EQUALS, facts.clock.timestamp)
).filter { residenceWithVacationUntilInPast ->
residenceWithVacationUntilInPast.getValueAsNumber().isPresent()
@@ -87,9 +90,9 @@ rules.add()
{ facts ->
facts.matchFirst(VacationMode) { vacationMode ->
facts.matchFirstAssetState(
- new AssetQuery().type(RESIDENCE)
- .id(vacationMode.residenceId)
- .attributeValue("vacationUntil")
+ new AssetQuery().types(RESIDENCE)
+ .ids(vacationMode.residenceId)
+ .attributes(new AttributePredicate(new StringPredicate("vacationUntil"), new ValueNotEmptyPredicate()))
).map { residence ->
vacationMode.until != residence.valueAsNumber.get()
}.orElse(false)
@@ -111,9 +114,9 @@ rules.add()
{ facts ->
facts.matchFirst(VacationMode) { vacationMode ->
!facts.matchFirstAssetState(
- new AssetQuery().type(RESIDENCE)
- .id(vacationMode.residenceId)
- .attributeValue("vacationUntil")).isPresent()
+ new AssetQuery().types(RESIDENCE)
+ .ids(vacationMode.residenceId)
+ .attributes(new AttributePredicate(new StringPredicate("vacationUntil"), new ValueNotEmptyPredicate()))).isPresent()
}.map { vacationMode ->
facts.bind("vacationMode", vacationMode)
true
diff --git a/manager/src/main/resources/demo/rules/DemoSmartCityCamera.groovy b/manager/src/main/resources/demo/rules/DemoSmartCityCamera.groovy
index 3966e2be8..6178cb8f4 100644
--- a/manager/src/main/resources/demo/rules/DemoSmartCityCamera.groovy
+++ b/manager/src/main/resources/demo/rules/DemoSmartCityCamera.groovy
@@ -3,7 +3,6 @@ package demo.rules
import org.openremote.manager.rules.RulesBuilder
import org.openremote.model.attribute.AttributeEvent
import org.openremote.model.query.AssetQuery
-import org.openremote.model.query.BaseAssetQuery
import org.openremote.model.query.filter.StringPredicate
import org.openremote.model.rules.Assets
import org.openremote.model.rules.Notifications
@@ -25,12 +24,12 @@ rules.add()
facts ->
def totals = facts.matchAssetState(new AssetQuery()
- .name(new StringPredicate(BaseAssetQuery.Match.BEGIN, "Camera"))
+ .names(new StringPredicate(AssetQuery.Match.BEGIN, "Camera"))
.attributeName("cameraCountIn"))
.map(
{
new Tuple(it.id, it.valueAsNumber.orElse(0) - facts.matchFirstAssetState(new AssetQuery()
- .name(new StringPredicate(BaseAssetQuery.Match.BEGIN, "Camera"))
+ .names(new StringPredicate(AssetQuery.Match.BEGIN, "Camera"))
.attributeName("cameraCountOut"))
.map({ it.valueAsNumber.orElse(0) }).orElse(0))
})
@@ -63,18 +62,18 @@ rules.add()
facts ->
def cameraIds = facts.matchAssetState(new AssetQuery()
- .name(new StringPredicate(BaseAssetQuery.Match.BEGIN, "Camera"))
+ .names(new StringPredicate(AssetQuery.Match.BEGIN, "Camera"))
.attributeName("cameraCountTotalAlert"))
.filter(
{
!it.valueAsBoolean.orElse(false) &&
facts.matchFirstAssetState(new AssetQuery()
- .id(it.id)
+ .ids(it.id)
.attributeName("cameraCountTotal"))
.map({ it.valueAsNumber.orElse(-1) })
.orElse(-1) >
facts.matchFirstAssetState(new AssetQuery()
- .id(it.id)
+ .ids(it.id)
.attributeName("cameraCountTotalAlertLevel"))
.map({ it.valueAsNumber.orElse(-1) })
.orElse(-1)
diff --git a/model/src/main/java/org/openremote/model/asset/Asset.java b/model/src/main/java/org/openremote/model/asset/Asset.java
index 30a2fb565..dd479952d 100644
--- a/model/src/main/java/org/openremote/model/asset/Asset.java
+++ b/model/src/main/java/org/openremote/model/asset/Asset.java
@@ -405,6 +405,10 @@ public class Asset implements IdentifiableEntity {
return createdOn;
}
+ public void setCreatedOn(Date createdOn) {
+ this.createdOn = createdOn;
+ }
+
public String getName() {
return name;
}
@@ -508,6 +512,10 @@ public class Asset implements IdentifiableEntity {
return path;
}
+ public void setPath(String[] path) {
+ this.path = path;
+ }
+
/**
* NOTE: This is a transient and optional property, set only in database query results.
* <p>
diff --git a/model/src/main/java/org/openremote/model/interop/Function.java b/model/src/main/java/org/openremote/model/interop/Function.java
index 718c7e2f4..4cd7cdeef 100644
--- a/model/src/main/java/org/openremote/model/interop/Function.java
+++ b/model/src/main/java/org/openremote/model/interop/Function.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2016, OpenRemote Inc.
+ * Copyright 2019, OpenRemote Inc.
*
* See the CONTRIBUTORS.txt file in the distribution for a
* full listing of individual contributors.
@@ -26,3 +26,4 @@ import jsinterop.annotations.JsFunction;
public interface Function<T,U> {
U apply(T object);
}
+
diff --git a/model/src/main/java/org/openremote/model/interop/Promise.java b/model/src/main/java/org/openremote/model/interop/Promise.java
index 3a191de0c..47463c47b 100644
--- a/model/src/main/java/org/openremote/model/interop/Promise.java
+++ b/model/src/main/java/org/openremote/model/interop/Promise.java
@@ -23,6 +23,10 @@ import jsinterop.annotations.JsMethod;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsType;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+import java.util.function.Function;
+
@JsType(isNative = true, namespace = JsPackage.GLOBAL, name = "Promise")
@SuppressWarnings("unchecked")
public class Promise<T,U> {
diff --git a/model/src/main/java/org/openremote/model/query/AssetQuery.java b/model/src/main/java/org/openremote/model/query/AssetQuery.java
index 095869575..e906558fc 100644
--- a/model/src/main/java/org/openremote/model/query/AssetQuery.java
+++ b/model/src/main/java/org/openremote/model/query/AssetQuery.java
@@ -19,11 +19,452 @@
*/
package org.openremote.model.query;
+import org.openremote.model.asset.AssetType;
+import org.openremote.model.asset.CalendarEventConfiguration;
+import org.openremote.model.attribute.MetaItemDescriptor;
+import org.openremote.model.query.filter.*;
+
+import java.util.Arrays;
+
/**
- * This was only done to allow GWT jackson to compile it; don't think GWT jackson
- * likes self referencing generic type parameters but hard to tell as the errors
- * generated are not helpful.
+ * Encapsulate asset query restriction, projection, and ordering of results.
*/
-public class AssetQuery extends BaseAssetQuery<AssetQuery> {
+// TODO: Add AssetQuery support for arbitrary attribute property path amd value (e.g. attributes.consoleProviders.geofence.version == "ORConsole")
+public class AssetQuery {
+
+ public static class Select {
+
+ public String[] attributes;
+ public String[] meta;
+ public boolean excludePath = true;
+ public boolean excludeAttributeMeta = true;
+ public boolean excludeAttributes = true;
+ public boolean excludeAttributeValue = true;
+ public boolean excludeAttributeTimestamp = true;
+ public boolean excludeAttributeType = true;
+ public boolean excludeParentInfo;
+ public boolean excludeRealm;
+
+ public Select() {
+ }
+
+ public static Select selectAll() {
+ return new Select()
+ .excludeAttributes(false)
+ .excludeAttributeMeta(false)
+ .excludeAttributeType(false)
+ .excludeAttributeTimestamp(false)
+ .excludeAttributeValue(false)
+ .excludePath(false)
+ .excludeParentInfo(false)
+ .excludeRealm(false);
+ }
+
+ public static Select selectExcludePathAndParentAndRealm() {
+ return new Select()
+ .excludeAttributes(false)
+ .excludeAttributeMeta(false)
+ .excludeAttributeType(false)
+ .excludeAttributeTimestamp(false)
+ .excludeAttributeValue(false)
+ .excludePath(true)
+ .excludeParentInfo(true)
+ .excludeRealm(true);
+ }
+
+ public static Select selectExcludePathAndAttributes() {
+ return new Select()
+ .excludePath(true)
+ .excludeAttributes(true);
+ }
+
+ public static Select selectExcludeAll() {
+ return new Select()
+ .excludeAttributes(true)
+ .excludeAttributeMeta(true)
+ .excludeAttributeType(true)
+ .excludeAttributeValue(true)
+ .excludeAttributeTimestamp(true)
+ .excludePath(true)
+ .excludeParentInfo(true)
+ .excludeRealm(true);
+ }
+
+ public Select attributes(String... attributeNames) {
+ this.attributes = attributeNames;
+ return this;
+ }
+
+ public Select meta(String... metaUrns) {
+ this.meta = metaUrns;
+ return this;
+ }
+
+ public Select meta(MetaItemDescriptor... meta) {
+ if (meta == null) {
+ this.meta = null;
+ return this;
+ }
+
+ return meta(Arrays.stream(meta).map(MetaItemDescriptor::getUrn).toArray(String[]::new));
+ }
+
+ public Select excludeAttributes(boolean exclude) {
+ this.excludeAttributes = exclude;
+ return this;
+ }
+
+ public Select excludeAttributeMeta(boolean exclude) {
+ this.excludeAttributeMeta = exclude;
+ return this;
+ }
+
+ public Select excludeAttributeType(boolean exclude) {
+ this.excludeAttributeType = exclude;
+ return this;
+ }
+
+ public Select excludeAttributeValue(boolean exclude) {
+ this.excludeAttributeValue = exclude;
+ return this;
+ }
+
+ public Select excludeAttributeTimestamp(boolean exclude) {
+ this.excludeAttributeTimestamp = exclude;
+ return this;
+ }
+
+ public Select excludePath(boolean exclude) {
+ this.excludePath = exclude;
+ return this;
+ }
+
+ public Select excludeParentInfo(boolean exclude) {
+ this.excludeParentInfo = exclude;
+ return this;
+ }
+
+ public Select excludeRealm(boolean exclude) {
+ this.excludeRealm = exclude;
+ return this;
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ ", excludeAttributes=" + excludeAttributes +
+ ", excludeAttributeMeta=" + excludeAttributeMeta +
+ ", excludeAttributeValue=" + excludeAttributeValue +
+ ", excludeAttributeTimestamp=" + excludeAttributeTimestamp +
+ ", excludeAttributeType=" + excludeAttributeType +
+ ", excludePath=" + excludePath +
+ ", excludeParentInfo=" + excludeParentInfo +
+ ", excludeRealm=" + excludeRealm +
+ ", attributeNames=" + Arrays.toString(attributes) +
+ '}';
+ }
+ }
+
+ public static class OrderBy {
+
+ public enum Property {
+ CREATED_ON,
+ NAME,
+ ASSET_TYPE,
+ PARENT_ID,
+ REALM
+ }
+
+ public Property property;
+ public boolean descending;
+
+ public OrderBy() {
+ }
+
+ public OrderBy(Property property) {
+ this.property = property;
+ }
+
+ public OrderBy(Property property, boolean descending) {
+ this.property = property;
+ this.descending = descending;
+ }
+
+ public OrderBy property(Property property) {
+ this.property = property;
+ return this;
+ }
+
+ public OrderBy descending(boolean descending) {
+ this.descending = descending;
+ return this;
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "property=" + property +
+ ", descending=" + descending +
+ '}';
+ }
+ }
+
+ public enum Access {
+ PRIVATE,
+ PROTECTED,
+ PUBLIC
+ }
+
+ /**
+ * String matching options
+ */
+ public enum Match {
+ EXACT,
+ BEGIN,
+ END,
+ CONTAINS;
+
+ public String prepare(String string) {
+ if (string == null)
+ return null;
+ switch (this) {
+ case BEGIN:
+ return string + "%";
+ case CONTAINS:
+ return "%" + string + "%";
+ case END:
+ return "%" + string;
+ }
+ return string;
+ }
+ }
+
+ /**
+ * Binary operators
+ */
+ public enum Operator {
+ EQUALS,
+ GREATER_THAN,
+ GREATER_EQUALS,
+ LESS_THAN,
+ LESS_EQUALS,
+ BETWEEN
+ }
+
+ public enum NumberType {
+ DOUBLE,
+ INTEGER
+ }
+
+ public boolean recursive;
+ // Projection
+ public Select select;
+ // Restriction predicates
+ public Access access = Access.PRIVATE;
+ public String[] ids;
+ public StringPredicate[] names;
+ public ParentPredicate[] parents;
+ public PathPredicate[] paths;
+ public TenantPredicate tenant;
+ public String[] userIds;
+ public StringPredicate[] types;
+ public LogicGroup<AttributePredicate> attributes;
+ public AttributeMetaPredicate[] attributeMeta;
+ public CalendarEventActivePredicate calendarEventActive;
+ // Ordering
+ public OrderBy orderBy;
+ public int limit;
+
+ public AssetQuery() {
+ }
+
+ public AssetQuery recursive(boolean recursive) {
+ this.recursive = recursive;
+ return this;
+ }
+
+ public AssetQuery access(Access access) {
+ this.access = access;
+ return this;
+ }
+
+ public AssetQuery select(Select select) {
+ if (select == null) {
+ select = new Select();
+ }
+
+ this.select = select;
+ return this;
+ }
+
+ public AssetQuery ids(String... ids) {
+ this.ids = ids;
+ return this;
+ }
+
+ public AssetQuery names(String... names) {
+ if (names == null || names.length == 0) {
+ this.names = null;
+ return this;
+ }
+ this.names = Arrays.stream(names).map(StringPredicate::new).toArray(StringPredicate[]::new);
+ return this;
+ }
+
+ public AssetQuery names(StringPredicate... names) {
+ this.names = names;
+ return this;
+ }
+
+ public AssetQuery parents(String... ids) {
+ if (ids == null || ids.length == 0) {
+ this.names = null;
+ return this;
+ }
+ this.parents = Arrays.stream(ids).map(ParentPredicate::new).toArray(ParentPredicate[]::new);
+ return this;
+ }
+
+ public AssetQuery parents(AssetType... assetTypes) {
+ if (assetTypes == null || assetTypes.length == 0) {
+ this.names = null;
+ return this;
+ }
+ this.parents = Arrays.stream(assetTypes).map(id -> new ParentPredicate().type(id)).toArray(ParentPredicate[]::new);
+ return this;
+ }
+
+ public AssetQuery parents(ParentPredicate... parentPredicates) {
+ this.parents = parentPredicates;
+ return this;
+ }
+
+ public AssetQuery paths(PathPredicate... pathPredicates) {
+ this.paths = pathPredicates;
+ return this;
+ }
+
+ public AssetQuery tenant(TenantPredicate tenantPredicate) {
+ this.tenant = tenantPredicate;
+ return this;
+ }
+
+ public AssetQuery userIds(String... userIds) {
+ this.userIds = userIds;
+ return this;
+ }
+
+ public AssetQuery types(StringPredicate... typePredicates) {
+ this.types = typePredicates;
+ return this;
+ }
+
+ public AssetQuery types(String... types) {
+ if (types == null || types.length == 0) {
+ this.types = null;
+ return this;
+ }
+
+ this.types = Arrays.stream(types).map(StringPredicate::new).toArray(StringPredicate[]::new);
+ return this;
+ }
+
+ public AssetQuery types(AssetType... types) {
+ if (types == null || types.length == 0) {
+ this.types = null;
+ return this;
+ }
+
+ this.types = Arrays.stream(types).map(at -> new StringPredicate(at.getType())).toArray(StringPredicate[]::new);
+ return this;
+ }
+
+ public AssetQuery attributes(AttributePredicate... attributePredicates) {
+ if (attributePredicates == null || attributePredicates.length == 0) {
+ this.attributes = null;
+ return this;
+ }
+
+ this.attributes = new LogicGroup<>(attributePredicates);
+ return this;
+ }
+
+ public AssetQuery attributes(LogicGroup<AttributePredicate> attributePredicateGroup) {
+ this.attributes = attributePredicateGroup;
+ return this;
+ }
+
+ public AssetQuery attributeName(String attributeName) {
+ return attributes(new AttributePredicate(attributeName));
+ }
+
+ public AssetQuery attributeValue(String name, ValuePredicate valuePredicate) {
+ return attributes(new AttributePredicate(new StringPredicate(name), valuePredicate));
+ }
+
+ public AssetQuery attributeValue(String name, boolean b) {
+ return attributeValue(name, new BooleanPredicate(b));
+ }
+
+ public AssetQuery attributeValue(String name, String s) {
+ return attributeValue(name, new StringPredicate(s));
+ }
+
+ public AssetQuery attributeValue(String name, Match match, String s) {
+ return attributeValue(name, new StringPredicate(match, s));
+ }
+
+ public AssetQuery attributeValue(String name, Match match, boolean caseSensitive, String s) {
+ return attributeValue(name, new StringPredicate(match, caseSensitive, s));
+ }
+
+ public AssetQuery attributeValue(String name, double d) {
+ return attributeValue(name, new NumberPredicate(d));
+ }
+
+ public AssetQuery attributeValue(String name, Operator operator, double d) {
+ return attributeValue(name, new NumberPredicate(d, operator));
+ }
+
+ public AssetQuery attributeMeta(AttributeMetaPredicate... attributeMetaPredicates) {
+ this.attributeMeta = attributeMetaPredicates;
+ return this;
+ }
+
+ public AssetQuery orderBy(OrderBy orderBy) {
+ this.orderBy = orderBy;
+ return 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).
+ *
+ * <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 AssetQuery calendarEventActive(long timestampSeconds) {
+ calendarEventActive = new CalendarEventActivePredicate(timestampSeconds);
+ return this;
+ }
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "select=" + select +
+ ", id='" + ids + '\'' +
+ ", name=" + names +
+ ", parent=" + parents +
+ ", path=" + paths +
+ ", tenant=" + tenant +
+ ", userId='" + userIds + '\'' +
+ ", type=" + types +
+ ", attribute=" + (attributes != null ? attributes.toString() : "null" ) +
+ ", attributeMeta=" + Arrays.toString(attributeMeta) +
+ ", orderBy=" + orderBy +
+ '}';
+ }
}
diff --git a/model/src/main/java/org/openremote/model/query/BaseAssetQuery.java b/model/src/main/java/org/openremote/model/query/BaseAssetQuery.java
deleted file mode 100644
index d61dc8319..000000000
--- a/model/src/main/java/org/openremote/model/query/BaseAssetQuery.java
+++ /dev/null
@@ -1,498 +0,0 @@
-/*
- * 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.query;
-
-import com.fasterxml.jackson.annotation.JsonProperty;
-import org.openremote.model.asset.AssetType;
-import org.openremote.model.asset.CalendarEventConfiguration;
-import org.openremote.model.query.filter.*;
-import org.openremote.model.value.*;
-
-import java.util.*;
-
-/**
- * Encapsulate asset query restriction, projection, and ordering of results.
- */
-// TODO: Add AssetQuery support for arbitrary attribute property path amd value (e.g. attributes.consoleProviders.geofence.version == "ORConsole")
-@SuppressWarnings("unchecked")
-public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {
-
- public enum Include {
- ALL_EXCEPT_PATH_AND_ATTRIBUTES,
- ALL_EXCEPT_PATH,
- ALL_EXCEPT_ATTRIBUTES,
- ONLY_ID_AND_NAME,
- ONLY_ID_AND_NAME_AND_ATTRIBUTES,
- ONLY_ID_AND_NAME_AND_ATTRIBUTE_NAMES,
- ALL
- }
-
- public enum Access {
- PRIVATE_READ,
- RESTRICTED_READ,
- PUBLIC_READ
- }
-
- /**
- * String matching options
- */
- public enum Match {
- EXACT,
- BEGIN,
- END,
- CONTAINS;
-
- public String prepare(String string) {
- if (string == null)
- return null;
- switch (this) {
- case BEGIN:
- return string + "%";
- case CONTAINS:
- return "%" + string + "%";
- case END:
- return "%" + string;
- }
- return string;
- }
- }
-
- /**
- * Binary operators
- */
- public enum Operator {
- EQUALS,
- GREATER_THAN,
- GREATER_EQUALS,
- LESS_THAN,
- LESS_EQUALS,
- BETWEEN
- }
-
- public enum NumberType {
- DOUBLE,
- INTEGER
- }
-
- public static class Select {
-
- public Include include;
- public boolean recursive;
- public Access access;
- public String[] attributeNames;
-
- public Select() {
- }
-
- public Select(Include include) {
- this(include, Access.PRIVATE_READ);
- }
-
- public Select(Include include, Access access) {
- this(include, false, access);
- }
-
- public Select(Include include, boolean recursive, Access access) {
- this(include, recursive, access, (String[]) null);
- }
-
- public Select(Include include, boolean recursive, String... attributeNames) {
- this(include, recursive, Access.PRIVATE_READ, attributeNames);
- }
-
- public Select(Include include, boolean recursive, Access access, String... attributeNames) {
- if (include == null) {
- include = Include.ALL_EXCEPT_PATH_AND_ATTRIBUTES;
- }
- this.include = include;
- this.access = access;
- this.recursive = recursive;
- this.attributeNames = attributeNames;
- }
-
- public static Select fromObjectValue(ObjectValue objectValue) {
- Select select = new Select();
- objectValue.getString("include").ifPresent(include -> {
- select.include = Include.valueOf(include);
- });
- objectValue.getString("access").ifPresent(access -> {
- select.access = Access.valueOf(access);
- });
- objectValue.getBoolean("recursive").ifPresent(recursive -> {
- select.recursive = recursive;
- });
- objectValue.getArray("attributeNames").ifPresent(attributeNames -> {
- select.attributeNames = attributeNames.stream()
- .map(value -> (StringValue) value)
- .map(StringValue::getString)
- .toArray(String[]::new);
- });
- return select;
- }
-
- public Select include(Include include) {
- this.include = include;
- return this;
- }
-
- public Select filterAccess(Access access) {
- this.access = access;
- return this;
- }
-
- public Select filterAttributes(String... attributeNames) {
- this.attributeNames = attributeNames;
- return this;
- }
-
- public Select recursive(boolean recursive) {
- this.recursive = recursive;
- return this;
- }
-
- public ObjectValue toModelValue() {
- ObjectValue objectValue = Values.createObject();
- objectValue.put("include", Values.create(include.toString()));
- objectValue.put("recursive", Values.create(recursive));
- objectValue.put("access", Values.create(access.toString()));
- objectValue.put("attributeNames",
- Values.createArray().addAll(Arrays.stream(attributeNames).map(Values::create).toArray(Value[]::new)));
- return objectValue;
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + "{" +
- "include=" + include +
- ", recursive=" + recursive +
- ", access=" + access +
- ", attributeNames=" + Arrays.toString(attributeNames) +
- '}';
- }
- }
-
- public static class OrderBy {
-
- public enum Property {
- CREATED_ON,
- NAME,
- ASSET_TYPE,
- PARENT_ID,
- REALM
- }
-
- public Property property;
- public boolean descending;
-
- public OrderBy() {
- }
-
- public OrderBy(Property property) {
- this.property = property;
- }
-
- public OrderBy(Property property, boolean descending) {
- this.property = property;
- this.descending = descending;
- }
-
- public OrderBy property(Property property) {
- this.property = property;
- return this;
- }
-
- public OrderBy descending(boolean descending) {
- this.descending = descending;
- return this;
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + "{" +
- "property=" + property +
- ", descending=" + descending +
- '}';
- }
- }
-
- // Projection
- public Select select;
- // Restriction predicates
- public List<String> ids;
- public StringPredicate name;
- public ParentPredicate parent;
- public PathPredicate path;
- public TenantPredicate tenant;
- public String userId;
- public StringPredicate type;
- public AttributePredicate[] attribute;
- public AttributeMetaPredicate[] attributeMeta;
- public CalendarEventActivePredicate calendarEventActive;
- // Ordering
- public OrderBy orderBy;
- public int limit;
-
- protected BaseAssetQuery() {
- }
-
- // TODO: Remove this
- public static final ArrayValue queriesAsValue(BaseAssetQuery... queries) {
- ArrayValue arrayValue = Values.createArray();
-
- for (BaseAssetQuery query : queries) {
- ObjectValue objectValue = Values.createObject();
- if (query.select != null) {
- objectValue.put("select", query.select.toModelValue());
- }
- if (query.type != null) {
- objectValue.put("type", query.type.toModelValue());
- }
- if (query.attribute != null && query.attribute.length > 0) {
- ArrayValue attributeArray = Values.createArray();
- for (AttributePredicate attributePredicate : query.attribute) {
- attributeArray.add(attributePredicate.toModelValue());
- }
- objectValue.put("attribute", attributeArray);
- }
- arrayValue.add(objectValue);
- }
- return arrayValue;
- }
-
- // TODO: Remove this
- public static final AssetQuery objectValueAsQuery(ObjectValue objectValue) {
- AssetQuery assetQuery = new AssetQuery();
-
- objectValue.getObject("select").ifPresent(selectValue -> {
- assetQuery.select = Select.fromObjectValue(selectValue);
- });
-
- objectValue.getObject("type").ifPresent(typeValue -> {
- assetQuery.type = StringPredicate.fromObjectValue(typeValue);
- });
-
- objectValue.getArray("attribute").ifPresent(attributeValue -> {
- assetQuery.attribute = attributeValue.stream()
- .map(val -> (ObjectValue) val)
- .map(attributePredicateValue -> {
- AttributePredicate attributePredicate = new AttributePredicate();
-
- attributePredicate.name = StringPredicate.fromObjectValue(attributePredicateValue
- .getObject("name")
- .orElseThrow(() -> new IllegalArgumentException(
- "StringPredicate missing for name in AttributePredicate"))
- );
-
- ObjectValue predicateValue = attributePredicateValue
- .getObject("value")
- .orElseThrow(() -> new IllegalArgumentException("value missing in AttributePredicate"));
-
- predicateValue.getString("predicateType").ifPresent(predicateType -> {
- switch (predicateType) {
- case StringPredicate.name:
- attributePredicate.value = StringPredicate.fromObjectValue(predicateValue);
- break;
- case BooleanPredicate.name:
- attributePredicate.value = BooleanPredicate.fromObjectValue(predicateValue);
- break;
- case StringArrayPredicate.name:
- attributePredicate.value = StringArrayPredicate.fromObjectValue(predicateValue);
- break;
- case DateTimePredicate.name:
- attributePredicate.value = DateTimePredicate.fromObjectValue(predicateValue);
- break;
- case NumberPredicate.name:
- attributePredicate.value = NumberPredicate.fromObjectValue(predicateValue);
- break;
- }
- });
- return attributePredicate;
- })
- .toArray(AttributePredicate[]::new);
- });
-
- return assetQuery;
- }
-
- public CHILD select(Select select) {
- if (select == null) {
- select = new Select();
- }
-
- this.select = select;
- return (CHILD) this;
- }
-
- @JsonProperty("id")
- public CHILD id(String id) {
- this.ids = Collections.singletonList(id);
- return (CHILD) this;
- }
-
- public CHILD ids(String...ids) {
- this.ids = ids != null ? Arrays.asList(ids) : null;
- return (CHILD) this;
- }
-
- public CHILD ids(Collection<String> ids) {
- this.ids = ids != null ? new ArrayList<>(ids) : null;
- return (CHILD) this;
- }
-
- public CHILD name(String name) {
- return name(new StringPredicate(name));
- }
-
- public CHILD name(StringPredicate name) {
- this.name = name;
- return (CHILD) this;
- }
-
- public CHILD parent(String id) {
- return parent(new ParentPredicate(id));
- }
-
- public CHILD parent(AssetType assetType) {
- return parent(new ParentPredicate().type(assetType));
- }
-
- public CHILD parent(ParentPredicate parentPredicate) {
- this.parent = parentPredicate;
- return (CHILD) this;
- }
-
- public CHILD path(PathPredicate pathPredicate) {
- this.path = pathPredicate;
- return (CHILD) this;
- }
-
- public CHILD tenant(TenantPredicate tenantPredicate) {
- this.tenant = tenantPredicate;
- return (CHILD) this;
- }
-
- public CHILD userId(String userId) {
- this.userId = userId;
- return (CHILD) this;
- }
-
- public CHILD type(StringPredicate type) {
- this.type = type;
- return (CHILD) this;
- }
-
- public CHILD type(String type) {
- return type(new StringPredicate(type));
- }
-
- public CHILD type(AssetType assetType) {
- return type(new StringPredicate(assetType.getType()));
- }
-
- public CHILD attributes(AttributePredicate... attributePredicates) {
- this.attribute = attributePredicates;
- return (CHILD) this;
- }
-
- public CHILD attributeName(String attributeName) {
- return attributes(new AttributePredicate(attributeName));
- }
-
- public CHILD attributeName(Match match, String attributeName) {
- return attributes(new AttributePredicate(new StringPredicate(match, attributeName)));
- }
-
- /**
- * Match non-empty attribute value.
- */
- public CHILD attributeValue(String name) {
- return attributes(new AttributePredicate(new StringPredicate(name), new ValueNotEmptyPredicate()));
- }
-
- public CHILD attributeValue(String name, ValuePredicate valuePredicate) {
- return attributes(new AttributePredicate(new StringPredicate(name), valuePredicate));
- }
-
- public CHILD attributeValue(String name, boolean b) {
- return attributeValue(name, new BooleanPredicate(b));
- }
-
- public CHILD attributeValue(String name, String s) {
- return attributeValue(name, new StringPredicate(s));
- }
-
- public CHILD attributeValue(String name, Match match, String s) {
- return attributeValue(name, new StringPredicate(match, s));
- }
-
- public CHILD attributeValue(String name, Match match, boolean caseSensitive, String s) {
- return attributeValue(name, new StringPredicate(match, caseSensitive, s));
- }
-
- public CHILD attributeValue(String name, double d) {
- return attributeValue(name, new NumberPredicate(d));
- }
-
- public CHILD attributeValue(String name, Operator operator, double d) {
- return attributeValue(name, new NumberPredicate(d, operator));
- }
-
- public CHILD attributeMeta(AttributeMetaPredicate... attributeMetaPredicates) {
- this.attributeMeta = attributeMetaPredicates;
- return (CHILD) this;
- }
-
- public CHILD orderBy(OrderBy orderBy) {
- this.orderBy = orderBy;
- 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).
- *
- * <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;
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + "{" +
- "select=" + select +
- ", id='" + ids + '\'' +
- ", name=" + name +
- ", parent=" + parent +
- ", path=" + path +
- ", tenant=" + tenant +
- ", userId='" + userId + '\'' +
- ", type=" + type +
- ", attribute=" + Arrays.toString(attribute) +
- ", attributeMeta=" + Arrays.toString(attributeMeta) +
- ", orderBy=" + orderBy +
- '}';
- }
-}
diff --git a/model/src/main/java/org/openremote/model/rules/json/LogicGroup.java b/model/src/main/java/org/openremote/model/query/LogicGroup.java
similarity index 67%
rename from model/src/main/java/org/openremote/model/rules/json/LogicGroup.java
rename to model/src/main/java/org/openremote/model/query/LogicGroup.java
index cbb3554fa..4d5f5315d 100644
--- a/model/src/main/java/org/openremote/model/rules/json/LogicGroup.java
+++ b/model/src/main/java/org/openremote/model/query/LogicGroup.java
@@ -17,7 +17,7 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-package org.openremote.model.rules.json;
+package org.openremote.model.query;
import java.util.ArrayList;
import java.util.Arrays;
@@ -25,19 +25,28 @@ import java.util.List;
public class LogicGroup<T> {
+ public enum Operator {
+ AND,
+ OR
+ }
+
public LogicGroup() {
}
- public LogicGroup(RuleOperator operator, T[] items, LogicGroup<T>[] groups) {
+ public LogicGroup(T[] items) {
+ this.items = items;
+ }
+
+ public LogicGroup(Operator operator, T[] items, LogicGroup<T>[] groups) {
this.operator = operator;
this.items = items;
this.groups = groups;
}
/**
- * If not specified then {@link RuleOperator#AND} is assumed.
+ * If not specified then {@link Operator#AND} is assumed.
*/
- public RuleOperator operator;
+ public Operator operator;
/**
* Defines the items that the {@link #operator} should be applied to
@@ -49,14 +58,12 @@ public class LogicGroup<T> {
*/
public LogicGroup<T>[] groups;
- public static <T> List<T> flatten(List<LogicGroup<T>> conditions) {
- List<T> flattened = new ArrayList<>();
- for (LogicGroup<T> ruleCondition : conditions) {
- flattened.addAll(Arrays.asList(ruleCondition.items));
- if (ruleCondition.groups != null) {
- flattened.addAll(flatten(Arrays.asList(ruleCondition.groups)));
- }
- }
- return flattened;
+ @Override
+ public String toString() {
+ return LogicGroup.class.getSimpleName() + "{" +
+ "operator=" + operator +
+ ", items=" + Arrays.toString(items) +
+ ", groups=" + Arrays.toString(groups) +
+ '}';
}
}
diff --git a/model/src/main/java/org/openremote/model/query/NewAssetQuery.java b/model/src/main/java/org/openremote/model/query/NewAssetQuery.java
deleted file mode 100644
index 00ad4f149..000000000
--- a/model/src/main/java/org/openremote/model/query/NewAssetQuery.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright 2018, 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.query;
-
-import org.openremote.model.query.filter.*;
-import org.openremote.model.rules.json.RuleActionTarget;
-import org.openremote.model.rules.json.LogicGroup;
-import org.openremote.model.rules.json.RuleConditionReset;
-
-/**
- * <p>
- * This predicate is designed to filter the {@link org.openremote.model.rules.AssetState}s and will evaluate to true
- * if after applying the filtering one or more {@link org.openremote.model.rules.AssetState}s are returned.
- * <p>
- * The {@link org.openremote.model.asset.Asset}s associated with the returned {@link org.openremote.model.rules.AssetState}s
- * are then used as the context for any {@link RuleConditionReset} to control when the
- * {@link NewAssetQuery} is allowed to be applied again to the same asset. They can also optionally be used as context
- * in the {@link RuleActionTarget}, to apply an action to the matched
- * {@link org.openremote.model.asset.Asset}s.
- * <p>
- * There is an implicit AND between properties and an implicit OR between each value of a property.
- */
-// TODO: Merge with existing AssetQuery
-// TODO: types and attributes are linked and shouldn't be independently specified
-public class NewAssetQuery {
-
- public String[] ids;
- public StringPredicate[] names;
- public ParentPredicate[] parents;
- public PathPredicate[] paths;
- public TenantPredicate tenant;
- public String[] userIds;
- public StringPredicate[] types;
- public LogicGroup<AttributePredicate> attributes;
-
- /**
- * To be used in combination with {@link #limit} to control the ordering of {@link org.openremote.model.asset.Asset}s
- * before applying the limit.
- */
- public BaseAssetQuery.OrderBy orderBy;
-
- /**
- * Means that number of matching {@link org.openremote.model.asset.Asset}s will be limited to this amount.
- */
- public int limit;
-}
diff --git a/model/src/main/java/org/openremote/model/query/UserQuery.java b/model/src/main/java/org/openremote/model/query/UserQuery.java
index c237766e1..e3aff36d2 100644
--- a/model/src/main/java/org/openremote/model/query/UserQuery.java
+++ b/model/src/main/java/org/openremote/model/query/UserQuery.java
@@ -5,7 +5,7 @@ import org.openremote.model.query.filter.PathPredicate;
import org.openremote.model.query.filter.TenantPredicate;
import org.openremote.model.query.filter.UserAssetPredicate;
-public class UserQuery<CHILD extends UserQuery<CHILD>> {
+public class UserQuery {
// Restriction predicates
public TenantPredicate tenantPredicate;
@@ -16,27 +16,23 @@ public class UserQuery<CHILD extends UserQuery<CHILD>> {
public UserQuery() {
}
- @SuppressWarnings("unchecked")
- public CHILD tenant(TenantPredicate tenantPredicate) {
+ public UserQuery tenant(TenantPredicate tenantPredicate) {
this.tenantPredicate = tenantPredicate;
- return (CHILD) this;
+ return this;
}
- @SuppressWarnings("unchecked")
- public CHILD asset(UserAssetPredicate assetPredicate) {
+ public UserQuery asset(UserAssetPredicate assetPredicate) {
this.assetPredicate = assetPredicate;
- return (CHILD) this;
+ return this;
}
- @SuppressWarnings("unchecked")
- public CHILD assetPath(PathPredicate pathPredicate) {
+ public UserQuery assetPath(PathPredicate pathPredicate) {
this.pathPredicate = pathPredicate;
- return (CHILD) this;
+ return this;
}
- @SuppressWarnings("unchecked")
- public CHILD limit(int limit) {
+ public UserQuery limit(int limit) {
this.limit = limit;
- return (CHILD) this;
+ return this;
}
}
diff --git a/model/src/main/java/org/openremote/model/query/filter/AttributeMetaPredicate.java b/model/src/main/java/org/openremote/model/query/filter/AttributeMetaPredicate.java
index abba89ca9..0a92d6a90 100644
--- a/model/src/main/java/org/openremote/model/query/filter/AttributeMetaPredicate.java
+++ b/model/src/main/java/org/openremote/model/query/filter/AttributeMetaPredicate.java
@@ -20,7 +20,7 @@
package org.openremote.model.query.filter;
import org.openremote.model.attribute.MetaItemDescriptor;
-import org.openremote.model.query.BaseAssetQuery;
+import org.openremote.model.query.AssetQuery;
public class AttributeMetaPredicate {
diff --git a/model/src/main/java/org/openremote/model/query/filter/AttributePredicate.java b/model/src/main/java/org/openremote/model/query/filter/AttributePredicate.java
index aa86fb960..c7dd55dfa 100644
--- a/model/src/main/java/org/openremote/model/query/filter/AttributePredicate.java
+++ b/model/src/main/java/org/openremote/model/query/filter/AttributePredicate.java
@@ -26,6 +26,7 @@ import org.openremote.model.value.Values;
public class AttributePredicate {
public StringPredicate name;
+ public boolean exists;
public ValuePredicate value;
public AttributePredicate() {
diff --git a/model/src/main/java/org/openremote/model/query/filter/DateTimePredicate.java b/model/src/main/java/org/openremote/model/query/filter/DateTimePredicate.java
index 8429c71da..cf08f485a 100644
--- a/model/src/main/java/org/openremote/model/query/filter/DateTimePredicate.java
+++ b/model/src/main/java/org/openremote/model/query/filter/DateTimePredicate.java
@@ -19,7 +19,7 @@
*/
package org.openremote.model.query.filter;
-import org.openremote.model.query.BaseAssetQuery;
+import org.openremote.model.query.AssetQuery;
import org.openremote.model.value.ObjectValue;
import org.openremote.model.value.Values;
@@ -33,19 +33,19 @@ public class DateTimePredicate implements ValuePredicate {
public static final String name = "datetime";
public String value; // Sliding window value e.g. 1h or fixed date time
public String rangeValue; // Sliding window value e.g. 1h or fixed date time (used as upper bound when Operator.BETWEEN)
- public BaseAssetQuery.Operator operator = BaseAssetQuery.Operator.EQUALS;
+ public AssetQuery.Operator operator = AssetQuery.Operator.EQUALS;
public boolean negate;
public DateTimePredicate() {
}
- public DateTimePredicate(BaseAssetQuery.Operator operator, String value) {
+ public DateTimePredicate(AssetQuery.Operator operator, String value) {
this.operator = operator;
this.value = value;
}
public DateTimePredicate(String rangeStart, String rangeEnd) {
- this.operator = BaseAssetQuery.Operator.BETWEEN;
+ this.operator = AssetQuery.Operator.BETWEEN;
this.value = rangeStart;
this.rangeValue = rangeEnd;
}
@@ -60,7 +60,7 @@ public class DateTimePredicate implements ValuePredicate {
dateTimePredicate.rangeValue = rangeValue;
});
objectValue.getString("operator").ifPresent(operator -> {
- dateTimePredicate.operator = BaseAssetQuery.Operator.valueOf(operator);
+ dateTimePredicate.operator = AssetQuery.Operator.valueOf(operator);
});
objectValue.getBoolean("negate").ifPresent(negate -> {
dateTimePredicate.negate = negate;
@@ -68,7 +68,7 @@ public class DateTimePredicate implements ValuePredicate {
return dateTimePredicate;
}
- public DateTimePredicate operator(BaseAssetQuery.Operator dateMatch) {
+ public DateTimePredicate operator(AssetQuery.Operator dateMatch) {
this.operator = dateMatch;
return this;
}
@@ -79,7 +79,7 @@ public class DateTimePredicate implements ValuePredicate {
}
public DateTimePredicate rangeValue(String rangeEnd) {
- this.operator = BaseAssetQuery.Operator.BETWEEN;
+ this.operator = AssetQuery.Operator.BETWEEN;
this.rangeValue = rangeEnd;
return this;
}
diff --git a/model/src/main/java/org/openremote/model/query/filter/LocationAttributePredicate.java b/model/src/main/java/org/openremote/model/query/filter/LocationAttributePredicate.java
index 4233c2ecf..23be7dcd9 100644
--- a/model/src/main/java/org/openremote/model/query/filter/LocationAttributePredicate.java
+++ b/model/src/main/java/org/openremote/model/query/filter/LocationAttributePredicate.java
@@ -20,8 +20,11 @@
package org.openremote.model.query.filter;
import org.openremote.model.attribute.AttributeType;
-import org.openremote.model.query.BaseAssetQuery;
+import org.openremote.model.query.AssetQuery;
+import org.openremote.model.query.LogicGroup;
+import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@@ -33,13 +36,23 @@ public class LocationAttributePredicate extends AttributePredicate {
super(new StringPredicate(AttributeType.LOCATION.getAttributeName()), geofencePredicate);
}
- public static List<GeofencePredicate> getLocationPredicates(List<AttributePredicate> attributePredicates) {
- return attributePredicates.stream()
+ public static List<GeofencePredicate> getLocationPredicates(LogicGroup<AttributePredicate> attributePredicates) {
+ List<GeofencePredicate> geofences = new ArrayList<>();
+
+ Arrays.stream(attributePredicates.items)
.filter(attributePredicate -> attributePredicate.name != null
- && attributePredicate.name.match == BaseAssetQuery.Match.EXACT
+ && attributePredicate.name.match == AssetQuery.Match.EXACT
&& LOCATION.getAttributeName().equals(attributePredicate.name.value)
&& attributePredicate.value instanceof GeofencePredicate)
.map(attributePredicate -> (GeofencePredicate) attributePredicate.value)
- .collect(Collectors.toList());
+ .forEach(geofences::add);
+
+ if (attributePredicates.groups != null) {
+ Arrays.stream(attributePredicates.groups).forEach(group ->
+ geofences.addAll(getLocationPredicates(group))
+ );
+ }
+
+ return geofences;
}
}
diff --git a/model/src/main/java/org/openremote/model/query/filter/NumberPredicate.java b/model/src/main/java/org/openremote/model/query/filter/NumberPredicate.java
index aea3d9025..341544fdf 100644
--- a/model/src/main/java/org/openremote/model/query/filter/NumberPredicate.java
+++ b/model/src/main/java/org/openremote/model/query/filter/NumberPredicate.java
@@ -19,7 +19,7 @@
*/
package org.openremote.model.query.filter;
-import org.openremote.model.query.BaseAssetQuery;
+import org.openremote.model.query.AssetQuery;
import org.openremote.model.value.ObjectValue;
import org.openremote.model.value.Values;
@@ -28,8 +28,8 @@ public class NumberPredicate implements ValuePredicate {
public static final String name = "number";
public double value;
public double rangeValue; // Used as upper bound when Operator.BETWEEN
- public BaseAssetQuery.Operator operator = BaseAssetQuery.Operator.EQUALS;
- public BaseAssetQuery.NumberType numberType = BaseAssetQuery.NumberType.DOUBLE;
+ public AssetQuery.Operator operator = AssetQuery.Operator.EQUALS;
+ public AssetQuery.NumberType numberType = AssetQuery.NumberType.DOUBLE;
public boolean negate;
public NumberPredicate() {
@@ -39,17 +39,17 @@ public class NumberPredicate implements ValuePredicate {
this.value = value;
}
- public NumberPredicate(double value, BaseAssetQuery.Operator operator) {
+ public NumberPredicate(double value, AssetQuery.Operator operator) {
this.value = value;
this.operator = operator;
}
- public NumberPredicate(double value, BaseAssetQuery.NumberType numberType) {
+ public NumberPredicate(double value, AssetQuery.NumberType numberType) {
this.value = value;
this.numberType = numberType;
}
- public NumberPredicate(double value, BaseAssetQuery.Operator operator, BaseAssetQuery.NumberType numberType) {
+ public NumberPredicate(double value, AssetQuery.Operator operator, AssetQuery.NumberType numberType) {
this.value = value;
this.operator = operator;
this.numberType = numberType;
@@ -67,7 +67,7 @@ public class NumberPredicate implements ValuePredicate {
numberPredicate.negate = negate;
});
objectValue.getString("operator").ifPresent(operator -> {
- numberPredicate.operator = BaseAssetQuery.Operator.valueOf(operator);
+ numberPredicate.operator = AssetQuery.Operator.valueOf(operator);
});
return numberPredicate;
}
@@ -77,18 +77,18 @@ public class NumberPredicate implements ValuePredicate {
return this;
}
- public NumberPredicate numberMatch(BaseAssetQuery.Operator operator) {
+ public NumberPredicate numberMatch(AssetQuery.Operator operator) {
this.operator = operator;
return this;
}
- public NumberPredicate numberType(BaseAssetQuery.NumberType numberType) {
+ public NumberPredicate numberType(AssetQuery.NumberType numberType) {
this.numberType = numberType;
return this;
}
public NumberPredicate rangeValue(double rangeValue) {
- this.operator = BaseAssetQuery.Operator.BETWEEN;
+ this.operator = AssetQuery.Operator.BETWEEN;
this.rangeValue = rangeValue;
return this;
}
diff --git a/model/src/main/java/org/openremote/model/query/filter/StringPredicate.java b/model/src/main/java/org/openremote/model/query/filter/StringPredicate.java
index bd21c13f0..e0b33e90f 100644
--- a/model/src/main/java/org/openremote/model/query/filter/StringPredicate.java
+++ b/model/src/main/java/org/openremote/model/query/filter/StringPredicate.java
@@ -19,7 +19,7 @@
*/
package org.openremote.model.query.filter;
-import org.openremote.model.query.BaseAssetQuery;
+import org.openremote.model.query.AssetQuery;
import org.openremote.model.value.ObjectValue;
import org.openremote.model.value.Values;
@@ -29,7 +29,7 @@ import java.util.function.Predicate;
public class StringPredicate implements ValuePredicate {
public static final String name = "string";
- public BaseAssetQuery.Match match = BaseAssetQuery.Match.EXACT;
+ public AssetQuery.Match match = AssetQuery.Match.EXACT;
public boolean caseSensitive = true;
public String value;
public boolean negate;
@@ -41,12 +41,12 @@ public class StringPredicate implements ValuePredicate {
this.value = value;
}
- public StringPredicate(BaseAssetQuery.Match match, String value) {
+ public StringPredicate(AssetQuery.Match match, String value) {
this.match = match;
this.value = value;
}
- public StringPredicate(BaseAssetQuery.Match match, boolean caseSensitive, String value) {
+ public StringPredicate(AssetQuery.Match match, boolean caseSensitive, String value) {
this.match = match;
this.caseSensitive = caseSensitive;
this.value = value;
@@ -55,7 +55,7 @@ public class StringPredicate implements ValuePredicate {
public static StringPredicate fromObjectValue(ObjectValue objectValue) {
StringPredicate stringPredicate = new StringPredicate();
objectValue.getString("match").ifPresent(match -> {
- stringPredicate.match = BaseAssetQuery.Match.valueOf(match);
+ stringPredicate.match = AssetQuery.Match.valueOf(match);
});
objectValue.getBoolean("caseSensitive").ifPresent(caseSensitive -> {
stringPredicate.caseSensitive = caseSensitive;
@@ -93,7 +93,7 @@ public class StringPredicate implements ValuePredicate {
};
}
- public StringPredicate match(BaseAssetQuery.Match match) {
+ public StringPredicate match(AssetQuery.Match match) {
this.match = match;
return this;
}
diff --git a/model/src/main/java/org/openremote/model/rules/Assets.java b/model/src/main/java/org/openremote/model/rules/Assets.java
index 538f3ab5c..091fc83a1 100644
--- a/model/src/main/java/org/openremote/model/rules/Assets.java
+++ b/model/src/main/java/org/openremote/model/rules/Assets.java
@@ -20,9 +20,12 @@
package org.openremote.model.rules;
import org.openremote.model.asset.Asset;
-import org.openremote.model.query.BaseAssetQuery;
+import org.openremote.model.asset.AssetType;
+import org.openremote.model.query.AssetQuery;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeExecuteStatus;
+import org.openremote.model.query.LogicGroup;
+import org.openremote.model.query.filter.*;
import org.openremote.model.value.Value;
import java.util.stream.Stream;
@@ -33,14 +36,7 @@ import java.util.stream.Stream;
*/
public abstract class Assets {
- public abstract class RestrictedQuery extends BaseAssetQuery<RestrictedQuery> {
-
- abstract public Asset getResult();
-
- abstract public Stream<Asset> stream();
- }
-
- abstract public RestrictedQuery query();
+ abstract public Stream<Asset> getResults(AssetQuery assetQuery);
abstract public Assets dispatch(AttributeEvent... event);
diff --git a/model/src/main/java/org/openremote/model/rules/Ruleset.java b/model/src/main/java/org/openremote/model/rules/Ruleset.java
index 6ab68e1dd..09f63ad57 100644
--- a/model/src/main/java/org/openremote/model/rules/Ruleset.java
+++ b/model/src/main/java/org/openremote/model/rules/Ruleset.java
@@ -56,7 +56,7 @@ public abstract class Ruleset {
" description: \"An example rule that sets 'bar' on someAttribute when it is 'foo'\",\n" +
" when: function(facts) {\n" +
" return facts.matchAssetState(\n" +
- " new AssetQuery().type(AssetType.THING).attributeValue(\"someAttribute\", \"foo\")\n" +
+ " new AssetQuery().types(AssetType.THING).attributeValue(\"someAttribute\", \"foo\")\n" +
" ).map(function(thing) {\n" +
" facts.bind(\"assetId\", thing.id);\n" +
" return true;\n" +
@@ -89,7 +89,7 @@ public abstract class Ruleset {
" .when(\n" +
" { facts ->\n" +
" facts.matchFirstAssetState(\n" +
- " new AssetQuery().type(AssetType.THING).attributeValue(\"someAttribute\", \"foo\")\n" +
+ " new AssetQuery().types(AssetType.THING).attributeValue(\"someAttribute\", \"foo\")\n" +
" ).map { thing ->\n" +
" facts.bind(\"assetId\", thing.id)\n" +
" true\n" +
diff --git a/model/src/main/java/org/openremote/model/rules/Users.java b/model/src/main/java/org/openremote/model/rules/Users.java
index a0136a341..c6039be6e 100644
--- a/model/src/main/java/org/openremote/model/rules/Users.java
+++ b/model/src/main/java/org/openremote/model/rules/Users.java
@@ -30,13 +30,5 @@ import java.util.stream.Stream;
*/
public abstract class Users {
- public abstract class RestrictedQuery extends UserQuery<RestrictedQuery> {
-
- abstract public List<String> getResults();
-
- abstract public Stream<String> stream();
- }
-
- abstract public RestrictedQuery query();
-
+ abstract public Stream<String> getResults(UserQuery userQuery);
}
diff --git a/model/src/main/java/org/openremote/model/rules/json/Rule.java b/model/src/main/java/org/openremote/model/rules/json/JsonRule.java
similarity index 81%
rename from model/src/main/java/org/openremote/model/rules/json/Rule.java
rename to model/src/main/java/org/openremote/model/rules/json/JsonRule.java
index 6ef8c3408..2102745b3 100644
--- a/model/src/main/java/org/openremote/model/rules/json/Rule.java
+++ b/model/src/main/java/org/openremote/model/rules/json/JsonRule.java
@@ -19,7 +19,8 @@
*/
package org.openremote.model.rules.json;
-import org.openremote.model.query.NewAssetQuery;
+import org.openremote.model.query.LogicGroup;
+import org.openremote.model.query.AssetQuery;
/**
* A declarative rule definition a.k.a. JSON rules; consists of:
@@ -35,9 +36,7 @@ import org.openremote.model.query.NewAssetQuery;
* re-trigger a rule if it is matched by a different {@link RuleCondition})
* <p>
* The {@link #otherwise} {@link RuleAction}s are applied to the {@link org.openremote.model.asset.Asset}s filtered by
- * the query that don't match the {@link NewAssetQuery#attributes} predicates.
- * {@link #and} - Optional condition that can be used to further restrict the LHS but without affecting the
- * {@link org.openremote.model.rules.AssetState}s that form the context for the RHS. If this is specified then the
+ * the query that don't match the {@link AssetQuery#attributes} predicates.
* {@link #when} must evaluate to true and this condition must evaluate to true.
* <h2>RHS</h2>
* <p>
@@ -45,9 +44,9 @@ import org.openremote.model.query.NewAssetQuery;
* {@link RuleCondition}s in the {@link #when} is true.
* <p>
* {@link #otherwise} - Defines a series of {@link RuleAction}s to perform when there is one or more asset that matched rule doesn't match the assets specified
- * in the {@link Rule#when}. The list of assets this applies to is the assets filtered by applying the
- * {@link Rule#when} but excluding the {@link NewAssetQuery#attributes} predicates and excluding any assets that match
- * the entire {@link Rule#when}. If the number of these assets is greater than 0 then these {@link RuleAction}s will be
+ * in the {@link JsonRule#when}. The list of assets this applies to is the assets filtered by applying the
+ * {@link JsonRule#when} but excluding the {@link AssetQuery#attributes} predicates and excluding any assets that match
+ * the entire {@link JsonRule#when}. If the number of these assets is greater than 0 then these {@link RuleAction}s will be
* executed.
* <h2>Reset</h2>
* <p>
@@ -57,7 +56,7 @@ import org.openremote.model.query.NewAssetQuery;
* <b>NOTE: Rule trigger history is not persisted so on system restart this information is lost and a rule will be
* able to fire again.</b>
*/
-public class Rule {
+public class JsonRule {
public String name;
public String description;
diff --git a/model/src/main/java/org/openremote/model/rules/json/JsonRulesetDefinition.java b/model/src/main/java/org/openremote/model/rules/json/JsonRulesetDefinition.java
index fbb288ac0..11200ba40 100644
--- a/model/src/main/java/org/openremote/model/rules/json/JsonRulesetDefinition.java
+++ b/model/src/main/java/org/openremote/model/rules/json/JsonRulesetDefinition.java
@@ -22,6 +22,6 @@ package org.openremote.model.rules.json;
import org.openremote.model.value.ObjectValue;
public class JsonRulesetDefinition {
- public Rule[] rules;
+ public JsonRule[] rules;
public ObjectValue meta;
}
diff --git a/model/src/main/java/org/openremote/model/rules/json/RuleActionTarget.java b/model/src/main/java/org/openremote/model/rules/json/RuleActionTarget.java
index 73b05c261..8ae9f0cf8 100644
--- a/model/src/main/java/org/openremote/model/rules/json/RuleActionTarget.java
+++ b/model/src/main/java/org/openremote/model/rules/json/RuleActionTarget.java
@@ -19,7 +19,7 @@
*/
package org.openremote.model.rules.json;
-import org.openremote.model.query.NewAssetQuery;
+import org.openremote.model.query.AssetQuery;
import org.openremote.model.query.UserQuery;
/**
@@ -32,6 +32,6 @@ import org.openremote.model.query.UserQuery;
*/
public class RuleActionTarget {
public String ruleConditionTag;
- public NewAssetQuery assets;
+ public AssetQuery assets;
public UserQuery users;
}
diff --git a/model/src/main/java/org/openremote/model/rules/json/RuleCondition.java b/model/src/main/java/org/openremote/model/rules/json/RuleCondition.java
index f16767640..550b44daf 100644
--- a/model/src/main/java/org/openremote/model/rules/json/RuleCondition.java
+++ b/model/src/main/java/org/openremote/model/rules/json/RuleCondition.java
@@ -19,7 +19,7 @@
*/
package org.openremote.model.rules.json;
-import org.openremote.model.query.NewAssetQuery;
+import org.openremote.model.query.AssetQuery;
import org.openremote.model.query.filter.DateTimePredicate;
/**
@@ -38,7 +38,7 @@ public class RuleCondition {
public String timer;
public DateTimePredicate datetime;
- public NewAssetQuery assets;
+ public AssetQuery assets;
public String tag;
public RuleConditionReset reset;
}
diff --git a/model/src/main/java/org/openremote/model/rules/json/RuleOperator.java b/model/src/main/java/org/openremote/model/rules/json/RuleOperator.java
deleted file mode 100644
index 18b81de3f..000000000
--- a/model/src/main/java/org/openremote/model/rules/json/RuleOperator.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright 2018, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.model.rules.json;
-
-public enum RuleOperator {
- AND,
- OR
-}
diff --git a/test/src/main/groovy/org/openremote/test/TestAppSecurity.java b/test/src/main/groovy/org/openremote/test/TestAppSecurity.java
index f20ad5d89..9fe85403c 100644
--- a/test/src/main/groovy/org/openremote/test/TestAppSecurity.java
+++ b/test/src/main/groovy/org/openremote/test/TestAppSecurity.java
@@ -26,10 +26,9 @@ import org.keycloak.representations.AccessToken;
import org.openremote.app.client.AppSecurity;
import org.openremote.model.Constants;
import org.openremote.model.http.RequestParams;
+import org.openremote.model.interop.Consumer;
import org.openremote.model.interop.Runnable;
-import java.util.function.Consumer;
-
/**
* Does the same job as or-app-security.
*/
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy
index f1c9715e6..4d68caad4 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy
@@ -63,7 +63,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
assets = assetResource.queryAssets(null,
new AssetQuery()
.tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.realm))
- .parent(new ParentPredicate(true))
+ .parents(new ParentPredicate(true))
)
then: "result should match"
@@ -73,7 +73,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
when: "the child assets of an asset in the authenticated realm are retrieved"
assets = assetResource.queryAssets(null,
new AssetQuery()
- .parent(new ParentPredicate(assets[0].id))
+ .parents(new ParentPredicate(assets[0].id))
)
then: "result should match"
@@ -84,7 +84,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
assets = assetResource.queryAssets(null,
new AssetQuery()
.tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.realm))
- .parent(new ParentPredicate(true))
+ .parents(new ParentPredicate(true))
)
then: "result should match"
@@ -95,7 +95,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
assets = assetResource.queryAssets(null,
new AssetQuery()
.tenant(new TenantPredicate(keycloakDemoSetup.tenantA.realm))
- .parent(new ParentPredicate(true))
+ .parents(new ParentPredicate(true))
)
then: "result should match"
@@ -105,7 +105,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
when: "the child assets of an asset in a foreign realm are retrieved"
assets = assetResource.queryAssets(null,
new AssetQuery()
- .parent(new ParentPredicate(assets[0].id))
+ .parents(new ParentPredicate(assets[0].id))
)
then: "result should match"
@@ -267,7 +267,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
assets = assetResource.queryAssets(null,
new AssetQuery()
.tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.realm))
- .parent(new ParentPredicate(true))
+ .parents(new ParentPredicate(true))
)
then: "result should match"
@@ -277,7 +277,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
when: "the child assets of an asset in the authenticated realm are retrieved"
assets = assetResource.queryAssets(null,
new AssetQuery()
- .parent(new ParentPredicate(assets[0].id))
+ .parents(new ParentPredicate(assets[0].id))
)
then: "result should match"
@@ -287,7 +287,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
when: "the root assets of the authenticated realm are retrieved"
assets = assetResource.queryAssets(null,
new AssetQuery()
- .parent(new ParentPredicate(true))
+ .parents(new ParentPredicate(true))
)
then: "result should match"
@@ -299,7 +299,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
assets = assetResource.queryAssets(null,
new AssetQuery()
.tenant(new TenantPredicate(keycloakDemoSetup.tenantA.realm))
- .parent(new ParentPredicate(true))
+ .parents(new ParentPredicate(true))
)
then: "result should match"
@@ -308,7 +308,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
when: "the child assets of an asset in a foreign realm are retrieved"
assets = assetResource.queryAssets(null,
new AssetQuery()
- .parent(new ParentPredicate(managerDemoSetup.smartBuildingId))
+ .parents(new ParentPredicate(managerDemoSetup.smartBuildingId))
)
then: "result should be empty"
@@ -436,7 +436,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
assets = assetResource.queryAssets(null,
new AssetQuery()
.tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.realm))
- .parent(new ParentPredicate(true))
+ .parents(new ParentPredicate(true))
)
then: "result should match"
@@ -445,7 +445,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
when: "the root assets of the authenticated realm are retrieved"
assets = assetResource.queryAssets(null,
new AssetQuery()
- .parent(new ParentPredicate(true))
+ .parents(new ParentPredicate(true))
)
then: "result should match"
@@ -457,7 +457,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
assets = assetResource.queryAssets(null,
new AssetQuery()
.tenant(new TenantPredicate(keycloakDemoSetup.tenantB.realm))
- .parent(new ParentPredicate(true))
+ .parents(new ParentPredicate(true))
)
then: "result should match"
@@ -466,7 +466,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
when: "the child assets of an asset in a foreign realm are retrieved"
assets = assetResource.queryAssets(null,
new AssetQuery()
- .parent(new ParentPredicate(managerDemoSetup.thingId))
+ .parents(new ParentPredicate(managerDemoSetup.thingId))
)
then: "result should be empty"
@@ -605,7 +605,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
assets = assetResource.queryAssets(null,
new AssetQuery()
.tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.realm))
- .parent(new ParentPredicate(true))
+ .parents(new ParentPredicate(true))
)
then: "result should match"
@@ -614,7 +614,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
when: "the root assets of the authenticated realm are retrieved"
assets = assetResource.queryAssets(null,
new AssetQuery()
- .parent(new ParentPredicate(true))
+ .parents(new ParentPredicate(true))
)
then: "result should match"
@@ -624,7 +624,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
assets = assetResource.queryAssets(null,
new AssetQuery()
.tenant(new TenantPredicate(keycloakDemoSetup.tenantB.realm))
- .parent(new ParentPredicate(true))
+ .parents(new ParentPredicate(true))
)
then: "result should match"
@@ -633,7 +633,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
when: "the child assets of linked asset are retrieved"
assets = assetResource.queryAssets(null,
new AssetQuery()
- .parent(new ParentPredicate(managerDemoSetup.apartment1Id))
+ .parents(new ParentPredicate(managerDemoSetup.apartment1Id))
)
then: "result should match"
@@ -642,7 +642,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
when: "the child assets of an asset in the authenticated realm are retrieved"
assets = assetResource.queryAssets(null,
new AssetQuery()
- .parent(new ParentPredicate(managerDemoSetup.smartBuildingId))
+ .parents(new ParentPredicate(managerDemoSetup.smartBuildingId))
)
then: "result should match"
@@ -651,7 +651,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
when: "the child assets of an asset in a foreign realm are retrieved"
assets = assetResource.queryAssets(null,
new AssetQuery()
- .parent(new ParentPredicate(managerDemoSetup.thingId))
+ .parents(new ParentPredicate(managerDemoSetup.thingId))
)
then: "result should be empty"
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetPublicQueryTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetPublicQueryTest.groovy
index 006aca2f0..ec7fe29f6 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetPublicQueryTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetPublicQueryTest.groovy
@@ -21,8 +21,7 @@ import static org.openremote.model.attribute.MetaItemType.ACCESS_PUBLIC_READ
import static org.openremote.model.attribute.MetaItemType.LABEL
import static org.openremote.model.asset.AssetType.THING
import static org.openremote.model.attribute.AttributeValueType.NUMBER
-import static org.openremote.model.query.BaseAssetQuery.Include
-import static org.openremote.model.query.BaseAssetQuery.Select
+import static org.openremote.model.query.AssetQuery.Select
class AssetPublicQueryTest extends Specification implements ManagerContainerTrait {
@@ -84,8 +83,8 @@ class AssetPublicQueryTest extends Specification implements ManagerContainerTrai
when: "a query for a specific public asset is executed"
def query = new AssetQuery()
- .select(new Select(Include.ALL))
- .id(returnedAssets.get(0).id)
+ .select(Select.selectAll())
+ .ids(returnedAssets.get(0).id)
def assets = assetResource.queryPublicAssets(null, query)
then: "the result should match"
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy
index cf8ffef56..bfb7953fb 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy
@@ -16,6 +16,7 @@ import org.openremote.model.calendar.CalendarEvent
import org.openremote.model.calendar.RecurrenceRule
import org.openremote.model.geo.GeoJSONPoint
import org.openremote.model.query.AssetQuery
+import org.openremote.model.query.AssetQuery.OrderBy
import org.openremote.model.query.filter.*
import org.openremote.model.value.Values
import org.openremote.test.ManagerContainerTrait
@@ -32,11 +33,11 @@ import java.util.function.Function
import static java.time.format.DateTimeFormatter.ISO_ZONED_DATE_TIME
import static org.openremote.model.asset.AssetType.THING
import static org.openremote.model.attribute.AttributeValueType.DATETIME
-import static org.openremote.model.query.BaseAssetQuery.*
-import static org.openremote.model.query.BaseAssetQuery.Access.PRIVATE_READ
-import static org.openremote.model.query.BaseAssetQuery.Access.RESTRICTED_READ
-import static org.openremote.model.query.BaseAssetQuery.OrderBy.Property.CREATED_ON
-import static org.openremote.model.query.BaseAssetQuery.OrderBy.Property.NAME
+import static org.openremote.model.query.AssetQuery.*
+import static org.openremote.model.query.AssetQuery.Access.PRIVATE
+import static org.openremote.model.query.AssetQuery.Access.PROTECTED
+import static org.openremote.model.query.AssetQuery.OrderBy.Property.CREATED_ON
+import static org.openremote.model.query.AssetQuery.OrderBy.Property.NAME
class AssetQueryTest extends Specification implements ManagerContainerTrait {
@@ -74,8 +75,8 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
when: "an agent filtering query is executed"
def assets = assetStorageService.findAll(
new AssetQuery()
- .select(new Select(Include.ONLY_ID_AND_NAME_AND_ATTRIBUTES))
- .type(AssetType.AGENT)
+ .select(Select.selectExcludePathAndParentAndRealm())
+ .types(AssetType.AGENT)
.tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.realm))
)
@@ -90,11 +91,11 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
assets[0].realm == null
assets[0].path == null
- when: "a user filtering query is executed that returns only IDs, names and attribute names"
+ when: "a user filtering query is executed that returns only IDs, names and attribute names and label meta"
assets = assetStorageService.findAll(
new AssetQuery()
- .select(new Select(Include.ONLY_ID_AND_NAME_AND_ATTRIBUTE_NAMES))
- .userId(keycloakDemoSetup.testuser3Id)
+ .select(Select.selectExcludeAll().excludeAttributes(false).excludeAttributeMeta(false).meta(MetaItemType.LABEL))
+ .userIds(keycloakDemoSetup.testuser3Id)
)
then: "only the users assets should be retrieved"
@@ -112,11 +113,15 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
assets.get(4).id == managerDemoSetup.apartment1Bedroom1Id
assets.get(5).id == managerDemoSetup.apartment1BathroomId
- when: "a user filtering query is executed that returns only IDs, names and attribute names and limits to protected attributes and meta"
+ when: "a user filtering query is executed that returns only IDs, names and attribute names with labels and limits to protected attributes"
assets = assetStorageService.findAll(
new AssetQuery()
- .select(new Select(Include.ONLY_ID_AND_NAME_AND_ATTRIBUTE_NAMES, RESTRICTED_READ))
- .userId(keycloakDemoSetup.testuser3Id)
+ .select(Select.selectExcludeAll()
+ .excludeAttributes(false)
+ .excludeAttributeMeta(false)
+ .meta(MetaItemType.LABEL))
+ .userIds(keycloakDemoSetup.testuser3Id)
+ .access(PROTECTED)
)
then: "only the users assets should be retrieved"
@@ -127,6 +132,8 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
!assets.get(1).getAttribute("motionSensor").isPresent()
!assets.get(1).getAttribute("currentTemperature").get().getValue().isPresent()
assets.get(1).getAttribute("currentTemperature").get().meta.size() == 1
+ assets[1].getAttribute("currentTemperature").get().getMetaItem(MetaItemType.LABEL).isPresent()
+ assets[1].getAttribute("currentTemperature").get().getLabelOrName().get() == "Current temperature"
!assets.get(1).getAttribute("targetTemperature").get().getValue().isPresent()
assets.get(1).getAttribute("targetTemperature").get().meta.size() == 1
assets.get(2).id == managerDemoSetup.apartment1KitchenId
@@ -137,8 +144,9 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
when: "a query is executed that returns a protected attribute without any other meta items"
assets = assetStorageService.findAll(
new AssetQuery()
- .select(new Select(Include.ALL_EXCEPT_PATH, RESTRICTED_READ))
- .id(managerDemoSetup.apartment2LivingroomId)
+ .select(Select.selectAll().excludePath(true))
+ .ids(managerDemoSetup.apartment2LivingroomId)
+ .access(PROTECTED)
)
then: "only one asset should be retrieved"
@@ -152,19 +160,21 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
when: "a recursive query is executed to select asset id, name and attribute names for apartment 1 assets"
assets = assetStorageService.findAll(
new AssetQuery()
- .id(managerDemoSetup.smartBuildingId)
- .select(new Select(Include.ONLY_ID_AND_NAME_AND_ATTRIBUTE_NAMES, true, RESTRICTED_READ))
- .orderBy(new OrderBy(CREATED_ON))
+ .ids(managerDemoSetup.smartBuildingId)
+ .select(Select.selectExcludeAll().excludeAttributes(false))
+ .orderBy(new OrderBy(CREATED_ON))
+ .recursive(true)
+ .access(PROTECTED)
)
- then: "result should contain only ids, names and attribute names and label meta"
+ then: "result should contain only basic info and attribute names"
assets.size() == 13
assets[0].id == managerDemoSetup.smartBuildingId
assets[0].name == "Smart Building"
assets[1].id == managerDemoSetup.apartment1Id
- assets[1].createdOn == null
assets[1].name == "Apartment 1"
assets[1].type == AssetType.RESIDENCE.getType()
+ assets[1].createdOn != null
assets[1].parentId == null
assets[1].parentName == null
assets[1].parentType == null
@@ -178,9 +188,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
assets[1].getAttribute("lastExecutedScene").isPresent()
assets[1].getAttribute("presenceDetected").isPresent()
assets[1].getAttribute("location").isPresent()
- assets[1].getAttribute("alarmEnabled").get().meta.size() == 1
- assets[1].getAttribute("alarmEnabled").get().getMetaItem(MetaItemType.LABEL).isPresent()
- assets[1].getAttribute("alarmEnabled").get().getLabelOrName().get() == "Alarm enabled"
+ assets[1].getAttribute("alarmEnabled").get().meta.size() == 0
assets[2].id == managerDemoSetup.apartment1ServiceAgentId
assets[3].id == managerDemoSetup.apartment1LivingroomId
assets[4].id == managerDemoSetup.apartment1KitchenId
@@ -219,7 +227,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
when: "a query is executed"
asset = assetStorageService.find(
new AssetQuery()
- .id(managerDemoSetup.smartOfficeId)
+ .ids(managerDemoSetup.smartOfficeId)
)
then: "result should match"
@@ -238,8 +246,8 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
when: "a query is executed"
asset = assetStorageService.find(
new AssetQuery()
- .select(new Select(Include.ALL))
- .id(managerDemoSetup.smartOfficeId)
+ .select(Select.selectAll())
+ .ids(managerDemoSetup.smartOfficeId)
)
then: "result should match"
@@ -259,7 +267,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
when: "a query is executed"
assets = assetStorageService.findAll(
new AssetQuery()
- .parent(new ParentPredicate(true))
+ .parents(new ParentPredicate(true))
.tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.realm))
)
@@ -280,8 +288,8 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
when: "a query is executed"
assets = assetStorageService.findAll(
new AssetQuery()
- .select(new Select(Include.ALL))
- .parent(new ParentPredicate(true))
+ .select(Select.selectAll())
+ .parents(new ParentPredicate(true))
.tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.realm))
)
@@ -303,7 +311,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
when: "a query is executed"
assets = assetStorageService.findAll(
new AssetQuery()
- .parent(new ParentPredicate(managerDemoSetup.smartBuildingId))
+ .parents(new ParentPredicate(managerDemoSetup.smartBuildingId))
)
then: "result should match"
@@ -324,7 +332,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
when: "a query is executed"
assets = assetStorageService.findAll(
new AssetQuery()
- .parent(new ParentPredicate(managerDemoSetup.smartBuildingId))
+ .parents(new ParentPredicate(managerDemoSetup.smartBuildingId))
.tenant(new TenantPredicate(keycloakDemoSetup.tenantA.realm))
)
@@ -337,7 +345,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
when: "a query is executed"
assets = assetStorageService.findAll(
new AssetQuery()
- .parent(new ParentPredicate(managerDemoSetup.smartBuildingId))
+ .parents(new ParentPredicate(managerDemoSetup.smartBuildingId))
.tenant(new TenantPredicate(keycloakDemoSetup.tenantA.realm))
.orderBy(new OrderBy(NAME, true))
)
@@ -351,7 +359,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
when: "a query is executed"
assets = assetStorageService.findAll(
new AssetQuery()
- .parent(new ParentPredicate(managerDemoSetup.smartBuildingId))
+ .parents(new ParentPredicate(managerDemoSetup.smartBuildingId))
.tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.realm))
)
@@ -361,7 +369,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
when: "a query is executed"
assets = assetStorageService.findAll(
new AssetQuery()
- .path(new PathPredicate(assetStorageService.find(managerDemoSetup.apartment1Id, true).getPath()))
+ .paths(new PathPredicate(assetStorageService.find(managerDemoSetup.apartment1Id, true).getPath()))
)
then: "result should match"
@@ -377,8 +385,8 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
when: "a query is executed"
assets = assetStorageService.findAll(
new AssetQuery()
- .path(new PathPredicate(assetStorageService.find(managerDemoSetup.apartment1Id, true).getPath()))
- .type(AssetType.ROOM)
+ .paths(new PathPredicate(assetStorageService.find(managerDemoSetup.apartment1Id, true).getPath()))
+ .types(AssetType.ROOM)
)
then: "result should match"
@@ -391,7 +399,10 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
when: "a query is executed"
assets = assetStorageService.findAll(
- new AssetQuery().select(new Select(Include.ALL, RESTRICTED_READ)).userId(keycloakDemoSetup.testuser3Id)
+ new AssetQuery()
+ .select(Select.selectAll())
+ .userIds(keycloakDemoSetup.testuser3Id)
+ .access(PROTECTED)
)
then: "result should match"
@@ -410,7 +421,9 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
when: "a query is executed"
assets = assetStorageService.findAll(
- new AssetQuery().select(new Select(Include.ALL, RESTRICTED_READ)).userId(keycloakDemoSetup.testuser2Id)
+ new AssetQuery().select(Select.selectAll())
+ .userIds(keycloakDemoSetup.testuser2Id)
+ .access(PROTECTED)
)
then: "result should match"
@@ -433,7 +446,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
when: "a query is executed"
def assets = assetStorageService.findAll(
- new AssetQuery().type(AssetType.AGENT)
+ new AssetQuery().types(AssetType.AGENT)
)
then: "result should match"
@@ -444,8 +457,8 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
when: "a query is executed"
assets = assetStorageService.findAll(new AssetQuery()
- .type(THING)
- .parent(new ParentPredicate(managerDemoSetup.agentId))
+ .types(THING)
+ .parents(new ParentPredicate(managerDemoSetup.agentId))
)
then: "result should match"
@@ -454,8 +467,8 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
when: "a query is executed"
assets = assetStorageService.findAll(new AssetQuery()
- .type(THING)
- .parent(new ParentPredicate().type(AssetType.AGENT))
+ .types(THING)
+ .parents(new ParentPredicate().type(AssetType.AGENT))
)
then: "result should match"
@@ -507,7 +520,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
managerDemoSetup.agentId,
managerDemoSetup.agentProtocolConfigName
)
- ).name(new StringPredicate(Match.CONTAINS, false, "thing"))
+ ).names(new StringPredicate(Match.CONTAINS, false, "thing"))
)
then: "result should match"
@@ -522,7 +535,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
managerDemoSetup.agentId,
managerDemoSetup.agentProtocolConfigName
)
- ).name(new StringPredicate(Match.CONTAINS, true, "thing"))
+ ).names(new StringPredicate(Match.CONTAINS, true, "thing"))
)
then: "result should match"
@@ -536,7 +549,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
managerDemoSetup.agentId,
managerDemoSetup.agentProtocolConfigName
)
- ).parent(new ParentPredicate(managerDemoSetup.agentId))
+ ).parents(new ParentPredicate(managerDemoSetup.agentId))
)
then: "result should match"
@@ -551,7 +564,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
managerDemoSetup.agentId,
managerDemoSetup.agentProtocolConfigName
)
- ).parent(new ParentPredicate(managerDemoSetup.apartment1LivingroomId))
+ ).parents(new ParentPredicate(managerDemoSetup.apartment1LivingroomId))
)
then: "result should match"
@@ -574,8 +587,9 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
when: "a query is executed to select a subset of attributes"
def asset = assetStorageService.find(
new AssetQuery()
- .id(managerDemoSetup.apartment1LivingroomId)
- .select(new Select(Include.ALL, false, PRIVATE_READ, "co2Level", "lastPresenceDetected", "motionSensor"))
+ .ids(managerDemoSetup.apartment1LivingroomId)
+ .select(Select.selectAll().attributes("co2Level", "lastPresenceDetected", "motionSensor"))
+ .access(PRIVATE)
)
then: "result should match"
@@ -600,8 +614,9 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
when: "a query is executed to select a subset of protected attributes"
asset = assetStorageService.find(
new AssetQuery()
- .id(managerDemoSetup.apartment1LivingroomId)
- .select(new Select(Include.ALL, false, RESTRICTED_READ, "co2Level", "lastPresenceDetected", "motionSensor"))
+ .ids(managerDemoSetup.apartment1LivingroomId)
+ .select(Select.selectAll().attributes("co2Level", "lastPresenceDetected", "motionSensor"))
+ .access(PROTECTED)
)
then: "result should contain only matches that are protected"
@@ -623,7 +638,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
when: "a query is executed to select an asset with an attribute of a certain value"
asset = assetStorageService.find(
- new AssetQuery().select(new Select(Include.ONLY_ID_AND_NAME_AND_ATTRIBUTES)).attributes(
+ new AssetQuery().select(Select.selectExcludePathAndParentAndRealm()).attributes(
new AttributePredicate(
new StringPredicate("windowOpen"), new BooleanPredicate(false)
),
@@ -650,7 +665,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
when: "a location filtering query is executed"
def assets = assetStorageService.findAll(
new AssetQuery()
- .select(new Select(Include.ONLY_ID_AND_NAME))
+ .select(Select.selectExcludeAll())
.attributes(new LocationAttributePredicate(new RadialGeofencePredicate(10, 51.44541688237109d, 5.460315214821094d)))
.tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.realm))
.orderBy(new OrderBy(NAME))
@@ -682,7 +697,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
when: "the same query is run again"
assets = assetStorageService.findAll(
new AssetQuery()
- .select(new Select(Include.ONLY_ID_AND_NAME))
+ .select(Select.selectExcludeAll())
.attributes(new LocationAttributePredicate(new RadialGeofencePredicate(10, 51.44541688237109d, 5.460315214821094d)))
.tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.realm))
.orderBy(new OrderBy(NAME))
@@ -695,7 +710,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
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))
+ .select(Select.selectExcludeAll())
.attributes(new LocationAttributePredicate(new RectangularGeofencePredicate(51.44540d, 5.46031d, 51.44594d, 5.46110d)))
.tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.realm))
.orderBy(new OrderBy(NAME))
@@ -717,7 +732,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
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))
+ .select(Select.selectExcludeAll())
.attributes(new LocationAttributePredicate(new RectangularGeofencePredicate(51.44542d, 5.46032d, 51.44590d, 5.46100d)))
.tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.realm))
.orderBy(new OrderBy(NAME))
@@ -729,7 +744,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
when: "the same region is used but negated"
assets = assetStorageService.findAll(
new AssetQuery()
- .select(new Select(Include.ONLY_ID_AND_NAME))
+ .select(Select.selectExcludeAll())
.attributes(new LocationAttributePredicate(new RectangularGeofencePredicate(51.44542d, 5.46032d, 51.44590d, 5.46100d).negate()))
.tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.realm))
.orderBy(new OrderBy(NAME))
@@ -775,7 +790,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
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
+ .select(Select.selectAll().excludePath(true)) // Need attributes to do calendar filtering
.tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.realm))
.calendarEventActive(1517155200) // 28/01/2018 @ 4:00pm (UTC)
.orderBy(new OrderBy(NAME))
@@ -797,7 +812,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
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))
+ .select(Select.selectAll().excludePath(true))
.tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.realm))
.calendarEventActive(1517335200) // 30/01/2018 @ 6:00pm (UTC)
.orderBy(new OrderBy(NAME))
@@ -810,7 +825,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
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))
+ .select(Select.selectAll().excludePath(true))
.tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.realm))
.calendarEventActive(1517238600) // 29/01/2018 @ 3:10pm (UTC)
.orderBy(new OrderBy(NAME))
@@ -823,7 +838,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
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
+ .select(Select.selectAll().excludePath(true)) // Need attributes to do calendar filtering
.tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.realm))
.calendarEventActive(1517849400) // 05/02/2018 @ 4:50pm (UTC))
.orderBy(new OrderBy(NAME))
@@ -845,7 +860,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
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))
+ .select(Select.selectAll().excludePath(true))
.tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.realm))
.calendarEventActive(1518017520) // 02/07/2018 @ 3:32pm (UTC)
.orderBy(new OrderBy(NAME))
diff --git a/test/src/test/groovy/org/openremote/test/protocol/TimerProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/TimerProtocolTest.groovy
index 4ad4249f9..e8dc85285 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/TimerProtocolTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/TimerProtocolTest.groovy
@@ -45,7 +45,7 @@ class TimerProtocolTest extends Specification implements ManagerContainerTrait {
assert noEventProcessedIn(assetProcessingService, 500)
apartment1 = assetStorageService.find(managerDemoSetup.apartment1Id, true)
- sceneAgent = assetStorageService.find(new AssetQuery().name("Scene Agent").type(AssetType.AGENT).parent(managerDemoSetup.apartment1Id))
+ sceneAgent = assetStorageService.find(new AssetQuery().names("Scene Agent").types(AssetType.AGENT).parents(managerDemoSetup.apartment1Id))
sceneAgent = assetStorageService.find(sceneAgent.id, true)
assert apartment1.getAttribute("daySceneTimeFRIDAY").get().getValueAsString().orElse("") == "08:30:00"
assert sceneAgent != null
diff --git a/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientProtocolTest.groovy
index bb8502dfc..ba79e01d2 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientProtocolTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientProtocolTest.groovy
@@ -40,7 +40,6 @@ import org.openremote.model.attribute.*
import org.openremote.model.event.shared.EventSubscription
import org.openremote.model.event.shared.SharedEvent
import org.openremote.model.query.AssetQuery
-import org.openremote.model.query.BaseAssetQuery
import org.openremote.model.query.filter.StringPredicate
import org.openremote.model.value.*
import org.openremote.test.ManagerContainerTrait
@@ -167,7 +166,7 @@ class WebsocketClientProtocolTest extends Specification implements ManagerContai
.headers(Values.<ObjectValue>parse(/{"header1": "header1Value1", "header2": ["header2Value1","header2Value2"]}/).get())
.uri("https://mockapi/assets")
.body(
- Container.JSON.writeValueAsString(new AssetQuery().id(managerDemoSetup.apartment1LivingroomId))
+ Container.JSON.writeValueAsString(new AssetQuery().ids(managerDemoSetup.apartment1LivingroomId))
)
))
).orElse(null)
@@ -209,7 +208,7 @@ class WebsocketClientProtocolTest extends Specification implements ManagerContai
] as ValueFilter[]
, Container.JSON).orElse(null)),
new MetaItem(WebsocketClientProtocol.META_ATTRIBUTE_MESSAGE_MATCH_PREDICATE,
- new StringPredicate(BaseAssetQuery.Match.CONTAINS, true, "targetTemperature").toModelValue()),
+ new StringPredicate(AssetQuery.Match.CONTAINS, true, "targetTemperature").toModelValue()),
new MetaItem(Protocol.META_ATTRIBUTE_VALUE_FILTERS,
Values.convert(
[
@@ -237,7 +236,7 @@ class WebsocketClientProtocolTest extends Specification implements ManagerContai
] as ValueFilter[]
, Container.JSON).orElse(null)),
new MetaItem(WebsocketClientProtocol.META_ATTRIBUTE_MESSAGE_MATCH_PREDICATE,
- new StringPredicate(BaseAssetQuery.Match.CONTAINS, "co2Level").toModelValue()),
+ new StringPredicate(AssetQuery.Match.CONTAINS, "co2Level").toModelValue()),
new MetaItem(Protocol.META_ATTRIBUTE_VALUE_FILTERS,
Values.convert(
[
diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesFactsTest.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesFactsTest.groovy
index aec3cfd91..ebfb900d0 100644
--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesFactsTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesFactsTest.groovy
@@ -8,7 +8,7 @@ import org.openremote.manager.asset.AssetStorageService
import org.openremote.manager.rules.RulesClock
import org.openremote.manager.rules.RulesEngine
import org.openremote.manager.rules.RulesFacts
-import org.openremote.model.rules.Assets
+import org.openremote.manager.rules.facade.AssetsFacade
import spock.lang.Specification
import java.util.stream.Collectors
@@ -50,7 +50,7 @@ class BasicRulesFactsTest extends Specification {
def setup() {
given: "some rule facts"
- assetsFacade = Mock(Assets)
+ assetsFacade = Mock(AssetsFacade)
def timerService = new TimerService()
def assetStorageService = new AssetStorageService()
timerService.clock = TimerService.Clock.PSEUDO
diff --git a/test/src/test/resources/org/openremote/test/rules/BasicJsonRules.json b/test/src/test/resources/org/openremote/test/rules/BasicJsonRules.json
index 96cc507f4..975f63d20 100644
--- a/test/src/test/resources/org/openremote/test/rules/BasicJsonRules.json
+++ b/test/src/test/resources/org/openremote/test/rules/BasicJsonRules.json
@@ -1,4 +1,4 @@
-{
+ {
"rules": [
{
"name": "Test Rule",
@@ -87,6 +87,13 @@
"match": "EXACT",
"value": "urn:openremote:asset:room"
}
+ ],
+ "names": [
+ {
+ "predicateType": "string",
+ "match": "EXACT",
+ "value": "Living Room"
+ }
]
}
},
@@ -110,6 +117,13 @@
"match": "EXACT",
"value": "urn:openremote:asset:room"
}
+ ],
+ "names": [
+ {
+ "predicateType": "string",
+ "match": "EXACT",
+ "value": "Living Room"
+ }
]
}
},
diff --git a/test/src/test/resources/org/openremote/test/rules/BasicSmartHomeMatchAllAssetStates.groovy b/test/src/test/resources/org/openremote/test/rules/BasicSmartHomeMatchAllAssetStates.groovy
index 2e45bf43a..b51321555 100644
--- a/test/src/test/resources/org/openremote/test/rules/BasicSmartHomeMatchAllAssetStates.groovy
+++ b/test/src/test/resources/org/openremote/test/rules/BasicSmartHomeMatchAllAssetStates.groovy
@@ -12,7 +12,7 @@ rules.add()
.when(
{ facts ->
!facts.matchFirst("Living Room All").isPresent() &&
- facts.matchFirstAssetState(new AssetQuery().name("Living Room")).isPresent()
+ facts.matchFirstAssetState(new AssetQuery().names("Living Room")).isPresent()
})
.then(
{ facts ->
@@ -24,7 +24,7 @@ rules.add()
.when(
{ facts ->
!facts.matchFirst("Kitchen All").isPresent() &&
- facts.matchFirstAssetState(new AssetQuery().name("Kitchen")).isPresent()
+ facts.matchFirstAssetState(new AssetQuery().names("Kitchen")).isPresent()
})
.then(
{ facts ->
@@ -36,7 +36,7 @@ rules.add()
.when(
{ facts ->
!facts.matchFirst("Kitchen Number Attributes").isPresent() &&
- facts.matchAssetState(new AssetQuery().name("Kitchen"))
+ facts.matchAssetState(new AssetQuery().names("Kitchen"))
.filter({ assetState -> assetState.attributeValueType == AttributeValueType.NUMBER })
.findFirst().isPresent()
})
@@ -92,7 +92,7 @@ rules.add()
.when(
{ facts ->
!facts.matchFirst("Parent Type Residence").isPresent() &&
- facts.matchAssetState(new AssetQuery().parent(AssetType.RESIDENCE))
+ facts.matchAssetState(new AssetQuery().parents(AssetType.RESIDENCE))
.findFirst().isPresent()
})
.then(
@@ -105,7 +105,7 @@ rules.add()
.when(
{ facts ->
!facts.matchFirst("Asset Type Room").isPresent() &&
- facts.matchAssetState(new AssetQuery().type(AssetType.ROOM))
+ facts.matchAssetState(new AssetQuery().types(AssetType.ROOM))
.findFirst().isPresent()
})
.then(