100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
More asset model and query optimization
Christian Bauer68a96256e8bb
diff --git a/container/src/main/java/org/openremote/container/persistence/ArrayUserType.java b/container/src/main/java/org/openremote/container/persistence/ArrayUserType.javadeleted file mode 100644index ce6e765ba..000000000--- a/container/src/main/java/org/openremote/container/persistence/ArrayUserType.java+++ /dev/null@@ -1,103 +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.container.persistence;--import org.hibernate.HibernateException;-import org.hibernate.engine.spi.SharedSessionContractImplementor;-import org.hibernate.usertype.UserType;--import java.io.Serializable;-import java.sql.*;--/**- * Map Postgres/JDBC text array to Java String array.- */-public class ArrayUserType implements UserType {-- protected static final int[] SQL_TYPES = {Types.ARRAY};-- public final int[] sqlTypes() {- return SQL_TYPES;- }-- public final Class returnedClass() {- return String[].class;- }-- @Override- public Object nullSafeGet(ResultSet resultSet, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {- if (resultSet.wasNull()) {- return null;- }- return resultSet.getArray(names[0]).getArray();- }-- @Override- public void nullSafeSet(PreparedStatement statement, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {- if (value == null) {- statement.setNull(index, SQL_TYPES[0]);- } else {- String[] castObject = (String[]) value;- Array array = session.connection().createArrayOf("text", castObject);- statement.setArray(index, array);- }- }-- @Override- public final Object deepCopy(final Object value) throws HibernateException {- return value;- }-- @Override- public final boolean isMutable() {- return false;- }-- @Override- public final boolean equals(final Object x, final Object y) throws HibernateException {- if (x == y) {- return true;- } else if (x == null || y == null) {- return false;- } else {- return x.equals(y);- }- }-- @Override- public final int hashCode(final Object x) throws HibernateException {- return x.hashCode();- }-- @Override- public final Object replace(final Object original, final Object target, final Object owner) throws HibernateException {- return original;- }-- @Override- public Serializable disassemble(Object value) throws HibernateException {- return (String[]) value;- }-- @Override- public Object assemble(Serializable cached, Object owner) throws HibernateException {- return cached;- }-}\ No newline at end of filediff --git a/container/src/main/java/org/openremote/container/persistence/StringArrayConverter.java b/container/src/main/java/org/openremote/container/persistence/StringArrayConverter.javadeleted file mode 100644index a973e6194..000000000--- a/container/src/main/java/org/openremote/container/persistence/StringArrayConverter.java+++ /dev/null@@ -1,37 +0,0 @@-/*- * Copyright 2016, 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.container.persistence;--import org.openremote.container.util.TextUtil;--import javax.persistence.AttributeConverter;--public class StringArrayConverter implements AttributeConverter<String[], String> {-- @Override- public String convertToDatabaseColumn(String[] attribute) {- return TextUtil.toCommaSeparated(attribute);- }-- @Override- public String[] convertToEntityAttribute(String data) {- return TextUtil.fromCommaSeparated(data);- }-}\ No newline at end of filediff --git a/container/src/main/java/org/openremote/container/util/TextUtil.java b/container/src/main/java/org/openremote/container/util/TextUtil.javaindex d0fe2d86e..ed513d59f 100644--- a/container/src/main/java/org/openremote/container/util/TextUtil.java+++ b/container/src/main/java/org/openremote/container/util/TextUtil.java@@ -71,7 +71,7 @@ public class TextUtil {}public static String[] fromCommaSeparated(String commaWords) {- if (commaWords == null)+ if (commaWords == null || commaWords.length() == 0)return new String[0];return commaWords.split(",");}diff --git a/manager/client/src/main/java/org/openremote/manager/client/admin/users/AdminUserActivity.java b/manager/client/src/main/java/org/openremote/manager/client/admin/users/AdminUserActivity.javaindex d01d72698..886c1702d 100644--- a/manager/client/src/main/java/org/openremote/manager/client/admin/users/AdminUserActivity.java+++ b/manager/client/src/main/java/org/openremote/manager/client/admin/users/AdminUserActivity.java@@ -37,6 +37,7 @@ import org.openremote.model.Runnable;import javax.inject.Inject;import java.util.*;+import java.util.logging.Logger;import static org.openremote.manager.client.http.RequestExceptionHandler.handleRequestException;@@ -44,6 +45,8 @@ public class AdminUserActivityextends AbstractAdminActivity<AdminUserPlace, AdminUser>implements AdminUser.Presenter {+ private static final Logger LOG = Logger.getLogger(AdminUserActivity.class.getName());+final protected Environment environment;final protected UserResource userResource;final protected UserMapper userMapper;@@ -331,7 +334,7 @@ public class AdminUserActivityroles -> {List<Role> roleList = new ArrayList<>();roleList.addAll(Arrays.asList(roles));- Collections.sort(roleList, (o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName()));+ roleList.sort((o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName()));this.roles = roleList.toArray(new Role[roleList.size()]);adminContent.enableRoles(true);onComplete.run();diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesBrowser.java b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesBrowser.javaindex f2cedff08..75cf57cc1 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesBrowser.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesBrowser.java@@ -112,7 +112,7 @@ public abstract class AttributesBrowser extends AttributesView<AttributesBrowserliveUpdatesCheckBox.addValueChangeHandler(event -> showInfo("TODO: Not implemented"));formField.add(liveUpdatesCheckBox);- if (attributes.get().length > 0) {+ if (attributes.size() > 0) {FormGroupActions formGroupActions = new FormGroupActions();FormButton readAllButton = new FormButton();diff --git a/manager/client/src/main/resources/org/openremote/manager/client/i18n/ManagerMessages.properties b/manager/client/src/main/resources/org/openremote/manager/client/i18n/ManagerMessages.propertiesindex 7e570a5f5..dbeb83840 100644--- a/manager/client/src/main/resources/org/openremote/manager/client/i18n/ManagerMessages.properties+++ b/manager/client/src/main/resources/org/openremote/manager/client/i18n/ManagerMessages.properties@@ -64,6 +64,7 @@ roleLabel[read-assets] = Read asset dataroleLabel[read-rules] = Read rule definitionsroleLabel[read-consoles] = List installed console applicationsroleLabel[write] = WRITE ALL DATA+roleLabel[write-user] = Write own user data (settings, preferences, registered consoles)roleLabel[write-admin] = Write system settings, tenants, and usersroleLabel[write-assets] = Write asset dataroleLabel[write-rules] = Write rules datadiff --git a/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.javaindex c3b708a9c..dff3b6da5 100644--- a/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java@@ -29,8 +29,12 @@ import org.openremote.container.message.MessageBrokerSetupService;import org.openremote.container.persistence.PersistenceEvent;import org.openremote.manager.server.asset.AssetStorageService;import org.openremote.manager.server.asset.AssetUpdate;+import org.openremote.manager.server.asset.ServerAsset;import org.openremote.manager.server.datapoint.AssetDatapointService;-import org.openremote.model.asset.*;+import org.openremote.model.asset.Asset;+import org.openremote.model.asset.AssetQuery;+import org.openremote.model.asset.AssetType;+import org.openremote.model.asset.ThingAttribute;import java.util.Collection;import java.util.List;@@ -69,8 +73,8 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons@Overridepublic void start(Container container) throws Exception {- Asset[] agents = assetStorageService.findByType(AGENT.getValue(), false);- LOG.fine("Deploy all agents in all realms: " + agents.length);+ List<ServerAsset> agents = assetStorageService.findAll(new AssetQuery().type(AssetType.AGENT));+ LOG.fine("Deploy all agents in all realms: " + agents.size());for (Asset agent : agents) {deployAgent(agent, PersistenceEvent.Cause.UPDATE);}@@ -102,7 +106,11 @@ public class AgentService extends RouteBuilder implements ContainerService, Consswitch (cause) {case UPDATE:// TODO: Find everything with this agent ID in the asset tree not just children- Asset[] things = assetStorageService.findChildrenByType(agent.getId(), THING, true);+ List<ServerAsset> things = assetStorageService.findAll(new AssetQuery()+ .select(new AssetQuery.Select(true, false))+ .type(THING)+ .parent(new AssetQuery.Parent(agent.getId()))+ );for (Asset thing : things) {deployThing(thing, PersistenceEvent.Cause.UPDATE);}@@ -179,7 +187,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons/*** If this update is not for an asset of type THING or it has been initiated by* a protocol then we ignore it.- *+ * <p>* Otherwise we push the update to the protocol to handle and prevent any further* processing of this event by the processing chain, the protocol should raise* sensor updates as required (i.e. the protocol is responsible for synchronising state)@@ -206,7 +214,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons// Check attribute is linked to an actual agentThingAttributes thingAttributes = new ThingAttributes(assetUpdate.getAsset());ThingAttribute thingAttribute = thingAttributes.getLinkedAttribute(- assetStorageService.getAgentLinkResolver(), assetUpdate.getAttribute().getName()+ assetStorageService.getAgentLinkResolver(), assetUpdate.getAttribute().getName());if (thingAttribute == null) {diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.javaindex 5d32342ec..e7fa50abe 100644--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java@@ -30,7 +30,7 @@ import org.openremote.model.AttributeEvent;import org.openremote.model.AttributeRef;import org.openremote.model.Attributes;import org.openremote.model.asset.Asset;-import org.openremote.model.asset.ProtectedAsset;+import org.openremote.model.asset.AssetQuery;import javax.ws.rs.WebApplicationException;import javax.ws.rs.core.Response;@@ -58,31 +58,34 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour}@Override- public ProtectedAsset[] getCurrentUserAssets(RequestParams requestParams) {+ public Asset[] getCurrentUserAssets(RequestParams requestParams) {try {if (isSuperUser() || !isRestrictedUser()) {- return new ProtectedAsset[0];+ return new Asset[0];}- List<ProtectedAsset> assets = Arrays.asList(assetStorageService.findProtectedOfUser(getUserId(), true));+ List<ServerAsset> assets = assetStorageService.findAll(+ new AssetQuery().select(new AssetQuery.Select(true, true)).userId(getUserId())+ );+// Filter assets that might have been moved into a different realm and can no longer be accessed by user// TODO: Should we forbid moving assets between realms?- Iterator<ProtectedAsset> it = assets.iterator();+ Iterator<ServerAsset> it = assets.iterator();while (it.hasNext()) {- ProtectedAsset asset = it.next();+ ServerAsset asset = it.next();String assetRealm = identityService.getActiveTenantRealm(asset.getRealmId());if (!assetRealm.equals(getAuthenticatedRealm())) {LOG.warning("User '" + getUsername() + "' has protected asset outside of authenticated realm, skipping: " + asset);it.remove();}}- return assets.toArray(new ProtectedAsset[assets.size()]);+ return assets.toArray(new ServerAsset[assets.size()]);} catch (IllegalStateException ex) {throw new WebApplicationException(ex, Response.Status.BAD_REQUEST);}}@Override- public void updateCurrentUserAsset(RequestParams requestParams, String assetId, ProtectedAsset protectedAsset) {+ public void updateCurrentUserAsset(RequestParams requestParams, String assetId, Asset protectedAsset) {throw new UnsupportedOperationException("Not Implemented"); // TODO}@@ -99,7 +102,14 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResourif (!isRealmAccessibleByUser(realm) || isRestrictedUser()) {return new Asset[0];}- return assetStorageService.findRoot(realmId, false);++ List<ServerAsset> result = assetStorageService.findAll(+ new AssetQuery()+ .parent(new AssetQuery.Parent(true))+ .realm(new AssetQuery.Realm(realmId))+ );+ return result.toArray(new Asset[result.size()]);+} catch (IllegalStateException ex) {throw new WebApplicationException(ex, Response.Status.BAD_REQUEST);}@@ -112,13 +122,22 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResourreturn new Asset[0];}if (isSuperUser()) {- return assetStorageService.findChildren(parentId, false);+ List<ServerAsset> result = assetStorageService.findAll(+ new AssetQuery()+ .parent(new AssetQuery.Parent(parentId))+ );+ return result.toArray(new Asset[result.size()]);} else {String realmId = identityService.getActiveTenantRealmId(getAuthenticatedRealm());if (realmId == null) {throw new WebApplicationException(NOT_FOUND);}- return assetStorageService.findChildrenInRealm(parentId, realmId, false);+ List<ServerAsset> result = assetStorageService.findAll(+ new AssetQuery()+ .parent(new AssetQuery.Parent(parentId))+ .realm(new AssetQuery.Realm(realmId))+ );+ return result.toArray(new Asset[result.size()]);}} catch (IllegalStateException ex) {throw new WebApplicationException(ex, Response.Status.BAD_REQUEST);@@ -157,7 +176,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResourif (isRestrictedUser()) {throw new WebApplicationException(Response.Status.FORBIDDEN);}- ServerAsset serverAsset = assetStorageService.find(assetId, true);+ ServerAsset serverAsset = assetStorageService.find(assetId, true, false);if (serverAsset == null)throw new WebApplicationException(NOT_FOUND);@@ -202,7 +221,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour@Overridepublic void writeAttributeValue(RequestParams requestParams, String assetId, String attributeName, String rawJson) {try {- ServerAsset asset = assetStorageService.find(assetId, true);+ ServerAsset asset = assetStorageService.find(assetId, true, false);if (asset == null)throw new WebApplicationException(NOT_FOUND);@@ -227,7 +246,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour// Check restrictedif (isRestrictedUser() &&- !assetStorageService.findProtectedOfUserContains(getUserId(), asset.getId())) {+ !assetStorageService.isUserAsset(getUserId(), asset.getId())) {throw new WebApplicationException(Response.Status.FORBIDDEN);}@@ -247,7 +266,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour@Overridepublic String readAttributeValue(RequestParams requestParams, String assetId, String attributeName) {try {- ServerAsset asset = assetStorageService.find(assetId, true);+ ServerAsset asset = assetStorageService.find(assetId, true, false);if (asset == null)throw new WebApplicationException(NOT_FOUND);@@ -267,7 +286,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour// Check restrictedif (isRestrictedUser() &&- !assetStorageService.findProtectedOfUserContains(getUserId(), asset.getId())) {+ !assetStorageService.isUserAsset(getUserId(), asset.getId())) {throw new WebApplicationException(Response.Status.FORBIDDEN);}@@ -329,7 +348,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResourif (isRestrictedUser()) {throw new WebApplicationException(Response.Status.FORBIDDEN);}- ServerAsset serverAsset = assetStorageService.find(assetId, true);+ ServerAsset serverAsset = assetStorageService.find(assetId, true, false);if (serverAsset == null)return;String realm = identityService.getActiveTenantRealm(serverAsset.getRealmId());diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.javaindex d79b5e9e8..8562d4193 100644--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java@@ -22,28 +22,24 @@ package org.openremote.manager.server.asset;import elemental.json.JsonType;import elemental.json.JsonValue;import org.hibernate.Session;+import org.hibernate.jdbc.AbstractReturningWork;import org.openremote.container.Container;import org.openremote.container.ContainerService;import org.openremote.container.persistence.PersistenceService;+import org.openremote.container.util.Pair;import org.openremote.container.web.WebService;import org.openremote.manager.server.agent.AgentAttributes;import org.openremote.manager.server.security.ManagerIdentityService;-import org.openremote.manager.server.security.RealmView;import org.openremote.model.*;import org.openremote.model.asset.Asset;-import org.openremote.model.asset.AssetType;+import org.openremote.model.asset.AssetQuery;import org.openremote.model.asset.ProtocolConfiguration;import org.openremote.model.asset.UserAsset;import org.postgresql.util.PGobject;import javax.persistence.EntityManager;-import javax.persistence.NoResultException;-import javax.persistence.criteria.*;-import java.sql.Array;-import java.sql.PreparedStatement;-import java.sql.ResultSet;+import java.sql.*;import java.util.ArrayList;-import java.util.Arrays;import java.util.List;import java.util.function.Consumer;import java.util.logging.Logger;@@ -64,7 +60,7 @@ public class AssetStorageService implements ContainerService, Consumer<AssetUpdafinal protected Function<AttributeRef, ProtocolConfiguration> agentLinkResolver = agentLink -> {// Resolve the agent and the protocol configuration// TODO This is very inefficient and requires Hibernate second-level caching- Asset agent = find(agentLink.getEntityId(), true);+ Asset agent = find(agentLink.getEntityId(), true, false);if (agent != null && agent.getWellKnownType().equals(AGENT)) {AgentAttributes agentAttributes = new AgentAttributes(agent);return agentAttributes.getProtocolConfiguration(agentLink.getAttributeName());@@ -96,165 +92,50 @@ public class AssetStorageService implements ContainerService, Consumer<AssetUpda}- public Function<AttributeRef, ProtocolConfiguration> getAgentLinkResolver() {- return agentLinkResolver;- }-- /**- * Find assets without a parent in a realm.- *- * @param realmId The realm to search.- * @param loadComplete If the whole asset data (including path and attributes) should be loaded.- * @return The root assets of the realm ordered ascending by creation date, or an empty array if there is no data.- */- public ServerAsset[] findRoot(String realmId, boolean loadComplete) {- if (realmId == null || realmId.length() == 0)- throw new IllegalArgumentException("Realm must be provided to query assets");- return persistenceService.doReturningTransaction(em -> {- List<ServerAsset> result = em.createQuery(buildAssetQuery(- em.getCriteriaBuilder(),- ServerAsset.class, null, null, realmId, null, null, true, loadComplete, null- )).getResultList();- return result.toArray(new ServerAsset[result.size()]);- });+ @Override+ public void accept(AssetUpdate assetUpdate) {+ String assetId = assetUpdate.getAsset().getId();+ String attributeName = assetUpdate.getAttribute().getName();+ JsonValue value = assetUpdate.getAttribute().getValue();+ // Some sanity checking, of course the timestamp should never be -1 if we store updated attribute state+ long timestamp = assetUpdate.getAttribute().getValueTimestamp();+ String valueTimestamp = Long.toString(+ timestamp >= 0 ? timestamp : System.currentTimeMillis()+ );+ if (!storeAttributeValue(assetId, attributeName, value, valueTimestamp)) {+ throw new RuntimeException("Database update failed, no rows updated");+ }}- /**- * Retrieve the children of an asset.- *- * @param parentId The ID of the parent asset.- * @param loadComplete If the whole asset data (including path and attributes) should be loaded.- * @return The child assets ordered ascending by creation date, or an empty array if there is no data.- */- public ServerAsset[] findChildren(String parentId, boolean loadComplete) {- return persistenceService.doReturningTransaction(em -> {- List<ServerAsset> result = em.createQuery(buildAssetQuery(- em.getCriteriaBuilder(),- ServerAsset.class, null, parentId, null, null, null, false, loadComplete, null- )).getResultList();- return result.toArray(new ServerAsset[result.size()]);- });+ public Function<AttributeRef, ProtocolConfiguration> getAgentLinkResolver() {+ return agentLinkResolver;}- /**- * Retrieve the children of an asset in a particular realm.- *- * @param parentId The ID of the parent asset.- * @param realmId The realm in which both parent asset and its children must be.- * @param loadComplete If the whole asset data (including path and attributes) should be loaded.- * @return The child assets ordered ascending by creation date, or an empty array if there is no data.- */- public ServerAsset[] findChildrenInRealm(String parentId, String realmId, boolean loadComplete) {- return persistenceService.doReturningTransaction(em -> {- List<ServerAsset> result = em.createQuery(buildAssetQuery(- em.getCriteriaBuilder(),- ServerAsset.class, null, parentId, realmId, null, null, false, loadComplete, null- )).getResultList();- return result.toArray(new ServerAsset[result.size()]);- });+ public ServerAsset find(String assetId) {+ return find(new AssetQuery().id(assetId));}/**- * Find an asset by primary key and populate all transient details (path, tenant).- *- * @param assetId The primary key identifier value of the asset.* @param loadComplete If the whole asset data (including path and attributes) should be loaded.- * @return The asset or <code>null</code> if the asset doesn't exist.*/public ServerAsset find(String assetId, boolean loadComplete) {- return persistenceService.doReturningTransaction(em -> {- try {- return em.createQuery(buildAssetQuery(- em.getCriteriaBuilder(),- ServerAsset.class, assetId, null, null, null, null, false, loadComplete, null- )).getSingleResult();- } catch (NoResultException ex) {- return null;- }- });+ return find(new AssetQuery().select(new AssetQuery.Select(loadComplete, false)).id(assetId));}/**- * Find assets by type in all realms.- *- * @param assetType The type of the assets to find.- * @param loadComplete If the whole asset data (including path and attributes) should be loaded.- * @return The found assets or an empty array+ * @param loadComplete If the whole asset data (including path and attributes) should be loaded.+ * @param filterProtected If the asset attributes should be filtered and only protected details included.*/- public ServerAsset[] findByType(String assetType, boolean loadComplete) {- return persistenceService.doReturningTransaction(em -> {- List<ServerAsset> result = em.createQuery(buildAssetQuery(- em.getCriteriaBuilder(),- ServerAsset.class, null, null, null, null, assetType, false, loadComplete, null- )).getResultList();- return result.toArray(new ServerAsset[result.size()]);- });+ public ServerAsset find(String assetId, boolean loadComplete, boolean filterProtected) {+ return find(new AssetQuery().select(new AssetQuery.Select(loadComplete, filterProtected)).id(assetId));}- /**- * Find children of the given asset by type.- *- * @param parentId The ID of the parent asset.- * @param assetType The well-known type of the assets to find.- * @param loadComplete If the whole asset data (including path and attributes) should be loaded.- * @return The found assets or an empty array- */- public ServerAsset[] findChildrenByType(String parentId, AssetType assetType, boolean loadComplete) {- return persistenceService.doReturningTransaction(em -> {- List<ServerAsset> result = em.createQuery(buildAssetQuery(- em.getCriteriaBuilder(),- ServerAsset.class, null, parentId, null, null, assetType.getValue(), false, loadComplete, null- )).getResultList();- return result.toArray(new ServerAsset[result.size()]);- });- }--- /**- * Find protected assets linked to a user.- *- * @param userId The primary key identifier value of the user.- * @param loadComplete If the whole asset data (including path and attributes) should be loaded.- * @return The found assets or an empty array.- */- public ProtectedServerAsset[] findProtectedOfUser(String userId, boolean loadComplete) {- return persistenceService.doReturningTransaction(em -> {- List<ProtectedServerAsset> result = em.createQuery(buildAssetQuery(- em.getCriteriaBuilder(),- ProtectedServerAsset.class, null, null, null, userId, null, false, loadComplete, null- )).getResultList();- return result.toArray(new ProtectedServerAsset[result.size()]);- });- }-- /**- * Confirm if protected assets linked to a user contains given asset.- *- * @return The found assets or an empty array.- */- public boolean findProtectedOfUserContains(String userId, String assetId) {- return persistenceService.doReturningTransaction(em -> {- List result = em.createQuery(- "select ua.assetId from UserAsset ua where ua.userId = :userId and ua.assetId = :assetId"- ).setParameter("assetId", assetId).setParameter("userId", userId).getResultList();- return result.size() > 0;- });- }-- public void storeProtected(String userId, String assetId) {- persistenceService.doTransaction(entityManager -> {- UserAsset userAsset = new UserAsset(userId, assetId);- entityManager.merge(userAsset);- });+ public ServerAsset find(AssetQuery query) {+ return persistenceService.doReturningTransaction(em -> find(em, query));}- public void deleteProtected(String userId, String assetId) {- persistenceService.doTransaction(entityManager -> {- UserAsset userAsset = entityManager.find(UserAsset.class, new UserAsset(userId, assetId));- if (userAsset != null) {- entityManager.remove(userAsset);- }- });+ public List<ServerAsset> findAll(AssetQuery query) {+ return persistenceService.doReturningTransaction(em -> findAll(em, query));}/**@@ -270,7 +151,7 @@ public class AssetStorageService implements ContainerService, Consumer<AssetUpda// Validate parentif (asset.getParentId() != null) {// If this is a not a root asset...- ServerAsset parent = loadAsset(em, asset.getParentId(), true);+ ServerAsset parent = find(em, asset.getParentId(), true, false);// .. the parent must existif (parent == null)throw new IllegalStateException("Parent not found: " + asset.getParentId());@@ -298,7 +179,10 @@ public class AssetStorageService implements ContainerService, Consumer<AssetUpdareturn persistenceService.doReturningTransaction(em -> {Asset asset = em.find(ServerAsset.class, assetId);if (asset != null) {- if (findChildren(asset.getId(), false).length > 0)+ List<ServerAsset> children = findAll(em, new AssetQuery()+ .parent(new AssetQuery.Parent(asset.getId()))+ );+ if (children.size() > 0)return false;em.remove(asset);}@@ -311,53 +195,231 @@ public class AssetStorageService implements ContainerService, Consumer<AssetUpdaassetProcessingService.updateAttributeValue(attributeEvent);}- @Override- public void accept(AssetUpdate assetUpdate) {- String assetId = assetUpdate.getAsset().getId();- String attributeName = assetUpdate.getAttribute().getName();- JsonValue value = assetUpdate.getAttribute().getValue();- // Some sanity checking, of course the timestamp should never be -1 if we store updated attribute state- long timestamp = assetUpdate.getAttribute().getValueTimestamp();- String valueTimestamp = Long.toString(- timestamp >= 0 ? timestamp : System.currentTimeMillis()- );- if (!storeAttributeValue(assetId, attributeName, value, valueTimestamp)) {- throw new RuntimeException("Database update failed, no rows updated");+ public boolean isUserAsset(String userId, String assetId) {+ return persistenceService.doReturningTransaction(entityManager -> {+ UserAsset userAsset = entityManager.find(UserAsset.class, new UserAsset(userId, assetId));+ return userAsset != null;+ });+ }++ public void storeUserAsset(String userId, String assetId) {+ persistenceService.doTransaction(entityManager -> {+ UserAsset userAsset = new UserAsset(userId, assetId);+ entityManager.merge(userAsset);+ });+ }++ /* ####################################################################################### */++ protected interface ParameterBinder extends Consumer<PreparedStatement> {+ @Override+ default void accept(PreparedStatement st) {+ try {+ acceptStatement(st);+ } catch (SQLException ex) {+ throw new RuntimeException(ex);+ }}++ void acceptStatement(PreparedStatement st) throws SQLException;}- protected ServerAsset loadAsset(EntityManager em, String assetId, boolean loadDetails) {- ServerAsset asset = em.find(ServerAsset.class, assetId);- if (asset == null)+ protected ServerAsset find(EntityManager em, String assetId, boolean loadComplete, boolean filterProtected) {+ return find(em, new AssetQuery().select(new AssetQuery.Select(loadComplete, filterProtected)).id(assetId));+ }++ public ServerAsset find(EntityManager em, AssetQuery query) {+ List<ServerAsset> result = findAll(em, query);+ if (result.size() == 0)return null;- if (!loadDetails)- return asset;-- asset.setTenantRealm(managerIdentityService.getActiveTenantRealm(asset.getRealmId()));- asset.setTenantDisplayName(managerIdentityService.getActiveTenantDisplayName(asset.getRealmId()));-- asset.setPath(em.unwrap(Session.class).doReturningWork(connection -> {- String query =- "with recursive ASSET_TREE(ID, PARENT_ID, PATH) as (" +- " select A1.ID, A1.PARENT_ID, array[text(A1.ID)] from ASSET A1 where A1.PARENT_ID is null" +- " union all" +- " select A2.ID, A2.PARENT_ID, array_append(AT.PATH, text(A2.ID)) from ASSET A2, ASSET_TREE AT where A2.PARENT_ID = AT.ID" +- ") select PATH from ASSET_TREE where ID = ?";-- ResultSet result = null;- try (PreparedStatement statement = connection.prepareStatement(query)) {- statement.setString(1, assetId);- result = statement.executeQuery();- if (result.next()) {- return (String[]) result.getArray("PATH").getArray();+ if (result.size() > 1) {+ throw new IllegalArgumentException("Query returned more than one asset");+ }+ return result.get(0);++ }++ protected List<ServerAsset> findAll(EntityManager em, AssetQuery query) {+ StringBuilder sb = new StringBuilder();+ sb.append(buildSelectString(query));+ sb.append(buildFromString(query));+ Pair<String, List<ParameterBinder>> whereClause = buildWhereClause(query);+ sb.append(whereClause.key);+ return em.unwrap(Session.class).doReturningWork(new AbstractReturningWork<List<ServerAsset>>() {+ @Override+ public List<ServerAsset> execute(Connection connection) throws SQLException {+ LOG.fine("Preparing asset query: " + sb.toString());+ PreparedStatement st = connection.prepareStatement(sb.toString());+ LOG.fine("Query binders: " + whereClause.value.size());+ for (ParameterBinder binder : whereClause.value) {+ binder.accept(st);+ }+ try (ResultSet rs = st.executeQuery()) {+ List<ServerAsset> result = new ArrayList<>();+ while (rs.next()) {+ result.add(mapResultTuple(query, rs));+ }+ return result;+ }+ }+ });+ }++ protected String buildSelectString(AssetQuery query) {+ StringBuilder sb = new StringBuilder();++ sb.append("select ");+ sb.append("A.ID as ID, A.OBJ_VERSION as OBJ_VERSION, A.CREATED_ON as CREATED_ON, A.NAME as NAME, A.ASSET_TYPE as ASSET_TYPE, ");+ sb.append("A.PARENT_ID as PARENT_ID, ");+ sb.append(query.parent != null && query.parent.noParent+ ? " NULL PARENT_NAME, NULL as PARENT_TYPE, "+ : " P.NAME as PARENT_NAME, P.ASSET_TYPE as PARENT_TYPE, "+ );+ sb.append("A.REALM_ID as REALM_ID, R.NAME as TENANT_NAME, ");+ sb.append("(select RA.VALUE from REALM_ATTRIBUTE RA where RA.REALM_ID = R.ID and RA.NAME = 'displayName') as TENANT_DISPLAY_NAME, ");+ sb.append("A.LOCATION as LOCATION");++ if (query.select != null && query.select.loadComplete) {+ sb.append(", get_asset_tree_path(A.ID) as PATH ");+ sb.append(", A.ATTRIBUTES as ATTRIBUTES");+ } else {+ sb.append(", NULL as PATH, NULL as ATTRIBUTES");+ }++ return sb.toString();+ }++ protected String buildFromString(AssetQuery query) {+ StringBuilder sb = new StringBuilder();++ sb.append(" from ASSET A cross join (select * from REALM) as R ");+++ if (query.parent != null && !query.parent.noParent) {+ sb.append(" cross join ASSET P ");+ } else {+ sb.append(" left outer join ASSET P on A.PARENT_ID = P.ID");+ }++ if (query.id != null) {+ return sb.toString();+ }++ if (query.userId != null) {+ sb.append(" cross join USER_ASSET ua ");+ }++ if (query.hasAttributeRestrictions()) {+ sb.append(" cross join jsonb_each(A.ATTRIBUTES) as AX ");+ sb.append(" cross join jsonb_array_elements(jsonb_extract_path(AX.VALUE, 'meta')) as AM ");+ }++ return sb.toString();+ }++ protected Pair<String, List<ParameterBinder>> buildWhereClause(AssetQuery query) {+ StringBuilder sb = new StringBuilder();+ List<ParameterBinder> binders = new ArrayList<>();++ sb.append(" where r.ID = a.REALM_ID ");++ if (query.id != null) {+ sb.append(" and A.ID = ? ");+ final int pos = binders.size() + 1;+ binders.add(st -> st.setString(pos, query.id));+ return new Pair<>(sb.toString(), binders);+ }++ if (query.name != null) {+ sb.append(query.name.caseSensitive ? " and A.NAME " : " and upper(A.NAME) ");+ sb.append(query.name.match == AssetQuery.Match.EXACT ? " = ? " : " like ? ");+ final int pos = binders.size() + 1;+ binders.add(st -> st.setString(pos, query.name.prepareValue()));+ }++ if (query.parent != null) {+ if (query.parent.id != null) {+ sb.append(" and 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.id));+ } else if (query.parent.type != null) {+ sb.append(" and p.ID = a.PARENT_ID ");+ sb.append(" and P.ASSET_TYPE = ? ");+ final int pos = binders.size() + 1;+ binders.add(st -> st.setString(pos, query.parent.type));+ } else if (query.parent.noParent) {+ sb.append(" and A.PARENT_ID is null ");+ } else {+ }+ }++ if (query.realm != null && query.realm.id != null) {+ sb.append(" and R.ID = ? ");+ final int pos = binders.size() + 1;+ binders.add(st -> st.setString(pos, query.realm.id));+ } else if (query.realm != null && query.realm.name != null) {+ sb.append(" and R.NAME = ? ");+ final int pos = binders.size() + 1;+ binders.add(st -> st.setString(pos, query.realm.id));+ }++ if (query.userId != null) {+ sb.append(" and ua.ASSET_ID = a.ID and ua.USER_ID = ? ");+ final int pos = binders.size() + 1;+ binders.add(st -> st.setString(pos, query.userId));+ }++ if (query.type != null) {+ sb.append(query.type.caseSensitive ? " and A.ASSET_TYPE" : " and upper(A.ASSET_TYPE) ");+ sb.append(query.type.match == AssetQuery.Match.EXACT ? " = ? " : " like ? ");+ final int pos = binders.size() + 1;+ binders.add(st -> st.setString(pos, query.type.prepareValue()));+ }++ if (query.attributeMeta != null) {+ if (query.attributeMeta.itemNameSearch != null) {+ sb.append(query.attributeMeta.itemNameSearch.caseSensitive+ ? " and jsonb_extract_path_text(AM.VALUE, 'name') "+ : " and upper(jsonb_extract_path_text(AM.VALUE, 'name')) "+ );+ sb.append(query.attributeMeta.itemNameSearch.match == AssetQuery.Match.EXACT ? " = ? " : " like ? ");+ final int pos = binders.size() + 1;+ binders.add(st -> st.setString(pos, query.attributeMeta.itemNameSearch.prepareValue()));+ }+ if (query.attributeMeta.itemValueSearch != null) {+ if (query.attributeMeta.itemValueSearch instanceof AssetQuery.StringSearch) {+ AssetQuery.StringSearch stringSearch = (AssetQuery.StringSearch) query.attributeMeta.itemValueSearch;+ sb.append(stringSearch.caseSensitive+ ? " and jsonb_extract_path(AM.VALUE, 'value') "+ : " and upper(jsonb_extract_path(AM.VALUE, 'value')) "+ );+ sb.append(stringSearch.match == AssetQuery.Match.EXACT ? " = ? " : " like ? ");+ final int pos = binders.size() + 1;+ binders.add(st -> st.setString(pos, stringSearch.prepareValue()));+ } else if (query.attributeMeta.itemValueSearch instanceof AssetQuery.BooleanSearch) {+ AssetQuery.BooleanSearch booleanSearch = (AssetQuery.BooleanSearch) query.attributeMeta.itemValueSearch;+ sb.append(" and jsonb_extract_path(AM.VALUE, 'value') = to_jsonb(")+ .append(booleanSearch.predicate)+ .append(") ");}- return null;- } finally {- if (result != null)- result.close();}- }));- return asset;+ // TODO Implement AssetQuery.DecimalSearch+ }++ return new Pair<>(sb.toString(), binders);+ }++ protected ServerAsset mapResultTuple(AssetQuery query, ResultSet rs) throws SQLException {+ LOG.fine("Mapping asset query result tuple: " + rs.getString("ID"));++ return new ServerAsset(+ query.select != null && query.select.filterProtected,+ rs.getString("ID"), rs.getLong("OBJ_VERSION"), rs.getTimestamp("CREATED_ON"), rs.getString("NAME"), rs.getString("ASSET_TYPE"),+ rs.getString("PARENT_ID"), rs.getString("PARENT_NAME"), rs.getString("PARENT_TYPE"),+ rs.getString("REALM_ID"), rs.getString("TENANT_NAME"), rs.getString("TENANT_DISPLAY_NAME"),+ rs.getObject("LOCATION"), rs.getArray("PATH"), rs.getString("ATTRIBUTES")+ );}protected boolean storeAttributeValue(String assetId, String attributeName, JsonValue value, String timestamp) {@@ -413,73 +475,6 @@ public class AssetStorageService implements ContainerService, Consumer<AssetUpda);}- protected <T extends Asset> CriteriaQuery<T> buildAssetQuery(CriteriaBuilder cb,- Class<T> resultClass,- String assetId,- String parentAssetId,- String realmId,- String userId,- String type,- boolean withoutParent,- boolean loadComplete,- String orderBy) {- CriteriaQuery<T> criteria = cb.createQuery(resultClass);- Root<ServerAsset> assetRoot = criteria.from(ServerAsset.class);- Root<ServerAsset> assetParentRoot = criteria.from(ServerAsset.class);- Root<RealmView> realmViewRoot = criteria.from(RealmView.class);- Root<UserAsset> userAssetRoot = userId != null ? criteria.from(UserAsset.class) : null;- List<Predicate> predicates = new ArrayList<Predicate>() {{- add(cb.equal(assetRoot.get("id"), assetParentRoot.get("id")));- add(cb.equal(assetRoot.get("realmId"), realmViewRoot.get("id")));- if (assetId != null) {- add(cb.equal(assetRoot.get("id"), assetId));- }- if (!withoutParent && parentAssetId != null) {- add(cb.equal(assetRoot.get("parentId"), parentAssetId));- } else if (withoutParent) {- add(cb.isNull(assetRoot.get("parentId")));- }- if (realmId != null) {- add(cb.equal(assetRoot.get("realmId"), realmId));- }- if (type != null) {- add(cb.equal(assetRoot.get("type"), type));- }- if (userId != null) {- add(cb.equal(userAssetRoot.get("userId"), userId));- add(cb.equal(assetRoot.get("id"), userAssetRoot.get("assetId")));- }- }};- criteria.where(predicates.toArray(new Predicate[predicates.size()]));- if (assetId == null) {- criteria.orderBy(cb.asc(assetRoot.get(orderBy != null ? orderBy : "createdOn")));- }- List<Selection> projectionArgs = new ArrayList<Selection>() {{- add(assetRoot.get("id"));- add(assetRoot.get("version"));- add(assetRoot.get("createdOn"));- add(assetRoot.get("name"));- add(assetRoot.get("type"));- add(assetRoot.get("parentId"));- add(assetParentRoot.get("name"));- add(assetParentRoot.get("type"));- if (loadComplete)- add(assetRoot.get("path"));- add(assetRoot.get("realmId"));- add(realmViewRoot.get("name"));- add(realmViewRoot.get("displayName"));- add(assetRoot.get("location"));- if (loadComplete)- add(assetRoot.get("attributes"));- }};- return criteria.select(- cb.construct(- resultClass,- projectionArgs.toArray(new Selection[projectionArgs.size()])- )- );- }-public String toString() {return getClass().getSimpleName() + "{" +'}';diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/ProtectedServerAsset.java b/manager/server/src/main/java/org/openremote/manager/server/asset/ProtectedServerAsset.javadeleted file mode 100644index 52b847160..000000000--- a/manager/server/src/main/java/org/openremote/manager/server/asset/ProtectedServerAsset.java+++ /dev/null@@ -1,60 +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.manager.server.asset;--import com.vividsolutions.jts.geom.Geometry;-import com.vividsolutions.jts.geom.Point;-import elemental.json.JsonObject;-import org.openremote.model.asset.ProtectedAsset;--import java.util.Date;--/**- * Provides constructors we can use in database query result marshaling.- */-public class ProtectedServerAsset extends ProtectedAsset {-- public ProtectedServerAsset(String id, long version, Date createdOn, String name, String type,- String parentId, String parentName, String parentType,- String realmId, String tenantRealm, String tenantDisplayName,- Geometry location) {- this(- id, version, createdOn, name, type,- parentId, parentName, parentType, null,- realmId, tenantRealm, tenantDisplayName,- location,- null- );- }-- public ProtectedServerAsset(String id, long version, Date createdOn, String name, String type,- String parentId, String parentName, String parentType, String[] path,- String realmId, String tenantRealm, String tenantDisplayName,- Geometry location,- JsonObject attributes) {- super(- id, version, createdOn, name, type,- parentId, parentName, parentType, path,- realmId, tenantRealm, tenantDisplayName,- attributes- );- ServerAsset.setCoordinates(this, (Point) location);- }-}diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/ServerAsset.java b/manager/server/src/main/java/org/openremote/manager/server/asset/ServerAsset.javaindex f0a2aac9e..ed5f6cafe 100644--- a/manager/server/src/main/java/org/openremote/manager/server/asset/ServerAsset.java+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/ServerAsset.java@@ -24,11 +24,16 @@ import com.vividsolutions.jts.geom.Coordinate;import com.vividsolutions.jts.geom.Geometry;import com.vividsolutions.jts.geom.GeometryFactory;import com.vividsolutions.jts.geom.Point;+import elemental.json.Json;import elemental.json.JsonObject;+import org.geolatte.geom.jts.JTS;import org.hibernate.annotations.Check;+import org.hibernate.spatial.dialect.postgis.PGGeometryTypeDescriptor;import org.openremote.model.asset.Asset;import javax.persistence.*;+import java.sql.Array;+import java.sql.SQLException;import java.util.Date;/**@@ -45,14 +50,14 @@ public class ServerAsset extends Asset {/*** Easy conversion between types, we copy all properties (not a deep copy!)*/- public static <T extends ServerAsset> T map(Asset asset, T serverAsset) {+ public static ServerAsset map(Asset asset, ServerAsset serverAsset) {return map(asset, serverAsset, null, null, null);}- public static <T extends ServerAsset> T map(Asset asset, T serverAsset,- String overrideParentId,- String overrideType,- Double[] overrideLocation) {+ public static ServerAsset map(Asset asset, ServerAsset serverAsset,+ String overrideParentId,+ String overrideType,+ Double[] overrideLocation) {serverAsset.setVersion(asset.getVersion());serverAsset.setRealmId(asset.getRealmId());serverAsset.setName(asset.getName());@@ -91,31 +96,26 @@ public class ServerAsset extends Asset {public ServerAsset() {}- public ServerAsset(String id, long version, Date createdOn, String name, String type,+ public ServerAsset(boolean filterProtectedAttributes,+ String id, long version, Date createdOn, String name, String type,String parentId, String parentName, String parentType,String realmId, String tenantRealm, String tenantDisplayName,- Geometry location) {- this(+ Object location,+ Array path, String attributes) throws SQLException {+ super(+ filterProtectedAttributes,id, version, createdOn, name, type,- parentId, parentName, parentType, null,+ parentId, parentName, parentType,realmId, tenantRealm, tenantDisplayName,- location,- null+ path != null ? (String[]) path.getArray() : null,+ attributes != null && attributes.length() > 0 ? Json.instance().parse(attributes) : null);- }- public ServerAsset(String id, long version, Date createdOn, String name, String type,- String parentId, String parentName, String parentType, String[] path,- String realmId, String tenantRealm, String tenantDisplayName,- Geometry location,- JsonObject attributes) {- super(- id, version, createdOn, name, type,- parentId, parentName, parentType, path,- realmId, tenantRealm, tenantDisplayName,- attributes+ setLocation(+ location != null+ ? (Point) JTS.to(PGGeometryTypeDescriptor.toGeometry(location))+ : null);- setLocation((Point) location);}public ServerAsset(Asset parent) {diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesResourceImpl.javaindex 9868e8dd1..2ce6877ef 100644--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesResourceImpl.java+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesResourceImpl.java@@ -79,8 +79,7 @@ public class RulesResourceImpl extends ManagerWebResource implements RulesResourif (!isRealmAccessibleByUser(asset.getTenantRealm())) {throw new WebApplicationException(Response.Status.FORBIDDEN);}- if (isRestrictedUser() &&- !assetStorageService.findProtectedOfUserContains(getUserId(), assetId)) {+ if (isRestrictedUser() && !assetStorageService.isUserAsset(getUserId(), assetId)) {throw new WebApplicationException(Response.Status.FORBIDDEN);}List<AssetRulesDefinition> result = rulesStorageService.findAssetDefinitions(asset.getRealmId(), assetId);@@ -211,8 +210,7 @@ public class RulesResourceImpl extends ManagerWebResource implements RulesResourif (!isRealmAccessibleByUser(asset.getTenantRealm())) {throw new WebApplicationException(Response.Status.FORBIDDEN);}- if (isRestrictedUser() &&- !assetStorageService.findProtectedOfUserContains(getUserId(), asset.getId())) {+ if (isRestrictedUser() && !assetStorageService.isUserAsset(getUserId(), asset.getId())) {throw new WebApplicationException(Response.Status.FORBIDDEN);}rulesStorageService.merge(rulesDefinition);@@ -231,8 +229,7 @@ public class RulesResourceImpl extends ManagerWebResource implements RulesResourif (!isRealmAccessibleByUser(asset.getTenantRealm())) {throw new WebApplicationException(Response.Status.FORBIDDEN);}- if (isRestrictedUser() &&- !assetStorageService.findProtectedOfUserContains(getUserId(), asset.getId())) {+ if (isRestrictedUser() && !assetStorageService.isUserAsset(getUserId(), asset.getId())) {throw new WebApplicationException(Response.Status.FORBIDDEN);}return existingDefinition;@@ -251,8 +248,7 @@ public class RulesResourceImpl extends ManagerWebResource implements RulesResourif (!isRealmAccessibleByUser(asset.getTenantRealm())) {throw new WebApplicationException(Response.Status.FORBIDDEN);}- if (isRestrictedUser() &&- !assetStorageService.findProtectedOfUserContains(getUserId(), asset.getId())) {+ if (isRestrictedUser() && !assetStorageService.isUserAsset(getUserId(), asset.getId())) {throw new WebApplicationException(Response.Status.FORBIDDEN);}if (!id.equals(rulesDefinition.getId())) {@@ -277,8 +273,7 @@ public class RulesResourceImpl extends ManagerWebResource implements RulesResourif (!isRealmAccessibleByUser(asset.getTenantRealm())) {throw new WebApplicationException(Response.Status.FORBIDDEN);}- if (isRestrictedUser() &&- !assetStorageService.findProtectedOfUserContains(getUserId(), asset.getId())) {+ if (isRestrictedUser() && !assetStorageService.isUserAsset(getUserId(), asset.getId())) {throw new WebApplicationException(Response.Status.FORBIDDEN);}rulesStorageService.delete(AssetRulesDefinition.class, id);diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.javaindex 3e916e470..983c83a99 100644--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java@@ -346,6 +346,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons.map(es ->new Pair<>(assetStorageService.find(es.getKey(), true), es.getValue()))+ .filter(assetAndRules -> assetAndRules.key != null).collect(Collectors.groupingBy(assetAndRules -> assetAndRules.key.getRealmId())).entrySet().stream()diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.javaindex 0d213b5f4..9b48ebf2a 100644--- a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java@@ -393,10 +393,10 @@ public class ManagerDemoSetup extends AbstractManagerSetup {KeycloakDemoSetup keycloakDemoSetup = setupService.getTaskOfType(KeycloakDemoSetup.class);identityService.setRestrictedUser(keycloakDemoSetup.testuser3Id, true);- assetStorageService.storeProtected(keycloakDemoSetup.testuser3Id, apartment1Id);- assetStorageService.storeProtected(keycloakDemoSetup.testuser3Id, apartment1LivingroomId);- assetStorageService.storeProtected(keycloakDemoSetup.testuser3Id, apartment1LivingroomThermostatId);- assetStorageService.storeProtected(keycloakDemoSetup.testuser3Id, apartment2Id);+ assetStorageService.storeUserAsset(keycloakDemoSetup.testuser3Id, apartment1Id);+ assetStorageService.storeUserAsset(keycloakDemoSetup.testuser3Id, apartment1LivingroomId);+ assetStorageService.storeUserAsset(keycloakDemoSetup.testuser3Id, apartment1LivingroomThermostatId);+ assetStorageService.storeUserAsset(keycloakDemoSetup.testuser3Id, apartment2Id);// ################################ Rules demo data ###################################diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/asset/AssetResource.java b/manager/shared/src/main/java/org/openremote/manager/shared/asset/AssetResource.javaindex a907e80ca..c14edff07 100644--- a/manager/shared/src/main/java/org/openremote/manager/shared/asset/AssetResource.java+++ b/manager/shared/src/main/java/org/openremote/manager/shared/asset/AssetResource.java@@ -23,7 +23,6 @@ import jsinterop.annotations.JsType;import org.openremote.manager.shared.http.RequestParams;import org.openremote.manager.shared.http.SuccessStatusCode;import org.openremote.model.asset.Asset;-import org.openremote.model.asset.ProtectedAsset;import javax.annotation.security.RolesAllowed;import javax.validation.Valid;@@ -45,12 +44,11 @@ import static javax.ws.rs.core.MediaType.APPLICATION_JSON;* A <em>restricted</em> user is linked to a subset of assets within its authenticated realm and* may have roles that allow read and/or write access to protected asset details (see* {@link org.openremote.model.asset.UserAsset}).- *+ * <p>* The only operations a restricted user is able to perform are {@link #getCurrentUserAssets},* {@link #updateCurrentUserAsset}, {@link #readAttributeValue} and {@link #writeAttributeValue}.* </li>* </ul>- **/@Path("asset")@JsType(isNative = true)@@ -66,7 +64,7 @@ public interface AssetResource {@Produces(APPLICATION_JSON)@SuccessStatusCode(200)@RolesAllowed({"read:assets"})- ProtectedAsset[] getCurrentUserAssets(@BeanParam RequestParams requestParams);+ Asset[] getCurrentUserAssets(@BeanParam RequestParams requestParams);/*** Updates an asset linked to the current user. A 403 status is returned if a regular user tries to update an@@ -78,7 +76,7 @@ public interface AssetResource {@Consumes(APPLICATION_JSON)@SuccessStatusCode(204)@RolesAllowed({"write:assets"})- void updateCurrentUserAsset(@BeanParam RequestParams requestParams, @PathParam("assetId") String assetId, ProtectedAsset protectedAsset);+ void updateCurrentUserAsset(@BeanParam RequestParams requestParams, @PathParam("assetId") String assetId, Asset protectedAsset);/*** Retrieve the assets without parent (root assets) of the given realm, or if the realm argumentdiff --git a/manager/shared/src/main/java/org/openremote/manager/shared/security/ClientRole.java b/manager/shared/src/main/java/org/openremote/manager/shared/security/ClientRole.javaindex d4074564b..a132e1439 100644--- a/manager/shared/src/main/java/org/openremote/manager/shared/security/ClientRole.java+++ b/manager/shared/src/main/java/org/openremote/manager/shared/security/ClientRole.java@@ -35,9 +35,9 @@ public enum ClientRole {READ_RULES("read:rules", "Read rule definitions"),READ_CONSOLES("read:consoles", "Read installed console applications"),+ WRITE_USER("write:user", "Write data of the authenticated user"),WRITE_ADMIN("write:admin", "Write system settings, tenants, and users"),WRITE_ASSETS("write:assets", "Write asset data"),- WRITE_USER("write:user", "Write data of the authenticated user"),WRITE_RULES("write:rules", "Write rule definitions"),READ("read", "Read all data", new ClientRole[]{@@ -49,6 +49,7 @@ public enum ClientRole {}),WRITE("write", "Write all data", new ClientRole[]{+ WRITE_USER,WRITE_ADMIN,WRITE_ASSETS,WRITE_RULESdiff --git a/manager/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovyindex d1349e55c..1e011c984 100644--- a/manager/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy@@ -1,18 +1,17 @@package org.openremote.test.assets-import org.openremote.manager.server.setup.builtin.ManagerDemoSetup+import org.openremote.container.util.IdentifierUtilimport org.openremote.manager.server.setup.SetupService+import org.openremote.manager.server.setup.builtin.ManagerDemoSetupimport org.openremote.manager.shared.asset.AssetResource+import org.openremote.model.AttributeTypeimport org.openremote.model.Attributesimport org.openremote.model.Metaimport org.openremote.model.asset.Asset-import org.openremote.model.asset.ProtectedAsset-import org.openremote.model.AttributeTypeimport org.openremote.model.asset.AssetMeta+import org.openremote.model.asset.AssetTypeimport org.openremote.test.ManagerContainerTraitimport spock.lang.Specification-import org.openremote.model.asset.AssetType-import org.openremote.container.util.IdentifierUtilimport javax.ws.rs.WebApplicationException@@ -452,7 +451,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraithen: "result should match"assets.length == 4- ProtectedAsset apartment1 = assets[0]+ Asset apartment1 = assets[0]apartment1.id == managerDemoSetup.apartment1Idapartment1.name == "Apartment 1"apartment1.createdOn.getTime() < System.currentTimeMillis()@@ -462,16 +461,16 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraiapartment1.coordinates[0] == 5.469751699216005dapartment1.coordinates[1] == 51.44760787406028d- ProtectedAsset apartment1Livingroom = assets[1]+ Asset apartment1Livingroom = assets[1]apartment1Livingroom.id == managerDemoSetup.apartment1LivingroomIdapartment1Livingroom.name == "Livingroom"- ProtectedAsset apartment1LivingroomThermostat = assets[2]+ Asset apartment1LivingroomThermostat = assets[2]apartment1LivingroomThermostat.id == managerDemoSetup.apartment1LivingroomThermostatIdapartment1LivingroomThermostat.name == "Livingroom Thermostat"Attributes protectedAttributes = new Attributes(apartment1LivingroomThermostat.attributes)- protectedAttributes.get().length == 1+ protectedAttributes.size() == 1protectedAttributes.get("currentTemperature")protectedAttributes.get("currentTemperature").getType() == AttributeType.DECIMALprotectedAttributes.get("currentTemperature").getValueAsDecimal() == 19.2d@@ -480,7 +479,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraiprotectedMeta.first(AssetMeta.LABEL).getValueAsString() == "Current Temp"protectedMeta.first(AssetMeta.READ_ONLY).getValueAsBoolean()- ProtectedAsset apartment2 = assets[3]+ Asset apartment2 = assets[3]apartment2.id == managerDemoSetup.apartment2Idapartment2.name == "Apartment 2"diff --git a/manager/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovynew file mode 100644index 000000000..da75e6993--- /dev/null+++ b/manager/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy@@ -0,0 +1,235 @@+package org.openremote.test.assets++import org.openremote.manager.server.asset.AssetStorageService+import org.openremote.manager.server.setup.SetupService+import org.openremote.manager.server.setup.builtin.ManagerDemoSetup+import org.openremote.manager.server.setup.builtin.KeycloakDemoSetup+import org.openremote.model.Attributes+import org.openremote.model.asset.AssetQuery+import org.openremote.model.asset.AssetMeta+import org.openremote.test.ManagerContainerTrait+import spock.lang.Specification+import org.openremote.model.asset.AssetType++import static org.openremote.model.asset.AssetType.THING++class AssetQueryTest extends Specification implements ManagerContainerTrait {++ def "Query assets"() {+ given: "the server container is started"+ def serverPort = findEphemeralPort()+ def container = startContainer(defaultConfig(serverPort), defaultServices())+ def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)+ def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)+ def assetStorageService = container.getService(AssetStorageService.class)++ when: "a query is executed"+ def asset = assetStorageService.find(+ new AssetQuery()+ .id(managerDemoSetup.smartOfficeId)+ )++ then: "result should match"+ asset.id == managerDemoSetup.smartOfficeId+ asset.version == 0+ asset.createdOn.time < System.currentTimeMillis()+ asset.name == "Smart Office"+ asset.wellKnownType == AssetType.BUILDING+ asset.parentId == null+ asset.parentName == null+ asset.parentType == null+ asset.realmId == keycloakDemoSetup.masterTenant.id+ asset.tenantRealm == keycloakDemoSetup.masterTenant.realm+ asset.tenantDisplayName == keycloakDemoSetup.masterTenant.displayName+ asset.coordinates.length == 2+ asset.path == null+ asset.attributes == null++ when: "a query is executed"+ asset = assetStorageService.find(+ new AssetQuery()+ .select(new AssetQuery.Select(true, false))+ .id(managerDemoSetup.smartOfficeId)+ )++ then: "result should match"+ asset.id == managerDemoSetup.smartOfficeId+ asset.version == 0+ asset.createdOn.time < System.currentTimeMillis()+ asset.name == "Smart Office"+ asset.wellKnownType == AssetType.BUILDING+ asset.parentId == null+ asset.parentName == null+ asset.parentType == null+ asset.realmId == keycloakDemoSetup.masterTenant.id+ asset.tenantRealm == keycloakDemoSetup.masterTenant.realm+ asset.tenantDisplayName == keycloakDemoSetup.masterTenant.displayName+ asset.coordinates.length == 2+ asset.path.length == 1+ asset.path[0] == managerDemoSetup.smartOfficeId+ new Attributes(asset.attributes).get("geoStreet").valueAsString == "Torenallee 20"++ when: "a query is executed"+ def assets = assetStorageService.findAll(+ new AssetQuery()+ .parent(new AssetQuery.Parent(true))+ .realm(new AssetQuery.Realm(keycloakDemoSetup.masterTenant.id))+ )++ then: "result should match"+ assets.size() == 1+ assets.get(0).id == managerDemoSetup.smartOfficeId+ assets.get(0).version == 0+ assets.get(0).createdOn.time < System.currentTimeMillis()+ assets.get(0).name == "Smart Office"+ assets.get(0).wellKnownType == AssetType.BUILDING+ assets.get(0).parentId == null+ assets.get(0).parentName == null+ assets.get(0).parentType == null+ assets.get(0).realmId == keycloakDemoSetup.masterTenant.id+ assets.get(0).tenantRealm == keycloakDemoSetup.masterTenant.realm+ assets.get(0).tenantDisplayName == keycloakDemoSetup.masterTenant.displayName+ assets.get(0).coordinates.length == 2+ assets.get(0).path == null+ assets.get(0).attributes == null++ when: "a query is executed"+ assets = assetStorageService.findAll(+ new AssetQuery()+ .select(new AssetQuery.Select(true, false))+ .parent(new AssetQuery.Parent(true))+ .realm(new AssetQuery.Realm(keycloakDemoSetup.masterTenant.id))+ )++ then: "result should match"+ assets.size() == 1+ assets.get(0).id == managerDemoSetup.smartOfficeId+ assets.get(0).version == 0+ assets.get(0).createdOn.time < System.currentTimeMillis()+ assets.get(0).name == "Smart Office"+ assets.get(0).wellKnownType == AssetType.BUILDING+ assets.get(0).parentId == null+ assets.get(0).parentName == null+ assets.get(0).parentType == null+ assets.get(0).realmId == keycloakDemoSetup.masterTenant.id+ assets.get(0).tenantRealm == keycloakDemoSetup.masterTenant.realm+ assets.get(0).tenantDisplayName == keycloakDemoSetup.masterTenant.displayName+ assets.get(0).coordinates.length == 2+ assets.get(0).path.length == 1+ assets.get(0).path[0] == managerDemoSetup.smartOfficeId+ new Attributes(assets.get(0).attributes).get("geoStreet").valueAsString == "Torenallee 20"++ when: "a query is executed"+ assets = assetStorageService.findAll(+ new AssetQuery()+ .parent(new AssetQuery.Parent(managerDemoSetup.smartHomeId))+ )++ then: "result should match"+ assets.size() == 3+ assets.get(0).id == managerDemoSetup.apartment1Id+ assets.get(0).version == 0+ assets.get(0).createdOn.time < System.currentTimeMillis()+ assets.get(0).name == "Apartment 1"+ assets.get(0).wellKnownType == AssetType.RESIDENCE+ assets.get(0).parentId == managerDemoSetup.smartHomeId+ assets.get(0).parentName == "Smart Home"+ assets.get(0).parentType == AssetType.BUILDING.value+ assets.get(0).realmId == keycloakDemoSetup.customerATenant.id+ assets.get(0).tenantRealm == keycloakDemoSetup.customerATenant.realm+ assets.get(0).tenantDisplayName == keycloakDemoSetup.customerATenant.displayName+ assets.get(0).coordinates.length == 2+ assets.get(0).path == null+ assets.get(0).attributes == null+ assets.get(1).id == managerDemoSetup.apartment2Id+ assets.get(2).id == managerDemoSetup.apartment3Id++ when: "a query is executed"+ assets = assetStorageService.findAll(+ new AssetQuery()+ .parent(new AssetQuery.Parent(managerDemoSetup.smartHomeId))+ .realm(new AssetQuery.Realm(keycloakDemoSetup.customerATenant.id))+ )++ then: "result should match"+ assets.size() == 3+ assets.get(0).id == managerDemoSetup.apartment1Id+ assets.get(1).id == managerDemoSetup.apartment2Id+ assets.get(2).id == managerDemoSetup.apartment3Id++ when: "a query is executed"+ assets = assetStorageService.findAll(+ new AssetQuery()+ .parent(new AssetQuery.Parent(managerDemoSetup.smartHomeId))+ .realm(new AssetQuery.Realm(keycloakDemoSetup.masterTenant.id))+ )++ then: "result should match"+ assets.size() == 0++ when: "a query is executed"+ assets = assetStorageService.findAll(+ new AssetQuery().select(new AssetQuery.Select(true, true)).userId(keycloakDemoSetup.testuser3Id)+ )++ then: "result should match"+ assets.size() == 4+ assets.get(0).id == managerDemoSetup.apartment1Id+ assets.get(1).id == managerDemoSetup.apartment1LivingroomId+ assets.get(2).id == managerDemoSetup.apartment1LivingroomThermostatId+ new Attributes(assets.get(2).attributes).size() == 1+ new Attributes(assets.get(2).attributes).get("currentTemperature").valueAsDecimal == 19.2d+ new Attributes(assets.get(2).attributes).get("currentTemperature").meta.size() == 2+ assets.get(3).id == managerDemoSetup.apartment2Id++ when: "a query is executed"+ assets = assetStorageService.findAll(+ new AssetQuery().select(new AssetQuery.Select(true, true)).userId(keycloakDemoSetup.testuser2Id)+ )++ then: "result should match"+ assets.size() == 0++ expect: "a result to match the executed query "+ assetStorageService.isUserAsset(keycloakDemoSetup.testuser3Id, managerDemoSetup.apartment1Id)+ assetStorageService.isUserAsset(keycloakDemoSetup.testuser3Id, managerDemoSetup.apartment1LivingroomId)+ assetStorageService.isUserAsset(keycloakDemoSetup.testuser3Id, managerDemoSetup.apartment1LivingroomThermostatId)+ assetStorageService.isUserAsset(keycloakDemoSetup.testuser3Id, managerDemoSetup.apartment2Id)+ !assetStorageService.isUserAsset(keycloakDemoSetup.testuser3Id, managerDemoSetup.apartment3Id)+ !assetStorageService.isUserAsset(keycloakDemoSetup.testuser3Id, managerDemoSetup.smartOfficeId)++ when: "a query is executed"+ assets = assetStorageService.findAll(+ new AssetQuery().type(AssetType.AGENT)+ )++ then: "result should match"+ assets.size() == 1+ assets.get(0).id == managerDemoSetup.demoAgentId++ when: "a query is executed"+ assets = assetStorageService.findAll(new AssetQuery()+ .type(THING)+ .parent(new AssetQuery.Parent(managerDemoSetup.demoAgentId))+ )++ then: "result should match"+ assets.size() == 1+ assets.get(0).id == managerDemoSetup.thingId+++ when: "a query is executed"+ assets = assetStorageService.findAll(+ new AssetQuery()+ .realm(new AssetQuery.Realm(keycloakDemoSetup.masterTenant.id))+ .attributeMeta(new AssetQuery.AttributeMeta(AssetMeta.STORE_DATA_POINTS, new AssetQuery.BooleanSearch(true)))+ )++ then: "result should match"+ assets.size() == 1+ assets.get(0).id == managerDemoSetup.thingId++ cleanup: "the server should be stopped"+ stopContainer(container)+ }+}diff --git a/model/src/main/java/org/openremote/model/Attributes.java b/model/src/main/java/org/openremote/model/Attributes.javaindex 485a9bea1..cf56f1c3e 100644--- a/model/src/main/java/org/openremote/model/Attributes.java+++ b/model/src/main/java/org/openremote/model/Attributes.java@@ -55,6 +55,10 @@ public class Attributes {return jsonObject.keys();}+ public int size() {+ return get().length;+ }+public Attribute[] get() {Set<Attribute> attributes = new LinkedHashSet<>();String[] keys = jsonObject.keys();diff --git a/model/src/main/java/org/openremote/model/asset/Asset.java b/model/src/main/java/org/openremote/model/asset/Asset.javaindex 0d43cecc5..7d7eb5d0e 100644--- a/model/src/main/java/org/openremote/model/asset/Asset.java+++ b/model/src/main/java/org/openremote/model/asset/Asset.java@@ -22,7 +22,7 @@ package org.openremote.model.asset;import elemental.json.JsonObject;import org.hibernate.annotations.Formula;import org.hibernate.annotations.Type;-import org.openremote.model.IdentifiableEntity;+import org.openremote.model.*;import javax.persistence.*;import javax.validation.constraints.NotNull;@@ -32,6 +32,7 @@ import java.util.Collections;import java.util.Date;import java.util.List;+import static org.openremote.model.Constants.NAMESPACE;import static org.openremote.model.Constants.PERSISTENCE_JSON_OBJECT_TYPE;import static org.openremote.model.Constants.PERSISTENCE_UNIQUE_ID_GENERATOR;@@ -71,6 +72,13 @@ import static org.openremote.model.Constants.PERSISTENCE_UNIQUE_ID_GENERATOR;* class to work with this API. This property can be empty when certain optimized loading* operations are used.* <p>+ * Constructors can filter attributes of an asset as to only contain protected attributes,+ * and their protected metadata (see {@link AssetMeta#PROTECTED}, {@link AssetMeta.Access}).+ * <p>+ * Note that third-party metadata items (not in the+ * {@link org.openremote.model.Constants#NAMESPACE}) are never included on+ * a protected attribute!+ * <p>* Example JSON representation of an asset tree:* <blockquote><pre>{@code{@@ -202,6 +210,43 @@ import static org.openremote.model.Constants.PERSISTENCE_UNIQUE_ID_GENERATOR;@MappedSuperclasspublic class Asset implements IdentifiableEntity {+ static JsonObject filterProtectedAttributes(JsonObject originalAttributes) {+ if (originalAttributes == null)+ return null;+ Attributes filteredAttributes = new Attributes();+ for (Attribute originalAttribute : new Attributes(originalAttributes).get()) {++ // An attribute must be protected to be included+ if (!originalAttribute.isProtected()) {+ continue;+ }++ Attribute protectedAttribute = originalAttribute.copy();+ filteredAttributes.put(protectedAttribute);++ if (!protectedAttribute.hasMeta())+ continue;++ // Any meta item of the attribute, if it's in our namespace, must be protected READ to be included+ Meta protectedMeta = new Meta();+ for (MetaItem metaItem : protectedAttribute.getMeta().all()) {+ if (!metaItem.getName().startsWith(NAMESPACE))+ continue;++ AssetMeta wellKnownMeta = AssetMeta.byName(metaItem.getName());+ if (wellKnownMeta != null && wellKnownMeta.getAccess().protectedRead) {+ protectedMeta.add(+ new MetaItem(metaItem.getName(), metaItem.getValue())+ );+ }+ }+ if (protectedMeta.size() > 0)+ protectedAttribute.setMeta(protectedMeta);++ }+ return filteredAttributes.getJsonObject();+ }+@Id@Column(name = "ID", length = 27)@GeneratedValue(generator = PERSISTENCE_UNIQUE_ID_GENERATOR)@@ -226,7 +271,7 @@ public class Asset implements IdentifiableEntity {@Column(name = "ASSET_TYPE", nullable = false, updatable = false)protected String type;- @Column(name = "PARENT_ID", length = 27)+ @Column(name = "PARENT_ID", length = 27)protected String parentId;@Transient@@ -235,10 +280,6 @@ public class Asset implements IdentifiableEntity {@Transientprotected String parentType;- @Formula("GET_ASSET_TREE_PATH(ID)")- @Type(type = "org.openremote.container.persistence.ArrayUserType")- protected String[] path;-@Column(name = "REALM_ID", nullable = false)protected String realmId;@@ -251,6 +292,11 @@ public class Asset implements IdentifiableEntity {@Transientprotected double[] coordinates;+ // The following are expensive to query, so if they are null, they might not have been loaded++ @Transient+ protected String[] path;+@Column(name = "ATTRIBUTES", columnDefinition = "jsonb")@org.hibernate.annotations.Type(type = PERSISTENCE_JSON_OBJECT_TYPE)protected JsonObject attributes;@@ -272,10 +318,11 @@ public class Asset implements IdentifiableEntity {this.type = type;}- public Asset(String id, long version, Date createdOn, String name, String type,- String parentId, String parentName, String parentType, String[] path,+ public Asset(boolean filterProtectedAttributes,+ String id, long version, Date createdOn, String name, String type,+ String parentId, String parentName, String parentType,String realmId, String tenantRealm, String tenantDisplayName,- JsonObject attributes) {+ String[] path, JsonObject attributes) {this.id = id;this.version = version;this.createdOn = createdOn;@@ -284,11 +331,11 @@ public class Asset implements IdentifiableEntity {this.parentId = parentId;this.parentName = parentName;this.parentType = parentType;- this.path = path;this.realmId = realmId;this.tenantRealm = tenantRealm;this.tenantDisplayName = tenantDisplayName;- this.attributes = attributes;+ this.path = path;+ this.attributes = filterProtectedAttributes ? filterProtectedAttributes(attributes) : attributes;}public Asset(Asset parent) {@@ -298,7 +345,7 @@ public class Asset implements IdentifiableEntity {this.realmId = parent.getRealmId();this.tenantRealm = parent.getTenantRealm();this.tenantDisplayName = parent.getTenantDisplayName();- };+ }public String getId() {return id;@@ -372,34 +419,6 @@ public class Asset implements IdentifiableEntity {this.parentType = parentType;}- /**- * The identifiers of all parents representing the path in the tree. The first element- * is the identifier of this instance, the last is the root asset without a parent.- */- public String[] getPath() {- return path;- }-- /**- * The identifiers of all parents representing the path in the tree. The first element- * is the root asset without a parent, the last is the identifier of this instance.- */- public String[] getReversePath() {- if (path == null)- return null;- List<String> list = Arrays.asList(getPath());- Collections.reverse(list);- return list.toArray(new String[list.size()]);- }-- public boolean pathContains(String assetId) {- return path != null && Arrays.asList(getPath()).contains(assetId);- }-- public void setPath(String[] path) {- this.path = path;- }-public String getRealmId() {return realmId;}@@ -436,6 +455,34 @@ public class Asset implements IdentifiableEntity {return getCoordinates() != null && getCoordinates().length > 0;}+ /**+ * The identifiers of all parents representing the path in the tree. The first element+ * is the identifier of this instance, the last is the root asset without a parent.+ */+ public String[] getPath() {+ return path;+ }++ /**+ * The identifiers of all parents representing the path in the tree. The first element+ * is the root asset without a parent, the last is the identifier of this instance.+ */+ public String[] getReversePath() {+ if (path == null)+ return null;+ List<String> list = Arrays.asList(getPath());+ Collections.reverse(list);+ return list.toArray(new String[list.size()]);+ }++ public boolean pathContains(String assetId) {+ return path != null && Arrays.asList(getPath()).contains(assetId);+ }++ public void setPath(String[] path) {+ this.path = path;+ }+public JsonObject getAttributes() {return attributes;}@@ -466,8 +513,8 @@ public class Asset implements IdentifiableEntity {", realmId='" + realmId + '\'' +", tenantRealm='" + tenantRealm + '\'' +", tenantDisplayName='" + tenantDisplayName + '\'' +- ", path=" + Arrays.toString(path) +", coordinates=" + Arrays.toString(coordinates) ++ ", path=" + Arrays.toString(path) +", attributes=" + attributes +'}';}diff --git a/model/src/main/java/org/openremote/model/asset/AssetQuery.java b/model/src/main/java/org/openremote/model/asset/AssetQuery.javanew file mode 100644index 000000000..d13b759c5--- /dev/null+++ b/model/src/main/java/org/openremote/model/asset/AssetQuery.java@@ -0,0 +1,336 @@+/*+ * Copyright 2016, 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.asset;++import java.util.Locale;++/**+ * Encapsulate asset query details. A query returns a collection of+ * {@link Asset} instances, unless if the {@link #id} is set, then only+ * a single instance can be found.+ */+public class AssetQuery {++ 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;+ }+ }++ public interface Search {++ }++ static public class StringSearch {+ public Match match = Match.EXACT;+ public boolean caseSensitive = true;+ public String value;++ public StringSearch() {+ }++ public StringSearch(String value) {+ this.value = value;+ }++ public StringSearch(Match match, String value) {+ this.match = match;+ this.value = value;+ }++ public StringSearch(Match match, boolean caseSensitive, String value) {+ this.match = match;+ this.caseSensitive = caseSensitive;+ this.value = value;+ }++ public StringSearch match(Match match) {+ this.match = match;+ return this;+ }++ public StringSearch caseSensitive(boolean caseSensitive) {+ this.caseSensitive = caseSensitive;+ return this;+ }++ public StringSearch search(String search) {+ this.value = search;+ return this;+ }++ public String prepareValue() {+ String s = match.prepare(this.value);+ if (!caseSensitive)+ s = s.toUpperCase(Locale.ROOT);+ return s;+ }+ }++ static public class BooleanSearch implements Search {++ public boolean predicate;++ public BooleanSearch() {+ }++ public BooleanSearch(boolean predicate) {+ this.predicate = predicate;+ }++ public BooleanSearch predicate(boolean predicate) {+ this.predicate = predicate;+ return this;+ }+ }++ static public class Parent {+ public String id;+ public String type;+ public boolean noParent;++ public Parent() {+ }++ public Parent(String id) {+ this.id = id;+ }++ public Parent(boolean noParent) {+ this.noParent = noParent;+ }++ public Parent id(String id) {+ this.id = id;+ return this;+ }++ public Parent type(String type) {+ this.type = type;+ return this;+ }++ public Parent noParent(boolean noParent) {+ this.noParent = noParent;+ return this;+ }+ }++ static public class Realm {+ public String id;+ public String name;++ public Realm() {+ }++ public Realm(String id) {+ this.id = id;+ }++ public Realm id(String id) {+ this.id = id;+ return this;+ }++ public Realm name(String name) {+ this.name = name;+ return this;+ }+ }++ static public class AttributeMeta {+ public StringSearch itemNameSearch;+ public Search itemValueSearch;++ public AttributeMeta() {+ }++ public AttributeMeta(StringSearch itemNameSearch) {+ this.itemNameSearch = itemNameSearch;+ }++ public AttributeMeta(AssetMeta assetMeta) {+ this.itemNameSearch = new StringSearch(assetMeta.getName());+ }++ public AttributeMeta(Search itemValueSearch) {+ this.itemValueSearch = itemValueSearch;+ }++ public AttributeMeta(StringSearch itemNameSearch, Search itemValueSearch) {+ this.itemNameSearch = itemNameSearch;+ this.itemValueSearch = itemValueSearch;+ }++ public AttributeMeta(AssetMeta assetMeta, Search itemValueSearch) {+ this(new StringSearch(assetMeta.getName()), itemValueSearch);+ }++ public AttributeMeta itemNameSearch(StringSearch itemNameSearch) {+ this.itemNameSearch = itemNameSearch;+ return this;+ }++ public AttributeMeta itemNameSearch(AssetMeta assetMeta) {+ return itemNameSearch(new StringSearch(assetMeta.getName()));+ }++ public AttributeMeta itemValueSearch(Search itemValueSearch) {+ this.itemValueSearch = itemValueSearch;+ return this;+ }+ }++ static public class Select {+ public boolean loadComplete;+ public boolean filterProtected;++ public Select() {+ }++ public Select(boolean loadComplete, boolean filterProtected) {+ this.loadComplete = loadComplete;+ this.filterProtected = filterProtected;+ }++ public Select loadComplete(boolean loadComplete) {+ this.loadComplete = loadComplete;+ return this;+ }++ public Select filterProtected(boolean filterProtected) {+ this.filterProtected = filterProtected;+ return this;+ }+ }++ static public class OrderBy {+ public String property;+ public boolean descending;++ public OrderBy() {+ }++ public OrderBy(String property) {+ this.property = property;+ }++ public OrderBy(String property, boolean descending) {+ this.property = property;+ this.descending = descending;+ }++ public OrderBy property(String property) {+ this.property = property;+ return this;+ }++ public OrderBy descending(boolean descending) {+ this.descending = descending;+ return this;+ }+ }++ public Select select = new Select(false, false);++ /**+ * If this value is set, no other restrictions will be applied and only a single result should be returned.+ */+ public String id;++ public StringSearch name;+ public Parent parent;+ public Realm realm;+ public String userId;+ public StringSearch type;+ public AttributeMeta attributeMeta;+ public OrderBy orderBy = new OrderBy("createdOn");++ public AssetQuery() {+ }++ public AssetQuery select(Select select) {+ this.select = select;+ return this;+ }++ public AssetQuery name(StringSearch name) {+ this.name = name;+ return this;+ }++ public AssetQuery id(String id) {+ this.id = id;+ return this;+ }++ public AssetQuery parent(Parent parent) {+ this.parent = parent;+ return this;+ }++ public AssetQuery realm(Realm realm) {+ this.realm = realm;+ return this;+ }++ public AssetQuery userId(String userId) {+ this.userId = userId;+ return this;+ }++ public AssetQuery type(StringSearch type) {+ this.type = type;+ return this;+ }++ public AssetQuery type(AssetType assetType) {+ return type(new StringSearch(assetType.getValue()));+ }++ public AssetQuery attributeMeta(AttributeMeta attributeMeta) {+ this.attributeMeta = attributeMeta;+ return this;+ }++ public AssetQuery orderBy(OrderBy orderBy) {+ this.orderBy = orderBy;+ return this;+ }++ public boolean hasAttributeRestrictions() {+ return attributeMeta != null;+ }+}diff --git a/model/src/main/java/org/openremote/model/asset/ProtectedAsset.java b/model/src/main/java/org/openremote/model/asset/ProtectedAsset.javadeleted file mode 100644index d8c023c4c..000000000--- a/model/src/main/java/org/openremote/model/asset/ProtectedAsset.java+++ /dev/null@@ -1,113 +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.asset;--import elemental.json.JsonObject;-import org.openremote.model.Attribute;-import org.openremote.model.Attributes;-import org.openremote.model.Meta;-import org.openremote.model.MetaItem;--import java.util.Date;--import static org.openremote.model.Constants.NAMESPACE;--/**- * Filters attributes of an asset as to only contain protected attributes, and their- * protected metadata (see {@link AssetMeta#PROTECTED}, {@link AssetMeta.Access}).- * <p>- * Note that third-party metadata items (not in the- * {@link org.openremote.model.Constants#NAMESPACE}) are never included on- * a protected attribute!- */-public class ProtectedAsset extends Asset {-- static JsonObject filterProtectedAttributes(JsonObject unfilteredAttributes) {- Attributes filteredAttributes = new Attributes();- Attributes attributes = new Attributes(unfilteredAttributes);- for (Attribute attribute : attributes.get()) {-- // An attribute must be protected to be included- if (!attribute.isProtected()) {- continue;- }-- Attribute protectedAttribute = attribute.copy();- filteredAttributes.put(protectedAttribute);-- if (!protectedAttribute.hasMeta())- continue;-- // Any meta item of the attribute, if it's in our namespace, must be protected READ to be included- Meta protectedMeta = new Meta();- for (MetaItem metaItem : protectedAttribute.getMeta().all()) {- if (!metaItem.getName().startsWith(NAMESPACE))- continue;-- AssetMeta wellKnownMeta = AssetMeta.byName(metaItem.getName());- if (wellKnownMeta != null && wellKnownMeta.getAccess().protectedRead) {- protectedMeta.add(- new MetaItem(metaItem.getName(), metaItem.getValue())- );- }- }- if (protectedMeta.size() > 0)- protectedAttribute.setMeta(protectedMeta);-- }- return filteredAttributes.getJsonObject();- }-- public ProtectedAsset() {- }-- public ProtectedAsset(String name, AssetType type) {- super(name, type);- }-- public ProtectedAsset(String realm, String name, AssetType type) {- super(realm, name, type);- }-- public ProtectedAsset(String realmId, String name, String type) {- super(realmId, name, type);- }-- public ProtectedAsset(String id, long version, Date createdOn, String name, String type,- String parentId, String parentName, String parentType, String[] path,- String realmId, String tenantRealm, String tenantDisplayName,- JsonObject attributes) {- super(- id, version, createdOn, name, type,- parentId, parentName, parentType, path,- realmId, tenantRealm, tenantDisplayName,- filterProtectedAttributes(attributes)- );- }-- public ProtectedAsset(Asset parent) {- super(parent);- }-- @Override- public void setAttributes(JsonObject attributes) {- super.setAttributes(filterProtectedAttributes(attributes));- }-}