Skip to content

armgit / core

Public Imported from GitHub
0

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

Removed AssetResource#readAttributeValue(), introduced ReadAttributesEvent, improved permission checking on attribute writes

Christian Bauerea45431a0358
diff --git a/container/src/main/java/org/openremote/container/security/IdentityService.java b/container/src/main/java/org/openremote/container/security/IdentityService.java
index c41e1c108..86256a52f 100644
--- a/container/src/main/java/org/openremote/container/security/IdentityService.java
+++ b/container/src/main/java/org/openremote/container/security/IdentityService.java
@@ -141,7 +141,7 @@ public abstract class IdentityService implements ContainerService {
.port(getInteger(container.getConfig(), KEYCLOAK_PORT, KEYCLOAK_PORT_DEFAULT))
.path(KeycloakResource.KEYCLOAK_CONTEXT_PATH);
- LOG.info("Keycloak service/token issuer URL: " + keycloakServiceUri.build());
+ LOG.info("Keycloak service URL: " + keycloakServiceUri.build());
// This client sets a custom Host header on outgoing requests, acting like a reverse proxy that "preserves"
// the Host header. Keycloak will verify token issuer name based on this, so it must match the external host
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewActivity.java b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewActivity.java
index 3d838985d..d39c5ee5e 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewActivity.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewActivity.java
@@ -20,8 +20,6 @@
package org.openremote.manager.client.assets.asset;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
-import elemental.json.Json;
-import elemental.json.JsonValue;
import org.openremote.manager.client.Environment;
import org.openremote.manager.client.TenantMapper;
import org.openremote.manager.client.assets.AssetMapper;
@@ -31,8 +29,6 @@ import org.openremote.manager.client.assets.browser.AssetBrowserSelection;
import org.openremote.manager.client.assets.browser.AssetTreeNode;
import org.openremote.manager.client.assets.browser.TenantTreeNode;
import org.openremote.manager.client.assets.tenant.AssetsTenantPlace;
-import org.openremote.model.event.bus.EventBus;
-import org.openremote.model.event.bus.EventRegistration;
import org.openremote.manager.client.interop.elemental.JsonObjectMapper;
import org.openremote.manager.client.map.MapView;
import org.openremote.manager.shared.asset.AssetResource;
@@ -40,8 +36,9 @@ import org.openremote.manager.shared.http.EntityWriter;
import org.openremote.manager.shared.map.MapResource;
import org.openremote.manager.shared.security.Tenant;
import org.openremote.manager.shared.security.TenantResource;
-import org.openremote.model.Runnable;
import org.openremote.model.asset.AssetAttribute;
+import org.openremote.model.event.bus.EventBus;
+import org.openremote.model.event.bus.EventRegistration;
import javax.inject.Inject;
import java.util.Collection;
@@ -182,22 +179,6 @@ public class AssetViewActivity
view.getAttributesBrowserContainer(),
asset
) {
- @Override
- protected void readAttributeValue(AssetAttribute attribute, Runnable onSuccess) {
- environment.getRequestService().execute(
- value -> value,
- requestParams -> assetResource.readAttributeValue(requestParams, assetId, attribute.getName()),
- 200,
- result -> {
- JsonValue value = Json.instance().parse(result);
- // TODO Bug in Elemental, can't check this value for null etc.
- attribute.setValueUnchecked(value);
- onSuccess.run();
- },
- ex -> handleRequestException(ex, environment)
- );
- }
-
@Override
protected void writeAttributeValue(AssetAttribute attribute) {
environment.getRequestService().execute(
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesBrowser.java b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesBrowser.java
index e0a9b41dc..94742f16d 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesBrowser.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesBrowser.java
@@ -25,8 +25,9 @@ import com.google.gwt.user.client.ui.Widget;
import elemental.client.Browser;
import org.openremote.manager.client.Environment;
import org.openremote.manager.client.widget.*;
+import org.openremote.model.Attribute;
import org.openremote.model.AttributeEvent;
-import org.openremote.model.Runnable;
+import org.openremote.model.ReadAttributesEvent;
import org.openremote.model.asset.Asset;
import org.openremote.model.asset.AssetAttribute;
import org.openremote.model.asset.AssetAttributes;
@@ -35,6 +36,7 @@ import org.openremote.model.event.bus.EventRegistration;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
+import java.util.stream.Collectors;
public abstract class AttributesBrowser
extends AttributesView<AttributesBrowser.Container, AttributesBrowser.Style, AssetAttributes, AssetAttribute> {
@@ -58,6 +60,19 @@ public abstract class AttributesBrowser
public AttributesBrowser(Environment environment, Container container, Asset asset) {
super(environment, container, new AssetAttributes(asset));
this.asset = asset;
+
+ eventRegistration = environment.getEventBus().register(
+ AttributeEvent.class,
+ event -> {
+ for (AssetAttribute assetAttribute : attributeGroups.keySet()) {
+ if (assetAttribute.getReference().equals(event.getAttributeRef())) {
+ assetAttribute.setValueUnchecked(event.getValue(), event.getTimestamp());
+ rebuildEditor(assetAttribute);
+ break;
+ }
+ }
+ }
+ );
}
@Override
@@ -78,7 +93,13 @@ public abstract class AttributesBrowser
@Override
public void close() {
super.close();
- enableLiveUpdates(false);
+
+ if (eventRegistration != null) {
+ environment.getEventBus().remove(eventRegistration);
+ eventRegistration = null;
+ }
+
+ subscribeToLiveUpdates(false);
}
@Override
@@ -95,22 +116,13 @@ public abstract class AttributesBrowser
writeValueButton.setText(container.getMessages().write());
writeValueButton.setPrimary(true);
writeValueButton.setIcon("cloud-upload");
- writeValueButton.addClickHandler(clickEvent -> {
- writeAttributeValue(attribute);
- /* TODO implement
- environment.getEventService().dispatch(
- new AttributeEvent(attribute.getState())
- );
- */
- });
+ writeValueButton.addClickHandler(clickEvent -> writeAttributeValue(attribute));
formGroupActions.add(writeValueButton);
FormButton readValueButton = new FormButton();
readValueButton.setText(container.getMessages().read());
readValueButton.setIcon("cloud-download");
- readValueButton.addClickHandler(clickEvent -> readAttributeValue(attribute, () -> {
- rebuildEditor(attribute);
- }));
+ readValueButton.addClickHandler(clickEvent -> readAttributeValue(attribute));
readButtons.add(readValueButton);
formGroupActions.add(readValueButton);
}
@@ -124,6 +136,21 @@ public abstract class AttributesBrowser
/* ####################################################################### */
+ protected void readAllAttributeValues() {
+ environment.getEventService().dispatch(
+ new ReadAttributesEvent(
+ asset.getId(),
+ attributeGroups.keySet().stream().map(Attribute::getName).collect(Collectors.toList())
+ )
+ );
+ }
+
+ protected void readAttributeValue(AssetAttribute attribute) {
+ environment.getEventService().dispatch(
+ new ReadAttributesEvent(attribute.getAssetId(), attribute.getName())
+ );
+ }
+
protected FormGroup createLiveUpdatesGroup() {
FormGroup formGroup = new FormGroup();
@@ -134,7 +161,7 @@ public abstract class AttributesBrowser
formGroup.addFormField(formField);
FormCheckBox liveUpdatesCheckBox = new FormCheckBox();
- liveUpdatesCheckBox.addValueChangeHandler(event -> enableLiveUpdates(event.getValue()));
+ liveUpdatesCheckBox.addValueChangeHandler(event -> subscribeToLiveUpdates(event.getValue()));
formField.add(liveUpdatesCheckBox);
if (attributes.size() > 0) {
@@ -142,7 +169,7 @@ public abstract class AttributesBrowser
FormButton readAllButton = new FormButton();
readAllButton.setText("Read and refresh all attributes");
- readAllButton.addClickHandler(event -> showInfo("TODO: Not implemented"));
+ readAllButton.addClickHandler(event -> readAllAttributeValues());
formGroupActions.add(readAllButton);
readButtons.add(readAllButton);
@@ -153,29 +180,12 @@ public abstract class AttributesBrowser
return formGroup;
}
- protected void enableLiveUpdates(boolean enable) {
+ protected void subscribeToLiveUpdates(boolean enable) {
for (FormButton readButton : readButtons) {
readButton.setEnabled(!enable);
}
- if (eventRegistration != null) {
- environment.getEventBus().remove(eventRegistration);
- eventRegistration = null;
- }
-
if (enable) {
- eventRegistration = environment.getEventBus().register(
- AttributeEvent.class,
- event -> {
- for (AssetAttribute assetAttribute : attributeGroups.keySet()) {
- if (assetAttribute.getReference().equals(event.getAttributeRef())) {
- assetAttribute.setValueUnchecked(event.getValue(), event.getTimestamp());
- rebuildEditor(assetAttribute);
- break;
- }
- }
- }
- );
environment.getEventService().subscribe(
AttributeEvent.class,
new AttributeEvent.EntityIdFilter(asset.getId())
@@ -217,8 +227,6 @@ public abstract class AttributesBrowser
/* ####################################################################### */
- abstract protected void readAttributeValue(AssetAttribute attribute, Runnable onSuccess);
-
abstract protected void writeAttributeValue(AssetAttribute attribute);
}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/service/EventService.java b/manager/client/src/main/java/org/openremote/manager/client/service/EventService.java
index 1e3fe18e8..e1e528701 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/service/EventService.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/service/EventService.java
@@ -32,9 +32,9 @@ import org.openremote.model.event.shared.SharedEvent;
* If your subscription fails, a {@link org.openremote.manager.client.event.SubscriptionFailureEvent}
* will be dispatched on the event bus.
* <p>
- * Events can be send to the server with {@link #dispatch}, dispatching any kind
- * of event (even {@link SharedEvent}s) on the local event bus will only dispatch
- * the events locally and not send them to the server.
+ * Events can be send to the server with {@link #dispatch}. This is how the client
+ * sends events to the server, because dispatching events on the local event bus
+ * will not send them to the server.
*/
public interface EventService {
diff --git a/manager/client/src/main/webapp/css/theme.html b/manager/client/src/main/webapp/css/theme.html
index 066e89080..d29bce0a9 100644
--- a/manager/client/src/main/webapp/css/theme.html
+++ b/manager/client/src/main/webapp/css/theme.html
@@ -277,14 +277,14 @@
.or-FormTreeItemImage {
}
- .or-FormTreeTopItem{
+ .or-FormTreeTopItem {
}
.or-FormTreeKeyboardSelectedItem {
background-color: var(--theme-mediumgrey);
}
- .or-FormTreeKeyboardSelectedItem .or-FormTreeIcon{
+ .or-FormTreeKeyboardSelectedItem .or-FormTreeIcon {
color: var(--theme-white);
}
@@ -356,6 +356,13 @@
.or-HighlightBackground {
background-color: var(--theme-lightgreen);
+ border-color: transparent;
+ color: white;
+ }
+
+ .or-HighlightBackground .or-FormControl {
+ color: var(--theme-white);
+ border-color: transparent;
}
</style>
\ No newline at end of file
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 63a31fdb9..1d965f885 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
@@ -26,7 +26,6 @@ import org.openremote.manager.server.web.ManagerWebResource;
import org.openremote.manager.shared.asset.AssetResource;
import org.openremote.manager.shared.http.RequestParams;
import org.openremote.manager.shared.security.Tenant;
-import org.openremote.model.Attribute;
import org.openremote.model.AttributeEvent;
import org.openremote.model.AttributeRef;
import org.openremote.model.asset.Asset;
@@ -227,9 +226,22 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
@Override
public void writeAttributeValue(RequestParams requestParams, String assetId, String attributeName, String rawJson) {
try {
- ServerAsset asset = assetStorageService.find(assetId, true, false);
- if (asset == null)
- throw new WebApplicationException(NOT_FOUND);
+
+ ServerAsset asset;
+
+ if (isRestrictedUser()) {
+ asset = assetStorageService.find(assetId, true, true);
+ if (asset == null)
+ throw new WebApplicationException(NOT_FOUND);
+
+ if (!assetStorageService.isUserAsset(getUserId(), assetId))
+ throw new WebApplicationException(Response.Status.FORBIDDEN);
+
+ } else {
+ asset = assetStorageService.find(assetId, true);
+ if (asset == null)
+ throw new WebApplicationException(NOT_FOUND);
+ }
// Check attribute exists
AssetAttributes attributes = new AssetAttributes(asset);
@@ -242,9 +254,8 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
throw new WebApplicationException(Response.Status.FORBIDDEN);
}
- // Check restricted
- if (isRestrictedUser() &&
- !assetStorageService.isUserAsset(getUserId(), asset.getId())) {
+ // Check read-only
+ if (!isSuperUser() && attributes.get(attributeName).isReadOnly()) {
throw new WebApplicationException(Response.Status.FORBIDDEN);
}
@@ -263,39 +274,6 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
}
}
- @Override
- public String readAttributeValue(RequestParams requestParams, String assetId, String attributeName) {
- try {
- ServerAsset asset = assetStorageService.find(assetId, true, false);
- if (asset == null)
- throw new WebApplicationException(NOT_FOUND);
-
- // Check realm, must be accessible
- if (!isTenantActiveAndAccessible(asset)) {
- LOG.fine("Forbidden access for user '" + getUsername() + "': " + asset);
- throw new WebApplicationException(Response.Status.FORBIDDEN);
- }
-
- // Check restricted
- if (isRestrictedUser() &&
- !assetStorageService.isUserAsset(getUserId(), asset.getId())) {
- throw new WebApplicationException(Response.Status.FORBIDDEN);
- }
-
- AssetAttributes attributes = new AssetAttributes(asset);
- Attribute attribute = attributes.get(attributeName);
- if (attribute == null) {
- throw new WebApplicationException(NOT_FOUND);
- }
-
- // No idea why toJson() would produce a Java null instead of a "null" literal, but it does
- return attribute.hasValue() ? attribute.getValue().toJson() : "null";
-
- } catch (IllegalStateException ex) {
- throw new WebApplicationException(ex, Response.Status.BAD_REQUEST);
- }
- }
-
@Override
public void create(RequestParams requestParams, Asset asset) {
try {
diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java
index bae6fb9e6..b7ebbbc13 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java
@@ -31,18 +31,21 @@ import org.openremote.container.persistence.PersistenceEvent;
import org.openremote.container.persistence.PersistenceService;
import org.openremote.container.util.Pair;
import org.openremote.container.web.WebService;
+import org.openremote.container.web.socket.WebsocketAuth;
import org.openremote.manager.server.event.EventService;
import org.openremote.manager.server.security.ManagerIdentityService;
import org.openremote.manager.shared.security.ClientRole;
import org.openremote.manager.shared.security.Tenant;
import org.openremote.model.Attribute;
import org.openremote.model.AttributeEvent;
+import org.openremote.model.ReadAttributesEvent;
import org.openremote.model.asset.*;
import org.postgresql.util.PGobject;
import javax.persistence.EntityManager;
import java.sql.*;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
@@ -50,6 +53,9 @@ import java.util.logging.Logger;
import static org.openremote.container.persistence.PersistenceEvent.PERSISTENCE_TOPIC;
import static org.openremote.manager.server.asset.AssetPredicates.isPersistenceEventForEntityType;
+import static org.openremote.manager.server.event.EventService.INCOMING_EVENT_TOPIC;
+import static org.openremote.manager.server.event.EventService.getSessionKey;
+import static org.openremote.manager.server.event.EventService.getWebsocketAuth;
public class AssetStorageService extends RouteBuilder implements ContainerService, Consumer<AssetState> {
@@ -137,6 +143,37 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
from(PERSISTENCE_TOPIC)
.filter(isPersistenceEventForEntityType(ServerAsset.class))
.process(exchange -> publishModificationEvents(exchange.getIn().getBody(PersistenceEvent.class)));
+
+ // React if a client wants to read attribute state
+ from(INCOMING_EVENT_TOPIC)
+ .filter(body().isInstanceOf(ReadAttributesEvent.class))
+ .process(exchange -> {
+ ReadAttributesEvent event = exchange.getIn().getBody(ReadAttributesEvent.class);
+ String sessionKey = getSessionKey(exchange);
+ WebsocketAuth auth = getWebsocketAuth(exchange);
+
+ // Superuser can get all
+ if (auth.isSuperUser()) {
+ ServerAsset asset = find(event.getEntityId(), true);
+ if (asset != null)
+ replyWithAttributeEvents(sessionKey, asset, Arrays.asList(event.getAttributeNames()));
+ return;
+ }
+
+ // User must have role
+ if (!auth.isUserInRole(ClientRole.READ_ASSETS.getValue())) {
+ return;
+ }
+
+ ServerAsset asset = find(
+ event.getEntityId(),
+ true,
+ managerIdentityService.isRestrictedUser(auth.getUserId()) // Restricted users get filtered state
+ );
+ if (asset != null)
+ replyWithAttributeEvents(sessionKey, asset, Arrays.asList(event.getAttributeNames()));
+ });
+
}
public ServerAsset find(String assetId) {
@@ -641,6 +678,14 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
}
}
+ protected void replyWithAttributeEvents(String sessionKey, ServerAsset asset, List<String> attributeNames) {
+ LOG.fine("For client session '" + sessionKey + "', reading asset attributes " + attributeNames + " on: " + asset);
+ new AssetAttributes(asset).get().stream()
+ .filter(assetAttribute -> attributeNames.contains(assetAttribute.getName()))
+ .map(AbstractAssetAttribute::getStateEvent)
+ .forEach(attributeEvent -> eventService.sendToSession(sessionKey, attributeEvent));
+ }
+
public String toString() {
return getClass().getSimpleName() + "{" +
'}';
diff --git a/manager/server/src/main/java/org/openremote/manager/server/event/EventService.java b/manager/server/src/main/java/org/openremote/manager/server/event/EventService.java
index e4f412b9f..5d5521a8c 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/event/EventService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/event/EventService.java
@@ -62,6 +62,11 @@ import static org.apache.camel.builder.PredicateBuilder.or;
* The payload is a serialized representation of {@link CancelEventSubscription}. If a client
* does not want to wait for expiration of its subscriptions, it can cancel a subscription.
* </p></dd>
+ * <dt><code>EVENT{...}</code></dt>
+ * <dd><p>
+ * The payload is a serialized representation of a subtype of {@link SharedEvent}. If the server
+ * does not recognize the event, it is silently ignored.
+ * </p></dd>
* </dl>
* <p>
* The following messages can be published/returned by the server:
@@ -153,15 +158,11 @@ public class EventService implements ContainerService {
String sessionKey = getSessionKey(exchange);
eventSubscriptions.cancel(sessionKey, exchange.getIn().getBody(CancelEventSubscription.class));
})
- /* TODO Implement properly
.when(bodyAs(String.class).startsWith(SharedEvent.MESSAGE_PREFIX))
.convertBodyTo(SharedEvent.class)
- .to(EventService.INCOMING_EVENT_TOPIC) // TODO SECURITY!
- */
+ .to(EventService.INCOMING_EVENT_TOPIC)
.otherwise()
- .process(exchange -> {
- LOG.fine("Unsupported message body: " + exchange.getIn().getBody());
- })
+ .process(exchange -> LOG.fine("Unsupported message body: " + exchange.getIn().getBody()))
.end();
from(EventService.OUTGOING_EVENT_QUEUE)
@@ -197,7 +198,7 @@ public class EventService implements ContainerService {
);
}
- protected void sendToSession(String sessionKey, Object data) {
+ public void sendToSession(String sessionKey, Object data) {
LOG.fine("Sending to session '" + sessionKey + "': " + data);
messageBrokerService.getProducerTemplate().sendBodyAndHeader(
"websocket://" + WEBSOCKET_EVENTS,
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 a1140d7a2..720b3244c 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
@@ -46,7 +46,7 @@ import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
* {@link org.openremote.model.asset.UserAsset}).
* <p>
* The only operations a restricted user is able to perform are {@link #getCurrentUserAssets},
- * {@link #get}, {@link #update}, {@link #readAttributeValue} and {@link #writeAttributeValue}.
+ * {@link #get}, {@link #update}, and {@link #writeAttributeValue}.
* </li>
* </ul>
*/
@@ -102,7 +102,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 its authenticated realm, or if the
- * user is restricted and the asset is not linked to the user.
+ * user is restricted and the asset is not linked to the user. All asset details (path, attributes)
+ * will be populated, the asset is loaded completely.
*/
@GET
@Path("{assetId}")
@@ -141,20 +142,6 @@ public interface AssetResource {
@RolesAllowed({"write:assets"})
void writeAttributeValue(@BeanParam RequestParams requestParams, @PathParam("assetId") String assetId, @PathParam("attributeName") String attributeName, String rawJson);
- /**
- * Reads the attribute state of an 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 its
- * authenticated realm, or if the user is restricted and the asset to read is not in the set of linked
- * assets of the restricted user.
- */
- @GET
- @Path("{assetId}/attribute/{attributeName}")
- @Produces(APPLICATION_JSON)
- @SuccessStatusCode(200)
- @RolesAllowed({"read:assets"})
- String readAttributeValue(@BeanParam RequestParams requestParams, @PathParam("assetId") String assetId, @PathParam("attributeName") String attributeName);
-
/**
* 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
diff --git a/manager/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy
index 5f02051e1..cd1839632 100644
--- a/manager/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy
@@ -84,7 +84,6 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTrait
then: "the attribute value should match"
new AssetAttributes(testAsset).get("foo").getValueAsString() == "bar2"
- assetResource.readAttributeValue(null, testAsset.getId(), "foo") == "\"bar2\""
when: "an asset attribute value null is written directly"
assetResource.writeAttributeValue(null, testAsset.getId(), "foo", "null")
@@ -92,7 +91,6 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTrait
then: "the attribute value should match"
!new AssetAttributes(testAsset).get("foo").hasValue()
- assetResource.readAttributeValue(null, testAsset.getId(), "foo") == "null"
when: "an asset is updated with a different type"
testAsset = assetResource.get(null, testAsset.getId())
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 62f952649..42d05fdbf 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
@@ -101,25 +101,6 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
then: "result should match"
demoSmartHome.id == managerDemoSetup.smartHomeId
- when: "an asset attribute is read in the authenticated realm"
- def attributeValue = assetResource.readAttributeValue(null, managerDemoSetup.smartOfficeId, "geoStreet")
-
- then: "result should match"
- attributeValue == Json.create("Torenallee 20").toJson()
-
- when: "an non-existent attribute is read in the authenticated realm"
- assetResource.readAttributeValue(null, managerDemoSetup.smartOfficeId, "doesnotexist")
-
- then: "the attribute should be not found"
- WebApplicationException ex = thrown()
- ex.response.status == 404
-
- when: "an asset attribute is read in a foreign realm"
- attributeValue = assetResource.readAttributeValue(null, managerDemoSetup.smartHomeId, "geoStreet")
-
- then: "result should match"
- attributeValue == Json.create("Wilhelminaplein 21C").toJson()
-
/* ############################################## WRITE ####################################### */
when: "an asset is created in the authenticated realm"
@@ -166,7 +147,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
assetResource.get(null, managerDemoSetup.thingId)
then: "the asset should not be found"
- ex = thrown()
+ WebApplicationException ex = thrown()
ex.response.status == 404
when: "an asset is deleted in a foreign realm"
@@ -179,10 +160,10 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
when: "an asset attribute is written in the authenticated realm"
assetResource.writeAttributeValue(null, managerDemoSetup.smartOfficeId, "geoStreet", Json.create("Teststreet 123").toJson())
- attributeValue = assetResource.readAttributeValue(null, managerDemoSetup.smartOfficeId, "geoStreet")
+ def asset = assetResource.get(null, managerDemoSetup.smartOfficeId)
then: "result should match"
- attributeValue == Json.create("Teststreet 123").toJson()
+ new AssetAttributes(asset).get("geoStreet").getValue().toJson() == Json.create("Teststreet 123").toJson()
when: "an non-existent attribute is written in the authenticated realm"
assetResource.writeAttributeValue(null, "doesnotexist", "geoStreet", Json.create("Teststreet 123").toJson())
@@ -200,10 +181,10 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
when: "an asset attribute is written in a foreign realm"
assetResource.writeAttributeValue(null, managerDemoSetup.smartHomeId, "geoStreet", Json.create("Teststreet 456").toJson())
- attributeValue = assetResource.readAttributeValue(null, managerDemoSetup.smartHomeId, "geoStreet")
+ asset = assetResource.get(null, managerDemoSetup.smartHomeId)
then: "result should match"
- attributeValue == Json.create("Teststreet 456").toJson()
+ new AssetAttributes(asset).get("geoStreet").getValue().toJson() == Json.create("Teststreet 456").toJson()
cleanup: "the server should be stopped"
stopContainer(container)
@@ -288,19 +269,6 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
WebApplicationException ex = thrown()
ex.response.status == 403
- when: "an asset attribute is read in the authenticated realm"
- def attributeValue = assetResource.readAttributeValue(null, managerDemoSetup.smartOfficeId, "geoStreet")
-
- then: "result should match"
- attributeValue == Json.create("Torenallee 20").toJson()
-
- when: "an asset attribute is read in a foreign realm"
- assetResource.readAttributeValue(null, managerDemoSetup.smartHomeId, "geoStreet")
-
- then: "access should be forbidden"
- ex = thrown()
- ex.response.status == 403
-
/* ############################################## WRITE ####################################### */
when: "an asset is created in the authenticated realm"
@@ -358,10 +326,10 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
when: "an asset attribute is written in the authenticated realm"
assetResource.writeAttributeValue(null, managerDemoSetup.smartOfficeId, "geoStreet", Json.create("Teststreet 123").toJson())
- attributeValue = assetResource.readAttributeValue(null, managerDemoSetup.smartOfficeId, "geoStreet")
+ def asset = assetResource.get(null, managerDemoSetup.smartOfficeId)
then: "result should match"
- attributeValue == Json.create("Teststreet 123").toJson()
+ new AssetAttributes(asset).get("geoStreet").getValue().toJson() == Json.create("Teststreet 123").toJson()
when: "an asset attribute is written in a foreign realm"
assetResource.writeAttributeValue(null, managerDemoSetup.smartHomeId, "geoStreet", Json.create("Teststreet 456").toJson())
@@ -444,19 +412,6 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
WebApplicationException ex = thrown()
ex.response.status == 403
- when: "an asset attribute is read in the authenticated realm"
- def attributeValue = assetResource.readAttributeValue(null, managerDemoSetup.smartHomeId, "geoStreet")
-
- then: "result should match"
- attributeValue == Json.create("Wilhelminaplein 21C").toJson()
-
- when: "an asset attribute is read in a foreign realm"
- assetResource.readAttributeValue(null, managerDemoSetup.smartOfficeId, "geoStreet")
-
- then: "access should be forbidden"
- ex = thrown()
- ex.response.status == 403
-
/* ############################################## WRITE ####################################### */
when: "an asset is created in a foreign realm"
@@ -635,26 +590,6 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
ex = thrown()
ex.response.status == 403
- when: "an asset attribute is read on a user asset"
- def attributeValue = assetResource.readAttributeValue(null, managerDemoSetup.apartment1LivingroomId, "lightSwitch")
-
- then: "result should match"
- attributeValue == Json.create(true).toJson()
-
- when: "an asset attribute is read in a foreign realm"
- assetResource.readAttributeValue(null, managerDemoSetup.smartOfficeId, "geoStreet")
-
- then: "access should be forbidden"
- ex = thrown()
- ex.response.status == 403
-
- when: "an asset attribute is read on a non-user asset"
- assetResource.readAttributeValue(null, managerDemoSetup.apartment3LivingroomId, "lightSwitch")
-
- then: "access should be forbidden"
- ex = thrown()
- ex.response.status == 403
-
/* ############################################## WRITE ####################################### */
when: "an asset is created in a foreign realm"
@@ -698,12 +633,26 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
ex = thrown()
ex.response.status == 403
- when: "an asset attribute is written on a user asset"
+ when: "a private asset attribute is written on a user asset"
assetResource.writeAttributeValue(null, managerDemoSetup.apartment1LivingroomId, "lightSwitch", Json.create(false).toJson())
- attributeValue = assetResource.readAttributeValue(null, managerDemoSetup.apartment1LivingroomId, "lightSwitch")
+
+ then: "the attribute should be not found"
+ ex = thrown()
+ ex.response.status == 404
+
+ when: "a protected read-only asset attribute is written on a user asset"
+ assetResource.writeAttributeValue(null, managerDemoSetup.apartment1LivingroomThermostatId, "currentTemperature", Json.create(22.123).toJson())
+
+ then: "the request should be forbidden"
+ ex = thrown()
+ ex.response.status == 403
+
+ when: "a protected asset attribute is written on a user asset"
+ assetResource.writeAttributeValue(null, managerDemoSetup.apartment1LivingroomThermostatId, "comfortTemperature", Json.create(22.123).toJson())
+ def asset = assetResource.get(null, managerDemoSetup.apartment1LivingroomThermostatId)
then: "result should match"
- attributeValue == Json.create(false).toJson()
+ new AssetAttributes(asset).get("comfortTemperature").getValue().toJson() == Json.create(22.123).toJson()
when: "an attribute is written on a non-existent user asset"
assetResource.writeAttributeValue(null, "doesnotexist", "lightSwitch", Json.create(false).toJson())
diff --git a/model/src/main/java/org/openremote/model/ReadAttributesEvent.java b/model/src/main/java/org/openremote/model/ReadAttributesEvent.java
new file mode 100644
index 000000000..3ed35e599
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/ReadAttributesEvent.java
@@ -0,0 +1,75 @@
+/*
+ * 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;
+
+import org.openremote.model.event.shared.SharedEvent;
+
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * A client sends this event to the server to refresh its attribute state, expecting
+ * the server to answer "soon" with {@link AttributeEvent}s. If the server
+ * decides that the client doesn't have the right permissions, or if anything
+ * else is not in order (e.g. the entity doesn't exist), the server might not react
+ * at all.
+ */
+public class ReadAttributesEvent extends SharedEvent {
+
+ protected String entityId;
+
+ protected String[] attributeNames;
+
+ protected ReadAttributesEvent() {
+ }
+
+ public ReadAttributesEvent(String entityId, String... attributeNames) {
+ this.entityId = entityId;
+ this.attributeNames = attributeNames;
+ }
+
+ public ReadAttributesEvent(String entityId, List<String> attributeNames) {
+ this(entityId, attributeNames.toArray(new String[attributeNames.size()]));
+ }
+
+ public String getEntityId() {
+ return entityId;
+ }
+
+ public void setEntityId(String entityId) {
+ this.entityId = entityId;
+ }
+
+ public String[] getAttributeNames() {
+ return attributeNames;
+ }
+
+ public void setAttributeNames(String[] attributeNames) {
+ this.attributeNames = attributeNames;
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "entityId='" + entityId + '\'' +
+ ", attributeNames=" + Arrays.toString(attributeNames) +
+ '}';
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/event/shared/SharedEvent.java b/model/src/main/java/org/openremote/model/event/shared/SharedEvent.java
index ca60ba83c..7a343429e 100644
--- a/model/src/main/java/org/openremote/model/event/shared/SharedEvent.java
+++ b/model/src/main/java/org/openremote/model/event/shared/SharedEvent.java
@@ -23,6 +23,7 @@ import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.openremote.model.AttributeEvent;
+import org.openremote.model.ReadAttributesEvent;
import org.openremote.model.asset.AssetTreeModifiedEvent;
import org.openremote.model.event.Event;
@@ -32,6 +33,7 @@ import org.openremote.model.event.Event;
@JsonSubTypes({
// Events used on client and server (serializable)
@JsonSubTypes.Type(value = AttributeEvent.class, name = "attribute"),
+ @JsonSubTypes.Type(value = ReadAttributesEvent.class, name = "read-attributes"),
@JsonSubTypes.Type(value = AssetTreeModifiedEvent.class, name = "asset-tree-modified")
})
@JsonTypeInfo(