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
Optimized Asset model and queries
Christian Bauer5e9b2017bd6d
diff --git a/container/src/main/java/org/openremote/container/persistence/ArrayUserType.java b/container/src/main/java/org/openremote/container/persistence/ArrayUserType.javanew file mode 100644index 000000000..ce6e765ba--- /dev/null+++ b/container/src/main/java/org/openremote/container/persistence/ArrayUserType.java@@ -0,0 +1,103 @@+/*+ * 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/EnhancedImportSqlCommandExtractor.java b/container/src/main/java/org/openremote/container/persistence/EnhancedImportSqlCommandExtractor.javanew file mode 100644index 000000000..b292d94aa--- /dev/null+++ b/container/src/main/java/org/openremote/container/persistence/EnhancedImportSqlCommandExtractor.java@@ -0,0 +1,71 @@+/*+ * 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.apache.commons.io.IOUtils;+import org.hibernate.hql.internal.antlr.SqlStatementLexer;+import org.hibernate.hql.internal.antlr.SqlStatementParser;+import org.hibernate.tool.hbm2ddl.ImportScriptException;+import org.hibernate.tool.hbm2ddl.ImportSqlCommandExtractor;++import java.io.IOException;+import java.io.Reader;+import java.io.StringReader;+import java.util.Arrays;+import java.util.List;+import java.util.logging.Logger;++/**+ * Load and parse import SQL files, either the whole file as a single statement if its first line+ * is <code>-- importOneStatementOnly</code>, or as a semicolon-separated list of statements.+ */+public class EnhancedImportSqlCommandExtractor implements ImportSqlCommandExtractor {++ private static final Logger LOG = Logger.getLogger(EnhancedImportSqlCommandExtractor.class.getName());++ @Override+ public String[] extractCommands(Reader reader) {+ try {+ String sql = IOUtils.toString(reader);+ if (sql.startsWith("-- importOneStatementOnly")) {+ return new String[] {sql};+ } else {+ return extractMultiLine(new StringReader(sql));+ }+ } catch (IOException e) {+ throw new ImportScriptException("Error during import script parsing.", e);+ }+ }++ protected String[] extractMultiLine(Reader reader) {+ final SqlStatementLexer lexer = new SqlStatementLexer(reader);+ final SqlStatementParser parser = new SqlStatementParser(lexer);+ try {+ parser.script(); // Parse script.+ parser.throwExceptionIfErrorOccurred();+ } catch (Exception e) {+ throw new ImportScriptException("Error during import script parsing.", e);+ }+ List<String> statementList = parser.getStatementList();+ String[] result = statementList.toArray(new String[statementList.size()]);+ LOG.info("Importing multiline SQL: " + Arrays.toString(result));+ return result;+ }+}diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/AssetInfoArrayMapper.java b/manager/client/src/main/java/org/openremote/manager/client/assets/AssetArrayMapper.javasimilarity index 81%rename from manager/client/src/main/java/org/openremote/manager/client/assets/AssetInfoArrayMapper.javarename to manager/client/src/main/java/org/openremote/manager/client/assets/AssetArrayMapper.javaindex 2c29e3152..8a3bf2a03 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/AssetInfoArrayMapper.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/AssetArrayMapper.java@@ -22,11 +22,11 @@ package org.openremote.manager.client.assets;import com.github.nmorel.gwtjackson.client.ObjectMapper;import com.github.nmorel.gwtjackson.client.annotation.JsonMixIns;import org.openremote.manager.client.interop.jackson.DefaultJsonMixin;-import org.openremote.model.asset.AssetInfo;import org.openremote.manager.shared.http.EntityReader;+import org.openremote.model.asset.Asset;-@JsonMixIns({@JsonMixIns.JsonMixIn(target = AssetInfo.class, mixIn = DefaultJsonMixin.class)})-public interface AssetInfoArrayMapper- extends ObjectMapper<AssetInfo[]>,- EntityReader<AssetInfo[]> {+@JsonMixIns({@JsonMixIns.JsonMixIn(target = Asset.class, mixIn = DefaultJsonMixin.class)})+public interface AssetArrayMapper+ extends ObjectMapper<Asset[]>,+ EntityReader<Asset[]> {}diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditActivity.java b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditActivity.javaindex 356c52fc5..32223db6c 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditActivity.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditActivity.java@@ -176,7 +176,7 @@ public class AssetEditActivity} else if (treeNode instanceof AssetTreeNode) {assetBrowserPresenter.loadAsset(treeNode.getId(), loadedAsset -> {// The selected parent can not be our child, or a leaf, or the same- if (Arrays.asList(loadedAsset.getPath()).contains(asset.getId())+ if (loadedAsset.pathContains(asset.getId())|| treeNode.isLeaf()|| loadedAsset.getId().equals(asset.getId())) {environment.getEventBus().dispatch(@@ -327,9 +327,7 @@ public class AssetEditActivityprotected void writeParentToView() {if (parentAsset != null) {- view.setParentNode(- new AssetTreeNode(parentAsset, parentAsset.getTenantDisplayName())- );+ view.setParentNode(new AssetTreeNode(parentAsset));} else {view.setParentNode(new TenantTreeNode(diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewActivity.java b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewActivity.javaindex 8cc95516f..08e14e0dd 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewActivity.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewActivity.java@@ -166,9 +166,7 @@ public class AssetViewActivityprotected void writeParentToView() {if (parentAsset != null) {- view.setParentNode(- new AssetTreeNode(parentAsset, parentAsset.getTenantDisplayName())- );+ view.setParentNode(new AssetTreeNode(parentAsset));} else {view.setParentNode(new TenantTreeNode(diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetBrowserPresenter.java b/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetBrowserPresenter.javaindex 5cdc075f6..b61f75678 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetBrowserPresenter.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetBrowserPresenter.java@@ -22,14 +22,13 @@ package org.openremote.manager.client.assets.browser;import com.google.gwt.view.client.HasData;import org.openremote.manager.client.Environment;import org.openremote.manager.client.admin.TenantArrayMapper;-import org.openremote.manager.client.assets.AssetInfoArrayMapper;+import org.openremote.manager.client.assets.AssetArrayMapper;import org.openremote.manager.client.assets.AssetMapper;import org.openremote.manager.shared.asset.AssetResource;import org.openremote.manager.shared.security.Tenant;import org.openremote.manager.shared.security.TenantResource;import org.openremote.model.Consumer;import org.openremote.model.asset.Asset;-import org.openremote.model.asset.AssetInfo;import javax.inject.Inject;import java.util.ArrayList;@@ -45,7 +44,7 @@ public class AssetBrowserPresenter implements AssetBrowser.Presenter {final AssetBrowser view;final AssetResource assetResource;final AssetMapper assetMapper;- final AssetInfoArrayMapper assetInfoArrayMapper;+ final AssetArrayMapper assetArrayMapper;final TenantResource tenantResource;final TenantArrayMapper tenantArrayMapper;@@ -59,7 +58,7 @@ public class AssetBrowserPresenter implements AssetBrowser.Presenter {AssetBrowser view,AssetResource assetResource,AssetMapper assetMapper,- AssetInfoArrayMapper assetInfoArrayMapper,+ AssetArrayMapper assetArrayMapper,TenantResource tenantResource,TenantArrayMapper tenantArrayMapper) {this.environment = environment;@@ -68,7 +67,7 @@ public class AssetBrowserPresenter implements AssetBrowser.Presenter {this.tenantArrayMapper = tenantArrayMapper;this.assetResource = assetResource;this.assetMapper = assetMapper;- this.assetInfoArrayMapper = assetInfoArrayMapper;+ this.assetArrayMapper = assetArrayMapper;view.setPresenter(this);}@@ -130,7 +129,7 @@ public class AssetBrowserPresenter implements AssetBrowser.Presenter {@Overridepublic void selectAsset(Asset asset) {- onNodeSelected(asset != null ? new AssetTreeNode(asset, asset.getTenantDisplayName()) : null);+ onNodeSelected(asset != null ? new AssetTreeNode(asset) : null);selectedNodePath = asset != null ? getTenantAdjustedAssetPath(asset) : null;if (selectedNode != null) {updateViewSelection(true);@@ -217,7 +216,7 @@ public class AssetBrowserPresenter implements AssetBrowser.Presenter {// TODO Pagination?// final Range range = display.getVisibleRange();environment.getRequestService().execute(- assetInfoArrayMapper,+ assetArrayMapper,requestParams -> {// This must be synchronous, so tree selection/searching worksrequestParams.setAsync(false);@@ -230,13 +229,13 @@ public class AssetBrowserPresenter implements AssetBrowser.Presenter {}},200,- assetInfos -> {+ assets -> {List<BrowserTreeNode> treeNodes = new ArrayList<>();- for (AssetInfo assetInfo : assetInfos) {- treeNodes.add(new AssetTreeNode(assetInfo, getTenantDisplayName(assetInfo)));+ for (Asset asset : assets) {+ treeNodes.add(new AssetTreeNode(asset));}display.setRowData(0, treeNodes);- display.setRowCount(assetInfos.length, true);+ display.setRowCount(assets.length, true);afterNodeLoadChildren(treeNodes);},ex -> handleRequestException(ex, environment)@@ -278,16 +277,8 @@ public class AssetBrowserPresenter implements AssetBrowser.Presenter {}}if (asset.getPath() != null) {- path.addAll(Arrays.asList(asset.getPath()));+ path.addAll(Arrays.asList(asset.getReversePath()));}return path.toArray(new String[path.size()]);}-- protected String getTenantDisplayName(AssetInfo assetInfo) {- for (TenantTreeNode tenantNode : tenantNodes) {- if (tenantNode.getId().equals(assetInfo.getRealmId()))- return tenantNode.getLabel();- }- return assetInfo.getRealmId();- }}diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetSelector.java b/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetSelector.javaindex 8bd50034d..e6e072512 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetSelector.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetSelector.java@@ -130,7 +130,7 @@ public abstract class AssetSelector extends FormGroup {outputAssetName.setText(managerMessages.assetHasNoParent());} else if (treeNode instanceof AssetTreeNode) {AssetTreeNode assetTreeNode = (AssetTreeNode) treeNode;- outputTenantDisplayName.setText(assetTreeNode.getTenantDisplayName());+ outputTenantDisplayName.setText(assetTreeNode.getAsset().getTenantDisplayName());outputAssetName.setText(treeNode.getLabel());}}diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetTreeNode.java b/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetTreeNode.javaindex 5272deaf3..791be4ee6 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetTreeNode.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetTreeNode.java@@ -20,47 +20,34 @@package org.openremote.manager.client.assets.browser;import org.openremote.model.asset.Asset;-import org.openremote.model.asset.AssetInfo;import org.openremote.model.asset.AssetType;public class AssetTreeNode extends BrowserTreeNode {- final protected AssetInfo assetInfo;+ final protected Asset asset;- final protected String tenantDisplayName;-- public AssetTreeNode(Asset asset, String tenantDisplayName) {- this(new AssetInfo(asset), tenantDisplayName);- }- public AssetTreeNode(AssetInfo assetInfo, String tenantDisplayName) {- super(assetInfo.getName());- this.assetInfo = assetInfo;- this.tenantDisplayName = tenantDisplayName;- }-- public AssetInfo getAssetInfo() {- return assetInfo;- }-- public String getTenantDisplayName() {- return tenantDisplayName;+ public AssetTreeNode(Asset asset) {+ super(asset.getName());+ this.asset = asset;}@Overridepublic String getId() {- return assetInfo.getId();+ return asset.getId();+ }++ public Asset getAsset() {+ return asset;}@Overridepublic boolean isLeaf() {- return assetInfo.isWellKnownType(AssetType.THING);+ return asset.isWellKnownType(AssetType.THING);}@Overridepublic String getIcon() {- if (assetInfo.getWellKnownType() == null)- return "cube";- switch (assetInfo.getWellKnownType()) {+ switch (asset.getWellKnownType()) {case BUILDING:return "building";case RESIDENCE:diff --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 0c308df5a..c3b708a9c 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@@ -69,7 +69,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons@Overridepublic void start(Container container) throws Exception {- Asset[] agents = assetStorageService.findByType(AGENT.getValue());+ Asset[] agents = assetStorageService.findByType(AGENT.getValue(), false);LOG.fine("Deploy all agents in all realms: " + agents.length);for (Asset agent : agents) {deployAgent(agent, PersistenceEvent.Cause.UPDATE);@@ -102,7 +102,7 @@ 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);+ Asset[] things = assetStorageService.findChildrenByType(agent.getId(), THING, true);for (Asset thing : things) {deployThing(thing, PersistenceEvent.Cause.UPDATE);}diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.javaindex e4104f240..938a7f4a2 100644--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java@@ -46,22 +46,22 @@ import static org.openremote.model.asset.AssetType.THING;/*** Process asset attribute changes, routing asset-related messages.- *+ * <p>* Receives {@link AttributeEvent} messages in {@link #updateAttributeValue(AttributeEvent)} and processes them.* <p>* {@link AttributeEvent} messages can come from various sources:- *+ * <p>* <ul>* <li>Protocol {@link org.openremote.agent3.protocol.AbstractProtocol#onSensorUpdate(AttributeState, long)}</li>* <li>User/Client initiated</li>* <li>Rules</li>* </ul>- *+ * <p>* <p>* The {@link AttributeEvent} messages are first validated (link and value type checking) then they are* converted into {@link AssetUpdate} messages which are then passed through the processing chain of* {@link Consumer<AssetUpdate>}.- *+ * <p>* <p>* The regular processing chain is:* <ul>@@ -70,7 +70,7 @@ import static org.openremote.model.asset.AssetType.THING;* <li>{@link AssetStorageService}</li>* <li>{@link AssetDatapointService}</li>* </ul>- *+ * <p>* <p>* Rules Service processing logic:* <p>@@ -80,24 +80,24 @@ import static org.openremote.model.asset.AssetType.THING;* the processing chain or changing the value that progresses through the processing chain. Rules can also set a status* of {@link AssetUpdate.Status#RULES_HANDLED} which means that the message shouldn't be processed by any more rule* engines but it should continue through the processing chain.- *+ * <p>* <p>* Agent service processing logic:* <p>* When the incoming messages come from a Protocol (i.e. generated by a call from* {@link org.openremote.agent3.protocol.AbstractProtocol#onSensorUpdate(AttributeState, long)} then* the Agent Service will ignore the message and just pass it onto the next consumer.- *+ * <p>* When the incoming messages come from any other source then the Agent Service will check if it relates* to a THING asset and if so it will check if the attribute is linked to an agent. If it is not linked to* an Agent then it ignores the message and just passes it to the next consumer. If it is linked to an Agent* and the Agent link is invalid then the message status is set to {@link AssetUpdate.Status#ERROR} and* the message will not be able to progress through the processing chain.- *+ * <p>* If the message is for a valid linked agent then a message is sent on the* {@link org.openremote.agent3.protocol.AbstractProtocol#ACTUATOR_TOPIC} which the Protocol will receive in* {@link org.openremote.agent3.protocol.AbstractProtocol#sendToActuator(AttributeEvent)}.- *+ * <p>* <p>* This means that a protocol implementation is responsible for producing a new {@link AttributeEvent} to* indicate to the system that the attribute value has/has not changed. The protocol should know best when to@@ -105,13 +105,13 @@ import static org.openremote.model.asset.AssetType.THING;* might send a separate sensor changed message or both or neither (fire and forget) the protocol must decide* what the best course of action is based on the 'things' it communicates with and the transport layer it uses etc.* <p>- *+ * <p>* <p>* Asset Storage Service processing logic:* <p>* Always tries to persist the attribute value in the DB and allows the message to continue if the commit was* successful.- *+ * <p>* <p>* Asset Datapoint Service processing logic:* <p>@@ -173,13 +173,13 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer* with single attribute value changes and pushes them through the attribute event processing chain* where each consumer is given the opportunity to consume the event or allow it progress to the* next consumer {@link AssetUpdate.Status}.- *+ * <p>* NOTE: An attribute value can be changed during Asset CRUD but this does not come through* this route but is handled separately see {@link AssetResourceImpl}. Any attribute values* assigned during Asset CRUD can be thought of as the attributes initial value and is subject* to change by the following actors (depending on attribute meta etc.) all actors use this* entry point to initiate an attribute value change:- *+ * <p>* Rules* Protocol* User@@ -189,14 +189,14 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSerpublic void updateAttributeValue(AttributeEvent attributeEvent) {// Check this event relates to a valid asset- ServerAsset asset = assetStorageService.find(attributeEvent.getEntityId());+ ServerAsset asset = assetStorageService.find(attributeEvent.getEntityId(), true);- if (asset == null) {- LOG.warning("Processing client update failed asset not found: " + attributeEvent);- return;- }+ if (asset == null) {+ LOG.warning("Processing client update failed asset not found: " + attributeEvent);+ return;+ }- // Prevent editing of individual agent attributes+ // Prevent editing of individual agent attributesif (asset.getWellKnownType() == AssetType.AGENT) {throw new RuntimeException("Agent attributes can not be updated individually, update the whole asset instead");}@@ -227,7 +227,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer*/protected void processSensorUpdate(AttributeEvent attributeEvent) {// Must reference a thing asset- ServerAsset thing = assetStorageService.find(attributeEvent.getEntityId());+ ServerAsset thing = assetStorageService.find(attributeEvent.getEntityId(), true);if (thing.getWellKnownType() != THING) {LOG.fine("Ignoring " + attributeEvent + ", not a thing: " + thing);return;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 aadeab6d4..5d32342ec 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,8 +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.AssetInfo;-import org.openremote.model.asset.ProtectedAssetInfo;+import org.openremote.model.asset.ProtectedAsset;import javax.ws.rs.WebApplicationException;import javax.ws.rs.core.Response;@@ -59,36 +58,36 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour}@Override- public ProtectedAssetInfo[] getCurrentUserAssets(RequestParams requestParams) {+ public ProtectedAsset[] getCurrentUserAssets(RequestParams requestParams) {try {if (isSuperUser() || !isRestrictedUser()) {- return new ProtectedAssetInfo[0];+ return new ProtectedAsset[0];}- List<ProtectedAssetInfo> assets = Arrays.asList(assetStorageService.findProtectedOfUser(getUserId()));+ List<ProtectedAsset> assets = Arrays.asList(assetStorageService.findProtectedOfUser(getUserId(), true));// 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<ProtectedAssetInfo> it = assets.iterator();+ Iterator<ProtectedAsset> it = assets.iterator();while (it.hasNext()) {- ProtectedAssetInfo assetInfo = it.next();- String assetRealm = identityService.getActiveTenantRealm(assetInfo.getRealmId());+ ProtectedAsset 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: " + assetInfo);+ LOG.warning("User '" + getUsername() + "' has protected asset outside of authenticated realm, skipping: " + asset);it.remove();}}- return assets.toArray(new ProtectedAssetInfo[assets.size()]);+ return assets.toArray(new ProtectedAsset[assets.size()]);} catch (IllegalStateException ex) {throw new WebApplicationException(ex, Response.Status.BAD_REQUEST);}}@Override- public void updateCurrentUserAsset(RequestParams requestParams, String assetId, ProtectedAssetInfo assetInfo) {+ public void updateCurrentUserAsset(RequestParams requestParams, String assetId, ProtectedAsset protectedAsset) {throw new UnsupportedOperationException("Not Implemented"); // TODO}@Override- public AssetInfo[] getRoot(RequestParams requestParams, String realmId) {+ public Asset[] getRoot(RequestParams requestParams, String realmId) {try {if (realmId == null || realmId.length() == 0) {realmId = identityService.getActiveTenantRealmId(getAuthenticatedRealm());@@ -98,28 +97,28 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResourthrow new WebApplicationException(NOT_FOUND);}if (!isRealmAccessibleByUser(realm) || isRestrictedUser()) {- return new AssetInfo[0];+ return new Asset[0];}- return assetStorageService.findRoot(realmId);+ return assetStorageService.findRoot(realmId, false);} catch (IllegalStateException ex) {throw new WebApplicationException(ex, Response.Status.BAD_REQUEST);}}@Override- public AssetInfo[] getChildren(RequestParams requestParams, String parentId) {+ public Asset[] getChildren(RequestParams requestParams, String parentId) {try {if (isRestrictedUser()) {- return new AssetInfo[0];+ return new Asset[0];}if (isSuperUser()) {- return assetStorageService.findChildren(parentId);+ return assetStorageService.findChildren(parentId, false);} else {String realmId = identityService.getActiveTenantRealmId(getAuthenticatedRealm());if (realmId == null) {throw new WebApplicationException(NOT_FOUND);}- return assetStorageService.findChildrenInRealm(parentId, realmId);+ return assetStorageService.findChildrenInRealm(parentId, realmId, false);}} catch (IllegalStateException ex) {throw new WebApplicationException(ex, Response.Status.BAD_REQUEST);@@ -132,7 +131,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResourif (isRestrictedUser()) {throw new WebApplicationException(Response.Status.FORBIDDEN);}- Asset asset = assetStorageService.find(assetId);+ Asset asset = assetStorageService.find(assetId, true);if (asset == null)throw new WebApplicationException(NOT_FOUND);String realm = identityService.getActiveTenantRealm(asset.getRealmId());@@ -158,7 +157,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResourif (isRestrictedUser()) {throw new WebApplicationException(Response.Status.FORBIDDEN);}- ServerAsset serverAsset = assetStorageService.find(assetId);+ ServerAsset serverAsset = assetStorageService.find(assetId, true);if (serverAsset == null)throw new WebApplicationException(NOT_FOUND);@@ -203,7 +202,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);+ ServerAsset asset = assetStorageService.find(assetId, true);if (asset == null)throw new WebApplicationException(NOT_FOUND);@@ -248,7 +247,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour@Overridepublic String readAttributeValue(RequestParams requestParams, String assetId, String attributeName) {try {- ServerAsset asset = assetStorageService.find(assetId);+ ServerAsset asset = assetStorageService.find(assetId, true);if (asset == null)throw new WebApplicationException(NOT_FOUND);@@ -330,7 +329,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResourif (isRestrictedUser()) {throw new WebApplicationException(Response.Status.FORBIDDEN);}- ServerAsset serverAsset = assetStorageService.find(assetId);+ ServerAsset serverAsset = assetStorageService.find(assetId, true);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 9826da56b..d79b5e9e8 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@@ -28,19 +28,26 @@ import org.openremote.container.persistence.PersistenceService;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.*;+import org.openremote.model.asset.Asset;+import org.openremote.model.asset.AssetType;+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.util.ArrayList;import java.util.Arrays;import java.util.List;+import java.util.function.Consumer;import java.util.logging.Logger;import java.util.regex.Pattern;-import java.util.function.Consumer;import static org.openremote.model.asset.AssetType.AGENT;@@ -57,7 +64,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());+ Asset agent = find(agentLink.getEntityId(), true);if (agent != null && agent.getWellKnownType().equals(AGENT)) {AgentAttributes agentAttributes = new AgentAttributes(agent);return agentAttributes.getProtocolConfiguration(agentLink.getAttributeName());@@ -96,96 +103,127 @@ public class AssetStorageService implements ContainerService, Consumer<AssetUpda/*** Find assets without a parent in a realm.*- * @param realmId The realm to search.+ * @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 AssetInfo[] findRoot(String realmId) {+ 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<AssetInfo> result = em.createQuery(- "select new org.openremote.manager.server.asset.ServerAssetInfo(" +- "a.id, a.version, a.name, a.createdOn, a.realmId, a.type, a.parent.id, a.location" +- ") from Asset a where a.parent is null and a.realmId = :realmId order by a.createdOn asc",- AssetInfo.class- ).setParameter("realmId", realmId).getResultList();- return result.toArray(new AssetInfo[result.size()]);+ 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()]);});}/*** Retrieve the children of an asset.*- * @param parentId The ID of the parent 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 AssetInfo[] findChildren(String parentId) {+ public ServerAsset[] findChildren(String parentId, boolean loadComplete) {return persistenceService.doReturningTransaction(em -> {- Asset parent = loadAsset(em, parentId, false);- if (parent == null)- return new AssetInfo[0];- List<AssetInfo> result =- em.createQuery(- "select new org.openremote.manager.server.asset.ServerAssetInfo(" +- "a.id, a.version, a.name, a.createdOn, a.realmId, a.type, a.parent.id, a.location" +- ") from Asset a where a.parent.id = :parentId order by a.createdOn asc",- AssetInfo.class- ).setParameter("parentId", parentId).getResultList();- return result.toArray(new AssetInfo[result.size()]);+ 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()]);});}/*** 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 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 AssetInfo[] findChildrenInRealm(String parentId, String realmId) {+ public ServerAsset[] findChildrenInRealm(String parentId, String realmId, boolean loadComplete) {return persistenceService.doReturningTransaction(em -> {- Asset parent = loadAsset(em, parentId, false);- if (parent == null)- return new AssetInfo[0];- List<AssetInfo> result =- em.createQuery(- "select new org.openremote.manager.server.asset.ServerAssetInfo(" +- "a.id, a.version, a.name, a.createdOn, a.realmId, a.type, a.parent.id, a.location" +- ") from Asset a, Asset p where p.id = :parentId and a.parent.id = :parentId " +- "and p.realmId = :realmId and a.realmId = :realmId " +- "order by a.createdOn asc",- AssetInfo.class- ).setParameter("parentId", parentId)- .setParameter("realmId", realmId)- .getResultList();- return result.toArray(new AssetInfo[result.size()]);+ 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()]);});}/*** Find an asset by primary key and populate all transient details (path, tenant).*- * @param assetId The primary key identifier value of the asset.+ * @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) {- return persistenceService.doReturningTransaction(em -> loadAsset(em, assetId, true));+ 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;+ }+ });+ }++ /**+ * 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+ */+ 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()]);+ });}+ /**+ * 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 ProtectedAssetInfo[] findProtectedOfUser(String userId) {+ public ProtectedServerAsset[] findProtectedOfUser(String userId, boolean loadComplete) {return persistenceService.doReturningTransaction(em -> {- List<ProtectedAssetInfo> result = em.createQuery(- "select new org.openremote.manager.server.asset.ProtectedServerAssetInfo(" +- "a.id, a.version, a.name, a.createdOn, a.realmId, a.type, a.parent.id, a.location, a.attributes" +- ") from Asset a, UserAsset ua where a.id = ua.assetId and ua.userId = :userId order by a.createdOn asc",- ProtectedAssetInfo.class- ).setParameter("userId", userId).getResultList();- return result.toArray(new ProtectedAssetInfo[result.size()]);+ 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()]);});}@@ -219,44 +257,6 @@ public class AssetStorageService implements ContainerService, Consumer<AssetUpda});}- /**- * Find assets by type in all realms.- *- * @param assetType The type of the assets to find.- * @return The found assets or an empty array- */- public ServerAsset[] findByType(String assetType) {- return persistenceService.doReturningTransaction(em -> {- List<ServerAsset> result =- em.createQuery(- "select a from Asset a where a.type = :assetType order by a.createdOn asc",- ServerAsset.class)- .setParameter("assetType", assetType)- .getResultList();- return result.toArray(new ServerAsset[result.size()]);- });- }-- /**- * 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.- * @return The found assets or an empty array- */- public ServerAsset[] findChildrenByType(String parentId, AssetType assetType) {- return persistenceService.doReturningTransaction(em -> {- List<ServerAsset> result =- em.createQuery(- "select a from Asset a where a.type = :assetType and a.parentId = :parentId order by a.createdOn asc",- ServerAsset.class)- .setParameter("assetType", assetType.getValue())- .setParameter("parentId", parentId)- .getResultList();- return result.toArray(new ServerAsset[result.size()]);- });- }-/*** @return The current stored asset state.* @throws IllegalArgumentException if the realm or parent is illegal, or other asset constraint is violated.@@ -275,7 +275,7 @@ public class AssetStorageService implements ContainerService, Consumer<AssetUpdaif (parent == null)throw new IllegalStateException("Parent not found: " + asset.getParentId());// ... the parent can not be a child of the asset- if (Arrays.asList(parent.getPath()).contains(asset.getId()))+ if (parent.pathContains(asset.getId()))throw new IllegalStateException("Invalid parent");}// Validate attribute names@@ -298,7 +298,7 @@ public class AssetStorageService implements ContainerService, Consumer<AssetUpdareturn persistenceService.doReturningTransaction(em -> {Asset asset = em.find(ServerAsset.class, assetId);if (asset != null) {- if (findChildren(asset.getId()).length > 0)+ if (findChildren(asset.getId(), false).length > 0)return false;em.remove(asset);}@@ -413,6 +413,72 @@ 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.javanew file mode 100644index 000000000..52b847160--- /dev/null+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/ProtectedServerAsset.java@@ -0,0 +1,60 @@+/*+ * 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/ProtectedServerAssetInfo.java b/manager/server/src/main/java/org/openremote/manager/server/asset/ProtectedServerAssetInfo.javadeleted file mode 100644index ba22ca9cb..000000000--- a/manager/server/src/main/java/org/openremote/manager/server/asset/ProtectedServerAssetInfo.java+++ /dev/null@@ -1,53 +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.Coordinate;-import com.vividsolutions.jts.geom.Geometry;-import elemental.json.JsonObject;-import org.openremote.model.asset.ProtectedAssetInfo;--import java.util.Date;--/**- * Provides a constructor we can use in database query result marshaling.- */-public class ProtectedServerAssetInfo extends ProtectedAssetInfo {-- public ProtectedServerAssetInfo(- String id,- long version,- String name,- Date createdOn,- String realmId,- String type,- String parentId,- Geometry location,- JsonObject attributes) {- super(- id, version, name, createdOn, realmId, type, parentId,- location != null ? new double[]{- location.getCoordinate().getOrdinate(Coordinate.X),- location.getCoordinate().getOrdinate(Coordinate.Y)- } : null,- attributes- );- }-}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 6366632e4..f0a2aac9e 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@@ -21,18 +21,23 @@ package org.openremote.manager.server.asset;import com.fasterxml.jackson.annotation.JsonIgnore;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.JsonObject;import org.hibernate.annotations.Check;import org.openremote.model.asset.Asset;import javax.persistence.*;+import java.util.Date;/**- * This can only be used on the server and offers types (such as Hibernate proxying, Geometry)- * which can not be serialized or compiled on the client.+ * This can only be used on the server and offers types (such as+ * {@link org.geolatte.geom.Geometry}) which can not be serialized+ * or compiled on the client and constructors for query result mapping.*/@Entity(name = "Asset")+@Table(name = "ASSET")@Check(constraints = "ID != PARENT_ID")// TODO Write on-insert/update SQL trigger that validates the asset realm, it must match the parent's realmpublic class ServerAsset extends Asset {@@ -40,14 +45,14 @@ public class ServerAsset extends Asset {/*** Easy conversion between types, we copy all properties (not a deep copy!)*/- public static ServerAsset map(Asset asset, ServerAsset serverAsset) {+ public static <T extends ServerAsset> T map(Asset asset, T serverAsset) {return map(asset, serverAsset, null, null, null);}- public static ServerAsset map(Asset asset, ServerAsset serverAsset,- String overrideParentId,- String overrideType,- Double[] overrideLocation) {+ public static <T extends ServerAsset> T map(Asset asset, T serverAsset,+ String overrideParentId,+ String overrideType,+ Double[] overrideLocation) {serverAsset.setVersion(asset.getVersion());serverAsset.setRealmId(asset.getRealmId());serverAsset.setName(asset.getName());@@ -78,11 +83,6 @@ public class ServerAsset extends Asset {return serverAsset;}- @JoinColumn(name = "PARENT_ID", insertable = false, updatable = false)- @ManyToOne(fetch = FetchType.LAZY)- @JsonIgnore- protected ServerAsset parent;-@Column(name = "LOCATION")@Access(AccessType.PROPERTY)@JsonIgnore@@ -91,15 +91,35 @@ public class ServerAsset extends Asset {public ServerAsset() {}- public ServerAsset(Asset parent) {- super(parent);- setRealmId(parent.getRealmId());- setTenantRealm(parent.getTenantRealm());- setTenantDisplayName(parent.getTenantDisplayName());+ public ServerAsset(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 ServerAsset getParent() {- return parent;+ 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((Point) location);+ }++ public ServerAsset(Asset parent) {+ super(parent);}public Point getLocation() {@@ -108,14 +128,17 @@ public class ServerAsset extends Asset {public void setLocation(Point location) {this.location = location;+ setCoordinates(this, location);+ }++ public static void setCoordinates(Asset asset, Point location) {if (location == null) {- setCoordinates();+ asset.setCoordinates();} else {- setCoordinates(+ asset.setCoordinates(location.getCoordinate().getOrdinate(Coordinate.X),location.getCoordinate().getOrdinate(Coordinate.Y));}}-}diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/ServerAssetInfo.java b/manager/server/src/main/java/org/openremote/manager/server/asset/ServerAssetInfo.javadeleted file mode 100644index 6dc583d25..000000000--- a/manager/server/src/main/java/org/openremote/manager/server/asset/ServerAssetInfo.java+++ /dev/null@@ -1,49 +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.manager.server.asset;--import com.vividsolutions.jts.geom.Coordinate;-import com.vividsolutions.jts.geom.Geometry;-import org.openremote.model.asset.AssetInfo;--import java.util.Date;--/**- * Provides a constructor we can use in database query result marshaling.- */-public class ServerAssetInfo extends AssetInfo {-- public ServerAssetInfo(String id,- long version,- String name,- Date createdOn,- String realmId,- String type,- String parentId,- Geometry location) {- super(- id, version, name, createdOn, realmId, type, parentId,- location != null ? new double[]{- location.getCoordinate().getOrdinate(Coordinate.X),- location.getCoordinate().getOrdinate(Coordinate.Y)- } : null- );- }-}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 3c1d09817..9868e8dd1 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@@ -72,15 +72,11 @@ public class RulesResourceImpl extends ManagerWebResource implements RulesResour@Overridepublic AssetRulesDefinition[] getAssetDefinitions(@BeanParam RequestParams requestParams, String assetId) {- Asset asset = assetStorageService.find(assetId);+ Asset asset = assetStorageService.find(assetId, false);if (asset == null)return new AssetRulesDefinition[0];- String realm = identityService.getActiveTenantRealm(asset.getRealmId());- if (realm == null) {- throw new WebApplicationException(BAD_REQUEST);- }- if (!isRealmAccessibleByUser(realm)) {+ if (!isRealmAccessibleByUser(asset.getTenantRealm())) {throw new WebApplicationException(Response.Status.FORBIDDEN);}if (isRestrictedUser() &&@@ -98,7 +94,7 @@ public class RulesResourceImpl extends ManagerWebResource implements RulesResourif (!isSuperUser()) {throw new WebApplicationException(Response.Status.FORBIDDEN);}- rulesDefinition = rulesStorageService.merge(rulesDefinition);+ rulesStorageService.merge(rulesDefinition);}@Override@@ -121,7 +117,7 @@ public class RulesResourceImpl extends ManagerWebResource implements RulesResourGlobalRulesDefinition existingDefinition = rulesStorageService.findById(GlobalRulesDefinition.class, id);if (existingDefinition == null)throw new WebApplicationException(NOT_FOUND);- rulesDefinition = rulesStorageService.merge(rulesDefinition);+ rulesStorageService.merge(rulesDefinition);}@Override@@ -143,7 +139,7 @@ public class RulesResourceImpl extends ManagerWebResource implements RulesResourif (!isRealmAccessibleByUser(realm) || isRestrictedUser()) {throw new WebApplicationException(Response.Status.FORBIDDEN);}- rulesDefinition = rulesStorageService.merge(rulesDefinition);+ rulesStorageService.merge(rulesDefinition);}@Override@@ -181,7 +177,7 @@ public class RulesResourceImpl extends ManagerWebResource implements RulesResourif (!existingDefinition.getRealmId().equals(rulesDefinition.getRealmId())) {throw new WebApplicationException("Requested realm and existing definition realm must match", BAD_REQUEST);}- rulesDefinition = rulesStorageService.merge(rulesDefinition);+ rulesStorageService.merge(rulesDefinition);}@Override@@ -208,22 +204,18 @@ public class RulesResourceImpl extends ManagerWebResource implements RulesResourif (assetId == null || assetId.length() == 0) {throw new WebApplicationException("Missing asset identifier value", BAD_REQUEST);}- Asset asset = assetStorageService.find(assetId);+ Asset asset = assetStorageService.find(assetId, false);if (asset == null) {throw new WebApplicationException(NOT_FOUND);}- String realm = identityService.getActiveTenantRealm(asset.getRealmId());- if (realm == null) {- throw new WebApplicationException(BAD_REQUEST);- }- if (!isRealmAccessibleByUser(realm)) {+ if (!isRealmAccessibleByUser(asset.getTenantRealm())) {throw new WebApplicationException(Response.Status.FORBIDDEN);}if (isRestrictedUser() &&!assetStorageService.findProtectedOfUserContains(getUserId(), asset.getId())) {throw new WebApplicationException(Response.Status.FORBIDDEN);}- rulesDefinition = rulesStorageService.merge(rulesDefinition);+ rulesStorageService.merge(rulesDefinition);}@Override@@ -232,15 +224,11 @@ public class RulesResourceImpl extends ManagerWebResource implements RulesResourif (existingDefinition == null) {throw new WebApplicationException(NOT_FOUND);}- Asset asset = assetStorageService.find(existingDefinition.getAssetId());+ Asset asset = assetStorageService.find(existingDefinition.getAssetId(), false);if (asset == null) {throw new WebApplicationException(NOT_FOUND);}- String realm = identityService.getActiveTenantRealm(asset.getRealmId());- if (realm == null) {- throw new WebApplicationException(BAD_REQUEST);- }- if (!isRealmAccessibleByUser(realm)) {+ if (!isRealmAccessibleByUser(asset.getTenantRealm())) {throw new WebApplicationException(Response.Status.FORBIDDEN);}if (isRestrictedUser() &&@@ -256,15 +244,11 @@ public class RulesResourceImpl extends ManagerWebResource implements RulesResourif (existingDefinition == null) {throw new WebApplicationException(NOT_FOUND);}- Asset asset = assetStorageService.find(existingDefinition.getAssetId());+ Asset asset = assetStorageService.find(existingDefinition.getAssetId(), false);if (asset == null) {throw new WebApplicationException(NOT_FOUND);}- String realm = identityService.getActiveTenantRealm(asset.getRealmId());- if (realm == null) {- throw new WebApplicationException(BAD_REQUEST);- }- if (!isRealmAccessibleByUser(realm)) {+ if (!isRealmAccessibleByUser(asset.getTenantRealm())) {throw new WebApplicationException(Response.Status.FORBIDDEN);}if (isRestrictedUser() &&@@ -277,7 +261,7 @@ public class RulesResourceImpl extends ManagerWebResource implements RulesResourif (!existingDefinition.getAssetId().equals(rulesDefinition.getAssetId())) {throw new WebApplicationException("Can't update asset ID, delete and create the definition to reassign", BAD_REQUEST);}- rulesDefinition = rulesStorageService.merge(rulesDefinition);+ rulesStorageService.merge(rulesDefinition);}@Override@@ -286,15 +270,11 @@ public class RulesResourceImpl extends ManagerWebResource implements RulesResourif (existingDefinition == null) {return;}- Asset asset = assetStorageService.find(existingDefinition.getAssetId());+ Asset asset = assetStorageService.find(existingDefinition.getAssetId(), false);if (asset == null) {throw new WebApplicationException(NOT_FOUND);}- String realm = identityService.getActiveTenantRealm(asset.getRealmId());- if (realm == null) {- throw new WebApplicationException(BAD_REQUEST);- }- if (!isRealmAccessibleByUser(realm)) {+ if (!isRealmAccessibleByUser(asset.getTenantRealm())) {throw new WebApplicationException(Response.Status.FORBIDDEN);}if (isRestrictedUser() &&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 3aea705f5..32480ef19 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@@ -100,43 +100,42 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons// If any asset was modified in the database, detect changed attributesfrom(PERSISTENCE_TOPIC)- .filter(isPersistenceEventForEntityType(Asset.class))- .process(exchange -> {- PersistenceEvent persistenceEvent = exchange.getIn().getBody(PersistenceEvent.class);- Asset asset = (Asset) persistenceEvent.getEntity();- ServerAsset serverAsset = ServerAsset.map(asset, new ServerAsset());-- switch (persistenceEvent.getCause())- {- case INSERT:- // New asset has been created so get attributes that have RULES_FACT meta- Attributes addedAttributes = new Attributes(asset.getAttributes());- Arrays.stream(addedAttributes.get())- .filter(attribute -> attribute.hasMetaItem(AssetMeta.RULES_FACT))- .forEach(attribute -> {- AssetUpdate update = new AssetUpdate(serverAsset, attribute, attribute.getStateEvent(asset.getId()), null);- // TODO: What if a rule engine marks the fact as handled it should still go into other engines here???- insertFact(update);- });- break;- case UPDATE:- // TODO: Handle update case- break;- case DELETE:- // Retract any facts that were associated with this asset- Attributes removedAttributes = new Attributes(asset.getAttributes());- Arrays.stream(removedAttributes.get())- .filter(attribute -> attribute.hasMetaItem(AssetMeta.RULES_FACT))- .forEach(attribute -> {- AssetUpdate update = new AssetUpdate(serverAsset, attribute, attribute.getStateEvent(asset.getId()), null);- // TODO: What if a rule engine marks the fact as handled it should still go into other engines here???- retractFact(update);- });- break;- }- // TODO: Detect which attribute was created/updated in the database and handle it-- });+ .filter(isPersistenceEventForEntityType(Asset.class))+ .process(exchange -> {+ PersistenceEvent persistenceEvent = exchange.getIn().getBody(PersistenceEvent.class);+ Asset asset = (Asset) persistenceEvent.getEntity();+ ServerAsset serverAsset = ServerAsset.map(asset, new ServerAsset());++ switch (persistenceEvent.getCause()) {+ case INSERT:+ // New asset has been created so get attributes that have RULES_FACT meta+ Attributes addedAttributes = new Attributes(asset.getAttributes());+ Arrays.stream(addedAttributes.get())+ .filter(attribute -> attribute.hasMetaItem(AssetMeta.RULES_FACT))+ .forEach(attribute -> {+ AssetUpdate update = new AssetUpdate(serverAsset, attribute, attribute.getStateEvent(asset.getId()), null);+ // TODO: What if a rule engine marks the fact as handled it should still go into other engines here???+ insertFact(update);+ });+ break;+ case UPDATE:+ // TODO: Handle update case+ break;+ case DELETE:+ // Retract any facts that were associated with this asset+ Attributes removedAttributes = new Attributes(asset.getAttributes());+ Arrays.stream(removedAttributes.get())+ .filter(attribute -> attribute.hasMetaItem(AssetMeta.RULES_FACT))+ .forEach(attribute -> {+ AssetUpdate update = new AssetUpdate(serverAsset, attribute, attribute.getStateEvent(asset.getId()), null);+ // TODO: What if a rule engine marks the fact as handled it should still go into other engines here???+ retractFact(update);+ });+ break;+ }+ // TODO: Detect which attribute was created/updated in the database and handle it++ });}@Override@@ -288,7 +287,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons.entrySet().stream().map(es ->- new Pair<>(assetStorageService.find(es.getKey()), es.getValue())+ new Pair<>(assetStorageService.find(es.getKey(), true), es.getValue())).collect(Collectors.groupingBy(assetAndRules -> assetAndRules.key.getRealmId())).entrySet()@@ -337,7 +336,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons// Get the chain of rule engines that we need to pass throughServerAsset asset = assetUpdate.getAsset();- List<RulesDeployment> rulesDeployments = getEnginesInScope(asset.getRealmId(), asset.getPath());+ List<RulesDeployment> rulesDeployments = getEnginesInScope(asset.getRealmId(), asset.getReversePath());// Pass through each engine and try and insert the factfor (RulesDeployment deployment : rulesDeployments) {@@ -360,7 +359,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons// Get the chain of rule engines that we need to pass throughServerAsset asset = assetUpdate.getAsset();- List<RulesDeployment> rulesDeployments = getEnginesInScope(asset.getRealmId(), asset.getPath());+ List<RulesDeployment> rulesDeployments = getEnginesInScope(asset.getRealmId(), asset.getReversePath());// Pass through each engine and retract this factfor (RulesDeployment deployment : rulesDeployments) {diff --git a/manager/server/src/main/java/org/openremote/manager/server/security/RealmView.java b/manager/server/src/main/java/org/openremote/manager/server/security/RealmView.javanew file mode 100644index 000000000..956ee523d--- /dev/null+++ b/manager/server/src/main/java/org/openremote/manager/server/security/RealmView.java@@ -0,0 +1,93 @@+/*+ * 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.security;++import org.hibernate.annotations.Formula;+import org.hibernate.annotations.Subselect;++import javax.persistence.Column;+import javax.persistence.Entity;+import javax.persistence.Id;++/**+ * Use this to query the Keycloak REALM table in JPA queries.+ */+@Entity+@Subselect("select * from REALM") // Map this immutable to an SQL view, don't use/create table+public class RealmView {++ protected String id;++ protected boolean enabled;++ protected String name;++ protected Integer notBefore;++ protected String displayName;++ public RealmView() {+ }++ @Id+ public String getId() {+ return id;+ }++ protected void setId(String id) {+ this.id = id;+ }++ public boolean isEnabled() {+ return enabled;+ }++ protected void setEnabled(boolean enabled) {+ this.enabled = enabled;+ }++ public String getName() {+ return name;+ }++ protected void setName(String name) {+ this.name = name;+ }++ @Column(name = "NOT_BEFORE")+ public Integer getNotBefore() {+ return notBefore;+ }++ public void setNotBefore(Integer notBefore) {+ this.notBefore = notBefore;+ }++ @Formula(+ "(select ra.VALUE from REALM_ATTRIBUTE ra where ra.REALM_ID = ID and ra.name = 'displayName')"+ )+ public String getDisplayName() {+ return displayName;+ }++ protected void setDisplayName(String displayName) {+ this.displayName = displayName;+ }+}diff --git a/manager/server/src/main/resources/LoadScript.sql b/manager/server/src/main/resources/Constraints.sqlsimilarity index 91%rename from manager/server/src/main/resources/LoadScript.sqlrename to manager/server/src/main/resources/Constraints.sqlindex dc0e9b134..0bf1b62c0 100644--- a/manager/server/src/main/resources/LoadScript.sql+++ b/manager/server/src/main/resources/Constraints.sql@@ -1,3 +1,6 @@+alter table ASSET+ add foreign key (PARENT_ID) references ASSET (ID);+alter table ASSETadd foreign key (REALM_ID) references REALM (ID);diff --git a/manager/server/src/main/resources/GetAssetTreePath.sql b/manager/server/src/main/resources/GetAssetTreePath.sqlnew file mode 100644index 000000000..dea70de7c--- /dev/null+++ b/manager/server/src/main/resources/GetAssetTreePath.sql@@ -0,0 +1,15 @@+-- importOneStatementOnly+create or replace function GET_ASSET_TREE_PATH(ASSET_ID text)+ returns text [] as+$$+begin+ return (with recursive ASSET_TREE(ID, PARENT_ID, PATH) as (+ select A1.ID, A1.PARENT_ID, array [text(A1.ID)] from ASSET A1 where A1.ID = ASSET_ID+ union all+ select A2.ID, A2.PARENT_ID, array_append(AT.PATH, text(A2.ID))+ from ASSET A2, ASSET_TREE AT+ where A2.ID = AT.PARENT_ID and AT.PARENT_ID is not null+ ) select PATH from ASSET_TREE where PARENT_ID is null);+end;+$$+language plpgsql;diff --git a/manager/server/src/main/resources/META-INF/persistence.xml b/manager/server/src/main/resources/META-INF/persistence.xmlindex 03ce221b6..5c9ff8786 100644--- a/manager/server/src/main/resources/META-INF/persistence.xml+++ b/manager/server/src/main/resources/META-INF/persistence.xml@@ -13,6 +13,7 @@<class>org.openremote.manager.server.notification.DeviceNotificationToken</class><class>org.openremote.manager.shared.notification.AlertNotification</class><class>org.openremote.manager.shared.notification.AlertAction</class>+ <class>org.openremote.manager.server.security.RealmView</class><class>org.openremote.manager.server.security.UserConfiguration</class><class>org.openremote.model.datapoint.AssetDatapoint</class><class>org.openremote.model.asset.UserAsset</class>@@ -27,8 +28,8 @@<property name="hibernate.use_sql_comments" value="true"/><property name="hibernate.archive.autodetection" value="none"/><property name="hibernate.current_session_context_class" value="thread"/>- <property name="hibernate.hbm2ddl.import_files_sql_extractor" value="org.hibernate.tool.hbm2ddl.MultipleLinesSqlCommandExtractor"/>- <property name="javax.persistence.sql-load-script-source" value="LoadScript.sql"/>+ <property name="hibernate.hbm2ddl.import_files_sql_extractor" value="org.openremote.container.persistence.EnhancedImportSqlCommandExtractor"/>+ <property name="hibernate.hbm2ddl.import_files" value="GetAssetTreePath.sql, LoadScript.sql"/></properties></persistence-unit>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 20ce22ab4..a907e80ca 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,8 +23,7 @@ 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.AssetInfo;-import org.openremote.model.asset.ProtectedAssetInfo;+import org.openremote.model.asset.ProtectedAsset;import javax.annotation.security.RolesAllowed;import javax.validation.Valid;@@ -67,7 +66,7 @@ public interface AssetResource {@Produces(APPLICATION_JSON)@SuccessStatusCode(200)@RolesAllowed({"read:assets"})- ProtectedAssetInfo[] getCurrentUserAssets(@BeanParam RequestParams requestParams);+ ProtectedAsset[] 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@@ -79,7 +78,7 @@ public interface AssetResource {@Consumes(APPLICATION_JSON)@SuccessStatusCode(204)@RolesAllowed({"write:assets"})- void updateCurrentUserAsset(@BeanParam RequestParams requestParams, @PathParam("assetId") String assetId, ProtectedAssetInfo assetInfo);+ void updateCurrentUserAsset(@BeanParam RequestParams requestParams, @PathParam("assetId") String assetId, ProtectedAsset protectedAsset);/*** Retrieve the assets without parent (root assets) of the given realm, or if the realm argument@@ -91,7 +90,7 @@ public interface AssetResource {@Produces(APPLICATION_JSON)@SuccessStatusCode(200)@RolesAllowed({"read:assets"})- AssetInfo[] getRoot(@BeanParam RequestParams requestParams, @QueryParam("realmId") String realmId);+ Asset[] getRoot(@BeanParam RequestParams requestParams, @QueryParam("realmId") String realmId);/*** Retrieve the child assets of the given parent asset. If the authenticated user is the superuser,@@ -104,7 +103,7 @@ public interface AssetResource {@Produces(APPLICATION_JSON)@SuccessStatusCode(200)@RolesAllowed({"read:assets"})- AssetInfo[] getChildren(@BeanParam RequestParams requestParams, @PathParam("assetId") String parentId);+ Asset[] getChildren(@BeanParam RequestParams requestParams, @PathParam("assetId") String parentId);/*** Retrieve the asset. Regular users can only access assets in their authenticated realm,diff --git a/manager/test/src/test/groovy/org/openremote/test/agent/AgentDeploymentTest.groovy b/manager/test/src/test/groovy/org/openremote/test/agent/AgentDeploymentTest.groovyindex 424b13e6f..82c8d0ee9 100644--- a/manager/test/src/test/groovy/org/openremote/test/agent/AgentDeploymentTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/agent/AgentDeploymentTest.groovy@@ -46,7 +46,7 @@ class AgentDeploymentTest extends Specification implements ManagerContainerTraitthen: "the simulator state and thing attribute value should be updated (simulator reflects actuator write as sensor read)"conditions.eventually {assert simulatorProtocol.getState(managerDemoSetup.thingId, "light1Dimmer").asNumber() == 66- def thing = assetStorageService.find(managerDemoSetup.thingId)+ def thing = assetStorageService.find(managerDemoSetup.thingId, true)def attributes = new Attributes(thing.getAttributes())assert attributes.get("light1Dimmer").getValue().getType() == JsonType.NUMBERassert attributes.get("light1Dimmer").getValueAsInteger() == 66@@ -58,7 +58,7 @@ class AgentDeploymentTest extends Specification implements ManagerContainerTraitthen: "the thing attribute value should be updated"conditions.eventually {- def thing = assetStorageService.find(managerDemoSetup.thingId)+ def thing = assetStorageService.find(managerDemoSetup.thingId, true)def attributes = new Attributes(thing.getAttributes())assert attributes.get("light1Dimmer").getValue().getType() == JsonType.NUMBERassert attributes.get("light1Dimmer").getValueAsInteger() == 77diff --git a/manager/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovyindex 9be302602..7533e3e7c 100644--- a/manager/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy@@ -43,7 +43,7 @@ class AssetDatapointTest extends Specification implements ManagerContainerTraitthen: "the thing attribute value should be updated and the datapoints stored"conditions.eventually {- def thing = assetStorageService.find(managerDemoSetup.thingId)+ def thing = assetStorageService.find(managerDemoSetup.thingId, true)def attributes = new Attributes(thing.getAttributes())assert attributes.get("light1PowerConsumption").getValueAsDecimal() == 15.5ddef datapoints = assetDatapointService.getDatapoints(new AttributeRef(managerDemoSetup.thingId, "light1PowerConsumption"))diff --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 04272bc2c..d1349e55c 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@@ -6,7 +6,7 @@ import org.openremote.manager.shared.asset.AssetResourceimport org.openremote.model.Attributesimport org.openremote.model.Metaimport org.openremote.model.asset.Asset-import org.openremote.model.asset.ProtectedAssetInfo+import org.openremote.model.asset.ProtectedAssetimport org.openremote.model.AttributeTypeimport org.openremote.model.asset.AssetMetaimport org.openremote.test.ManagerContainerTrait@@ -49,48 +49,48 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai/* ############################################## READ ####################################### */when: "the home assets of the authenticated user are retrieved"- def assetInfos = assetResource.getCurrentUserAssets(null)+ def assets = assetResource.getCurrentUserAssets(null)then: "result should match"- assetInfos.length == 0+ assets.length == 0when: "the root assets of the authenticated realm are retrieved"- assetInfos = assetResource.getRoot(null, masterRealmId)+ assets = assetResource.getRoot(null, masterRealmId)then: "result should match"- assetInfos.length == 1- assetInfos[0].id == managerDemoSetup.smartOfficeId+ assets.length == 1+ assets[0].id == managerDemoSetup.smartOfficeIdwhen: "the child assets of an asset in the authenticated realm are retrieved"- assetInfos = assetResource.getChildren(null, assetInfos[0].id)+ assets = assetResource.getChildren(null, assets[0].id)then: "result should match"- assetInfos.length == 1- assetInfos[0].id == managerDemoSetup.groundFloorId+ assets.length == 1+ assets[0].id == managerDemoSetup.groundFloorIdwhen: "the root assets of the authenticated realm are retrieved"- assetInfos = assetResource.getRoot(null, null)+ assets = assetResource.getRoot(null, null)then: "result should match"- assetInfos.length == 1- assetInfos[0].id == managerDemoSetup.smartOfficeId+ assets.length == 1+ assets[0].id == managerDemoSetup.smartOfficeIdwhen: "the root assets of the given realm are retrieved"- assetInfos = assetResource.getRoot(null, customerARealmId)+ assets = assetResource.getRoot(null, customerARealmId)then: "result should match"- assetInfos.length == 1- assetInfos[0].id == managerDemoSetup.smartHomeId+ assets.length == 1+ assets[0].id == managerDemoSetup.smartHomeIdwhen: "the child assets of an asset in a foreign realm are retrieved"- assetInfos = assetResource.getChildren(null, assetInfos[0].id)+ assets = assetResource.getChildren(null, assets[0].id)then: "result should match"- assetInfos.length == 3+ assets.length == 3// Should be ordered by creation time- assetInfos[0].id == managerDemoSetup.apartment1Id- assetInfos[1].id == managerDemoSetup.apartment2Id- assetInfos[2].id == managerDemoSetup.apartment3Id+ assets[0].id == managerDemoSetup.apartment1Id+ assets[1].id == managerDemoSetup.apartment2Id+ assets[2].id == managerDemoSetup.apartment3Idwhen: "an asset is retrieved by ID in the authenticated realm"def demoThing = assetResource.get(null, managerDemoSetup.thingId)@@ -192,44 +192,44 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai/* ############################################## READ ####################################### */when: "the home assets of the authenticated user are retrieved"- def assetInfos = assetResource.getCurrentUserAssets(null)+ def assets = assetResource.getCurrentUserAssets(null)then: "result should match"- assetInfos.length == 0+ assets.length == 0when: "the root assets of the authenticated realm are retrieved"- assetInfos = assetResource.getRoot(null, masterRealmId)+ assets = assetResource.getRoot(null, masterRealmId)then: "result should match"- assetInfos.length == 1- assetInfos[0].id == managerDemoSetup.smartOfficeId+ assets.length == 1+ assets[0].id == managerDemoSetup.smartOfficeIdwhen: "the child assets of an asset in the authenticated realm are retrieved"- assetInfos = assetResource.getChildren(null, assetInfos[0].id)+ assets = assetResource.getChildren(null, assets[0].id)then: "result should match"- assetInfos.length == 1- assetInfos[0].id == managerDemoSetup.groundFloorId+ assets.length == 1+ assets[0].id == managerDemoSetup.groundFloorIdwhen: "the root assets of the authenticated realm are retrieved"- assetInfos = assetResource.getRoot(null, null)+ assets = assetResource.getRoot(null, null)then: "result should match"- assetInfos.length == 1- assetInfos[0].id == managerDemoSetup.smartOfficeId- assetInfos[0].realmId == masterRealmId+ assets.length == 1+ assets[0].id == managerDemoSetup.smartOfficeId+ assets[0].realmId == masterRealmIdwhen: "the root assets of the given realm are retrieved"- assetInfos = assetResource.getRoot(null, customerARealmId)+ assets = assetResource.getRoot(null, customerARealmId)then: "result should match"- assetInfos.length == 0+ assets.length == 0when: "the child assets of an asset in a foreign realm are retrieved"- assetInfos = assetResource.getChildren(null, managerDemoSetup.smartHomeId)+ assets = assetResource.getChildren(null, managerDemoSetup.smartHomeId)then: "result should be empty"- assetInfos.length == 0+ assets.length == 0when: "an asset is retrieved by ID in the authenticated realm"def demoThing = assetResource.get(null, managerDemoSetup.thingId)@@ -330,36 +330,36 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai/* ############################################## READ ####################################### */when: "the home assets of the authenticated user are retrieved"- def assetInfos = assetResource.getCurrentUserAssets(null)+ def assets = assetResource.getCurrentUserAssets(null)then: "result should match"- assetInfos.length == 0+ assets.length == 0when: "the root assets of a foreign realm are retrieved"- assetInfos = assetResource.getRoot(null, masterRealmId)+ assets = assetResource.getRoot(null, masterRealmId)then: "result should match"- assetInfos.length == 0+ assets.length == 0when: "the root assets of the authenticated realm are retrieved"- assetInfos = assetResource.getRoot(null, null)+ assets = assetResource.getRoot(null, null)then: "result should match"- assetInfos.length == 1- assetInfos[0].id == managerDemoSetup.smartHomeId- assetInfos[0].realmId == customerARealmId+ assets.length == 1+ assets[0].id == managerDemoSetup.smartHomeId+ assets[0].realmId == customerARealmIdwhen: "the root assets of the given realm are retrieved"- assetInfos = assetResource.getRoot(null, customerBRealmId)+ assets = assetResource.getRoot(null, customerBRealmId)then: "result should match"- assetInfos.length == 0+ assets.length == 0when: "the child assets of an asset in a foreign realm are retrieved"- assetInfos = assetResource.getChildren(null, managerDemoSetup.thingId)+ assets = assetResource.getChildren(null, managerDemoSetup.thingId)then: "result should be empty"- assetInfos.length == 0+ assets.length == 0when: "an asset is retrieved by ID in the authenticated realm"def demoSmartHome = assetResource.get(null, managerDemoSetup.smartHomeId)@@ -448,11 +448,11 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai/* ############################################## READ ####################################### */when: "the home assets of the authenticated user are retrieved"- def assetInfos = assetResource.getCurrentUserAssets(null)+ def assets = assetResource.getCurrentUserAssets(null)then: "result should match"- assetInfos.length == 4- ProtectedAssetInfo apartment1 = assetInfos[0]+ assets.length == 4+ ProtectedAsset apartment1 = assets[0]apartment1.id == managerDemoSetup.apartment1Idapartment1.name == "Apartment 1"apartment1.createdOn.getTime() < System.currentTimeMillis()@@ -462,11 +462,11 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraiapartment1.coordinates[0] == 5.469751699216005dapartment1.coordinates[1] == 51.44760787406028d- ProtectedAssetInfo apartment1Livingroom = assetInfos[1]+ ProtectedAsset apartment1Livingroom = assets[1]apartment1Livingroom.id == managerDemoSetup.apartment1LivingroomIdapartment1Livingroom.name == "Livingroom"- ProtectedAssetInfo apartment1LivingroomThermostat = assetInfos[2]+ ProtectedAsset apartment1LivingroomThermostat = assets[2]apartment1LivingroomThermostat.id == managerDemoSetup.apartment1LivingroomThermostatIdapartment1LivingroomThermostat.name == "Livingroom Thermostat"@@ -480,45 +480,45 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraiprotectedMeta.first(AssetMeta.LABEL).getValueAsString() == "Current Temp"protectedMeta.first(AssetMeta.READ_ONLY).getValueAsBoolean()- ProtectedAssetInfo apartment2 = assetInfos[3]+ ProtectedAsset apartment2 = assets[3]apartment2.id == managerDemoSetup.apartment2Idapartment2.name == "Apartment 2"when: "the root assets of a foreign realm are retrieved"- assetInfos = assetResource.getRoot(null, masterRealmId)+ assets = assetResource.getRoot(null, masterRealmId)then: "result should match"- assetInfos.length == 0+ assets.length == 0when: "the root assets of the authenticated realm are retrieved"- assetInfos = assetResource.getRoot(null, null)+ assets = assetResource.getRoot(null, null)then: "result should match"- assetInfos.length == 0+ assets.length == 0when: "the root assets of the given realm are retrieved"- assetInfos = assetResource.getRoot(null, customerBRealmId)+ assets = assetResource.getRoot(null, customerBRealmId)then: "result should match"- assetInfos.length == 0+ assets.length == 0when: "the child assets of linked asset are retrieved"- assetInfos = assetResource.getChildren(null, managerDemoSetup.apartment1Id)+ assets = assetResource.getChildren(null, managerDemoSetup.apartment1Id)then: "result should match"- assetInfos.length == 0+ assets.length == 0when: "the child assets of an asset in the authenticated realm are retrieved"- assetInfos = assetResource.getChildren(null, managerDemoSetup.smartHomeId)+ assets = assetResource.getChildren(null, managerDemoSetup.smartHomeId)then: "result should match"- assetInfos.length == 0+ assets.length == 0when: "the child assets of an asset in a foreign realm are retrieved"- assetInfos = assetResource.getChildren(null, managerDemoSetup.thingId)+ assets = assetResource.getChildren(null, managerDemoSetup.thingId)then: "result should be empty"- assetInfos.length == 0+ assets.length == 0when: "an asset is retrieved by ID in the authenticated realm"def asset = assetResource.get(null, managerDemoSetup.smartHomeId)diff --git a/model/src/main/java/org/openremote/model/Attributes.java b/model/src/main/java/org/openremote/model/Attributes.javaindex 2df0eec44..485a9bea1 100644--- a/model/src/main/java/org/openremote/model/Attributes.java+++ b/model/src/main/java/org/openremote/model/Attributes.java@@ -24,7 +24,6 @@ import elemental.json.Json;import elemental.json.JsonObject;import java.util.*;-import java.util.regex.Pattern;/*** Convenience overlay API for {@link JsonObject}.diff --git a/model/src/main/java/org/openremote/model/asset/Asset.java b/model/src/main/java/org/openremote/model/asset/Asset.javaindex 2ed1bec87..0d43cecc5 100644--- a/model/src/main/java/org/openremote/model/asset/Asset.java+++ b/model/src/main/java/org/openremote/model/asset/Asset.java@@ -1,5 +1,5 @@/*- * Copyright 2016, OpenRemote Inc.+ * Copyright 2017, OpenRemote Inc.** See the CONTRIBUTORS.txt file in the distribution for a* full listing of individual contributors.@@ -20,12 +20,17 @@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 javax.persistence.*;import javax.validation.constraints.NotNull;import javax.validation.constraints.Size;-import java.util.*;+import java.util.Arrays;+import java.util.Collections;+import java.util.Date;+import java.util.List;import static org.openremote.model.Constants.PERSISTENCE_JSON_OBJECT_TYPE;import static org.openremote.model.Constants.PERSISTENCE_UNIQUE_ID_GENERATOR;@@ -38,10 +43,13 @@ import static org.openremote.model.Constants.PERSISTENCE_UNIQUE_ID_GENERATOR;* of assets can be managed through a <code>null</code> {@link #parentId} property for root* assets, and a valid parent identifier for sub-assets.* <p>+ * The properties {@link #parentName} and {@link #parentType} are transient, not required+ * for storing assets, and only resolved and usable when the asset is loaded from storage.+ * <p>* An asset is stored in and therefore access-controlled through a {@link #realmId}. The- * transient and optional properties {@link #tenantRealm} (the unique realm name of the realm+ * transient properties {@link #tenantRealm} (the unique realm name of the realm* ID) and {@link #tenantDisplayName} are only resolved and usable when the asset is loaded- * from storage.+ * from storage and not relevant for storing assets.* <p>* The {@link #createdOn} value is milliseconds since the Unix epoch.* <p>@@ -50,26 +58,30 @@ import static org.openremote.model.Constants.PERSISTENCE_UNIQUE_ID_GENERATOR;* the core platform are defined in {@link AssetType}, third-party extensions can defined* their own asset types.* <p>- * An asset may have dynamically-typed {@link #attributes} with an underlying- * {@link elemental.json.JsonObject} model. Use the {@link org.openremote.model.Attributes}- * class to work with this API.- * <p>- * The {@link #path} is a list of parent asset identifiers, starting with the root of the- * asset tree.+ * The {@link #path} is a list of parent asset identifiers, starting with the identifier of+ * this asset, followed by parent asset identifiers, and ending with the identifier of the+ * root asset in the tree. This is a transient property and only resolved and usable when+ * the asset is loaded from storage and as calculating it is costly, might be empty when+ * certain optimized loading operations are used.* <p>* The {@link #coordinates} are a pair of LNG/LAT values with the location of the asset.* <p>+ * An asset may have dynamically-typed {@link #attributes} with an underlying+ * {@link elemental.json.JsonObject} model. Use the {@link org.openremote.model.Attributes}+ * class to work with this API. This property can be empty when certain optimized loading+ * operations are used.+ * <p>* Example JSON representation of an asset tree:* <blockquote><pre>{@code{"id": "0oI7Gf_kTh6WyRJFUTr8Lg","version": 0,- "realmId": "c38a3fdf-9d74-4dac-940c-50d3dce1d248"- "tenantRealm": "customerA",- "tenantDisplayName": "Customer A","createdOn": 1489042784142,"name": "Smart Home","type": "urn:openremote:asset:building",+ "realmId": "c38a3fdf-9d74-4dac-940c-50d3dce1d248",+ "tenantRealm": "customerA",+ "tenantDisplayName": "Customer A","path": ["0oI7Gf_kTh6WyRJFUTr8Lg"],@@ -83,16 +95,18 @@ import static org.openremote.model.Constants.PERSISTENCE_UNIQUE_ID_GENERATOR;{"id": "B0x8ZOqZQHGjq_l0RxAJBA","version": 0,- "realmId": "c38a3fdf-9d74-4dac-940c-50d3dce1d248"- "tenant": "customerA",- "tenantDisplayName": "Customer A","createdOn": 1489042784148,"name": "Apartment 1","type": "urn:openremote:asset:residence","parentId": "0oI7Gf_kTh6WyRJFUTr8Lg",+ "parentName": "Smart Home",+ "parentType": "urn:openremote:asset:building",+ "realmId": "c38a3fdf-9d74-4dac-940c-50d3dce1d248",+ "tenant": "customerA",+ "tenantDisplayName": "Customer A","path": [- "0oI7Gf_kTh6WyRJFUTr8Lg",- "B0x8ZOqZQHGjq_l0RxAJBA"+ "B0x8ZOqZQHGjq_l0RxAJBA",+ "0oI7Gf_kTh6WyRJFUTr8Lg"],"coordinates": [5.469751699216005,@@ -104,17 +118,19 @@ import static org.openremote.model.Constants.PERSISTENCE_UNIQUE_ID_GENERATOR;{"id": "bzlRiJmSSMCl8HIUt9-lMg","version": 0,- "realmId": "c38a3fdf-9d74-4dac-940c-50d3dce1d248"- "tenant": "customerA",- "tenantDisplayName": "Customer A","createdOn": 1489042784157,"name": "Livingroom","type": "urn:openremote:asset:room","parentId": "B0x8ZOqZQHGjq_l0RxAJBA",+ "parentName": "Apartment 1",+ "parentType": "urn:openremote:asset:residence",+ "realmId": "c38a3fdf-9d74-4dac-940c-50d3dce1d248",+ "tenant": "customerA",+ "tenantDisplayName": "Customer A","path": [- "0oI7Gf_kTh6WyRJFUTr8Lg",+ "bzlRiJmSSMCl8HIUt9-lMg","B0x8ZOqZQHGjq_l0RxAJBA",- "bzlRiJmSSMCl8HIUt9-lMg"+ "0oI7Gf_kTh6WyRJFUTr8Lg"],"coordinates": [5.469751699216005,@@ -126,18 +142,20 @@ import static org.openremote.model.Constants.PERSISTENCE_UNIQUE_ID_GENERATOR;{"id": "W7GV_lFeQVyHLlgHgE3dEQ","version": 0,- "realmId": "c38a3fdf-9d74-4dac-940c-50d3dce1d248"- "tenant": "customerA",- "tenantDisplayName": "Customer A","createdOn": 1489042784164,"name": "Livingroom Thermostat","type": "urn:openremote:asset:thing","parentId": "bzlRiJmSSMCl8HIUt9-lMg",+ "parentName": "Livingroom",+ "parentType": "urn:openremote:asset:room",+ "realmId": "c38a3fdf-9d74-4dac-940c-50d3dce1d248",+ "tenant": "customerA",+ "tenantDisplayName": "Customer A","path": [- "0oI7Gf_kTh6WyRJFUTr8Lg",- "B0x8ZOqZQHGjq_l0RxAJBA",+ "W7GV_lFeQVyHLlgHgE3dEQ","bzlRiJmSSMCl8HIUt9-lMg",- "W7GV_lFeQVyHLlgHgE3dEQ"+ "B0x8ZOqZQHGjq_l0RxAJBA",+ "0oI7Gf_kTh6WyRJFUTr8Lg"],"coordinates": [5.460315214821094,@@ -182,7 +200,6 @@ import static org.openremote.model.Constants.PERSISTENCE_UNIQUE_ID_GENERATOR;*/// @formatter:on@MappedSuperclass-@Table(name = "ASSET")public class Asset implements IdentifiableEntity {@Id@@ -194,9 +211,6 @@ public class Asset implements IdentifiableEntity {@Column(name = "OBJ_VERSION", nullable = false)protected long version;- @Column(name = "REALM_ID", nullable = false)- protected String realmId;-@Temporal(TemporalType.TIMESTAMP)@Column(name = "CREATED_ON", updatable = false, nullable = false)@org.hibernate.annotations.CreationTimestamp@@ -212,30 +226,44 @@ public class Asset implements IdentifiableEntity {@Column(name = "ASSET_TYPE", nullable = false, updatable = false)protected String type;- @Column(name = "PARENT_ID")+ @Column(name = "PARENT_ID", length = 27)protected String parentId;- @Column(name = "ATTRIBUTES", columnDefinition = "jsonb")- @org.hibernate.annotations.Type(type = PERSISTENCE_JSON_OBJECT_TYPE)- protected JsonObject attributes;+ @Transient+ protected String parentName;@Transient- protected String tenantRealm;+ protected 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;@Transient- protected String tenantDisplayName;+ protected String tenantRealm;@Transient- protected String[] path;+ protected String tenantDisplayName;@Transientprotected double[] coordinates;+ @Column(name = "ATTRIBUTES", columnDefinition = "jsonb")+ @org.hibernate.annotations.Type(type = PERSISTENCE_JSON_OBJECT_TYPE)+ protected JsonObject attributes;+public Asset() {}- public Asset(String name, String type) {- this(null, name, type);+ public Asset(String name, AssetType type) {+ this(null, name, type.getValue());+ }++ public Asset(String realm, String name, AssetType type) {+ this(realm, name, type.getValue());}public Asset(String realmId, String name, String type) {@@ -244,18 +272,33 @@ public class Asset implements IdentifiableEntity {this.type = type;}- public Asset(String name, AssetType type) {- this(null, name, type.getValue());- }-- public Asset(String realm, String name, AssetType type) {- this(realm, name, type.getValue());+ public Asset(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) {+ this.id = id;+ this.version = version;+ this.createdOn = createdOn;+ this.name = name;+ this.type = type;+ this.parentId = parentId;+ this.parentName = parentName;+ this.parentType = parentType;+ this.path = path;+ this.realmId = realmId;+ this.tenantRealm = tenantRealm;+ this.tenantDisplayName = tenantDisplayName;+ this.attributes = attributes;}public Asset(Asset parent) {- this.realmId = parent.getRealmId();this.parentId = parent.getId();- }+ this.parentName = parent.getName();+ this.parentType = parent.getType();+ this.realmId = parent.getRealmId();+ this.tenantRealm = parent.getTenantRealm();+ this.tenantDisplayName = parent.getTenantDisplayName();+ };public String getId() {return id;@@ -273,14 +316,6 @@ public class Asset implements IdentifiableEntity {this.version = version;}- public String getRealmId() {- return realmId;- }-- public void setRealmId(String realmId) {- this.realmId = realmId;- }-public Date getCreatedOn() {return createdOn;}@@ -301,6 +336,10 @@ public class Asset implements IdentifiableEntity {return AssetType.getByValue(getType());}+ public boolean isWellKnownType(AssetType assetType) {+ return assetType.equals(getWellKnownType());+ }+public void setType(String type) {this.type = type;}@@ -317,42 +356,74 @@ public class Asset implements IdentifiableEntity {this.parentId = parentId;}- public String getTenantRealm() {- return tenantRealm;- }-- public void setTenantRealm(String tenantRealm) {- this.tenantRealm = tenantRealm;- }-- public String getTenantDisplayName() {- return tenantDisplayName;+ public String getParentName() {+ return parentName;}- public void setTenantDisplayName(String tenantDisplayName) {- this.tenantDisplayName = tenantDisplayName;+ public void setParentName(String parentName) {+ this.parentName = parentName;}- public JsonObject getAttributes() {- return attributes;+ public String getParentType() {+ return parentType;}- public void setAttributes(JsonObject attributes) {- this.attributes = attributes;+ public void setParentType(String parentType) {+ this.parentType = parentType;}/**- * The identifiers of all parents representing the path in the tree. The last element- * is the identifier of this instance.+ * 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;+ }++ public void setRealmId(String realmId) {+ this.realmId = realmId;+ }++ public String getTenantRealm() {+ return tenantRealm;+ }++ public void setTenantRealm(String tenantRealm) {+ this.tenantRealm = tenantRealm;+ }++ public String getTenantDisplayName() {+ return tenantDisplayName;+ }++ public void setTenantDisplayName(String tenantDisplayName) {+ this.tenantDisplayName = tenantDisplayName;+ }+public double[] getCoordinates() {return coordinates;}@@ -365,6 +436,14 @@ public class Asset implements IdentifiableEntity {return getCoordinates() != null && getCoordinates().length > 0;}+ public JsonObject getAttributes() {+ return attributes;+ }++ public void setAttributes(JsonObject attributes) {+ this.attributes = attributes;+ }+@Overridepublic String toString() {return getClass().getSimpleName() + "{" +@@ -373,4 +452,23 @@ public class Asset implements IdentifiableEntity {", type ='" + type + '\'' +'}';}++ public String toStringAll() {+ return "Asset{" ++ "id='" + id + '\'' ++ ", version=" + version ++ ", createdOn=" + createdOn ++ ", name='" + name + '\'' ++ ", type='" + type + '\'' ++ ", parentId='" + parentId + '\'' ++ ", parentName='" + parentName + '\'' ++ ", parentType='" + parentType + '\'' ++ ", realmId='" + realmId + '\'' ++ ", tenantRealm='" + tenantRealm + '\'' ++ ", tenantDisplayName='" + tenantDisplayName + '\'' ++ ", path=" + Arrays.toString(path) ++ ", coordinates=" + Arrays.toString(coordinates) ++ ", attributes=" + attributes ++ '}';+ }}diff --git a/model/src/main/java/org/openremote/model/asset/AssetInfo.java b/model/src/main/java/org/openremote/model/asset/AssetInfo.javadeleted file mode 100644index 7a332f945..000000000--- a/model/src/main/java/org/openremote/model/asset/AssetInfo.java+++ /dev/null@@ -1,173 +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.model.asset;--import java.util.Arrays;-import java.util.Date;--/**- * A DTO for performance-critical operations with assets, such as tree loading/rendering.- */-public class AssetInfo {-- protected String id;-- protected long version;-- protected String name;-- protected Date createdOn;-- protected String realmId;-- protected String type;-- protected String parentId;-- protected double[] coordinates;-- public AssetInfo(String id) {- this.id = id;- }-- public AssetInfo() {- }-- public AssetInfo(Asset asset) {- this(- asset.getId(),- asset.getVersion(),- asset.getName(),- asset.getCreatedOn(),- asset.getRealmId(),- asset.getType(),- asset.getParentId(),- asset.getCoordinates()- );- }-- public AssetInfo(String id,- long version,- String name,- Date createdOn,- String realmId,- String type,- String parentId,- double[] coordinates) {- this.id = id;- this.version = version;- this.name = name;- this.createdOn = createdOn;- this.realmId = realmId;- this.type = type;- this.parentId = parentId;- this.coordinates = coordinates;- }-- public AssetInfo(String name, String type) {- this.name = name;- this.type = type;- }-- public String getId() {- return id;- }-- public void setId(String id) {- this.id = id;- }-- public long getVersion() {- return version;- }-- public void setVersion(long version) {- this.version = version;- }-- public String getRealmId() {- return realmId;- }-- public void setRealmId(String realmId) {- this.realmId = realmId;- }-- public String getName() {- return name;- }-- public void setName(String name) {- this.name = name;- }-- public Date getCreatedOn() {- return createdOn;- }-- public void setCreatedOn(Date createdOn) {- this.createdOn = createdOn;- }-- public String getType() {- return type;- }-- public AssetType getWellKnownType() {- return getType() != null ? AssetType.getByValue(getType()) : null;- }-- public boolean isWellKnownType(AssetType assetType) {- return assetType.equals(getWellKnownType());- }-- public void setType(String type) {- this.type = type;- }-- public String getParentId() {- return parentId;- }-- public void setParentId(String parentId) {- this.parentId = parentId;- }-- public double[] getCoordinates() {- return coordinates;- }-- public void setCoordinates(double[] coordinates) {- this.coordinates = coordinates;- }-- @Override- public String toString() {- return getClass().getSimpleName() + "{" +- "id='" + id + '\'' +- ", realmId='" + realmId + '\'' +- ", name='" + name + '\'' +- ", createdOn='" + createdOn + '\'' +- ", type='" + type + '\'' +- ", parentId='" + parentId + '\'' +- ", coordinates='" + Arrays.toString(coordinates) + '\'' +- '}';- }-}diff --git a/model/src/main/java/org/openremote/model/asset/ProtectedAssetInfo.java b/model/src/main/java/org/openremote/model/asset/ProtectedAsset.javasimilarity index 64%rename from model/src/main/java/org/openremote/model/asset/ProtectedAssetInfo.javarename to model/src/main/java/org/openremote/model/asset/ProtectedAsset.javaindex 471d11777..d8c023c4c 100644--- a/model/src/main/java/org/openremote/model/asset/ProtectedAssetInfo.java+++ b/model/src/main/java/org/openremote/model/asset/ProtectedAsset.java@@ -30,16 +30,14 @@ import java.util.Date;import static org.openremote.model.Constants.NAMESPACE;/**- * Contains protected asset properties such as realm, name, creation timestamp, type,- * parent identifier, and location of an {@link Asset}, as well as all protected- * attributes, and their protected metadata (see {@link AssetMeta#PROTECTED},- * {@link AssetMeta.Access}).+ * 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 ProtectedAssetInfo extends AssetInfo {+public class ProtectedAsset extends Asset {static JsonObject filterProtectedAttributes(JsonObject unfilteredAttributes) {Attributes filteredAttributes = new Attributes();@@ -51,7 +49,7 @@ public class ProtectedAssetInfo extends AssetInfo {continue;}- Attribute protectedAttribute = new Attribute(attribute.getName(), attribute.getJsonObject());+ Attribute protectedAttribute = attribute.copy();filteredAttributes.put(protectedAttribute);if (!protectedAttribute.hasMeta())@@ -77,43 +75,39 @@ public class ProtectedAssetInfo extends AssetInfo {return filteredAttributes.getJsonObject();}- protected JsonObject attributes;+ public ProtectedAsset() {+ }- public ProtectedAssetInfo() {+ public ProtectedAsset(String name, AssetType type) {+ super(name, type);}- public ProtectedAssetInfo(Asset asset) {- this(- asset.getId(),- asset.getVersion(),- asset.getName(),- asset.getCreatedOn(),- asset.getRealmId(),- asset.getType(),- asset.parentId,- asset.getCoordinates(),- asset.getAttributes()- );+ public ProtectedAsset(String realm, String name, AssetType type) {+ super(realm, name, type);}- public ProtectedAssetInfo(String id,- long version,- String name,- Date createdOn,- String realmId,- String type,- String parentId,- double[] coordinates,- JsonObject attributes) {- super(id, version, name, createdOn, realmId, type, parentId, coordinates);- this.attributes = filterProtectedAttributes(attributes);+ 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 JsonObject getAttributes() {- return attributes;+ public ProtectedAsset(Asset parent) {+ super(parent);}+ @Overridepublic void setAttributes(JsonObject attributes) {- this.attributes = attributes;+ super.setAttributes(filterProtectedAttributes(attributes));}}diff --git a/model/src/main/java/org/openremote/model/asset/UserAsset.java b/model/src/main/java/org/openremote/model/asset/UserAsset.javaindex fb3fa11c8..c290190cf 100644--- a/model/src/main/java/org/openremote/model/asset/UserAsset.java+++ b/model/src/main/java/org/openremote/model/asset/UserAsset.java@@ -37,7 +37,7 @@ import java.io.Serializable;* </li>* </ul>* Asset attribute data can be protected with {@link AssetMeta#PROTECTED} and {@link AssetMeta.Access},- * it is filtered in {@link ProtectedAssetInfo}.+ * it is filtered in {@link ProtectedAsset}.*/@Entity@Table(name = "USER_ASSET")