Skip to content

armgit / core

Public Imported from GitHub
0

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

Support for linking users with "home" assets

Christian Bauer6d85d589a941
diff --git a/agent/src/main/java/org/openremote/agent/deploy/CommandDefinition.java b/agent/src/main/java/org/openremote/agent/deploy/CommandDefinition.java
index f6324c850..ed9aa0d8a 100644
--- a/agent/src/main/java/org/openremote/agent/deploy/CommandDefinition.java
+++ b/agent/src/main/java/org/openremote/agent/deploy/CommandDefinition.java
@@ -1,8 +1,12 @@
package org.openremote.agent.deploy;
+import org.openremote.model.Constants;
+
import java.util.Locale;
import java.util.Map;
+import static org.openremote.model.Constants.NAMESPACE;
+
/**
* Command deployment model
*/
@@ -10,8 +14,8 @@ public class CommandDefinition {
public final static String NAME_PROPERTY = "name";
public final static String NAME_PROPERTY_DEFAULT_VALUE = "<No Name>";
- public final static String DEVICE_NAME_PROPERTY = "urn:openremote:device-command:device-name";
- public final static String DEVICE_ID_PROPERTY = "urn:openremote:device-command:device-id";
+ public final static String DEVICE_NAME_PROPERTY = NAMESPACE + ":device-command:device-name";
+ public final static String DEVICE_ID_PROPERTY = NAMESPACE + ":device-command:device-id";
final protected String protocolType;
final protected int commandID;
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/simulator/SimulatorProtocol.java b/agent/src/main/java/org/openremote/agent3/protocol/simulator/SimulatorProtocol.java
index bfcf3a087..2bb64864f 100644
--- a/agent/src/main/java/org/openremote/agent3/protocol/simulator/SimulatorProtocol.java
+++ b/agent/src/main/java/org/openremote/agent3/protocol/simulator/SimulatorProtocol.java
@@ -124,8 +124,8 @@ public class SimulatorProtocol extends AbstractProtocol {
case "decimal":
return new DecimalSimulatorElement();
case "range":
- MetadataItem minItem = attribute.firstMetaItem(RANGE_MIN.getName());
- MetadataItem maxItem = attribute.firstMetaItem(RANGE_MAX.getName());
+ MetadataItem minItem = attribute.firstMetaItem(RANGE_MIN);
+ MetadataItem maxItem = attribute.firstMetaItem(RANGE_MAX);
double min = minItem != null ? minItem.getValueAsInteger() : 0;
double max = maxItem != null ? maxItem.getValueAsInteger() : 100;
return new IntegerSimulatorElement(min, max);
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/ColorSimulatorElement.java b/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/ColorSimulatorElement.java
index 321d8af11..a17f43a24 100644
--- a/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/ColorSimulatorElement.java
+++ b/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/ColorSimulatorElement.java
@@ -24,6 +24,6 @@ import org.openremote.model.AttributeType;
public class ColorSimulatorElement extends SimulatorElement {
public ColorSimulatorElement() {
- super(AttributeType.STRING);
+ super(AttributeType.OBJECT);
}
}
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/SimulatorElement.java b/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/SimulatorElement.java
index 4eadc2f0e..b30d7a4b1 100644
--- a/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/SimulatorElement.java
+++ b/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/SimulatorElement.java
@@ -45,7 +45,7 @@ public abstract class SimulatorElement<T> {
if (isValid(state)) {
this.state = state;
} else {
- throw new IllegalArgumentException("Invalid state, expected '" + expectedType + "': " + state);
+ throw new IllegalArgumentException("Invalid state, expected JSON type '" + expectedType + "': " + state.getType());
}
}
diff --git a/container/src/main/java/org/openremote/container/web/WebResource.java b/container/src/main/java/org/openremote/container/web/WebResource.java
index 00fae2cf8..67c6353c8 100644
--- a/container/src/main/java/org/openremote/container/web/WebResource.java
+++ b/container/src/main/java/org/openremote/container/web/WebResource.java
@@ -24,7 +24,7 @@ import org.keycloak.KeycloakSecurityContext;
import org.keycloak.representations.AccessToken;
import org.openremote.container.Container;
import org.openremote.model.Constants;
-import org.openremote.model.asset.HomeAssets;
+import org.openremote.model.asset.ProtectedUserAssets;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.*;
@@ -120,10 +120,9 @@ public class WebResource {
}
/**
- * @return The identifiers of "home" assets linked to the authenticated user or an empty array if the user
- * has no linked assets.
+ * @return <code>true</code> if the authenticated user is a restricted user (access token claim check).
*/
- public String[] getHomeAssetIds() {
- return HomeAssets.getAssetIds(getAccessToken().getOtherClaims());
+ public boolean isRestrictedUser() {
+ return ProtectedUserAssets.isRestrictedUser(getAccessToken().getOtherClaims());
}
}
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.java
index 93559c124..be37f9205 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
@@ -37,10 +37,7 @@ import org.openremote.model.asset.AssetInfo;
import org.openremote.model.asset.AssetType;
import javax.inject.Inject;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
+import java.util.*;
import java.util.logging.Logger;
import static org.openremote.manager.client.http.RequestExceptionHandler.handleRequestException;
@@ -202,6 +199,7 @@ public class AssetBrowserPresenter implements AssetBrowser.Presenter {
tenant.getId(),
0,
tenant.getDisplayName(),
+ new Date(),
tenant.getRealm(),
AssetType.TENANT.getValue(),
null,
@@ -231,7 +229,7 @@ public class AssetBrowserPresenter implements AssetBrowser.Presenter {
assetResource.getRoot(requestParams, realm);
} else if (parent.getId() == null) {
LOG.fine("Loading the home assets of authenticated tenant");
- assetResource.getHomeAssets(requestParams);
+ assetResource.getCurrentUserAssets(requestParams);
} else {
assetResource.getChildren(requestParams, parent.getId());
}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/flows/FlowsActivity.java b/manager/client/src/main/java/org/openremote/manager/client/flows/FlowsActivity.java
index 94f35786c..d353ec2d6 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/flows/FlowsActivity.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/flows/FlowsActivity.java
@@ -28,6 +28,7 @@ import org.openremote.manager.client.event.bus.EventBus;
import org.openremote.manager.client.event.bus.EventRegistration;
import org.openremote.manager.client.mvp.AppActivity;
import org.openremote.manager.shared.agent.Agent;
+import org.openremote.model.Constants;
import org.openremote.model.asset.AssetInfo;
import org.openremote.manager.shared.asset.AssetResource;
import org.openremote.manager.shared.event.ui.ShowInfoEvent;
@@ -112,7 +113,7 @@ public class FlowsActivity
agentAsset -> {
Attributes attributes = new Attributes(agentAsset.getAttributes());
Agent agent = new Agent(attributes);
- if ("urn:openremote:connector:controller2".equals(agent.getConnectorType())) {
+ if ((Constants.NAMESPACE + ":connector:controller2").equals(agent.getConnectorType())) {
StringBuilder sb = new StringBuilder();
sb.append("http://");
sb.append(attributes.get("host").getValueAsString());
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.java
index 777cb15cf..be245535b 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
@@ -65,7 +65,7 @@ public class AgentService extends RouteBuilder implements ContainerService {
@Override
public void start(Container container) throws Exception {
- Asset[] agents = assetService.findByTypeInAllRealms(AGENT.getValue());
+ Asset[] agents = assetService.findByType(AGENT.getValue());
LOG.fine("Deploy all agents in all realms: " + agents.length);
for (Asset agent : agents) {
deployAgent(agent, PersistenceEvent.Cause.UPDATE);
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.java
index 007a4dc44..b25f3cfe9 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
@@ -19,21 +19,23 @@
*/
package org.openremote.manager.server.asset;
+import elemental.json.JsonValue;
import org.openremote.container.web.WebResource;
import org.openremote.manager.server.security.ManagerIdentityService;
import org.openremote.manager.shared.asset.AssetResource;
import org.openremote.manager.shared.http.RequestParams;
import org.openremote.model.asset.Asset;
import org.openremote.model.asset.AssetInfo;
+import org.openremote.model.asset.ProtectedAssetInfo;
import javax.ws.rs.BeanParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
+import java.nio.file.attribute.UserPrincipal;
import java.util.logging.Level;
import java.util.logging.Logger;
-import static javax.ws.rs.core.Response.Status.BAD_REQUEST;
-import static javax.ws.rs.core.Response.Status.NOT_FOUND;
+import static javax.ws.rs.core.Response.Status.*;
public class AssetResourceImpl extends WebResource implements AssetResource {
@@ -48,45 +50,48 @@ public class AssetResourceImpl extends WebResource implements AssetResource {
}
@Override
- public AssetInfo[] getHomeAssets(@BeanParam RequestParams requestParams) {
+ public ProtectedAssetInfo[] getCurrentUserAssets(@BeanParam RequestParams requestParams) {
try {
- String realm = getAuthenticatedRealm();
- String[] homeAssetIds = getHomeAssetIds();
- if (homeAssetIds.length == 0) {
- return assetService.getRoot(realm, null);
- } else {
- return assetService.findById(realm, getHomeAssetIds());
+ if (isSuperUser() || !isRestrictedUser()) {
+ return new ProtectedAssetInfo[0];
}
+ return assetService.findProtectedOfUser(getAuthenticatedRealm(), getUsername());
} catch (IllegalStateException ex) {
LOG.log(Level.FINE, "Bad request, aborting: " + uriInfo.getAbsolutePath(), ex);
throw new WebApplicationException(Response.Status.BAD_REQUEST);
}
}
+ @Override
+ public void updateCurrentUserAsset(@BeanParam RequestParams requestParams, String assetId, ProtectedAssetInfo assetInfo) {
+ throw new UnsupportedOperationException("Not Implemented"); // TODO
+ }
+
@Override
public AssetInfo[] getRoot(@BeanParam RequestParams requestParams, String realm) {
try {
if (realm == null || realm.length() == 0) {
realm = getAuthenticatedRealm();
- } else if (!isRealmAccessibleByUser(realm)) {
- LOG.fine("Forbidden access for user '" + getUsername() + "', can't retrieve root assets of realm: " + realm);
- throw new WebApplicationException(Response.Status.FORBIDDEN);
}
- return assetService.getRoot(realm, getHomeAssetIds());
+ if (!isRealmAccessibleByUser(realm) || isRestrictedUser()) {
+ return new AssetInfo[0];
+ }
+ return assetService.findRoot(realm);
} catch (IllegalStateException ex) {
LOG.log(Level.FINE, "Bad request, aborting: " + uriInfo.getAbsolutePath(), ex);
throw new WebApplicationException(Response.Status.BAD_REQUEST);
}
}
- // TODO: All the following operations are untested for "home" asset restrictions!
-
@Override
public AssetInfo[] getChildren(@BeanParam RequestParams requestParams, String parentId) {
try {
+ if (isRestrictedUser()) {
+ return new AssetInfo[0];
+ }
return isSuperUser()
- ? assetService.getChildren(parentId, getHomeAssetIds())
- : assetService.getChildrenInRealm(parentId, getAuthenticatedRealm(), getHomeAssetIds());
+ ? assetService.findChildren(parentId)
+ : assetService.findChildrenInRealm(parentId, getAuthenticatedRealm());
} catch (IllegalStateException ex) {
LOG.log(Level.FINE, "Bad request, aborting: " + uriInfo.getAbsolutePath(), ex);
throw new WebApplicationException(Response.Status.BAD_REQUEST);
@@ -96,7 +101,10 @@ public class AssetResourceImpl extends WebResource implements AssetResource {
@Override
public Asset get(@BeanParam RequestParams requestParams, String assetId) {
try {
- Asset asset = assetService.get(assetId);
+ if (isRestrictedUser()) {
+ throw new WebApplicationException(Response.Status.FORBIDDEN);
+ }
+ Asset asset = assetService.find(assetId);
if (asset == null)
throw new WebApplicationException(NOT_FOUND);
if (!isRealmAccessibleByUser(asset.getRealm())) {
@@ -116,7 +124,10 @@ public class AssetResourceImpl extends WebResource implements AssetResource {
@Override
public void update(@BeanParam RequestParams requestParams, String assetId, Asset asset) {
try {
- ServerAsset serverAsset = assetService.get(assetId);
+ if (isRestrictedUser()) {
+ throw new WebApplicationException(Response.Status.FORBIDDEN);
+ }
+ ServerAsset serverAsset = assetService.find(assetId);
if (serverAsset == null)
throw new WebApplicationException(NOT_FOUND);
@@ -152,14 +163,17 @@ public class AssetResourceImpl extends WebResource implements AssetResource {
}
}
+ @Override
+ public void updateAttribute(@BeanParam RequestParams requestParams, String assetId, String attributeName, JsonValue value) {
+ throw new UnsupportedOperationException("Not Implemented"); // TODO
+ }
+
@Override
public void create(@BeanParam RequestParams requestParams, Asset asset) {
try {
-
- // TODO we should check if the realm actually exists, but we can't do
- // that without giving the manager permanent admin access on Keycloak
- // checkRealmExists(updatedAsset.getRealm());
-
+ if (isRestrictedUser()) {
+ throw new WebApplicationException(Response.Status.FORBIDDEN);
+ }
if (!isRealmAccessibleByUser(asset.getRealm())) {
LOG.fine("Forbidden access for user '" + getUsername() + "', can't create asset in realm: " + asset.getRealm());
throw new WebApplicationException(Response.Status.FORBIDDEN);
@@ -188,7 +202,10 @@ public class AssetResourceImpl extends WebResource implements AssetResource {
@Override
public void delete(@BeanParam RequestParams requestParams, String assetId) {
try {
- ServerAsset serverAsset = assetService.get(assetId);
+ if (isRestrictedUser()) {
+ throw new WebApplicationException(Response.Status.FORBIDDEN);
+ }
+ ServerAsset serverAsset = assetService.find(assetId);
if (serverAsset == null)
return;
if (!isRealmAccessibleByUser(serverAsset.getRealm())) {
@@ -198,7 +215,9 @@ public class AssetResourceImpl extends WebResource implements AssetResource {
);
throw new WebApplicationException(Response.Status.FORBIDDEN);
}
- assetService.delete(assetId);
+ if (!assetService.delete(assetId)) {
+ throw new WebApplicationException(BAD_REQUEST);
+ }
} catch (IllegalStateException ex) {
LOG.log(Level.FINE, "Bad request, aborting: " + uriInfo.getAbsolutePath(), ex);
throw new WebApplicationException(Response.Status.BAD_REQUEST);
diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetService.java
index 2ded6792c..f1768cd21 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetService.java
@@ -22,31 +22,31 @@ package org.openremote.manager.server.asset;
import elemental.json.JsonValue;
import org.apache.camel.builder.RouteBuilder;
import org.hibernate.Session;
-import org.openremote.container.message.MessageBrokerSetupService;
-import org.openremote.manager.server.agent.AgentAttributes;
-import org.openremote.manager.server.agent.ThingAttributes;
-import org.openremote.manager.server.security.ManagerIdentityService;
-import org.openremote.model.Function;
import org.openremote.container.Container;
import org.openremote.container.ContainerService;
-import org.openremote.container.message.MessageBrokerService;
+import org.openremote.container.message.MessageBrokerSetupService;
import org.openremote.container.persistence.PersistenceEvent;
import org.openremote.container.persistence.PersistenceService;
import org.openremote.container.web.WebService;
+import org.openremote.manager.server.agent.AgentAttributes;
+import org.openremote.manager.server.agent.ThingAttributes;
import org.openremote.manager.server.event.EventService;
+import org.openremote.manager.server.security.ManagerIdentityService;
import org.openremote.manager.shared.asset.SubscribeAssetModified;
import org.openremote.manager.shared.asset.UnsubscribeAssetModified;
import org.openremote.model.AttributeRef;
import org.openremote.model.AttributeValueChange;
+import org.openremote.model.Function;
import org.openremote.model.asset.*;
import org.postgresql.util.PGobject;
import javax.persistence.EntityManager;
+import javax.persistence.NoResultException;
+import javax.persistence.Query;
import java.sql.Array;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Arrays;
-import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;
@@ -66,7 +66,7 @@ public class AssetService extends RouteBuilder implements ContainerService {
final 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 = get(agentLink.getEntityId());
+ Asset agent = find(agentLink.getEntityId());
if (agent != null && agent.getWellKnownType().equals(AGENT)) {
AgentAttributes agentAttributes = new AgentAttributes(agent);
return agentAttributes.getProtocolConfiguration(agentLink.getAttributeName());
@@ -79,10 +79,11 @@ public class AssetService extends RouteBuilder implements ContainerService {
eventService = container.getService(EventService.class);
persistenceService = container.getService(PersistenceService.class);
+ // TODO None of this is secure or considers the realm of an asset or the logged-in user's realm
assetListenerSubscriptions = new AssetListenerSubscriptions(eventService) {
@Override
protected Asset getAsset(String assetId) {
- return AssetService.this.get(assetId);
+ return AssetService.this.find(assetId);
}
};
@@ -137,66 +138,138 @@ public class AssetService extends RouteBuilder implements ContainerService {
return agentLinkResolver;
}
- public AssetInfo[] getRoot(String realm, String[] restrictedAssetIds) {
+ /**
+ * Find assets without a parent in a realm.
+ *
+ * @param realm The realm to search.
+ * @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 realm) {
if (realm == null || realm.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.realm, a.type, a.parent.id, a.location" +
+ "a.id, a.version, a.name, a.createdOn, a.realm, a.type, a.parent.id, a.location" +
") from Asset a where a.parent is null and a.realm = :realm order by a.createdOn asc",
AssetInfo.class
).setParameter("realm", realm).getResultList();
- filterRestrictedAssetInfos(result, restrictedAssetIds);
return result.toArray(new AssetInfo[result.size()]);
});
}
- public AssetInfo[] findById(String realm, String[] assetIds) {
- if (realm == null || realm.length() == 0)
- throw new IllegalArgumentException("Realm must be provided to query assets");
+ /**
+ * Retrieve the children of an asset.
+ *
+ * @param parentId The ID of the parent asset.
+ * @return The child assets ordered ascending by creation date, or an empty array if there is no data.
+ */
+ public AssetInfo[] findChildren(String parentId) {
return persistenceService.doReturningTransaction(em -> {
- List<AssetInfo> result = em.createQuery(
- "select new org.openremote.manager.server.asset.ServerAssetInfo(" +
- "a.id, a.version, a.name, a.realm, a.type, a.parent.id, a.location" +
- ") from Asset a where a.id in :assetIds and a.realm = :realm order by a.createdOn asc",
- AssetInfo.class
- ).setParameter("realm", realm)
- .setParameter("assetIds", Arrays.asList(assetIds))
- .getResultList();
+ Asset parent = loadAsset(em, parentId);
+ 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.realm, 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()]);
});
}
- public ServerAsset[] findByType(String realm, AssetType assetType) {
- if (realm == null || realm.length() == 0)
- throw new IllegalArgumentException("Realm must be provided to query assets");
+ /**
+ * Retrieve the children of an asset in a particular realm.
+ *
+ * @param parentId The ID of the parent asset.
+ * @param realm The realm in which both parent asset and its children must be.
+ * @return The child assets ordered ascending by creation date, or an empty array if there is no data.
+ */
+ public AssetInfo[] findChildrenInRealm(String parentId, String realm) {
return persistenceService.doReturningTransaction(em -> {
- List<ServerAsset> result =
+ Asset parent = loadAsset(em, parentId);
+ if (parent == null)
+ return new AssetInfo[0];
+ List<AssetInfo> result =
em.createQuery(
- "select a from Asset a where a.realm = :realm and a.type = :assetType order by a.createdOn asc",
- ServerAsset.class)
+ "select new org.openremote.manager.server.asset.ServerAssetInfo(" +
+ "a.id, a.version, a.name, a.createdOn, a.realm, a.type, a.parent.id, a.location" +
+ ") from Asset a, Asset p where p.id = :parentId and a.parent.id = :parentId " +
+ "and p.realm = :realm and a.realm = :realm " +
+ "order by a.createdOn asc",
+ AssetInfo.class
+ ).setParameter("parentId", parentId)
.setParameter("realm", realm)
- .setParameter("assetType", assetType.getValue())
.getResultList();
- return result.toArray(new ServerAsset[result.size()]);
+ return result.toArray(new AssetInfo[result.size()]);
});
}
- public ServerAsset[] findChildrenByType(String parentId, AssetType assetType) {
+ /**
+ * Find an asset by primary key.
+ *
+ * @param assetId The primary key identifier value of the asset.
+ * @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));
+ }
+
+ /**
+ * Find protected assets by primary keys.
+ *
+ * @param realm The realm in which the assets must be.
+ * @param assetIds The primary key identifier values of the assets to find.
+ * @return The found assets or an empty array
+ */
+ public ProtectedAssetInfo[] findProtectedById(String realm, String[] assetIds) {
+ if (realm == null || realm.length() == 0)
+ throw new IllegalArgumentException("Realm must be provided to query assets");
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()]);
+ // TODO The SQL IN clause is not limited on Postgres, we should have some sanity check here on the number of IDs!
+ List<ProtectedAssetInfo> result = em.createQuery(
+ "select new org.openremote.manager.server.asset.ProtectedServerAssetInfo(" +
+ "a.id, a.version, a.name, a.createdOn, a.realm, a.type, a.parent.id, a.location, a.attributes" +
+ ") from Asset a where a.id in :assetIds and a.realm = :realm order by a.createdOn asc",
+ ProtectedAssetInfo.class
+ ).setParameter("realm", realm)
+ .setParameter("assetIds", Arrays.asList(assetIds))
+ .getResultList();
+ return result.toArray(new ProtectedAssetInfo[result.size()]);
+ });
+ }
+
+ /**
+ * Find protected assets linked to a user.
+ *
+ * @param realm The realm in which the assets must be.
+ * @param username The username of the user.
+ * @return The found assets or an empty array
+ */
+ public ProtectedAssetInfo[] findProtectedOfUser(String realm, String username) {
+ return persistenceService.doReturningTransaction(em -> {
+ Query userAttributesQuery = em.createNativeQuery(
+ "SELECT ua.NAME, ua.VALUE " +
+ "FROM USER_ATTRIBUTE ua JOIN USER_ENTITY u ON u.ID = ua.USER_ID " +
+ "WHERE u.USERNAME = :username"
+ );
+ @SuppressWarnings("unchecked")
+ String[] assetIds = ProtectedUserAssets.getAssetIdsFromUserAttributes(
+ userAttributesQuery.setParameter("username", username).getResultList()
+ );
+ return findProtectedById(realm, assetIds);
});
}
- public ServerAsset[] findByTypeInAllRealms(String assetType) {
+ /**
+ * 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(
@@ -208,84 +281,93 @@ public class AssetService extends RouteBuilder implements ContainerService {
});
}
- public AssetInfo[] getChildren(String parentId, String[] restrictedAssetIds) {
+ /**
+ * Find assets by type in a given realm.
+ *
+ * @param realm The realm in which the assets must be.
+ * @param assetType The type of the assets to find.
+ * @return The found assets or an empty array
+ */
+ public ServerAsset[] findByType(String realm, String assetType) {
+ if (realm == null || realm.length() == 0)
+ throw new IllegalArgumentException("Realm must be provided to query assets");
return persistenceService.doReturningTransaction(em -> {
- List<AssetInfo> result =
+ List<ServerAsset> result =
em.createQuery(
- "select new org.openremote.manager.server.asset.ServerAssetInfo(" +
- "a.id, a.version, a.name, a.realm, 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)
+ "select a from Asset a where a.realm = :realm and a.type = :assetType order by a.createdOn asc",
+ ServerAsset.class)
+ .setParameter("realm", realm)
+ .setParameter("assetType", assetType)
.getResultList();
- filterRestrictedAssetInfos(result, restrictedAssetIds);
- return result.toArray(new AssetInfo[result.size()]);
+ return result.toArray(new ServerAsset[result.size()]);
});
}
- public AssetInfo[] getChildrenInRealm(String parentId, String realm, String[] restrictedAssetIds) {
+ /**
+ * 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<AssetInfo> result =
+ List<ServerAsset> result =
em.createQuery(
- "select new org.openremote.manager.server.asset.ServerAssetInfo(" +
- "a.id, a.version, a.name, a.realm, a.type, a.parent.id, a.location" +
- ") from Asset a, Asset p where p.id = :parentId and a.parent.id = :parentId " +
- "and p.realm = :realm and a.realm = :realm " +
- "order by a.createdOn asc",
- AssetInfo.class
- ).setParameter("parentId", parentId)
- .setParameter("realm", realm)
+ "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();
- filterRestrictedAssetInfos(result, restrictedAssetIds);
- return result.toArray(new AssetInfo[result.size()]);
+ return result.toArray(new ServerAsset[result.size()]);
});
}
- public ServerAsset get(String assetId) {
- return persistenceService.doReturningTransaction(em -> loadAsset(em, assetId));
- }
-
+ /**
+ * @return The current stored asset state.
+ * @throws IllegalArgumentException if the realm or parent is invalid.
+ */
public ServerAsset merge(ServerAsset asset) {
return persistenceService.doReturningTransaction(em -> {
- validateParent(em, asset);
+ // Validate realm
+ if (!isRealmActive(asset.getRealm())) {
+ throw new IllegalStateException("Realm not found: " + asset.getRealm());
+ }
+ // Validate parent
+ if (asset.getParentId() != null) {
+ // If this is a not a root asset...
+ ServerAsset parent = loadAsset(em, asset.getParentId());
+ // .. the parent must exist
+ if (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()))
+ throw new IllegalStateException("Invalid parent");
+ }
return em.merge(asset);
});
}
- public void delete(String assetId) {
- persistenceService.doTransaction(em -> {
+ /**
+ * @return <code>true</code> if the asset was deleted, false if the asset still has children and can't be deleted.
+ */
+ public boolean delete(String assetId) {
+ return persistenceService.doReturningTransaction(em -> {
Asset asset = em.find(ServerAsset.class, assetId);
if (asset != null) {
+ if (findChildren(asset.getId()).length > 0)
+ return false;
em.remove(asset);
}
+ return true;
});
}
- /* TODO: What is the asset lifecycle and how do we handle tree integrity?
- public void deleteChildren(String parentId) {
- persistenceService.doTransaction(em -> {
- List<AssetInfo> result =
- em.createQuery(
- "select new org.openremote.manager.server.asset.ServerAssetInfo(" +
- "a.id, a.version, a.name, a.realm, 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();
- for (AssetInfo assetInfo : result) {
- Asset asset = em.find(ServerAsset.class, assetInfo.getId());
- if (asset != null) {
- em.remove(asset);
- }
- }
- });
- }
- */
-
public boolean updateThingAttributeValue(AttributeValueChange attributeValueChange) {
// TODO: More fine-grained return to distinguish failures ("wrong value type" is not the same as "not found")
AttributeRef attributeRef = attributeValueChange.getAttributeRef();
- ServerAsset thing = get(attributeRef.getEntityId());
+ ServerAsset thing = find(attributeRef.getEntityId());
if (thing == null) {
LOG.fine("Ignoring attribute update for unknown asset: " + attributeValueChange);
return false;
@@ -341,14 +423,15 @@ public class AssetService extends RouteBuilder implements ContainerService {
return asset;
}
- protected void validateParent(EntityManager em, Asset asset) {
- if (asset.getParentId() == null)
- return;
- ServerAsset parent = loadAsset(em, asset.getParentId());
- if (parent == null)
- throw new IllegalStateException("Parent asset not found: " + asset.getParentId());
- if (Arrays.asList(parent.getPath()).contains(asset.getId()))
- throw new IllegalStateException("Parent asset can not be a child of the asset: " + asset.getParentId());
+ protected boolean isRealmActive(String realm) {
+ return persistenceService.doReturningTransaction(entityManager -> {
+ // TODO Should also check NOT_BEFORE?
+ @SuppressWarnings("unchecked")
+ List<Object[]> result = entityManager.createNativeQuery(
+ "SELECT ID FROM REALM WHERE ENABLED = TRUE AND NAME = :realm"
+ ).setParameter("realm", realm).getResultList();
+ return result.size() > 0;
+ });
}
protected boolean updateAttributeValue(String assetId, String attributeName, JsonValue value) {
@@ -383,35 +466,6 @@ public class AssetService extends RouteBuilder implements ContainerService {
);
}
- protected void filterRestrictedAssetInfos(List<AssetInfo> assetInfos, String[] restrictedAssetIds) {
- if (restrictedAssetIds == null || restrictedAssetIds.length == 0)
- return;
- persistenceService.doTransaction(entityManager -> {
- Iterator<AssetInfo> it = assetInfos.iterator();
- while (it.hasNext()) {
- AssetInfo assetInfo = it.next();
- ServerAsset serverAsset = loadAsset(entityManager, assetInfo.getId());
- if (!isValidAssetPath(serverAsset, restrictedAssetIds))
- it.remove();
- }
- });
- }
-
- /**
- * @return <code>true</code> if any of the assets in the path of the asset have an ID that matches the restricted IDs.
- */
- protected boolean isValidAssetPath(Asset asset, String[] restrictedAssetIds) {
- if (asset == null)
- return false;
- for (String pathElement : asset.getPath()) {
- for (String restrictedAssetId : restrictedAssetIds) {
- if (restrictedAssetId.equals(pathElement))
- return true;
- }
- }
- return false;
- }
-
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
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.java
new file mode 100644
index 000000000..269a958fc
--- /dev/null
+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/ProtectedServerAssetInfo.java
@@ -0,0 +1,44 @@
+/*
+ * 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 realm, String type, String parentId, Geometry location, JsonObject attributes) {
+ super(
+ id, version, name, createdOn, realm, 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/ServerAssetInfo.java b/manager/server/src/main/java/org/openremote/manager/server/asset/ServerAssetInfo.java
index 1c6f2a388..5c38644cb 100644
--- 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.java
@@ -23,11 +23,16 @@ 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, String realm, String type, String parentId, Geometry location) {
+ public ServerAssetInfo(String id, long version, String name, Date createdOn, String realm, String type, String parentId, Geometry location) {
super(
- id, version, name, realm, type, parentId,
+ id, version, name, createdOn, realm, type, parentId,
location != null ? new double[]{
location.getCoordinate().getOrdinate(Coordinate.X),
location.getCoordinate().getOrdinate(Coordinate.Y)
diff --git a/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityService.java b/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityService.java
index 7c69657e4..f28c14fdf 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityService.java
@@ -31,7 +31,7 @@ import org.openremote.container.web.WebService;
import org.openremote.manager.shared.security.ClientRole;
import org.openremote.manager.shared.security.Tenant;
import org.openremote.model.Constants;
-import org.openremote.model.asset.HomeAssets;
+import org.openremote.model.asset.ProtectedUserAssets;
import javax.ws.rs.core.UriBuilder;
import java.util.*;
@@ -182,9 +182,9 @@ public class ManagerIdentityService extends IdentityService {
ProtocolMapperRepresentation userAssetMapper = new ProtocolMapperRepresentation();
userAssetMapper.setProtocol("openid-connect");
userAssetMapper.setProtocolMapper("oidc-usermodel-attribute-mapper");
- userAssetMapper.setName(HomeAssets.HOME_ASSETS_ATTRIBUTE);
+ userAssetMapper.setName(ProtectedUserAssets.ASSETS_ATTRIBUTE);
userAssetMapper.setConsentRequired(false);
- userAssetMapper.setConfig(HomeAssets.HOME_ASSET_MAPPER_CONFIG);
+ userAssetMapper.setConfig(ProtectedUserAssets.RESTRICTED_MAPPER);
protocolMappers.createMapper(userAssetMapper);
}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/BuiltinSetupTasks.java b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/BuiltinSetupTasks.java
index 2cf003ff3..bd091b7ba 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/BuiltinSetupTasks.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/BuiltinSetupTasks.java
@@ -55,30 +55,32 @@ public class BuiltinSetupTasks extends AbstractSetupTasks {
if (container.isDevMode()) {
+ addTask(new KeycloakCleanSetup(container));
+ addTask(new KeycloakInitSetup(container));
+
addTask(new ManagerCleanSetup(container));
addTask(new ManagerInitSetup(container));
- addTask(new ManagerDemoSetup(container));
- addTask(new KeycloakCleanSetup(container));
- addTask(new KeycloakInitSetup(container));
addTask(new KeycloakDemoSetup(container));
+ addTask(new ManagerDemoSetup(container));
+ addTask(new FinalizeKeycloakDemoSetup(container));
} else {
+ if (getBoolean(container.getConfig(), SETUP_CLEAN_INIT_KEYCLOAK, SETUP_CLEAN_INIT_KEYCLOAK_DEFAULT)) {
+ addTask(new KeycloakCleanSetup(container));
+ addTask(new KeycloakInitSetup(container));
+ }
+
if (getBoolean(container.getConfig(), SETUP_CLEAN_INIT_MANAGER, SETUP_CLEAN_INIT_MANAGER_DEFAULT)) {
addTask(new ManagerCleanSetup(container));
addTask(new ManagerInitSetup(container));
}
- if (getBoolean(container.getConfig(), SETUP_IMPORT_DEMO_DATA, SETUP_IMPORT_DEMO_DATA_DEFAULT)) {
- addTask(new ManagerDemoSetup(container));
- }
- if (getBoolean(container.getConfig(), SETUP_CLEAN_INIT_KEYCLOAK, SETUP_CLEAN_INIT_KEYCLOAK_DEFAULT)) {
- addTask(new KeycloakCleanSetup(container));
- addTask(new KeycloakInitSetup(container));
- }
if (getBoolean(container.getConfig(), SETUP_IMPORT_DEMO_DATA, SETUP_IMPORT_DEMO_DATA_DEFAULT)) {
addTask(new KeycloakDemoSetup(container));
+ addTask(new ManagerDemoSetup(container));
+ addTask(new FinalizeKeycloakDemoSetup(container));
}
}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/FinalizeKeycloakDemoSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/FinalizeKeycloakDemoSetup.java
new file mode 100644
index 000000000..e9a320fa6
--- /dev/null
+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/FinalizeKeycloakDemoSetup.java
@@ -0,0 +1,54 @@
+/*
+ * 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.setup.builtin;
+
+import org.keycloak.admin.client.resource.UserResource;
+import org.keycloak.admin.client.resource.UsersResource;
+import org.keycloak.representations.idm.UserRepresentation;
+import org.openremote.container.Container;
+import org.openremote.manager.server.setup.AbstractKeycloakSetup;
+import org.openremote.model.asset.ProtectedUserAssets;
+
+/**
+ * Things that must be done after Keycloak and Manager data exists, e.g. linking both.
+ */
+public class FinalizeKeycloakDemoSetup extends AbstractKeycloakSetup {
+
+ public FinalizeKeycloakDemoSetup(Container container) {
+ super(container);
+ }
+
+ @Override
+ public void execute() throws Exception {
+
+ // Restrict access to assets
+ UsersResource customerAUsersResource = identityService.getRealms(accessToken, false).realm("customerA").users();
+ UserRepresentation testuser3 = customerAUsersResource.search("testuser3", null, null, null, null, null).get(0);
+ UserResource testuser3Resource = customerAUsersResource.get(testuser3.getId());
+ ManagerDemoSetup managerDemoSetup = setupService.getTaskOfType(ManagerDemoSetup.class);
+ testuser3.setAttributes(ProtectedUserAssets.createUserAttributes(
+ managerDemoSetup.apartment1Id,
+ managerDemoSetup.apartment1LivingroomId,
+ managerDemoSetup.apartment1LivingroomThermostatId,
+ managerDemoSetup.apartment2Id
+ ));
+ testuser3Resource.update(testuser3);
+ }
+}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/KeycloakDemoSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/KeycloakDemoSetup.java
index 49e23c273..fa2499ce2 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/KeycloakDemoSetup.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/KeycloakDemoSetup.java
@@ -28,7 +28,7 @@ import org.openremote.container.Container;
import org.openremote.manager.server.setup.AbstractKeycloakSetup;
import org.openremote.manager.shared.security.ClientRole;
import org.openremote.manager.shared.security.Tenant;
-import org.openremote.model.asset.HomeAssets;
+import org.openremote.model.asset.ProtectedUserAssets;
import java.util.*;
import java.util.logging.Logger;
@@ -121,8 +121,10 @@ public class KeycloakDemoSetup extends AbstractKeycloakSetup {
testuser3.setEnabled(true);
// Restrict access to assets
ManagerDemoSetup managerDemoSetup = setupService.getTaskOfType(ManagerDemoSetup.class);
- testuser3.setAttributes(HomeAssets.setAssetId(
+ testuser3.setAttributes(ProtectedUserAssets.createUserAttributes(
managerDemoSetup.apartment1Id,
+ managerDemoSetup.apartment1LivingroomId,
+ managerDemoSetup.apartment1LivingroomThermostatId,
managerDemoSetup.apartment2Id
));
customerAUsersResource.create(testuser3);
diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java
index 7b33c8ec0..7fd250b91 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java
@@ -20,7 +20,6 @@
package org.openremote.manager.server.setup.builtin;
import com.vividsolutions.jts.geom.Coordinate;
-import com.vividsolutions.jts.geom.GeometryFactory;
import elemental.json.Json;
import org.openremote.agent3.protocol.simulator.SimulatorProtocol;
import org.openremote.container.Container;
@@ -48,6 +47,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
public String smartHomeId;
public String apartment1Id;
public String apartment1LivingroomId;
+ public String apartment1LivingroomThermostatId;
public String apartment2Id;
public String apartment3Id;
public String apartment2LivingroomId;
@@ -129,11 +129,12 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
new Attribute("light1Toggle", BOOLEAN, Json.create(true))
.setMetadata(new Metadata()
.add(new MetadataItem(
- AssetAttributeMeta.DESCRIPTION.getName(),
+ AssetAttributeMeta.DESCRIPTION,
Json.create("The switch for the light in the living room"))
)
.add(new MetadataItem(
- ThingAttribute.META_NAME_LINK, new AttributeRef(agent.getId(), "simulator123").asJsonValue()
+ AssetAttributeMeta.AGENT_LINK,
+ new AttributeRef(agent.getId(), "simulator123").asJsonValue()
))
.add(new MetadataItem(
SimulatorProtocol.META_NAME_ELEMENT, Json.create("switch")
@@ -142,36 +143,38 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
new Attribute("light1Dimmer", INTEGER) // No initial value!
.setMetadata(new Metadata()
.add(new MetadataItem(
- AssetAttributeMeta.DESCRIPTION.getName(),
+ AssetAttributeMeta.DESCRIPTION,
Json.create("The dimmer for the light in the living room"))
)
.add(new MetadataItem(
- AssetAttributeMeta.RANGE_MIN.getName(),
+ AssetAttributeMeta.RANGE_MIN,
Json.create(0))
)
.add(new MetadataItem(
- AssetAttributeMeta.RANGE_MAX.getName(),
+ AssetAttributeMeta.RANGE_MAX,
Json.create(100))
)
.add(new MetadataItem(
- ThingAttribute.META_NAME_LINK, new AttributeRef(agent.getId(), "simulator123").asJsonValue()
+ AssetAttributeMeta.AGENT_LINK,
+ new AttributeRef(agent.getId(), "simulator123").asJsonValue()
))
.add(new MetadataItem(
SimulatorProtocol.META_NAME_ELEMENT, Json.create("range")
))
),
- new Attribute("light1Color", STRING, new Color(88, 123, 88).asJsonValue())
+ new Attribute("light1Color", OBJECT, new ColorRGB(88, 123, 88).asJsonValue())
.setMetadata(new Metadata()
.add(new MetadataItem(
- AssetAttributeMeta.UNITS.getName(),
+ AssetAttributeMeta.UNITS,
Json.create(AttributeUnits.COLOR_RGB.toString())
))
.add(new MetadataItem(
- AssetAttributeMeta.DESCRIPTION.getName(),
+ AssetAttributeMeta.DESCRIPTION,
Json.create("The color of the living room light"))
)
.add(new MetadataItem(
- ThingAttribute.META_NAME_LINK, new AttributeRef(agent.getId(), "simulator123").asJsonValue()
+ AssetAttributeMeta.AGENT_LINK,
+ new AttributeRef(agent.getId(), "simulator123").asJsonValue()
))
.add(new MetadataItem(
SimulatorProtocol.META_NAME_ELEMENT, Json.create("color")
@@ -180,19 +183,20 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
new Attribute("light1PowerConsumption", DECIMAL, Json.create(12.345))
.setMetadata(new Metadata()
.add(new MetadataItem(
- AssetAttributeMeta.DESCRIPTION.getName(),
+ AssetAttributeMeta.DESCRIPTION,
Json.create("The total power consumption of the living room light"))
)
.add(new MetadataItem(
- AssetAttributeMeta.READ_ONLY.getName(),
+ AssetAttributeMeta.READ_ONLY,
Json.create(true))
)
.add(new MetadataItem(
- AssetAttributeMeta.FORMAT.getName(),
+ AssetAttributeMeta.FORMAT,
Json.create("%3d kWh"))
)
.add(new MetadataItem(
- ThingAttribute.META_NAME_LINK, new AttributeRef(agent.getId(), "simulator123").asJsonValue()
+ AssetAttributeMeta.AGENT_LINK,
+ new AttributeRef(agent.getId(), "simulator123").asJsonValue()
))
.add(new MetadataItem(
SimulatorProtocol.META_NAME_ELEMENT, Json.create("decimal")
@@ -227,6 +231,41 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
apartment1Livingroom = assetService.merge(apartment1Livingroom);
apartment1LivingroomId = apartment1Livingroom.getId();
+ ServerAsset apartment1LivingroomThermostat = new ServerAsset(apartment1Livingroom);
+ apartment1LivingroomThermostat.setName("Livingroom Thermostat");
+ apartment1LivingroomThermostat.setLocation(geometryFactory.createPoint(new Coordinate(5.460315214821094, 51.44541688237109)));
+ apartment1LivingroomThermostat.setType(AssetType.THING);
+ ThingAttributes apartment1LivingroomThermostatAttributes = new ThingAttributes(apartment1LivingroomThermostat);
+ apartment1LivingroomThermostatAttributes.put(
+ new Attribute("currentTemperature", DECIMAL, Json.create("19.2"))
+ .setMetadata(new Metadata()
+ .add(new MetadataItem(
+ AssetAttributeMeta.LABEL,
+ Json.create("Current Temp"))
+ )
+ .add(new MetadataItem(
+ AssetAttributeMeta.PROTECTED,
+ Json.create(true))
+ )
+ .add(new MetadataItem(
+ AssetAttributeMeta.READ_ONLY,
+ Json.create(true))
+ )
+ .add(new MetadataItem(
+ Constants.NAMESPACE + ":foo:bar", Json.create("FOO")
+ ))
+ .add(new MetadataItem(
+ "urn:thirdparty:bar", Json.create("BAR")
+ ))
+ )
+ );
+ apartment1LivingroomThermostatAttributes.put(
+ new Attribute("somethingPrivate", INTEGER, Json.create("123"))
+ );
+ apartment1LivingroomThermostat.setAttributes(apartment1LivingroomThermostatAttributes.getJsonObject());
+ apartment1LivingroomThermostat = assetService.merge(apartment1LivingroomThermostat);
+ apartment1LivingroomThermostatId = apartment1LivingroomThermostat.getId();
+
ServerAsset apartment2 = new ServerAsset(smartHome);
apartment2.setName("Apartment 2");
apartment2.setLocation(geometryFactory.createPoint(new Coordinate(5.469751699216005, 51.44760787406028)));
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.java
index 7e5d21d7d..38c57ee36 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
@@ -19,12 +19,14 @@
*/
package org.openremote.manager.shared.asset;
+import elemental.json.JsonValue;
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.HomeAssets;
+import org.openremote.model.asset.ProtectedAssetInfo;
+import org.openremote.model.asset.ProtectedUserAssets;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.*;
@@ -34,9 +36,19 @@ import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
/**
* Asset access rules:
* <ul>
- * <li>The superuser (the admin in the master realm) can access all assets.</li>
- * <li>A regular user can have roles that allow read, write, or no access to assets with her authenticated realm.</li>
- * <li>A regular user can have restricted access to a subset of "home" assets within her authenticated realm (see {@link HomeAssets})</li>
+ * <li>
+ * The superuser (the admin in the master realm) may access all assets.
+ * </li>
+ * <li>
+ * A regular user may have roles that allow read, write, or no access to any assets within
+ * its authenticated realm.
+ * </li>
+ * <li>
+ * A <em>restricted</em> user is linked to a subset of assets within its authenticated realm and
+ * may have roles that allow read and/or write access to protected asset details (see {@link ProtectedUserAssets}).
+ * The only operations a restricted user is able to perform are {@link #getCurrentUserAssets},
+ * {@link #updateCurrentUserAsset}, and {@link #updateAttribute}
+ * </li>
* </ul>
*
*/
@@ -45,22 +57,34 @@ import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
public interface AssetResource {
/**
- * Retrieve the (restricted) home assets of the currently authenticated user. If the request is made
- * by the superuser, or if the regular user making the request is not restricted to home assets, the
- * root assets of the authenticated realm will be returned.
+ * Retrieve the linked assets of the currently authenticated user. If the request is made
+ * by the superuser, or if the user has no linked assets and is therefore not restricted, an empty
+ * result will be returned.
*/
@GET
- @Path("home/current")
+ @Path("user/current")
@Produces(APPLICATION_JSON)
@SuccessStatusCode(200)
@RolesAllowed({"read:assets"})
- AssetInfo[] getHomeAssets(@BeanParam RequestParams requestParams);
+ ProtectedAssetInfo[] getCurrentUserAssets(@BeanParam RequestParams requestParams);
/**
- * Retrieve the assets without parent (root assets) of the given realm, or if the realm is empty,
- * of the authenticated realm. Regular users can only access assets in their authenticated realm,
- * the superuser can access assets in other (all) realms. A 403 status is returned if a regular
- * user tries to access a realm different than her authenticated realm.
+ * Updates an asset linked to the current user. A 403 status is returned if a regular user tries to update an
+ * asset in a realm different than its authenticated realm, or if the user is restricted and the given asset
+ * is not in the set of linked assets.
+ */
+ @PUT
+ @Path("user/current/{assetId}")
+ @Consumes(APPLICATION_JSON)
+ @SuccessStatusCode(204)
+ @RolesAllowed({"write:assets"})
+ void updateCurrentUserAsset(@BeanParam RequestParams requestParams, @PathParam("assetId") String assetId, ProtectedAssetInfo assetInfo);
+
+ /**
+ * Retrieve the assets without parent (root assets) of the given realm, or if the realm argument
+ * is empty, of the authenticated realm. Regular users can only access assets in their authenticated
+ * realm. The superuser can access assets in other (all) realms. An empty result is returned if the user
+ * does not have access to the assets or if the user is restricted.
*/
@GET
@Produces(APPLICATION_JSON)
@@ -71,7 +95,8 @@ public interface AssetResource {
/**
* Retrieve the child assets of the given parent asset. If the authenticated user is the superuser,
* parent and child assets can be in any realm. Otherwise, assets must in the same realm as the
- * authenticated user. An empty result is returned if the user does not have access to the assets.
+ * authenticated user. An empty result is returned if the user does not have access to the assets
+ * or if the user is restricted.
*/
@GET
@Path("{assetId}/children")
@@ -83,7 +108,8 @@ public interface AssetResource {
/**
* Retrieve the asset. Regular users can only access assets in their authenticated realm,
* the superuser can access assets in other (all) realms. A 403 status is returned if a regular
- * user tries to access an asset in a realm different than her authenticated realm.
+ * user tries to access an asset in a realm different than its authenticated realm, or if the
+ * user is restricted.
*/
@GET
@Path("{assetId}")
@@ -95,23 +121,43 @@ public interface AssetResource {
/**
* Updates the asset. Regular users can only update assets in their authenticated realm,
* the superuser can update assets in other (all) realms. A 403 status is returned if a regular
- * user tries to update an asset in a realm different than her authenticated realm.
+ * user tries to update an asset in a realm different than its authenticated realm, or if the
+ * user is restricted. A 400 status is returned if the asset's parent or realm doesn't exist.
*/
@PUT
@Path("{assetId}")
@Consumes(APPLICATION_JSON)
- @Produces(APPLICATION_JSON)
@SuccessStatusCode(204)
@RolesAllowed({"write:assets"})
void update(@BeanParam RequestParams requestParams, @PathParam("assetId") String assetId, Asset asset);
+ /**
+ * Updates an attribute of a user with a JSON value. Regular users can only update assets in
+ * their authenticated realm, the superuser can update assets in other (all) realms. A 403 status
+ * is returned if a regular user tries to update an asset in a realm different than its
+ * authenticated realm, or if the user is restricted and the asset to update is not in the set of linked
+ * assets of the restricted user. A 400 status is returned if the update was not successful, e.g. because
+ * the given value does not match the attribute's type.
+ */
+ @PUT
+ @Path("{assetId}/attribute/{attributeName}")
+ @Consumes(APPLICATION_JSON)
+ @SuccessStatusCode(204)
+ @RolesAllowed({"write:assets"})
+ void updateAttribute(@BeanParam RequestParams requestParams,
+ @PathParam("assetId") String assetId,
+ @PathParam("attributeName") String attributeName,
+ JsonValue value);
+
+
/**
* Creates an asset. The identifier value of the asset can be provided, it should be a
* globally unique string value, and must be at least 22 characters long. If no identifier
* value is provided, a unique value will be generated by the system upon insert. Regular
* users can only create assets in their authenticated realm, the superuser can create
* assets in other (all) realms. A 403 status is returned if a regular user tries to create
- * an asset in a realm different than her authenticated realm.
+ * an asset in a realm different than its authenticated realm, or if the user is restricted.
+ * A 400 status is returned if the asset's parent or realm doesn't exist.
*/
@POST
@Consumes(APPLICATION_JSON)
@@ -123,7 +169,9 @@ public interface AssetResource {
/**
* Deletes an asset. Regular users can only delete assets in their authenticated realm,
* the superuser can delete assets in other (all) realms. A 403 status is returned if a regular
- * user tries to delete an asset in a realm different than her authenticated realm.
+ * user tries to delete an asset in a realm different than its authenticated realm, or if the
+ * user is restricted. A 400 status code is returned if the asset has children and therefore
+ * can't be deleted.
*/
@DELETE
@Path("{assetId}")
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/device/DeviceResource.java b/manager/shared/src/main/java/org/openremote/manager/shared/device/DeviceResource.java
index 2361fd5b1..9414ea2fd 100644
--- a/manager/shared/src/main/java/org/openremote/manager/shared/device/DeviceResource.java
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/device/DeviceResource.java
@@ -23,6 +23,7 @@ import elemental.json.Json;
import elemental.json.JsonObject;
import org.openremote.model.Attribute;
import org.openremote.model.AttributeType;
+import org.openremote.model.Constants;
/**
* An attribute of an asset that represents a device resource.
@@ -40,9 +41,9 @@ import org.openremote.model.AttributeType;
public class DeviceResource extends Attribute {
public static final String DEVICE_RESOURCE = "deviceResource";
- public static final String DEVICE_RESOURCE_TYPE = "urn:openremote:device:resource:type";
+ public static final String DEVICE_RESOURCE_TYPE = Constants.NAMESPACE + ":device:resource:type";
public static final String ACCESS = "access";
- public static final String ACCESS_TYPE = "urn:openremote:device:resource:access";
+ public static final String ACCESS_TYPE = Constants.NAMESPACE + ":device:resource:access";
public static final String PASSIVE = "passive";
public static final String CONSTANT = "constant";
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.groovy
index 77f216a04..0dcb360af 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
@@ -11,7 +11,7 @@ import org.openremote.manager.server.setup.SetupService
import org.openremote.model.AttributeRef
import org.openremote.model.AttributeValueChange
import org.openremote.model.Attributes
-import org.openremote.model.asset.Color
+import org.openremote.model.asset.ColorRGB
import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
@@ -36,7 +36,7 @@ class AgentDeploymentTest extends Specification implements ManagerContainerTrait
conditions.eventually {
assert simulatorProtocol.getState(managerDemoSetup.thingId, "light1Toggle").asBoolean()
assert simulatorProtocol.getState(managerDemoSetup.thingId, "light1Dimmer").getType() == JsonType.NULL // No initial value!
- assert new Color(simulatorProtocol.getState(managerDemoSetup.thingId, "light1Color") as JsonObject) == new Color(88, 123, 88)
+ assert new ColorRGB(simulatorProtocol.getState(managerDemoSetup.thingId, "light1Color") as JsonObject) == new ColorRGB(88, 123, 88)
assert simulatorProtocol.getState(managerDemoSetup.thingId, "light1PowerConsumption").asNumber() == 12.345d
}
@@ -90,7 +90,7 @@ class AgentDeploymentTest extends Specification implements ManagerContainerTrait
then: "the thing attribute value should be updated"
conditions.eventually {
- def thing = assetService.get(managerDemoSetup.thingId)
+ def thing = assetService.find(managerDemoSetup.thingId)
def attributes = new Attributes(thing.getAttributes())
assert attributes.get("light1Dimmer").getValue_TODO_BUG_IN_JAVASCRIPT().getType() == JsonType.NUMBER
assert attributes.get("light1Dimmer").getValueAsInteger() == 77
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.groovy
index e951992b1..c689eec37 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
@@ -3,7 +3,13 @@ package org.openremote.test.assets
import org.openremote.manager.server.setup.builtin.ManagerDemoSetup
import org.openremote.manager.server.setup.SetupService
import org.openremote.manager.shared.asset.AssetResource
+import org.openremote.model.Attributes
+import org.openremote.model.Metadata
import org.openremote.model.asset.Asset
+import org.openremote.model.asset.ProtectedAssetInfo
+import org.openremote.model.AttributeType
+import org.openremote.model.AttributeUnits
+import org.openremote.model.asset.AssetAttributeMeta
import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
import org.openremote.model.asset.AssetType
@@ -42,14 +48,13 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
/* ############################################## READ ####################################### */
when: "the home assets of the authenticated user are retrieved"
- def assetInfos = assetResource.getHomeAssets(null);
+ def assetInfos = assetResource.getCurrentUserAssets(null)
then: "result should match"
- assetInfos.length == 1
- assetInfos[0].id == managerDemoSetup.smartOfficeId
+ assetInfos.length == 0
when: "the root assets of the authenticated realm are retrieved"
- assetInfos = assetResource.getRoot(null, MASTER_REALM);
+ assetInfos = assetResource.getRoot(null, MASTER_REALM)
then: "result should match"
assetInfos.length == 1
@@ -63,14 +68,14 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
assetInfos[0].id == managerDemoSetup.groundFloorId
when: "the root assets of the authenticated realm are retrieved"
- assetInfos = assetResource.getRoot(null, null);
+ assetInfos = assetResource.getRoot(null, null)
then: "result should match"
assetInfos.length == 1
assetInfos[0].id == managerDemoSetup.smartOfficeId
when: "the root assets of the given realm are retrieved"
- assetInfos = assetResource.getRoot(null, "customerA");
+ assetInfos = assetResource.getRoot(null, "customerA")
then: "result should match"
assetInfos.length == 1
@@ -87,13 +92,13 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
assetInfos[2].id == managerDemoSetup.apartment3Id
when: "an asset is retrieved by ID in the authenticated realm"
- def demoThing = assetResource.get(null, managerDemoSetup.thingId);
+ def demoThing = assetResource.get(null, managerDemoSetup.thingId)
then: "result should match"
demoThing.id == managerDemoSetup.thingId
when: "an asset is retrieved by ID in a foreign realm"
- def demoSmartHome = assetResource.get(null, managerDemoSetup.smartHomeId);
+ def demoSmartHome = assetResource.get(null, managerDemoSetup.smartHomeId)
then: "result should match"
demoSmartHome.id == managerDemoSetup.smartHomeId
@@ -149,14 +154,13 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
when: "an asset is deleted in a foreign realm"
assetResource.delete(null, managerDemoSetup.apartment1LivingroomId)
- testAsset = assetResource.get(null, managerDemoSetup.apartment1LivingroomId)
- then: "the asset should not be found"
+ then: "there should be a conflict because it has children"
ex = thrown()
- ex.response.status == 404
+ ex.response.status == 400
cleanup: "the server should be stopped"
- stopContainer(container);
+ stopContainer(container)
}
def "Access assets as testuser1"() {
@@ -184,14 +188,13 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
/* ############################################## READ ####################################### */
when: "the home assets of the authenticated user are retrieved"
- def assetInfos = assetResource.getHomeAssets(null);
+ def assetInfos = assetResource.getCurrentUserAssets(null)
then: "result should match"
- assetInfos.length == 1
- assetInfos[0].id == managerDemoSetup.smartOfficeId
+ assetInfos.length == 0
when: "the root assets of the authenticated realm are retrieved"
- assetInfos = assetResource.getRoot(null, MASTER_REALM);
+ assetInfos = assetResource.getRoot(null, MASTER_REALM)
then: "result should match"
assetInfos.length == 1
@@ -205,7 +208,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
assetInfos[0].id == managerDemoSetup.groundFloorId
when: "the root assets of the authenticated realm are retrieved"
- assetInfos = assetResource.getRoot(null, null);
+ assetInfos = assetResource.getRoot(null, null)
then: "result should match"
assetInfos.length == 1
@@ -213,11 +216,10 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
assetInfos[0].realm == MASTER_REALM
when: "the root assets of the given realm are retrieved"
- assetInfos = assetResource.getRoot(null, "customerA");
+ assetInfos = assetResource.getRoot(null, "customerA")
- then: "access should be forbidden"
- WebApplicationException ex = thrown()
- ex.response.status == 403
+ then: "result should match"
+ assetInfos.length == 0
when: "the child assets of an asset in a foreign realm are retrieved"
assetInfos = assetResource.getChildren(null, managerDemoSetup.smartHomeId)
@@ -226,16 +228,16 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
assetInfos.length == 0
when: "an asset is retrieved by ID in the authenticated realm"
- def demoThing = assetResource.get(null, managerDemoSetup.thingId);
+ def demoThing = assetResource.get(null, managerDemoSetup.thingId)
then: "result should match"
demoThing.id == managerDemoSetup.thingId
when: "an asset is retrieved by ID in a foreign realm"
- def demoBuilding = assetResource.get(null, managerDemoSetup.smartHomeId);
+ def demoBuilding = assetResource.get(null, managerDemoSetup.smartHomeId)
then: "access should be forbidden"
- ex = thrown()
+ WebApplicationException ex = thrown()
ex.response.status == 403
/* ############################################## WRITE ####################################### */
@@ -294,7 +296,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
ex.response.status == 403
cleanup: "the server should be stopped"
- stopContainer(container);
+ stopContainer(container)
}
def "Access assets as testuser2"() {
@@ -321,22 +323,19 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
/* ############################################## READ ####################################### */
when: "the home assets of the authenticated user are retrieved"
- def assetInfos = assetResource.getHomeAssets(null);
+ def assetInfos = assetResource.getCurrentUserAssets(null)
then: "result should match"
- assetInfos.length == 1
- assetInfos[0].id == managerDemoSetup.smartHomeId
- assetInfos[0].realm == "customerA"
+ assetInfos.length == 0
when: "the root assets of a foreign realm are retrieved"
- assetInfos = assetResource.getRoot(null, MASTER_REALM);
+ assetInfos = assetResource.getRoot(null, MASTER_REALM)
- then: "access should be forbidden"
- WebApplicationException ex = thrown()
- ex.response.status == 403
+ then: "result should match"
+ assetInfos.length == 0
when: "the root assets of the authenticated realm are retrieved"
- assetInfos = assetResource.getRoot(null, null);
+ assetInfos = assetResource.getRoot(null, null)
then: "result should match"
assetInfos.length == 1
@@ -344,11 +343,10 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
assetInfos[0].realm == "customerA"
when: "the root assets of the given realm are retrieved"
- assetInfos = assetResource.getRoot(null, "customerB");
+ assetInfos = assetResource.getRoot(null, "customerB")
- then: "access should be forbidden"
- ex = thrown()
- ex.response.status == 403
+ then: "result should match"
+ assetInfos.length == 0
when: "the child assets of an asset in a foreign realm are retrieved"
assetInfos = assetResource.getChildren(null, managerDemoSetup.thingId)
@@ -357,16 +355,16 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
assetInfos.length == 0
when: "an asset is retrieved by ID in the authenticated realm"
- def demoSmartHome = assetResource.get(null, managerDemoSetup.smartHomeId);
+ def demoSmartHome = assetResource.get(null, managerDemoSetup.smartHomeId)
then: "result should match"
demoSmartHome.id == managerDemoSetup.smartHomeId
when: "an asset is retrieved by ID in a foreign realm"
- def demoThing = assetResource.get(null, managerDemoSetup.thingId);
+ def demoThing = assetResource.get(null, managerDemoSetup.thingId)
then: "access should be forbidden"
- ex = thrown()
+ WebApplicationException ex = thrown()
ex.response.status == 403
/* ############################################## WRITE ####################################### */
@@ -413,7 +411,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
ex.response.status == 403
cleanup: "the server should be stopped"
- stopContainer(container);
+ stopContainer(container)
}
def "Access assets as testuser3"() {
@@ -440,33 +438,71 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
/* ############################################## READ ####################################### */
when: "the home assets of the authenticated user are retrieved"
- def assetInfos = assetResource.getHomeAssets(null);
+ def assetInfos = assetResource.getCurrentUserAssets(null)
then: "result should match"
- assetInfos.length == 2
- assetInfos[0].id == managerDemoSetup.apartment1Id
- assetInfos[1].id == managerDemoSetup.apartment2Id
- assetInfos[0].realm == "customerA"
+ assetInfos.length == 4
+ ProtectedAssetInfo apartment1 = assetInfos[0]
+ apartment1.id == managerDemoSetup.apartment1Id
+ apartment1.name == "Apartment 1"
+ apartment1.createdOn.getTime() < System.currentTimeMillis()
+ apartment1.realm == "customerA"
+ apartment1.type == AssetType.RESIDENCE.value
+ apartment1.parentId == managerDemoSetup.smartHomeId
+ apartment1.coordinates[0] == 5.469751699216005d
+ apartment1.coordinates[1] == 51.44760787406028d
+
+ ProtectedAssetInfo apartment1Livingroom = assetInfos[1]
+ apartment1Livingroom.id == managerDemoSetup.apartment1LivingroomId
+ apartment1Livingroom.name == "Livingroom"
+
+ ProtectedAssetInfo apartment1LivingroomThermostat = assetInfos[2]
+ apartment1LivingroomThermostat.id == managerDemoSetup.apartment1LivingroomThermostatId
+ apartment1LivingroomThermostat.name == "Livingroom Thermostat"
+
+ Attributes protectedAttributes = new Attributes(apartment1LivingroomThermostat.attributes)
+ protectedAttributes.get().length == 1
+ protectedAttributes.get("currentTemperature")
+ protectedAttributes.get("currentTemperature").getType() == AttributeType.DECIMAL
+ protectedAttributes.get("currentTemperature").getValueAsDecimal() == 19.2d
+ Metadata protectedMetadata = protectedAttributes.get("currentTemperature").getMetadata()
+ protectedMetadata.all().length == 2
+ protectedMetadata.first(AssetAttributeMeta.LABEL).getValueAsString() == "Current Temp"
+ protectedMetadata.first(AssetAttributeMeta.READ_ONLY).getValueAsBoolean()
+
+ ProtectedAssetInfo apartment2 = assetInfos[3]
+ apartment2.id == managerDemoSetup.apartment2Id
+ apartment2.name == "Apartment 2"
when: "the root assets of a foreign realm are retrieved"
- assetInfos = assetResource.getRoot(null, MASTER_REALM);
+ assetInfos = assetResource.getRoot(null, MASTER_REALM)
- then: "access should be forbidden"
- WebApplicationException ex = thrown()
- ex.response.status == 403
+ then: "result should match"
+ assetInfos.length == 0
when: "the root assets of the authenticated realm are retrieved"
- assetInfos = assetResource.getRoot(null, null);
+ assetInfos = assetResource.getRoot(null, null)
then: "result should match"
assetInfos.length == 0
when: "the root assets of the given realm are retrieved"
- assetInfos = assetResource.getRoot(null, "customerB");
+ assetInfos = assetResource.getRoot(null, "customerB")
- then: "access should be forbidden"
- ex = thrown()
- ex.response.status == 403
+ then: "result should match"
+ assetInfos.length == 0
+
+ when: "the child assets of linked asset are retrieved"
+ assetInfos = assetResource.getChildren(null, managerDemoSetup.apartment1Id)
+
+ then: "result should match"
+ assetInfos.length == 0
+
+ when: "the child assets of an asset in the authenticated realm are retrieved"
+ assetInfos = assetResource.getChildren(null, managerDemoSetup.smartHomeId)
+
+ then: "result should match"
+ assetInfos.length == 0
when: "the child assets of an asset in a foreign realm are retrieved"
assetInfos = assetResource.getChildren(null, managerDemoSetup.thingId)
@@ -475,20 +511,21 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
assetInfos.length == 0
when: "an asset is retrieved by ID in the authenticated realm"
- def demoSmartHome = assetResource.get(null, managerDemoSetup.smartHomeId);
+ def asset = assetResource.get(null, managerDemoSetup.smartHomeId)
+
+ then: "access should be forbidden"
+ WebApplicationException ex = thrown()
+ ex.response.status == 403
- then: "result should match"
- demoSmartHome.id == managerDemoSetup.smartHomeId
-/* TODO
when: "an asset is retrieved by ID in a foreign realm"
- def demoThing = assetResource.get(null, managerDemoSetup.thingId);
+ asset = assetResource.get(null, managerDemoSetup.thingId)
then: "access should be forbidden"
ex = thrown()
ex.response.status == 403
-*/
+
/* ############################################## WRITE ####################################### */
-/*
+
when: "an asset is created in a foreign realm"
def testAsset = new Asset(MASTER_REALM, "Test Room", AssetType.ROOM)
testAsset.setId(IdentifierUtil.generateGlobalUniqueId())
@@ -529,8 +566,8 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
then: "access should be forbidden"
ex = thrown()
ex.response.status == 403
-*/
+
cleanup: "the server should be stopped"
- stopContainer(container);
+ stopContainer(container)
}
}
diff --git a/model/src/main/java/org/openremote/model/Attribute.java b/model/src/main/java/org/openremote/model/Attribute.java
index 523a730dc..381909977 100644
--- a/model/src/main/java/org/openremote/model/Attribute.java
+++ b/model/src/main/java/org/openremote/model/Attribute.java
@@ -20,6 +20,7 @@
package org.openremote.model;
import elemental.json.*;
+import org.openremote.model.asset.AssetAttributeMeta;
import java.util.NoSuchElementException;
@@ -94,10 +95,18 @@ public class Attribute extends AbstractValueHolder<Attribute> {
return this;
}
+ public boolean hasMetaItem(AssetAttributeMeta assetAttributeMeta) {
+ return hasMetaItem(assetAttributeMeta.getName());
+ }
+
public boolean hasMetaItem(String name) {
return hasMetadata() && getMetadata().contains(name);
}
+ public MetadataItem firstMetaItem(AssetAttributeMeta assetAttributeMeta) {
+ return firstMetaItem(assetAttributeMeta.getName());
+ }
+
public MetadataItem firstMetaItem(String name) {
return hasMetaItem(name) ? getMetadata().first(name) : null;
}
diff --git a/model/src/main/java/org/openremote/model/AttributeUnits.java b/model/src/main/java/org/openremote/model/AttributeUnits.java
index 2e5ce4990..475a1a039 100644
--- a/model/src/main/java/org/openremote/model/AttributeUnits.java
+++ b/model/src/main/java/org/openremote/model/AttributeUnits.java
@@ -27,7 +27,7 @@ public enum AttributeUnits {
COLOR_HEX, // Hex value e.g. #FFFFFF
TEMPERATURE_CELCIUS,
TEMPERATURE_KELVIN,
- TEMPERATURE_FARENHEIT,
+ TEMPERATURE_FAHRENHEIT,
DISTANCE_M,
DISTANCE_CM,
DISTANCE_MM,
diff --git a/model/src/main/java/org/openremote/model/Constants.java b/model/src/main/java/org/openremote/model/Constants.java
index 6b3769551..a78bc6da5 100644
--- a/model/src/main/java/org/openremote/model/Constants.java
+++ b/model/src/main/java/org/openremote/model/Constants.java
@@ -30,6 +30,9 @@ public interface Constants {
String PERSISTENCE_UNIQUE_ID_GENERATOR = "UNIQUE_ID_GENERATOR";
String PERSISTENCE_JSON_OBJECT_TYPE = "json_object";
String PERSISTENCE_JSON_ARRAY_TYPE = "json_array";
- String PROTOCOL_NAMESPACE = "urn:openremote:protocol";
+ String NAMESPACE = "urn:openremote";
+ String PROTOCOL_NAMESPACE = NAMESPACE + ":protocol";
+ String ASSET_NAMESPACE = NAMESPACE + ":asset";
+ String ASSET_META_NAMESPACE = ASSET_NAMESPACE + ":meta";
}
diff --git a/model/src/main/java/org/openremote/model/Metadata.java b/model/src/main/java/org/openremote/model/Metadata.java
index 2f25c7ec5..332409d96 100644
--- a/model/src/main/java/org/openremote/model/Metadata.java
+++ b/model/src/main/java/org/openremote/model/Metadata.java
@@ -22,6 +22,7 @@ package org.openremote.model;
import elemental.json.Json;
import elemental.json.JsonArray;
import elemental.json.JsonObject;
+import org.openremote.model.asset.AssetAttributeMeta;
import java.util.ArrayList;
import java.util.List;
@@ -65,6 +66,10 @@ public class Metadata {
: null;
}
+ public MetadataItem first(AssetAttributeMeta assetAttributeMeta) {
+ return first(assetAttributeMeta.getName());
+ }
+
public MetadataItem first(String name) {
List<MetadataItem> list = asList();
for (MetadataItem item : list) {
@@ -74,6 +79,10 @@ public class Metadata {
return null;
}
+ public boolean contains(AssetAttributeMeta assetAttributeMeta) {
+ return contains(assetAttributeMeta.getName());
+ }
+
public boolean contains(String name) {
return first(name) != null;
}
diff --git a/model/src/main/java/org/openremote/model/MetadataItem.java b/model/src/main/java/org/openremote/model/MetadataItem.java
index 3ebeb64bc..5de2ad341 100644
--- a/model/src/main/java/org/openremote/model/MetadataItem.java
+++ b/model/src/main/java/org/openremote/model/MetadataItem.java
@@ -22,6 +22,7 @@ package org.openremote.model;
import elemental.json.Json;
import elemental.json.JsonObject;
import elemental.json.JsonValue;
+import org.openremote.model.asset.AssetAttributeMeta;
public class MetadataItem extends AbstractValueHolder<MetadataItem> {
@@ -33,10 +34,18 @@ public class MetadataItem extends AbstractValueHolder<MetadataItem> {
super(jsonObject);
}
+ public MetadataItem(AssetAttributeMeta assetAttributeMeta) {
+ this(assetAttributeMeta, null);
+ }
+
public MetadataItem(String name) {
this(name, null);
}
+ public MetadataItem(AssetAttributeMeta assetAttributeMeta, JsonValue value) {
+ this(assetAttributeMeta.getName(), value);
+ }
+
public MetadataItem(String name, JsonValue value) {
super(Json.createObject());
setName(name);
diff --git a/model/src/main/java/org/openremote/model/asset/Asset.java b/model/src/main/java/org/openremote/model/asset/Asset.java
index e77857bf6..605c2509d 100644
--- a/model/src/main/java/org/openremote/model/asset/Asset.java
+++ b/model/src/main/java/org/openremote/model/asset/Asset.java
@@ -205,6 +205,7 @@ public class Asset {
"id='" + id + '\'' +
", realm='" + realm + '\'' +
", name='" + name + '\'' +
+ ", createOn='" + createdOn + '\'' +
", type ='" + type + '\'' +
", parent ='" + parentId + '\'' +
", path ='" + Arrays.toString(path) + '\'' +
diff --git a/model/src/main/java/org/openremote/model/asset/AssetAttributeMeta.java b/model/src/main/java/org/openremote/model/asset/AssetAttributeMeta.java
index 97654c889..be60197a6 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetAttributeMeta.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetAttributeMeta.java
@@ -22,11 +22,16 @@ package org.openremote.model.asset;
import elemental.json.JsonType;
import elemental.json.JsonValue;
import org.openremote.model.Attribute;
+import org.openremote.model.Constants;
import org.openremote.model.MetadataItem;
+import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
+import static org.openremote.model.Constants.ASSET_META_NAMESPACE;
+import static org.openremote.model.Constants.NAMESPACE;
+
/**
* Asset attribute meta item name is an arbitrary string. It should be URI. This enum contains
* the well-known URIs for functionality we want to depend on in our platform.
@@ -35,69 +40,79 @@ import java.util.List;
*/
public enum AssetAttributeMeta {
+ /**
+ * Links the attribute to an agent, connecting it to a sensor and/or actuator.
+ */
+ AGENT_LINK(ASSET_META_NAMESPACE + ":agentLink", new Access(false, false, true), JsonType.ARRAY),
+
/**
* A human-friendly string that can be displayed in UI instead of the raw attribute name.
*/
- LABEL("urn:openremote:asset:meta:label", true, JsonType.STRING),
+ LABEL(ASSET_META_NAMESPACE + ":label", new Access(true, true, true), JsonType.STRING),
/**
* Format string that can be used to render the attribute value, see {@link java.util.Formatter}.
*/
- FORMAT("urn:openremote:asset:meta:format", true, JsonType.STRING),
+ FORMAT(ASSET_META_NAMESPACE + ":format", new Access(true, false, true), JsonType.STRING),
/**
* A human-friendly string describing the purpose of an attribute, useful when rendering editors.
*/
- DESCRIPTION("urn:openremote:asset:meta:description", true, JsonType.STRING),
+ DESCRIPTION(ASSET_META_NAMESPACE + ":description", new Access(true, false, true), JsonType.STRING),
/**
* Points to semantic description of the attribute, typically a URI.
*/
- ABOUT("urn:openremote:asset:meta:about", true, JsonType.STRING),
+ ABOUT(ASSET_META_NAMESPACE + ":about", new Access(true, false, true), JsonType.STRING),
/**
* Marks the attribute as read-only.
*/
- READ_ONLY("urn:openremote:asset:meta:readOnly", true, JsonType.BOOLEAN),
+ READ_ONLY(ASSET_META_NAMESPACE + ":readOnly", new Access(true, false, true), JsonType.BOOLEAN),
+
+ /**
+ * Marks the attribute as protected and accessible to restricted users, see {@link ProtectedUserAssets}.
+ */
+ PROTECTED(ASSET_META_NAMESPACE + ":protected", new Access(false, false, true), JsonType.BOOLEAN),
/**
* Default value that might be used when editing an attribute.
*/
- DEFAULT("urn:openremote:asset:meta:default", false, JsonType.STRING),
+ DEFAULT(ASSET_META_NAMESPACE + ":default", new Access(false, false, false), JsonType.STRING),
/**
* Minimum range constraint for numeric attribute values.
*/
- RANGE_MIN("urn:openremote:asset:meta:rangeMin", true, JsonType.NUMBER),
+ RANGE_MIN(ASSET_META_NAMESPACE + ":rangeMin", new Access(true, false, true), JsonType.NUMBER),
/**
* Maximum range constraint for numeric attribute values.
*/
- RANGE_MAX("urn:openremote:asset:meta:rangeMax", true, JsonType.NUMBER),
+ RANGE_MAX(ASSET_META_NAMESPACE + ":rangeMax", new Access(true, false, true), JsonType.NUMBER),
/**
* Step increment/decrement constraint for numeric attribute values.
*/
- STEP("urn:openremote:asset:meta:step", true, JsonType.NUMBER),
+ STEP(ASSET_META_NAMESPACE + ":step", new Access(true, false, true), JsonType.NUMBER),
/**
* Regex (Java syntax) constraint for string attribute values.
*/
- PATTERN("urn:openremote:asset:meta:pattern", true, JsonType.STRING),
+ PATTERN(ASSET_META_NAMESPACE + ":pattern", new Access(true, false, true), JsonType.STRING),
/**
- * Indicates the units (data type) of the attribute value should be a valid
- * {@link org.openremote.model.AttributeUnits} value
+ * Indicates the units (data sub-type) of the attribute value (should be a valid
+ * {@link org.openremote.model.AttributeUnits} string representation)
*/
- UNITS("urn:openremote:asset:meta:units", true, JsonType.STRING);
+ UNITS(ASSET_META_NAMESPACE + ":units", new Access(true, false, true), JsonType.STRING);
final protected String name;
- final protected boolean editable; // Can the user edit an asset and apply this meta item?
+ final protected Access access;
final protected JsonType valueType;
- AssetAttributeMeta(String name, boolean editable, JsonType valueType) {
+ AssetAttributeMeta(String name, Access access, JsonType valueType) {
this.name = name;
- this.editable = editable;
+ this.access = access;
this.valueType = valueType;
}
@@ -105,8 +120,8 @@ public enum AssetAttributeMeta {
return name;
}
- public boolean isEditable() {
- return editable;
+ public Access getAccess() {
+ return access;
}
public JsonType getValueType() {
@@ -116,7 +131,7 @@ public enum AssetAttributeMeta {
public static AssetAttributeMeta[] editable() {
List<AssetAttributeMeta> list = new ArrayList<>();
for (AssetAttributeMeta meta : values()) {
- if (meta.isEditable())
+ if (meta.getAccess().editable)
list.add(meta);
}
return list.toArray(new AssetAttributeMeta[list.size()]);
@@ -125,7 +140,15 @@ public enum AssetAttributeMeta {
public static Boolean isEditable(String name) {
for (AssetAttributeMeta assetAttributeMeta : editable()) {
if (assetAttributeMeta.getName().equals(name))
- return assetAttributeMeta.isEditable();
+ return assetAttributeMeta.getAccess().editable;
+ }
+ return null;
+ }
+
+ public static AssetAttributeMeta byName(String name) {
+ for (AssetAttributeMeta assetAttributeMeta : values()) {
+ if (assetAttributeMeta.getName().equals(name))
+ return assetAttributeMeta;
}
return null;
}
@@ -163,4 +186,28 @@ public enum AssetAttributeMeta {
}
}
+ public static class Access {
+
+ /**
+ * When restricted clients read protected asset attributes, should this meta item be included?
+ */
+ final public boolean protectedRead;
+
+ /**
+ * When restricted clients write protected asset attributes, should this meta item be included?
+ */
+ final public boolean protectedWrite;
+
+ /**
+ * Can a user add this meta item when editing an asset?
+ */
+ final public boolean editable;
+
+ public Access(boolean protectedRead, boolean protectedWrite, boolean editable) {
+ this.protectedRead = protectedRead;
+ this.protectedWrite = protectedWrite;
+ this.editable = editable;
+ }
+ }
+
}
diff --git a/model/src/main/java/org/openremote/model/asset/AssetInfo.java b/model/src/main/java/org/openremote/model/asset/AssetInfo.java
index 0ddecbccc..59d8985e0 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetInfo.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetInfo.java
@@ -19,6 +19,9 @@
*/
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.
*/
@@ -30,6 +33,8 @@ public class AssetInfo {
protected String name;
+ protected Date createdOn;
+
protected String realm;
protected String type;
@@ -46,13 +51,14 @@ public class AssetInfo {
}
public AssetInfo(Asset asset) {
- this(asset.getId(), asset.getVersion(), asset.getName(), asset.getRealm(), asset.getType(), asset.getParentId(), asset.getCoordinates());
+ this(asset.getId(), asset.getVersion(), asset.getName(), asset.getCreatedOn(), asset.getRealm(), asset.getType(), asset.getParentId(), asset.getCoordinates());
}
- public AssetInfo(String id, long version, String name, String realm, String type, String parentId, double[] coordinates) {
+ public AssetInfo(String id, long version, String name, Date createdOn, String realm, String type, String parentId, double[] coordinates) {
this.id = id;
this.version = version;
this.name = name;
+ this.createdOn = createdOn;
this.realm = realm;
this.type = type;
this.parentId = parentId;
@@ -96,6 +102,14 @@ public class AssetInfo {
this.name = name;
}
+ public Date getCreatedOn() {
+ return createdOn;
+ }
+
+ public void setCreatedOn(Date createdOn) {
+ this.createdOn = createdOn;
+ }
+
public String getType() {
return type;
}
@@ -120,15 +134,24 @@ public class AssetInfo {
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 + '\'' +
", name='" + name + '\'' +
+ ", createOn='" + createdOn + '\'' +
", realm='" + realm + '\'' +
", type='" + type + '\'' +
", parentId='" + parentId + '\'' +
- ", coordinates='" + coordinates+ '\'' +
+ ", coordinates='" + Arrays.toString(coordinates) + '\'' +
'}';
}
}
diff --git a/model/src/main/java/org/openremote/model/asset/AssetType.java b/model/src/main/java/org/openremote/model/asset/AssetType.java
index 38aee2ce2..ed2242e33 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetType.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetType.java
@@ -21,14 +21,12 @@ package org.openremote.model.asset;
import elemental.json.Json;
import elemental.json.JsonObject;
-import org.openremote.model.Attribute;
-import org.openremote.model.AttributeType;
-import org.openremote.model.Attributes;
-import org.openremote.model.Metadata;
+import org.openremote.model.*;
import java.util.ArrayList;
import java.util.List;
+import static org.openremote.model.Constants.ASSET_NAMESPACE;
import static org.openremote.model.asset.AssetAttributeMeta.*;
import static org.openremote.model.AttributeType.INTEGER;
import static org.openremote.model.AttributeType.STRING;
@@ -43,12 +41,12 @@ public enum AssetType {
CUSTOM(null, true, null),
- TENANT("urn:openremote:asset:tenant", false, null),
+ TENANT(ASSET_NAMESPACE + ":tenant", false, null),
// TODO Arbitrary group of assets? Semantics?
- GROUP("urn:openremote:asset:group", true, null),
+ GROUP(ASSET_NAMESPACE + ":group", true, null),
- BUILDING("urn:openremote:asset:building", true, new Attributes().put(
+ BUILDING(ASSET_NAMESPACE + ":building", true, new Attributes().put(
new Attribute("area", INTEGER)
.setMetadata(new Metadata()
.add(createMetadataItem(LABEL, Json.create("Surface area")))
@@ -77,19 +75,19 @@ public enum AssetType {
)
).getJsonObject()),
- FLOOR("urn:openremote:asset:floor", true, null),
+ FLOOR(ASSET_NAMESPACE + ":floor", true, null),
- RESIDENCE("urn:openremote:asset:residence", true, null),
+ RESIDENCE(ASSET_NAMESPACE + ":residence", true, null),
- ROOM("urn:openremote:asset:room", true, null),
+ ROOM(ASSET_NAMESPACE + ":room", true, null),
- AGENT("urn:openremote:asset:agent", true, null),
+ AGENT(ASSET_NAMESPACE + ":agent", true, null),
/**
* When a Thing asset is modified (created, updated, deleted), its attributes are examined
* and linked to and unlinked from the configured Protocol.
*/
- THING("urn:openremote:asset:thing", true, null);
+ THING(ASSET_NAMESPACE + ":thing", true, null);
final protected String value;
final protected boolean editable;
diff --git a/model/src/main/java/org/openremote/model/asset/Color.java b/model/src/main/java/org/openremote/model/asset/ColorRGB.java
similarity index 79%
rename from model/src/main/java/org/openremote/model/asset/Color.java
rename to model/src/main/java/org/openremote/model/asset/ColorRGB.java
index a26a70c30..ffe72bb99 100644
--- a/model/src/main/java/org/openremote/model/asset/Color.java
+++ b/model/src/main/java/org/openremote/model/asset/ColorRGB.java
@@ -22,19 +22,19 @@ package org.openremote.model.asset;
import elemental.json.Json;
import elemental.json.JsonObject;
-public class Color {
+public class ColorRGB {
final protected int red;
final protected int green;
final protected int blue;
- public Color(int red, int green, int blue) {
+ public ColorRGB(int red, int green, int blue) {
this.red = red;
this.green = green;
this.blue = blue;
}
- public Color(JsonObject jsonObject) {
+ public ColorRGB(JsonObject jsonObject) {
this(
(int)jsonObject.get("red").asNumber(),
(int)jsonObject.get("green").asNumber(),
@@ -62,16 +62,16 @@ public class Color {
return object;
}
- public Color red(int red) {
- return new Color(red, getGreen(), getBlue());
+ public ColorRGB red(int red) {
+ return new ColorRGB(red, getGreen(), getBlue());
}
- public Color green(int green) {
- return new Color(getRed(), green, getBlue());
+ public ColorRGB green(int green) {
+ return new ColorRGB(getRed(), green, getBlue());
}
- public Color blue(int blue) {
- return new Color(getRed(), getGreen(), blue);
+ public ColorRGB blue(int blue) {
+ return new ColorRGB(getRed(), getGreen(), blue);
}
@Override
@@ -79,11 +79,11 @@ public class Color {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
- Color color = (Color) o;
+ ColorRGB colorRGB = (ColorRGB) o;
- if (red != color.red) return false;
- if (green != color.green) return false;
- return blue == color.blue;
+ if (red != colorRGB.red) return false;
+ if (green != colorRGB.green) return false;
+ return blue == colorRGB.blue;
}
@Override
diff --git a/model/src/main/java/org/openremote/model/asset/HomeAssets.java b/model/src/main/java/org/openremote/model/asset/HomeAssets.java
deleted file mode 100644
index 0e63bbf9f..000000000
--- a/model/src/main/java/org/openremote/model/asset/HomeAssets.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright 2017, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.model.asset;
-
-import java.util.*;
-
-/**
- * A user can have links to assets, these are her "home" assets.
- * <p>
- * We currently use home asset links to implement access control: if a user has home assets,
- * she can only access those assets and their children.
- *
- * TODO Supporting multiple home assets comes with some unsolved problems.
- * Can one home asset be a child of another home asset? What are the consequences? Do we
- * actually need multiple home assets? Who guarantees that all home assets are within the
- * users realm? What happens if a home asset is moved around?
- */
-public class HomeAssets {
-
- // Name of Keycloak user attribute where the linked asset identifiers are stored
- public static final String HOME_ASSETS_ATTRIBUTE = "urn:openremote:homeAssets";
-
- // Name of the claim in a user's access token where the linked asset identifiers can be found
- public static final String HOME_ASSETS_CLAIM = "openremoteHomeAssets";
-
- public static final Map<String, String> HOME_ASSET_MAPPER_CONFIG = new HashMap<String, String>() {
- {
- put("user.attribute", HomeAssets.HOME_ASSETS_ATTRIBUTE);
- put("access.token.claim", "true");
- put("claim.name", HomeAssets.HOME_ASSETS_CLAIM);
- put("jsonType.label", "String");
- put("multivalued", "true");
- }
- };
-
- public static Map<String, List<String>> setAssetId(String... assetId) {
- Map<String, List<String>> userAttributes = new HashMap<>();
- addAssetId(userAttributes, assetId);
- return userAttributes;
- }
-
- public static void addAssetId(Map<String, List<String>> userAttributes, String... assetId) {
- if (!userAttributes.containsKey(HOME_ASSETS_ATTRIBUTE))
- userAttributes.put(HOME_ASSETS_ATTRIBUTE, new ArrayList<>());
- List<String> userAssets = userAttributes.get(HOME_ASSETS_ATTRIBUTE);
- userAssets.addAll(Arrays.asList(assetId));
- }
-
- public static String[] getAssetIds(Map<String, Object> accessTokenClaims) {
- if (!accessTokenClaims.containsKey(HOME_ASSETS_CLAIM))
- return new String[0];
- @SuppressWarnings("unchecked")
- List<String> homeAssetIds = (List<String>) accessTokenClaims.get(HOME_ASSETS_CLAIM);
- return homeAssetIds.toArray(new String[homeAssetIds.size()]);
- }
-
-}
diff --git a/model/src/main/java/org/openremote/model/asset/ProtectedAssetInfo.java b/model/src/main/java/org/openremote/model/asset/ProtectedAssetInfo.java
new file mode 100644
index 000000000..810e75c0b
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/asset/ProtectedAssetInfo.java
@@ -0,0 +1,99 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.asset;
+
+import elemental.json.JsonObject;
+import org.openremote.model.Attribute;
+import org.openremote.model.Attributes;
+import org.openremote.model.Metadata;
+import org.openremote.model.MetadataItem;
+
+import java.util.Date;
+
+import static org.openremote.model.Constants.NAMESPACE;
+import static org.openremote.model.asset.AssetAttributeMeta.PROTECTED;
+
+/**
+ * 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 AssetAttributeMeta#PROTECTED},
+ * {@link AssetAttributeMeta.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 {
+
+ static JsonObject filterProtectedAttributes(JsonObject unfilteredAttributes) {
+ Attributes filteredAttributes = new Attributes();
+ Attributes attributes = new Attributes(unfilteredAttributes);
+ for (Attribute attribute : attributes.get()) {
+
+ // An attribute must have the PROTECTED flag to be included
+ MetadataItem protectedItem = attribute.firstMetaItem(PROTECTED);
+ if (protectedItem != null && protectedItem.getValueAsBoolean()) {
+ Attribute protectedAttribute = new Attribute(attribute.getName(), attribute.getJsonObject());
+
+ // Any meta item of the attribute, if it's in our namespace, must be protected READ to be included
+ if (protectedAttribute.hasMetadata()) {
+ Metadata protectedMetadata = new Metadata();
+ for (MetadataItem metadataItem : protectedAttribute.getMetadata().all()) {
+ if (metadataItem.getName().startsWith(NAMESPACE)) {
+ AssetAttributeMeta wellKnownMeta = AssetAttributeMeta.byName(metadataItem.getName());
+ if (wellKnownMeta != null && wellKnownMeta.getAccess().protectedRead) {
+ protectedMetadata.add(
+ new MetadataItem(metadataItem.getName(), metadataItem.getValue_TODO_BUG_IN_JAVASCRIPT())
+ );
+ }
+ }
+ }
+ if (protectedMetadata.getJsonArray().length() > 0)
+ protectedAttribute.setMetadata(protectedMetadata);
+ }
+
+ filteredAttributes.put(protectedAttribute);
+ }
+ }
+ return filteredAttributes.getJsonObject();
+ }
+
+ protected JsonObject attributes;
+
+ public ProtectedAssetInfo() {
+ }
+
+ public ProtectedAssetInfo(Asset asset) {
+ this(asset.getId(), asset.getVersion(), asset.getName(), asset.getCreatedOn(), asset.getRealm(), asset.getType(), asset.getParentId(), asset.getCoordinates(), asset.getAttributes());
+ }
+
+ public ProtectedAssetInfo(String id, long version, String name, Date createdOn, String realm, String type, String parentId, double[] coordinates, JsonObject attributes) {
+ super(id, version, name, createdOn, realm, type, parentId, coordinates);
+ this.attributes = filterProtectedAttributes(attributes);
+ }
+
+ public JsonObject getAttributes() {
+ return attributes;
+ }
+
+ public void setAttributes(JsonObject attributes) {
+ this.attributes = attributes;
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/asset/ProtectedUserAssets.java b/model/src/main/java/org/openremote/model/asset/ProtectedUserAssets.java
new file mode 100644
index 000000000..d159073dc
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/asset/ProtectedUserAssets.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.asset;
+
+import java.util.*;
+
+import static org.openremote.model.Constants.NAMESPACE;
+
+/**
+ * An asset can be linked to many users, and a user can have links to many assets.
+ * <p>
+ * If a user has linked assets, it's a <em>restricted</em> user. Such a user can only
+ * access its assigned assets and their protected data, and it has a limited
+ * set of client operations available, see {@link AssetAttributeMeta.Access}:
+ * <ul>
+ * <li>
+ * When a restricted user client loads asset data, only protected asset details are included.
+ * </li>
+ * <li>
+ * When a restricted user client updates asset data, only a subset of protected data can be changed.
+ * </li>
+ * </ul>
+ * This mechanism is implemented with Keycloak user attributes:
+ * <p>
+ * The flag {@link #RESTRICTED_ATTRIBUTE} is set to <code>true</code> if the user
+ * has linked assets. This flag is also mapped into the user's access token as the claim
+ * {@link #RESTRICTED_CLAIM}, so access token receivers can check if the user is supposed
+ * to have a restriction to linked assets.
+ * <p>
+ * The actual linked assets identifiers are stored in {@link #ASSETS_ATTRIBUTE} and therefore
+ * in the Keycloak table <code>USER_ATTRIBUTES</code>. We query that table directly to retrieve
+ * the assets linked to a user.
+ */
+public class ProtectedUserAssets {
+
+ // Keycloak user attribute where the boolean flag "this user has linked assets" is stored
+ public static final String RESTRICTED_ATTRIBUTE = NAMESPACE + ":restrictedUser";
+
+ // Keycloak user attribute where the actual linked asset identifiers are stored
+ public static final String ASSETS_ATTRIBUTE = NAMESPACE + ":userAssets";
+
+ // Name of the claim in a user's access token where the "this user has linked assets" flag can be found
+ public static final String RESTRICTED_CLAIM = "openremoteRestrictedUser";
+
+ // Map the user attribute to the claim
+ public static final Map<String, String> RESTRICTED_MAPPER = new HashMap<String, String>() {
+ {
+ put("user.attribute", ProtectedUserAssets.RESTRICTED_ATTRIBUTE);
+ put("claim.name", ProtectedUserAssets.RESTRICTED_CLAIM);
+ put("access.token.claim", "true"); // Put it in the access token
+ put("jsonType.label", "boolean"); // As a boolean JSON value
+ }
+ };
+
+ /**
+ * @return The user attributes containing the linked assets and the <em>restricted</em> flag to be stored in Keycloak.
+ */
+ public static Map<String, List<String>> createUserAttributes(String... assetId) {
+ Map<String, List<String>> userAttributes = new HashMap<>();
+ setAssetsOnUserAttributes(userAttributes, assetId);
+ return userAttributes;
+ }
+
+ public static void setAssetsOnUserAttributes(Map<String, List<String>> userAttributes, String... assetId) {
+ if (assetId != null && assetId.length > 0) {
+ userAttributes.put(ASSETS_ATTRIBUTE, new ArrayList<>(Arrays.asList(assetId)));
+ userAttributes.put(RESTRICTED_ATTRIBUTE, new ArrayList<>(Collections.singletonList("true")));
+ } else {
+ userAttributes.remove(ASSETS_ATTRIBUTE);
+ userAttributes.remove(RESTRICTED_ATTRIBUTE);
+ }
+ }
+
+ public static boolean isRestrictedUser(Map<String, Object> accessTokenClaims) {
+ if (!accessTokenClaims.containsKey(RESTRICTED_CLAIM))
+ return false;
+ return (Boolean) accessTokenClaims.get(RESTRICTED_CLAIM);
+ }
+
+ public static String[] getAssetIdsFromUserAttributes(List<Object[]> userAttributes) {
+ List<String> assetIds = new ArrayList<>();
+ for (Object[] userAttribute : userAttributes) {
+ String name = (String) userAttribute[0];
+ String value = (String) userAttribute[1];
+ if (name.equals(ASSETS_ATTRIBUTE))
+ assetIds.add(value);
+ }
+ return assetIds.toArray(new String[assetIds.size()]);
+ }
+
+}
diff --git a/model/src/main/java/org/openremote/model/asset/ThingAttribute.java b/model/src/main/java/org/openremote/model/asset/ThingAttribute.java
index 89554a96d..224c646d7 100644
--- a/model/src/main/java/org/openremote/model/asset/ThingAttribute.java
+++ b/model/src/main/java/org/openremote/model/asset/ThingAttribute.java
@@ -26,8 +26,6 @@ import org.openremote.model.AttributeRef;
public class ThingAttribute extends Attribute {
- public static final String META_NAME_LINK = "urn:openremote:agent:link";
-
final protected ProtocolConfiguration protocolConfiguration;
final protected String thingId;
@@ -36,8 +34,8 @@ public class ThingAttribute extends Attribute {
}
static public AttributeRef getAgentLink(Attribute attribute) {
- JsonArray array = attribute.hasMetaItem(META_NAME_LINK)
- ? attribute.firstMetaItem(META_NAME_LINK).getValueAsArray()
+ JsonArray array = attribute.hasMetaItem(AssetAttributeMeta.AGENT_LINK)
+ ? attribute.firstMetaItem(AssetAttributeMeta.AGENT_LINK).getValueAsArray()
: null;
if (array == null || array.length() != 2)
return null;