Skip to content

armgit / core

Public Imported from GitHub
0

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

Work on asset processing routes

Christian Bauer425f644fe524
diff --git a/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java
index beef8ce1f..abfc9de1e 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java
@@ -33,13 +33,14 @@ import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeRef;
import org.openremote.model.attribute.AttributeState;
import org.openremote.model.attribute.MetaItem;
-import org.openremote.model.event.shared.SharedEvent;
import org.openremote.model.util.Triplet;
-import java.util.*;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
import java.util.function.Consumer;
import java.util.logging.Logger;
-import java.util.stream.Collectors;
public abstract class AbstractProtocol implements Protocol {
@@ -103,6 +104,7 @@ public abstract class AbstractProtocol implements Protocol {
}
}
+
@Override
public void linkProtocolConfiguration(AssetAttribute protocolConfiguration, Consumer<DeploymentStatus> deploymentStatusConsumer) {
synchronized (linkedProtocolConfigurations) {
@@ -172,24 +174,6 @@ public abstract class AbstractProtocol implements Protocol {
}
}
- @Override
- public List<AssetAttribute> getLinkedProtocolConfigurations() {
- synchronized (linkedProtocolConfigurations) {
- return linkedProtocolConfigurations
- .values()
- .stream()
- .map(triplet -> triplet.getValue1())
- .collect(Collectors.toList());
- }
- }
-
- @Override
- public List<AssetAttribute> getLinkedAttributes() {
- synchronized (linkedAttributes) {
- return new ArrayList<>(linkedAttributes.values());
- }
- }
-
/**
* Send an arbitrary {@link AttributeState} through the processing chain
* using the current system time as the timestamp. Use {@link #updateLinkedAttribute}
@@ -197,7 +181,7 @@ public abstract class AbstractProtocol implements Protocol {
* different messaging queue.
*/
protected void sendAttributeEvent(AttributeState state) {
- assetService.sendAttributeEvent(this, new AttributeEvent(state, timerService.getCurrentTimeMillis()));
+ sendAttributeEvent(new AttributeEvent(state, timerService.getCurrentTimeMillis()));
}
/**
@@ -206,7 +190,20 @@ public abstract class AbstractProtocol implements Protocol {
* additional verification and uses a different messaging queue.
*/
protected void sendAttributeEvent(AttributeEvent event) {
- assetService.sendAttributeEvent(this, event);
+ // Don't allow updating linked attributes with this mechanism as it could cause an infinite loop
+ synchronized (linkedAttributes) {
+ boolean isForLinkedAttribute = linkedAttributes.values()
+ .stream()
+ .anyMatch(attribute -> attribute.getReferenceOrThrow()
+ .equals(event.getAttributeRef())
+ );
+
+ if (isForLinkedAttribute) {
+ LOG.warning("Cannot update an attribute linked to the same protocol; use updateLinkedAttribute for that: " + event);
+ return;
+ }
+ }
+ assetService.sendAttributeEvent(event);
}
/**
@@ -215,11 +212,7 @@ public abstract class AbstractProtocol implements Protocol {
protected void updateLinkedAttribute(AttributeState state, long timestamp) {
AttributeEvent attributeEvent = new AttributeEvent(state, timestamp);
LOG.fine("Sending on sensor queue: " + attributeEvent);
- producerTemplate.sendBodyAndHeader(
- SENSOR_QUEUE,
- attributeEvent,
- SharedEvent.HEADER_SENDER,
- this);
+ producerTemplate.sendBodyAndHeader(SENSOR_QUEUE, attributeEvent, Protocol.SENSOR_QUEUE_SOURCE_PROTOCOL, getProtocolName());
}
/**
diff --git a/agent/src/main/java/org/openremote/agent/protocol/Protocol.java b/agent/src/main/java/org/openremote/agent/protocol/Protocol.java
index ecee566e6..b136b04e3 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/Protocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/Protocol.java
@@ -28,7 +28,6 @@ import org.openremote.model.asset.agent.ProtocolConfiguration;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeType;
import org.openremote.model.attribute.MetaItem;
-import org.openremote.model.event.shared.SharedEvent;
import org.openremote.model.value.ValueType;
import java.util.Collection;
@@ -67,7 +66,7 @@ import java.util.function.Consumer;
* If the actual state of the device (or service) changes, the linked protocol writes the new
* state into the attribute value and notifies the context broker of the change. A protocol updates
* a linked attributes' value by sending an {@link AttributeEvent} messages on the
- * {@link #SENSOR_QUEUE}, including the source protocol in header {@link SharedEvent#HEADER_SENDER}.
+ * {@link #SENSOR_QUEUE}, including the source protocol name in header {@link #SENSOR_QUEUE_SOURCE_PROTOCOL}.
* <p>
* If the user writes a new value into the linked attribute, the protocol translates this value
* change into a device (or service) action. Write operations on attributes linked to a protocol
@@ -171,6 +170,7 @@ public interface Protocol extends ContainerService {
}
String ACTUATOR_TOPIC_TARGET_PROTOCOL = "Protocol";
+ String SENSOR_QUEUE_SOURCE_PROTOCOL = "Protocol";
// TODO: Some of these options should be configurable depending on expected load etc.
@@ -182,10 +182,6 @@ public interface Protocol extends ContainerService {
String getProtocolName();
- List<AssetAttribute> getLinkedProtocolConfigurations();
-
- List<AssetAttribute> getLinkedAttributes();
-
/**
* Links attributes to their protocolConfiguration; the protocolConfiguration would have
* been linked before this call. If an attribute is not valid for this protocol or the protocol
diff --git a/agent/src/main/java/org/openremote/agent/protocol/ProtocolAssetService.java b/agent/src/main/java/org/openremote/agent/protocol/ProtocolAssetService.java
index 620b79516..37d4b4f19 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/ProtocolAssetService.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/ProtocolAssetService.java
@@ -37,6 +37,6 @@ public interface ProtocolAssetService extends ContainerService {
/**
* Protocols can send arbitrary attribute change events for regular processing.
*/
- void sendAttributeEvent(Protocol sender, AttributeEvent attributeEvent);
+ void sendAttributeEvent(AttributeEvent attributeEvent);
}
diff --git a/container/src/main/java/org/openremote/container/security/AccessTokenAuthContext.java b/container/src/main/java/org/openremote/container/security/AccessTokenAuthContext.java
new file mode 100644
index 000000000..ba9fb9ff8
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/security/AccessTokenAuthContext.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.container.security;
+
+import org.keycloak.representations.AccessToken;
+
+/**
+ * Keycloak-based authorization.
+ */
+public class AccessTokenAuthContext implements AuthContext {
+
+ final protected String authenticatedRealm;
+ final protected AccessToken accessToken;
+
+ public AccessTokenAuthContext(String authenticatedRealm, AccessToken accessToken) {
+ this.authenticatedRealm = authenticatedRealm;
+ this.accessToken = accessToken;
+ }
+
+ @Override
+ public String getAuthenticatedRealm() {
+ return authenticatedRealm;
+ }
+
+ @Override
+ public String getUsername() {
+ return accessToken.getPreferredUsername();
+ }
+
+ @Override
+ public String getUserId() {
+ return accessToken.getSubject();
+ }
+
+ @Override
+ public boolean hasRealmRole(String role) {
+ return accessToken.getRealmAccess().isUserInRole(role);
+ }
+
+ @Override
+ public boolean hasResourceRole(String role, String resource) {
+ return accessToken.getResourceAccess().containsKey(resource)
+ && accessToken.getResourceAccess().get(resource).isUserInRole(role);
+ }
+}
diff --git a/container/src/main/java/org/openremote/container/security/AuthContext.java b/container/src/main/java/org/openremote/container/security/AuthContext.java
new file mode 100644
index 000000000..f861f5663
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/security/AuthContext.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.container.security;
+
+import org.openremote.model.Constants;
+
+/**
+ * Services should use this interface to access a user's identity and perform authorization checks.
+ */
+public interface AuthContext {
+
+ String getAuthenticatedRealm();
+
+ String getUsername();
+
+ String getUserId();
+
+ /**
+ * @return <code>true</code> if the user is authenticated in the "master" realm and has the realm role "admin".
+ */
+ default boolean isSuperUser() {
+ return getAuthenticatedRealm().equals(Constants.MASTER_REALM) && hasRealmRole(Constants.REALM_ADMIN_ROLE);
+ }
+
+ boolean hasRealmRole(String role);
+
+ boolean hasResourceRole(String role, String resource);
+
+ default boolean hasResourceRoleOrIsSuperUser(String role, String resource) {
+ return hasResourceRole(role, resource) || isSuperUser();
+ }
+
+ /**
+ * @return <code>true</code> if the user is authenticated in the same realm or if the user is the superuser (admin).
+ */
+ default boolean isRealmAccessibleByUser(String realm) {
+ return realm != null && realm.length() > 0 && (realm.equals(getAuthenticatedRealm()) || isSuperUser());
+ }
+}
diff --git a/container/src/main/java/org/openremote/container/web/DefaultWebsocketComponent.java b/container/src/main/java/org/openremote/container/web/DefaultWebsocketComponent.java
index 7b18fd0c0..fe36af6d1 100644
--- a/container/src/main/java/org/openremote/container/web/DefaultWebsocketComponent.java
+++ b/container/src/main/java/org/openremote/container/web/DefaultWebsocketComponent.java
@@ -26,9 +26,15 @@ import io.undertow.servlet.util.ImmediateInstanceHandle;
import io.undertow.websockets.jsr.DefaultContainerConfigurator;
import io.undertow.websockets.jsr.UndertowContainerProvider;
import io.undertow.websockets.jsr.WebSocketDeploymentInfo;
+import org.keycloak.KeycloakPrincipal;
+import org.keycloak.KeycloakSecurityContext;
import org.openremote.container.message.MessageBrokerSetupService;
+import org.openremote.container.security.AccessTokenAuthContext;
import org.openremote.container.security.IdentityService;
-import org.openremote.container.web.socket.*;
+import org.openremote.container.web.socket.WebsocketAdapter;
+import org.openremote.container.web.socket.WebsocketCORSFilter;
+import org.openremote.container.web.socket.WebsocketComponent;
+import org.openremote.container.web.socket.WebsocketConstants;
import org.xnio.OptionMap;
import org.xnio.Options;
import org.xnio.Xnio;
@@ -38,8 +44,11 @@ import javax.servlet.Filter;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
+import javax.ws.rs.WebApplicationException;
import java.util.logging.Logger;
+import static javax.ws.rs.core.Response.Status.FORBIDDEN;
+
public class DefaultWebsocketComponent extends WebsocketComponent {
private static final Logger LOG = Logger.getLogger(DefaultWebsocketComponent.class.getName());
@@ -64,7 +73,7 @@ public class DefaultWebsocketComponent extends WebsocketComponent {
WebSocketDeploymentInfo webSocketDeploymentInfo = new WebSocketDeploymentInfo();
- getConsumers().entrySet().stream().forEach(consumerEntry -> {
+ getConsumers().entrySet().forEach(consumerEntry -> {
String endpointPath = MessageBrokerSetupService.WEBSOCKET_PATH + "/" + consumerEntry.getKey();
LOG.info("Deploying websocket endpoint: " + endpointPath);
webSocketDeploymentInfo.addEndpoint(
@@ -76,17 +85,26 @@ public class DefaultWebsocketComponent extends WebsocketComponent {
return (T) new WebsocketAdapter(consumerEntry.getValue());
}
+ @SuppressWarnings("unchecked")
@Override
public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {
+
+ KeycloakPrincipal<KeycloakSecurityContext> keycloakPrincipal =
+ (KeycloakPrincipal<KeycloakSecurityContext>) request.getUserPrincipal();
+ if (keycloakPrincipal == null) {
+ throw new WebApplicationException(
+ "Websocket session is not authenticated, can't access user principal", FORBIDDEN
+ );
+ }
+
config.getUserProperties().put(
- WebsocketConstants.AUTH,
- new WebsocketAuth(request.getUserPrincipal()) {
- @Override
- public boolean isUserInRole(String role) {
- return request.isUserInRole(role);
- }
- }
+ WebsocketConstants.HANDSHAKE_AUTH,
+ new AccessTokenAuthContext(
+ keycloakPrincipal.getKeycloakSecurityContext().getRealm(),
+ keycloakPrincipal.getKeycloakSecurityContext().getToken()
+ )
);
+
super.modifyHandshake(config, request, response);
}
})
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 2f8db151a..5c3f831ec 100644
--- a/container/src/main/java/org/openremote/container/web/WebResource.java
+++ b/container/src/main/java/org/openremote/container/web/WebResource.java
@@ -21,18 +21,17 @@ package org.openremote.container.web;
import org.keycloak.KeycloakPrincipal;
import org.keycloak.KeycloakSecurityContext;
-import org.keycloak.representations.AccessToken;
import org.openremote.container.Container;
-import org.openremote.model.Constants;
+import org.openremote.container.security.AccessTokenAuthContext;
+import org.openremote.container.security.AuthContext;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.*;
-import static javax.ws.rs.core.Response.Status.BAD_REQUEST;
import static javax.ws.rs.core.Response.Status.FORBIDDEN;
-public class WebResource {
+public class WebResource implements AuthContext {
@Context
protected Application application;
@@ -49,6 +48,8 @@ public class WebResource {
@Context
protected SecurityContext securityContext;
+ protected AuthContext authContext;
+
public WebApplication getApplication() {
return (WebApplication) application;
}
@@ -61,73 +62,46 @@ public class WebResource {
return request.getRemoteAddr();
}
- /**
- * Will try to access the realm from request header. This works even if the
- * current caller is not authenticated, as the header will be set on
- * all API requests by the {@link WebService)}, extracted from a request path segment.
- */
- public String getRealm() {
- String realm = httpHeaders.getHeaderString(WebService.REQUEST_HEADER_REALM);
- if (realm == null || realm.length() == 0) {
- throw new WebApplicationException("Missing header '" + WebService.REQUEST_HEADER_REALM + "':", BAD_REQUEST);
- }
- return realm;
- }
-
@SuppressWarnings("unchecked")
- public KeycloakPrincipal<KeycloakSecurityContext> getCallerPrincipal() {
- KeycloakPrincipal<KeycloakSecurityContext> principal =
- (KeycloakPrincipal<KeycloakSecurityContext>) securityContext.getUserPrincipal();
- if (principal == null) {
- throw new WebApplicationException("Request is not authenticated, can't access user principal", FORBIDDEN);
+ public AuthContext getAuthContext() {
+ if (authContext == null) {
+ KeycloakPrincipal<KeycloakSecurityContext> principal =
+ (KeycloakPrincipal<KeycloakSecurityContext>) securityContext.getUserPrincipal();
+ if (principal == null) {
+ throw new WebApplicationException("Request is not authenticated, can't access user principal", FORBIDDEN);
+ }
+ authContext = new AccessTokenAuthContext(
+ principal.getKeycloakSecurityContext().getRealm(),
+ principal.getKeycloakSecurityContext().getToken()
+ );
}
- return principal;
+ return authContext;
}
- public AccessToken getAccessToken() {
- return getCallerPrincipal().getKeycloakSecurityContext().getToken();
+ // Convenience methods
+
+ @Override
+ public String getAuthenticatedRealm() {
+ return getAuthContext().getAuthenticatedRealm();
}
+ @Override
public String getUsername() {
- return getAccessToken().getPreferredUsername();
+ return getAuthContext().getUsername();
}
+ @Override
public String getUserId() {
- return getAccessToken().getSubject();
- }
-
- /**
- * This works only if the current caller is authenticated, we obtain the
- * realm from auth material.
- */
- public String getAuthenticatedRealm() {
- return getCallerPrincipal().getKeycloakSecurityContext().getRealm();
- }
-
- /**
- * @return <code>true</code> if the user is authenticated in the "master" realm and has the realm role "admin".
- */
- public boolean isSuperUser() {
- return getRealm().equals(Constants.MASTER_REALM) && hasRealmRole(Constants.REALM_ADMIN_ROLE);
+ return getAuthContext().getUserId();
}
+ @Override
public boolean hasRealmRole(String role) {
- return getAccessToken().getRealmAccess().isUserInRole(role);
+ return getAuthContext().hasRealmRole(role);
}
+ @Override
public boolean hasResourceRole(String role, String resource) {
- return getAccessToken().getResourceAccess().containsKey(resource)
- && getAccessToken().getResourceAccess().get(resource).isUserInRole(role);
- }
-
- public boolean hasResourceRoleOrIsSuperUser(String role, String resource) {
- return hasResourceRole(role, resource) || isSuperUser();
- }
-
- /**
- * @return <code>true</code> if the user is authenticated in the same realm or if the user is the superuser (admin).
- */
- public boolean isRealmAccessibleByUser(String realm) {
- return realm != null && realm.length() > 0 && (realm.equals(getAuthenticatedRealm()) || isSuperUser());
+ return getAuthContext().hasResourceRole(role, resource);
}
}
diff --git a/container/src/main/java/org/openremote/container/web/socket/UserPredicates.java b/container/src/main/java/org/openremote/container/web/socket/UserPredicates.java
deleted file mode 100644
index 76b94c72a..000000000
--- a/container/src/main/java/org/openremote/container/web/socket/UserPredicates.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright 2016, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.container.web.socket;
-
-import org.apache.camel.Predicate;
-
-public class UserPredicates {
-
- public static Predicate isUserInRole(String... roles) {
- return exchange -> {
- if (roles == null)
- return true;
- WebsocketAuth auth = exchange.getIn().getHeader(WebsocketConstants.AUTH, WebsocketAuth.class);
- for (String role : roles) {
- if (!auth.isUserInRole(role))
- return false;
- }
- return true;
- };
- }
-}
diff --git a/container/src/main/java/org/openremote/container/web/socket/WebsocketAdapter.java b/container/src/main/java/org/openremote/container/web/socket/WebsocketAdapter.java
index 10296391d..a9b5dfe4d 100644
--- a/container/src/main/java/org/openremote/container/web/socket/WebsocketAdapter.java
+++ b/container/src/main/java/org/openremote/container/web/socket/WebsocketAdapter.java
@@ -19,6 +19,8 @@
*/
package org.openremote.container.web.socket;
+import org.openremote.container.security.AuthContext;
+
import javax.websocket.CloseReason;
import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
@@ -42,14 +44,14 @@ public class WebsocketAdapter extends Endpoint {
LOG.fine("Websocket session open: " + session.getId());
session.setMaxIdleTimeout(WebsocketConstants.SESSION_MAX_IDLE_TIMEOUT_SECONDS * 1000);
consumer.getEndpoint().getWebsocketSessions().add(session);
- this.consumer.sendMessage(session.getId(), getWebsocketAuth(session), null, exchange -> {
+ this.consumer.sendMessage(session.getId(), getHandshakeAuth(session), null, exchange -> {
exchange.getIn().setHeader(WebsocketConstants.SESSION, session);
exchange.getIn().setHeader(WebsocketConstants.SESSION_OPEN, true);
});
session.addMessageHandler(String.class, message -> {
if (LOG.isLoggable(Level.FINE))
LOG.fine("Websocket session " + session.getId() + " message received: " + message);
- this.consumer.sendMessage(session.getId(), getWebsocketAuth(session), message, exchange -> {
+ this.consumer.sendMessage(session.getId(), getHandshakeAuth(session), message, exchange -> {
exchange.getIn().setHeader(WebsocketConstants.SESSION, session);
});
});
@@ -59,7 +61,7 @@ public class WebsocketAdapter extends Endpoint {
public void onClose(Session session, CloseReason closeReason) {
if (LOG.isLoggable(Level.FINE))
LOG.fine("Websocket session close: " + session.getId() + " " + closeReason);
- this.consumer.sendMessage(session.getId(), getWebsocketAuth(session), closeReason, exchange -> {
+ this.consumer.sendMessage(session.getId(), getHandshakeAuth(session), closeReason, exchange -> {
exchange.getIn().setHeader(WebsocketConstants.SESSION, session);
exchange.getIn().setHeader(WebsocketConstants.SESSION_CLOSE, true);
});
@@ -71,15 +73,15 @@ public class WebsocketAdapter extends Endpoint {
super.onError(session, thr);
if (LOG.isLoggable(Level.INFO))
LOG.log(Level.INFO, "Websocket session error: " + session.getId(), thr);
- this.consumer.sendMessage(session.getId(), getWebsocketAuth(session), thr, exchange -> {
+ this.consumer.sendMessage(session.getId(), getHandshakeAuth(session), thr, exchange -> {
exchange.getIn().setHeader(WebsocketConstants.SESSION, session);
exchange.getIn().setHeader(WebsocketConstants.SESSION_CLOSE_ERROR, true);
});
consumer.getEndpoint().getWebsocketSessions().remove(session);
}
- protected WebsocketAuth getWebsocketAuth(Session session) {
- WebsocketAuth auth = (WebsocketAuth) session.getUserProperties().get(WebsocketConstants.AUTH);
+ protected AuthContext getHandshakeAuth(Session session) {
+ AuthContext auth = (AuthContext) session.getUserProperties().get(WebsocketConstants.HANDSHAKE_AUTH);
if (auth == null)
throw new IllegalStateException("No authorization details in websocket session: " + session.getId());
return auth;
diff --git a/container/src/main/java/org/openremote/container/web/socket/WebsocketAuth.java b/container/src/main/java/org/openremote/container/web/socket/WebsocketAuth.java
deleted file mode 100644
index a209a4870..000000000
--- a/container/src/main/java/org/openremote/container/web/socket/WebsocketAuth.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright 2016, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.container.web.socket;
-
-import org.keycloak.KeycloakPrincipal;
-import org.keycloak.KeycloakSecurityContext;
-import org.keycloak.representations.AccessToken;
-import org.openremote.model.Constants;
-
-import javax.ws.rs.WebApplicationException;
-
-import java.security.Principal;
-
-import static javax.ws.rs.core.Response.Status.FORBIDDEN;
-
-public abstract class WebsocketAuth {
-
- final protected Principal principal;
-
- public WebsocketAuth(Principal principal) {
- this.principal = principal;
- }
-
- @SuppressWarnings("unchecked")
- public KeycloakPrincipal<KeycloakSecurityContext> getCallerPrincipal() {
- KeycloakPrincipal<KeycloakSecurityContext> keycloakPrincipal = (KeycloakPrincipal<KeycloakSecurityContext>) principal;
- if (keycloakPrincipal == null) {
- throw new WebApplicationException("Websocket session is not authenticated, can't access user principal", FORBIDDEN);
- }
- return keycloakPrincipal;
- }
-
- public AccessToken getAccessToken() {
- return getCallerPrincipal().getKeycloakSecurityContext().getToken();
- }
-
- public String getUsername() {
- return getAccessToken().getPreferredUsername();
- }
-
- public String getUserId() {
- return getAccessToken().getSubject();
- }
-
- /**
- * This works only if the current caller is authenticated, we obtain the
- * realm from auth material.
- */
- public String getAuthenticatedRealm() {
- return getCallerPrincipal().getKeycloakSecurityContext().getRealm();
- }
-
- /**
- * @return <code>true</code> if the user is authenticated in the "master" realm and has the realm role "admin".
- */
- public boolean isSuperUser() {
- return getAuthenticatedRealm().equals(Constants.MASTER_REALM) && hasRealmRole(Constants.REALM_ADMIN_ROLE);
- }
-
- public boolean hasRealmRole(String role) {
- return getAccessToken().getRealmAccess().isUserInRole(role);
- }
-
- public abstract boolean isUserInRole(String role);
-}
diff --git a/container/src/main/java/org/openremote/container/web/socket/WebsocketConstants.java b/container/src/main/java/org/openremote/container/web/socket/WebsocketConstants.java
index 548ed809d..108830182 100644
--- a/container/src/main/java/org/openremote/container/web/socket/WebsocketConstants.java
+++ b/container/src/main/java/org/openremote/container/web/socket/WebsocketConstants.java
@@ -25,7 +25,7 @@ public interface WebsocketConstants {
String SESSION = "websocket.session";
String SESSION_KEY = "websocket.sessionKey";
String SEND_TO_ALL = "websocket.sendToAll";
- String AUTH = "websocket.auth";
+ String HANDSHAKE_AUTH = "websocket.auth";
String SESSION_OPEN = "websocket.sessionOpen";
String SESSION_CLOSE = "websocket.sessionClose";
String SESSION_CLOSE_ERROR = "websocket.sessionCloseError";
diff --git a/container/src/main/java/org/openremote/container/web/socket/WebsocketConsumer.java b/container/src/main/java/org/openremote/container/web/socket/WebsocketConsumer.java
index 368c3c8e2..30ba704d5 100644
--- a/container/src/main/java/org/openremote/container/web/socket/WebsocketConsumer.java
+++ b/container/src/main/java/org/openremote/container/web/socket/WebsocketConsumer.java
@@ -22,6 +22,8 @@ package org.openremote.container.web.socket;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.impl.DefaultConsumer;
+import org.openremote.container.security.AuthContext;
+import org.openremote.model.Constants;
import java.util.function.Consumer;
@@ -50,18 +52,18 @@ public class WebsocketConsumer extends DefaultConsumer {
return endpoint;
}
- public void sendMessage(final String sessionKey, final WebsocketAuth websocketAuth, final String message) {
- sendMessage(sessionKey, websocketAuth, (Object) message);
+ public void sendMessage(final String sessionKey, final AuthContext authContext, final String message) {
+ sendMessage(sessionKey, authContext, (Object) message);
}
- public void sendMessage(final String sessionKey, final WebsocketAuth websocketAuth, final Object message) {
- sendMessage(sessionKey, websocketAuth, message, null);
+ public void sendMessage(final String sessionKey, final AuthContext authContext, final Object message) {
+ sendMessage(sessionKey, authContext, message, null);
}
- public void sendMessage(final String sessionKey, final WebsocketAuth websocketAuth, final Object message, Consumer<Exchange> exchangePreparer) {
+ public void sendMessage(final String sessionKey, final AuthContext authContext, final Object message, Consumer<Exchange> exchangePreparer) {
final Exchange exchange = getEndpoint().createExchange();
exchange.getIn().setHeader(WebsocketConstants.SESSION_KEY, sessionKey);
- exchange.getIn().setHeader(WebsocketConstants.AUTH, websocketAuth);
+ exchange.getIn().setHeader(Constants.AUTH_CONTEXT, authContext);
exchange.getIn().setBody(message);
if (exchangePreparer != null) {
exchangePreparer.accept(exchange);
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 adcff235d..e665bc2c2 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
@@ -37,7 +37,6 @@ import org.openremote.model.asset.agent.AgentLink;
import org.openremote.model.asset.agent.ProtocolConfiguration;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeRef;
-import org.openremote.model.event.shared.SharedEvent;
import org.openremote.model.util.Pair;
import org.openremote.model.value.ObjectValue;
@@ -52,9 +51,8 @@ import java.util.stream.Stream;
import static org.openremote.agent.protocol.Protocol.ACTUATOR_TOPIC;
import static org.openremote.agent.protocol.Protocol.DeploymentStatus.*;
import static org.openremote.container.persistence.PersistenceEvent.PERSISTENCE_TOPIC;
-import static org.openremote.manager.server.asset.AssetPredicates.isPersistenceEventForAssetType;
-import static org.openremote.manager.server.asset.AssetPredicates.isPersistenceEventForEntityType;
-import static org.openremote.manager.server.asset.AssetProcessingService.ASSET_QUEUE;
+import static org.openremote.manager.server.asset.AssetRoute.isPersistenceEventForAssetType;
+import static org.openremote.manager.server.asset.AssetRoute.isPersistenceEventForEntityType;
import static org.openremote.model.asset.AssetAttribute.attributesFromJson;
import static org.openremote.model.asset.AssetType.AGENT;
import static org.openremote.model.asset.agent.AgentLink.getAgentLink;
@@ -62,7 +60,7 @@ import static org.openremote.model.util.TextUtil.isNullOrEmpty;
import static org.openremote.model.util.TextUtil.isValidURN;
/**
- * Finds all {@link AssetType#AGENT} and {@link AssetType#THING} assets and starts the protocols for them.
+ * Finds all {@link AssetType#AGENT} assets and manages their {@link ProtocolConfiguration}s.
*/
public class AgentService extends RouteBuilder implements ContainerService, Consumer<AssetState>, ProtocolAssetService {
@@ -134,6 +132,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons
@Override
public void configure() throws Exception {
from(PERSISTENCE_TOPIC)
+ .routeId("AgentPersistenceChanges")
.filter(isPersistenceEventForEntityType(Asset.class))
.process(exchange -> {
PersistenceEvent persistenceEvent = exchange.getIn().getBody(PersistenceEvent.class);
@@ -178,24 +177,8 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons
}
@Override
- public void sendAttributeEvent(Protocol sender, AttributeEvent attributeEvent) {
- // Don't allow updating linked attributes with this mechanism as it could cause
- // an infinite loop
- boolean isForLinkedAttribute = sender
- .getLinkedAttributes()
- .stream()
- .anyMatch(attribute -> attribute.getReferenceOrThrow()
- .equals(attributeEvent.getAttributeRef())
- );
-
- if (isForLinkedAttribute) {
- LOG.warning("Cannot update an attribute linked to the same protocol; use updateLinkedAttribute for that");
- return;
- }
-
- messageBrokerService
- .getProducerTemplate()
- .sendBodyAndHeader(ASSET_QUEUE, attributeEvent, SharedEvent.HEADER_SENDER, sender);
+ public void sendAttributeEvent(AttributeEvent attributeEvent) {
+ assetProcessingService.sendAttributeEvent(attributeEvent, AttributeEvent.Source.INTERNAL);
}
/**
@@ -545,11 +528,8 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons
*/
@Override
public void accept(AssetState assetState) {
- if (assetState.isSensorUpdate()) {
- LOG.fine("Ignoring sensor update: " + assetState);
+ if (assetState.getSource() == AttributeEvent.Source.SENSOR) {
return;
- } else {
- LOG.fine("Handling update: " + assetState);
}
AgentLink.getAgentLink(assetState.getAttribute())
@@ -564,13 +544,12 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons
)
.map(protocolConfiguration -> {
// Its' a send to actuator - push the update to the protocol
- LOG.fine("Processing: " + assetState);
-
Optional<AttributeEvent> event = assetState
.getAttribute()
.getStateEvent();
if (event.isPresent()) {
+ LOG.fine("Sending to actuator topic: " + event.get());
messageBrokerService.getProducerTemplate().sendBodyAndHeader(
ACTUATOR_TOPIC,
event.get(),
diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetPredicates.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetPredicates.java
deleted file mode 100644
index 3a5ae5c14..000000000
--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetPredicates.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright 2016, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.manager.server.asset;
-
-import org.apache.camel.Predicate;
-import org.openremote.container.persistence.PersistenceEvent;
-import org.openremote.model.asset.Asset;
-import org.openremote.model.asset.AssetType;
-
-public class AssetPredicates {
-
- public static Predicate isPersistenceEventForEntityType(Class<?> type) {
- return exchange -> {
- Class<?> entityType = exchange.getIn().getHeader(PersistenceEvent.HEADER_ENTITY_TYPE, Class.class);
- return type.isAssignableFrom(entityType);
- };
- }
-
- public static Predicate isPersistenceEventForAssetType(AssetType assetType) {
- return exchange -> {
- if (!(exchange.getIn().getBody() instanceof PersistenceEvent))
- return false;
- PersistenceEvent persistenceEvent = exchange.getIn().getBody(PersistenceEvent.class);
- Asset asset = (Asset) persistenceEvent.getEntity();
- return asset.getWellKnownType() == assetType;
- };
- }
-}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java
index a3eba852f..5fa1c4633 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java
@@ -19,63 +19,56 @@
*/
package org.openremote.manager.server.asset;
+import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
-import org.openremote.agent.protocol.AbstractProtocol;
import org.openremote.agent.protocol.Protocol;
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.security.AuthContext;
import org.openremote.container.timer.TimerService;
import org.openremote.manager.server.agent.AgentService;
import org.openremote.manager.server.datapoint.AssetDatapointService;
import org.openremote.manager.server.event.EventService;
-import org.openremote.manager.server.rules.RulesEngine;
import org.openremote.manager.server.rules.RulesService;
import org.openremote.manager.server.security.ManagerIdentityService;
import org.openremote.manager.shared.asset.AssetProcessingException;
import org.openremote.manager.shared.security.ClientRole;
-import org.openremote.manager.shared.security.Tenant;
-import org.openremote.manager.shared.security.User;
+import org.openremote.model.Constants;
import org.openremote.model.ValidationFailure;
import org.openremote.model.asset.*;
import org.openremote.model.attribute.AttributeEvent;
-import org.openremote.model.attribute.AttributeExecuteStatus;
-import org.openremote.model.event.shared.SharedEvent;
-import org.openremote.model.value.Values;
-
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-import java.util.Optional;
+import org.openremote.model.attribute.AttributeEvent.Source;
+
+import java.util.*;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
import static org.openremote.agent.protocol.Protocol.SENSOR_QUEUE;
-import static org.openremote.model.asset.agent.AgentLink.getAgentLink;
+import static org.openremote.manager.server.asset.AssetRoute.*;
+import static org.openremote.manager.server.event.EventService.INCOMING_EVENT_TOPIC;
+import static org.openremote.model.attribute.AttributeEvent.HEADER_SOURCE;
+import static org.openremote.model.attribute.AttributeEvent.Source.CLIENT;
+import static org.openremote.model.attribute.AttributeEvent.Source.INTERNAL;
/**
* Receives {@link AttributeEvent}s and processes them.
* <p>
- * {@link AttributeEvent}s can come from various sources:
- * <ul>
- * <li>Protocol sensor updates ({@link AbstractProtocol#updateLinkedAttribute})</li>
- * <li>Protocol arbitrary updates ({@link AbstractProtocol#sendAttributeEvent})</li>
- * <li>User/Client REST initiated ({@link AssetResourceImpl#writeAttributeValue})</li>
- * <li>User/Client Web Socket initiated ({@link EventService})</li>
- * <li>Rules Engine ({@link org.openremote.model.rules.Assets#dispatch})</li>
- * </ul>
- * The {@link AttributeEvent}s are first validated using basic validation {@link #validateAttributeEvent} then they are
- * validated based on sender:
+ * {@link AttributeEvent}s can come from various {@link AttributeEvent.Source}s:
* <ul>
- * <li>User/client - {@link #validateUserRequest}</li>
+ * <li>Events sent to {@link #ASSET_QUEUE} or through {@link #sendAttributeEvent} convenience methods</li>
+ * <li>Client event bus write requests received on {@link EventService#INCOMING_EVENT_TOPIC}</li>
+ * <li>Protocol sensor updates sent to {@link Protocol#SENSOR_QUEUE}</li>
* </ul>
- * If validation fails at any point then an {@link AssetProcessingException} will be thrown with a
- * {@link AssetProcessingException.Reason} indicating the cause of validation failure.
+ * <p>
+ * The {@link AttributeEvent}s are first validated depending on their source, and if validation fails
+ * at any point then an {@link AssetProcessingException} will be logged as a warning with an
+ * {@link AssetProcessingException.Reason}.
* <p>
* Once successfully validated the event is converted into an {@link AssetState} message which is then passed through
- * the processing chain of <code>Consumer&lt;AssetState&gt;</code> consumers.
+ * the processing chain of consumers.
* <p>
* The regular processing chain is:
* <ul>
@@ -87,62 +80,53 @@ import static org.openremote.model.asset.agent.AgentLink.getAgentLink;
* <h2>Rules Service processing logic</h2>
* <p>
* Checks if attribute is {@link AssetAttribute#isRuleState} or {@link AssetAttribute#isRuleEvent}, and if
- * it does then the message is passed through the rule engines that are in scope for the asset.
+ * so the message is passed through the rule engines that are in scope for the asset.
* <p>
* For {@link AssetState} messages, the rules service keeps the facts and thus the state of each rules
* knowledge session in sync with the asset state changes that occur. If an asset attribute value changes,
* the {@link AssetState} in each rules session will be updated to reflect the change.
* <p>
- * For {@link AssetEvent} messages, they are inserted in the rules sessions in scope
- * and expired automatically either by a) the rules session if no time-pattern can possibly match the event source
- * timestamp anymore or b) by the rules service if the event lifetime set in {@link RulesService#RULE_EVENT_EXPIRES} is
- * reached or c) by the rules service if the event lifetime set in the attribute {@link AssetMeta#RULE_EVENT_EXPIRES}
- * is reached.
+ * For {@link AssetEvent} messages (obtained by converting the {@link AssetState}), they are inserted in the rules
+ * sessions in scope and expired automatically either by a) the rules session if no time-pattern can possibly match
+ * the event source timestamp anymore or b) by the rules service if the event lifetime set in
+ * {@link RulesService#RULE_EVENT_EXPIRES} is reached or c) by the rules service if the event lifetime set in the
+ * attribute {@link AssetMeta#RULE_EVENT_EXPIRES} is reached.
* <h2>Agent service processing logic</h2>
* <p>
- * When the {@link AssetState} originates from a protocol sensor update (i.e. generated by a call to
- * {@link org.openremote.agent.protocol.AbstractProtocol#updateLinkedAttribute} then the agent service will ignore the
- * message.
- * <p>
- * When the {@link AssetState} originates from any other source (including a protocol for arbitrary attribute updates)
- * then the agent service will validate that the attribute has a valid {@link AssetMeta#AGENT_LINK}.
- * <p>
- * If it is not linked to an agent then it ignores the message.
+ * The agent service's role is to communicate asset attribute writes to actuators, through protocols.
+ * When the update messages' source is {@link AttributeEvent.Source#SENSOR}, the agent service ignores the message.
+ * The message will also be ignored if the updated attribute is not linked to a protocol configuration.
* <p>
- * If it is linked to an agent and the agent link is invalid then the message status is set to
- * {@link AssetState.ProcessingStatus#HANDLED} and the message will not be able to progress through the processing chain.
+ * If the updated attribute has an invalid agent link, the message status is set to {@link AssetState.ProcessingStatus#ERROR}.
* <p>
- * If the message is for a valid linked agent then an {@link AttributeEvent} is sent on the
- * {@link org.openremote.agent.protocol.AbstractProtocol#ACTUATOR_TOPIC} which the protocol will receive in
- * {@link org.openremote.agent.protocol.AbstractProtocol#processLinkedAttributeWrite} for execution on an actual device or
- * service 'things'.
+ * If the updated attribute has a valid agent link, an {@link AttributeEvent} is sent on the {@link Protocol#ACTUATOR_TOPIC},
+ * for execution on an actual device or service 'things'.
* <p>
* This means that a protocol implementation is responsible for producing a new {@link AttributeEvent} to
* indicate to the system that the attribute value has/has not changed. The protocol should know best when to
- * do this and will vary from protocol to protocol; some 'things' might respond to an actuator command immediately
- * with a new sensor read, or they might send a separate sensor changed message or both or neither (fire and
+ * do this and it will vary from protocol to protocol; some 'things' might respond to an actuator write immediately
+ * with a new sensor read, or they might send a later "sensor changed" message or both or neither (fire and
* forget). The protocol must decide what the best course of action is based on the 'things' it communicates with
* and the transport layer it uses etc.
* <h2>Asset Storage Service processing logic</h2>
* <p>
- * Always tries to persist the attribute value in the DB and allows the message to continue if the commit was
+ * Always tries to persist the attribute value in the database and allows the message to continue if the commit was
* successful.
* <h2>Asset Datapoint Service processing logic</h2>
* <p>
- * Checks if attribute has {@link org.openremote.model.asset.AssetMeta#STORE_DATA_POINTS} meta item with a value of true
- * and if it does then the {@link AttributeEvent} is stored in a time series DB. Then allows the message to continue
- * if the commit was successful.
+ * Checks if attribute is {@link AssetAttribute#isStoreDatapoints()}, and if so the {@link AttributeEvent} is stored
+ * is stored in a time series of historical data. Then allows the message to continue if the commit was successful.
*/
public class AssetProcessingService extends RouteBuilder implements ContainerService {
private static final Logger LOG = Logger.getLogger(AssetProcessingService.class.getName());
// TODO: Some of these options should be configurable depending on expected load etc.
- // Message topic for communicating from client to asset/thing layer
- public static final String ASSET_QUEUE = "seda://AssetQueue?waitForTaskToComplete=NEVER&purgeWhenStopping=true&discardIfNoConsumers=false&size=1000";
+ // Message topic for communicating individual asset attribute changes
+ String ASSET_QUEUE = "seda://AssetQueue?waitForTaskToComplete=IfReplyExpected&timeout=10000&purgeWhenStopping=true&discardIfNoConsumers=false&size=1000";
protected TimerService timerService;
- protected ManagerIdentityService managerIdentityService;
+ protected ManagerIdentityService identityService;
protected RulesService rulesService;
protected AgentService agentService;
protected AssetStorageService assetStorageService;
@@ -157,7 +141,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
@Override
public void init(Container container) throws Exception {
timerService = container.getService(TimerService.class);
- managerIdentityService = container.getService(ManagerIdentityService.class);
+ identityService = container.getService(ManagerIdentityService.class);
rulesService = container.getService(RulesService.class);
agentService = container.getService(AgentService.class);
assetStorageService = container.getService(AssetStorageService.class);
@@ -184,11 +168,11 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
return true;
// Regular user must have role
- if (!auth.isUserInRole(ClientRole.READ_ASSETS.getValue())) {
+ if (!auth.hasResourceRole(ClientRole.READ_ASSETS.getValue(), Constants.KEYCLOAK_CLIENT_ID)) {
return false;
}
- if (managerIdentityService.isRestrictedUser(auth.getUserId())) {
+ if (identityService.isRestrictedUser(auth.getUserId())) {
// Restricted users can only get attribute events for their linked assets
if (assetStorageService.isUserAsset(auth.getUserId(), filter.getEntityId()))
return true;
@@ -222,238 +206,82 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
@Override
public void configure() throws Exception {
- // Process new sensor values from protocols, must be events for
- // attributes linked to an agent's protocol configurations
- from(SENSOR_QUEUE)
+ // A client wants to write attribute state through event bus
+ from(INCOMING_EVENT_TOPIC)
+ .routeId("FromClientUpdates")
.filter(body().isInstanceOf(AttributeEvent.class))
- .process(exchange -> {
- AttributeEvent event = exchange.getIn().getBody(AttributeEvent.class);
- Protocol protocol = exchange.getIn().getHeader(
- SharedEvent.HEADER_SENDER, Protocol.class
- );
-
- if (protocol == null) {
- LOG.warning("Sensor update received from a protocol but the protocol is not included in the header");
- return;
- }
-
- LOG.fine("Received from protocol '" + protocol.getProtocolName() + "' on sensor queue: " + event);
- ServerAsset asset = assetStorageService.find(event.getEntityId(), true);
+ .setHeader(HEADER_SOURCE, () -> CLIENT)
+ .to(ASSET_QUEUE);
- // Get the attribute and check it is actually linked to an agent (although the
- // event comes from a Protocol, we can not assume that the attribute is still linked,
- // consider a protocol that receives a batch of messages because a gateway was offline
- // for a day)
- AssetAttribute attribute = asset.getAttribute(event.getAttributeName()).orElse(null);
-
- validateAttributeEvent(event, asset, attribute, true);
-
- AssetAttribute protocolConfiguration =
- getAgentLink(attribute)
- .flatMap(agentService::getProtocolConfiguration)
- .orElse(null);
-
- if (protocolConfiguration == null) {
- LOG.warning(
- "Processing sensor update from protocol '" + protocol.getProtocolName()
- + "' failed, linked agent protocol configuration not found: " + event
- );
- return;
- }
-
- if (!protocol.getLinkedProtocolConfigurations().contains(protocolConfiguration)) {
- LOG.warning("Protocol isn't linked to this protocol configuration: " + protocolConfiguration.getReferenceOrThrow());
- return;
- }
-
- // Process as non-client source (not southbound)
- processUpdate(asset, attribute, event, false, true, protocol);
-
- });
+ // A protocol wants to write a new sensor value
+ from(SENSOR_QUEUE)
+ .routeId("FromSensorUpdates")
+ .filter(body().isInstanceOf(AttributeEvent.class))
+ .setHeader(HEADER_SOURCE, () -> Source.SENSOR)
+ .to(ASSET_QUEUE);
- // All attribute events (except protocol sensor updates) come through here
+ // Process attribute events
from(ASSET_QUEUE)
+ .routeId("AssetUpdates")
.filter(body().isInstanceOf(AttributeEvent.class))
- .process(exchange -> {
- AttributeEvent event = exchange.getIn().getBody(AttributeEvent.class);
- Object sender = exchange.getIn().getHeader(SharedEvent.HEADER_SENDER);
- LOG.fine("Received from '" + sender + "' on asset queue: " + event);
-
- ServerAsset asset = assetStorageService.find(event.getEntityId(), true);
- AssetAttribute attribute = asset == null ? null : asset.getAttribute(event.getAttributeName()).orElse(null);
- validateAttributeEvent(event, asset, attribute, false);
-
- if (sender instanceof User) {
- // This is from southbound so ensure user can perform the update
- User user = (User)sender;
- validateUserRequest(event, asset, user);
- } else if (sender instanceof Protocol) {
- // TODO: implement any protocol specific validation
- } else if (sender instanceof RulesEngine) {
- // TODO: implement any rules specific validation
- }
-
- boolean southbound = sender == null || sender instanceof User;
- processUpdate(asset, attribute, event, southbound, false, sender);
- });
+ .doTry()
+ .process(extractAttributeEventDetails(assetStorageService))
+ .process(validateAttributeEvent())
+ .choice()
+ .when(header(HEADER_SOURCE).isEqualTo(CLIENT))
+ .process(validateAttributeEventFromClient(assetStorageService, identityService))
+ .when(header(HEADER_SOURCE).isEqualTo(Source.SENSOR))
+ .process(validateAttributeEventFromSensor(agentService))
+ .end()
+ .process(this::processAttributeEvent)
+ .endDoTry()
+ .doCatch(AssetProcessingException.class)
+ .process(handleAssetProcessingException(LOG));
}
/**
- * Send attribute change events into the {@link #ASSET_QUEUE}.
- *
- * The sender indicates the source of the attribute event this should be one of:
- * <ul>
- * <li>{@link org.openremote.manager.shared.security.User} - From user/client</li>
- * <li>{@link Protocol} - From a protocol</li>
- * <li>{@link org.openremote.manager.server.rules.RulesEngine} - From rules</li>
- * </ul>
+ * Send attribute change events into the {@link #ASSET_QUEUE}, from {@link AttributeEvent.Source#CLIENT}.
+ * The calling thread will block until processing is complete or queue default timeout is reached. The
+ * {@link AuthContext} is used to check if the attribute update is permissible for the client. An
+ * {@link AssetProcessingException} will be thrown if processing failed.
*/
- public void sendAttributeEvent(AttributeEvent attributeEvent, Object sender) {
- messageBrokerService.getProducerTemplate().sendBodyAndHeader(
- ASSET_QUEUE,
- attributeEvent,
- SharedEvent.HEADER_SENDER,
- sender
+ public void processFromClient(AuthContext authContext, AttributeEvent attributeEvent) throws AssetProcessingException {
+ Map<String, Object> headers = new HashMap<>();
+ headers.put(HEADER_SOURCE, CLIENT);
+ headers.put(Constants.AUTH_CONTEXT, authContext);
+
+ Object result = messageBrokerService.getProducerTemplate().requestBodyAndHeaders(
+ ASSET_QUEUE, attributeEvent, headers
);
- }
- // TODO: Remove this once AssetResourceImpl can get exceptions from camel route
- public void sendAttributeEventWithoutCamel(AttributeEvent event, Object sender) {
- LOG.fine("Received from '" + sender + "' on asset queue: " + event);
-
- ServerAsset asset = assetStorageService.find(event.getEntityId(), true);
- AssetAttribute attribute = asset == null ? null : asset.getAttribute(event.getAttributeName()).orElse(null);
- validateAttributeEvent(event, asset, attribute, false);
-
- if (sender instanceof User) {
- // This is from southbound so ensure user can perform the update
- User user = (User)sender;
- validateUserRequest(event, asset, user);
- } else if (sender instanceof Protocol) {
- // TODO: implement any protocol specific validation
- } else if (sender instanceof RulesEngine) {
- // TODO: implement any rules specific validation
+ if (result instanceof AssetProcessingException) {
+ throw (AssetProcessingException) result;
}
-
- processUpdate(asset, attribute, event, true, false, sender);
- }
-
- // TODO: Update tests to include sender and remove this
- protected void sendAttributeEvent(AttributeEvent attributeEvent) {
- sendAttributeEvent(attributeEvent, null);
}
/**
- * Performs basic validation of all {@link AttributeEvent}s:
- * <ol>
- * <li>Check event refers to a valid asset</li>
- * <li>Check event refers to a valid attribute</li>
- * <li>Check event doesn't refer to an {@link AssetType#AGENT} Asset</li>
- * <li>Check that events for executable attributes are of type {@link AttributeExecuteStatus} and are
- * {@link AttributeExecuteStatus#isWrite} (unless this is a sensor update)</li>
- * </ol>
+ * Send attribute change events into the {@link #ASSET_QUEUE}, from {@link AttributeEvent.Source#INTERNAL}.
*/
- protected void validateAttributeEvent(AttributeEvent event, Asset asset, AssetAttribute attribute, boolean isSensorUpdate) throws AssetProcessingException {
-
- if (asset == null) {
- LOG.warning("Asset doesn't exist: " + event.getAttributeRef());
- throw new AssetProcessingException(AssetProcessingException.Reason.ASSET_NOT_FOUND);
- }
-
- if (attribute == null) {
- LOG.warning("Attribute doesn't exist: " + event.getAttributeRef());
- throw new AssetProcessingException(AssetProcessingException.Reason.ATTRIBUTE_NOT_FOUND);
- }
-
- // Prevent editing of individual agent attributes
- if (asset.getWellKnownType() == AssetType.AGENT) {
- LOG.warning("Agent attributes can not be updated individually, update the whole asset instead: " + asset);
- throw new AssetProcessingException(AssetProcessingException.Reason.INVALID_ACTION);
- }
-
- // Only sensor updates can send AttributeExecuteStatus marked as read values
- if (!isSensorUpdate && attribute.isExecutable()) {
- Optional<AttributeExecuteStatus> status = event.getValue()
- .flatMap(Values::getString)
- .flatMap(AttributeExecuteStatus::fromString);
-
- if (!status.isPresent()) {
- LOG.warning("Attribute event doesn't contain a valid AttributeExecuteStatus value: " + event);
- throw new AssetProcessingException(AssetProcessingException.Reason.INVALID_ACTION);
- }
-
- if (!status.get().isWrite()) {
- LOG.warning("Only AttributeExecuteStatus write value can be written to an attribute: " + event);
- throw new AssetProcessingException(AssetProcessingException.Reason.INVALID_ACTION);
- }
- }
+ public void sendAttributeEvent(AttributeEvent attributeEvent) {
+ sendAttributeEvent(attributeEvent, INTERNAL);
}
/**
- * Performs validation of {@link AttributeEvent}s sent by users/clients:
- * <p>
- * All users (including super users):
- * <ol>
- * <li>Check asset's realm is valid and active</li>
- * <li>Check that the event is not for a read only attribute (not even super users are allowed to write to readonly attributes)</li>
- * </ol>
- * Additional checks for non super users:
- * <ol>
- * <li>User must have {@link ClientRole#WRITE_ASSETS} role</li>
- * <li>User must be in the same realm as the asset</li>
- * <li>Restricted users can only write to assets linked to them</li>
- * <li>Restricted users can only write to attributes marked as protected</li>
- * </ol>
- *
+ * Send attribute change events into the {@link #ASSET_QUEUE}.
*/
- protected void validateUserRequest(AttributeEvent event, Asset asset, User user) throws AssetProcessingException {
-
- // Attribute presence has already been verified
- //noinspection ConstantConditions
- AssetAttribute attribute = asset.getAttribute(event.getAttributeName()).get();
-
- // Check realm is active and accessible
- Tenant tenant = managerIdentityService.getTenant(asset.getRealmId());
- if (tenant == null || !tenant.isActive()) {
- throw new AssetProcessingException(AssetProcessingException.Reason.INVALID_ACTION);
- }
-
- // Prevent editing of read only attributes
- if (attribute.isReadOnly()) {
- LOG.warning("Ignoring southbound " + event + ", attribute is read-only in: " + asset);
- throw new AssetProcessingException(AssetProcessingException.Reason.INVALID_ACTION);
- }
-
- // All other checks only apply to non super user
- if (user.isSuperUser()) {
- return;
- }
-
- // Regular user must have write assets role
- if (!user.hasRole(ClientRole.WRITE_ASSETS.getValue())) {
- throw new AssetProcessingException(AssetProcessingException.Reason.INSUFFICIENT_ACCESS);
- }
-
- // Regular users can only write attribute events for assets in their realm
- if (!asset.getTenantRealm().equals(user.getRealm())) {
- throw new AssetProcessingException(AssetProcessingException.Reason.INSUFFICIENT_ACCESS);
- }
-
- // Restricted users can only write attribute events for their linked assets
- if (user.isRestricted() && !assetStorageService.isUserAsset(user.getId(), asset.getId())) {
- throw new AssetProcessingException(AssetProcessingException.Reason.INSUFFICIENT_ACCESS);
- }
-
- // Restricted users can only write attribute events for protected attributes
- if (user.isRestricted() && !attribute.isProtected()) {
- throw new AssetProcessingException(AssetProcessingException.Reason.INSUFFICIENT_ACCESS);
- }
+ public void sendAttributeEvent(AttributeEvent attributeEvent, AttributeEvent.Source source) {
+ messageBrokerService.getProducerTemplate().sendBodyAndHeader(
+ ASSET_QUEUE,
+ attributeEvent,
+ HEADER_SOURCE,
+ source
+ );
}
- /*
+ /**
* This deals with single attribute value changes and pushes them through the attribute event
* processing chain where each consumer is given the opportunity to consume the event or allow
- * it progress to the next consumer {@link AssetState.ProcessingStatus}.
+ * its progress to the next consumer, see {@link AssetState.ProcessingStatus}.
* <p>
* NOTE: An attribute value can be changed during Asset CRUD but this does not come through
* this route but is handled separately see {@link AssetResourceImpl}. Any attribute values
@@ -462,64 +290,67 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
* entry point to initiate an attribute value change: Sensor updates from protocols, attribute
* write requests from protocols, attribute write requests from clients, and attribute write
* dispatching as rules RHS action.
+ * <p>
+ * TODO: This can be migrated to Camel route as well
*/
- protected void processUpdate(ServerAsset asset,
- AssetAttribute attribute,
- AttributeEvent attributeEvent,
- boolean isSouthbound,
- boolean isSensorUpdate,
- Object sender) {
- // Ensure timestamp of event is not in the future as that would essentially block access to
- // the attribute until after that time (maybe that is desirable behaviour)
- // Allow a leniency of 1s
- long currentMillis = timerService.getCurrentTimeMillis();
- if (attributeEvent.getTimestamp() - currentMillis > 1000) {
- // TODO: Decide how to handle update events in the future - ignore or change timestamp
- LOG.warning("Ignoring future " + attributeEvent
- + ", current time: " + new Date(currentMillis) + "/" + currentMillis
- + ", event time: " + new Date(attributeEvent.getTimestamp()) + "/" + attributeEvent.getTimestamp() + " in: " + asset);
- return;
- }
+ protected void processAttributeEvent(Exchange exchange) {
- // Hold on to existing attribute state so we can use it during processing
- Optional<AttributeEvent> lastStateEvent = attribute.getStateEvent();
+ AttributeEvent event = exchange.getIn().getBody(AttributeEvent.class);
+ AttributeEvent.Source source = exchange.getIn().getHeader(HEADER_SOURCE, AttributeEvent.Source.class);
+ ServerAsset asset = exchange.getIn().getHeader(HEADER_ASSET, ServerAsset.class);
+ AssetAttribute attribute = exchange.getIn().getHeader(HEADER_ATTRIBUTE, AssetAttribute.class);
- // Check the last update timestamp of the attribute, ignoring any event that is older than last update
- // TODO: This means we drop out-of-sequence events, we might need better at-least-once handling
- if (lastStateEvent.isPresent() && lastStateEvent.get().getTimestamp() >= 0 && attributeEvent.getTimestamp() <= lastStateEvent.get().getTimestamp()) {
- LOG.warning("Ignoring outdated " + attributeEvent
- + ", last asset state time: " + lastStateEvent.map(event -> new Date(event.getTimestamp()).toString()).orElse("-1") + "/" + lastStateEvent.map(AttributeEvent::getTimestamp).orElse(-1L)
- + ", event time: " + new Date(attributeEvent.getTimestamp()) + "/" + attributeEvent.getTimestamp() + " in: " + asset);
+ long eventTime = event.getTimestamp();
+ long processingTime = timerService.getCurrentTimeMillis();
- return;
- }
+ try {
+ LOG.fine(">>> Processing start, source " + source +
+ " (event time: " + new Date(eventTime) + "/" + eventTime +
+ ", processing time: " + new Date(processingTime) + "/" + processingTime
+ + ") : " + event);
+
+ // Ensure timestamp of event is not in the future as that would essentially block access to
+ // the attribute until after that time (maybe that is desirable behaviour)
+ // Allow a leniency of 1s
+ if (eventTime - processingTime > 1000) {
+ // TODO: Decide how to handle update events in the future - ignore or change timestamp
+ LOG.warning("Ignoring future " + event
+ + ", current time: " + new Date(processingTime) + "/" + processingTime
+ + ", event time: " + new Date(eventTime) + "/" + eventTime + " in: " + asset);
+ return;
+ }
- // Set new value and event timestamp on attribute
- attribute.setValue(attributeEvent.getValue().orElse(null), attributeEvent.getTimestamp());
+ // Hold on to existing attribute state so we can use it during processing
+ Optional<AttributeEvent> lastStateEvent = attribute.getStateEvent();
- // Validate constraints of attribute
- List<ValidationFailure> validationFailures = attribute.getValidationFailures();
- if (!validationFailures.isEmpty()) {
- LOG.warning("Validation failure(s) " + validationFailures + ", can't process update of: " + attribute);
- return;
- }
+ // Check the last update timestamp of the attribute, ignoring any event that is older than last update
+ // TODO: This means we drop out-of-sequence events, we might need better at-least-once handling
+ if (lastStateEvent.isPresent() && lastStateEvent.get().getTimestamp() >= 0 && eventTime <= lastStateEvent.get().getTimestamp()) {
+ LOG.warning("Ignoring outdated " + event
+ + ", last asset state time: " + lastStateEvent.map(e -> new Date(e.getTimestamp()).toString()).orElse("-1") + "/" + lastStateEvent.map(AttributeEvent::getTimestamp).orElse(-1L)
+ + ", event time: " + new Date(eventTime) + "/" + eventTime + " in: " + asset);
+
+ return;
+ }
+ // Set new value and event timestamp on attribute
+ attribute.setValue(event.getValue().orElse(null), eventTime);
+
+ // Validate constraints of attribute
+ List<ValidationFailure> validationFailures = attribute.getValidationFailures();
+ if (!validationFailures.isEmpty()) {
+ LOG.warning("Validation failure(s) " + validationFailures + ", can't process update of: " + attribute);
+ return;
+ }
- // Push as an asset state through the processing chain
- AssetState assetState = new AssetState(
+ AssetState assetState = new AssetState(
asset,
attribute,
lastStateEvent.flatMap(AttributeEvent::getValue).orElse(null),
lastStateEvent.map(AttributeEvent::getTimestamp).orElse(-1L),
- isSouthbound,
- isSensorUpdate,
- sender);
+ source
+ );
- try {
- LOG.fine(">>> Processing start " +
- "(event time: " + new Date(assetState.getValueTimestamp()) + "/" + assetState.getValueTimestamp() +
- ", processing time: " + new Date(currentMillis) + "/" + currentMillis
- + ") : " + assetState);
processorLoop:
for (Consumer<AssetState> processor : processors) {
try {
@@ -536,27 +367,25 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
LOG.fine("<== Processor " + processor + " finally handled: " + assetState);
break processorLoop;
case ERROR:
- LOG.log(Level.SEVERE, "Processor " + processor + " error: " + assetState, assetState.getError());
+ LOG.log(Level.SEVERE, "<== Processor " + processor + " error: " + assetState, assetState.getError());
break processorLoop;
+ default:
+ LOG.fine("<== Processor " + processor + " done with: " + assetState);
}
}
if (assetState.getProcessingStatus() != AssetState.ProcessingStatus.ERROR) {
assetState.setProcessingStatus(AssetState.ProcessingStatus.COMPLETED);
- publishEvent(assetState);
+ eventService.publishEvent(
+ new AttributeEvent(assetState.getId(), assetState.getAttributeName(), assetState.getValue())
+ );
}
} finally {
lastProcessedEventTimestamp = System.currentTimeMillis();
- LOG.fine("<<< Processing complete: " + assetState);
+ LOG.fine("<<< Processing complete: " + event);
}
}
- protected void publishEvent(AssetState assetState) {
- eventService.publishEvent(
- new AttributeEvent(assetState.getId(), assetState.getAttributeName(), assetState.getValue())
- );
- }
-
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
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 85666ba9f..e19494b1e 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,20 +19,18 @@
*/
package org.openremote.manager.server.asset;
-import org.apache.camel.CamelExecutionException;
-import org.openremote.container.message.MessageBrokerService;
import org.openremote.manager.server.security.ManagerIdentityService;
import org.openremote.manager.server.web.ManagerWebResource;
import org.openremote.manager.shared.asset.AssetProcessingException;
import org.openremote.manager.shared.asset.AssetResource;
import org.openremote.manager.shared.http.RequestParams;
import org.openremote.manager.shared.security.Tenant;
-import org.openremote.manager.shared.security.User;
import org.openremote.model.asset.Asset;
import org.openremote.model.asset.AssetQuery;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeRef;
import org.openremote.model.value.Value;
+import org.openremote.model.value.ValueException;
import org.openremote.model.value.Values;
import javax.ws.rs.WebApplicationException;
@@ -50,16 +48,13 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
protected final AssetStorageService assetStorageService;
protected final AssetProcessingService assetProcessingService;
- protected final MessageBrokerService messageBrokerService;
public AssetResourceImpl(ManagerIdentityService identityService,
AssetStorageService assetStorageService,
- AssetProcessingService assetProcessingService,
- MessageBrokerService messageBrokerService) {
+ AssetProcessingService assetProcessingService) {
super(identityService);
this.assetStorageService = assetStorageService;
this.assetProcessingService = assetProcessingService;
- this.messageBrokerService = messageBrokerService;
}
@Override
@@ -232,51 +227,38 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
@Override
public void writeAttributeValue(RequestParams requestParams, String assetId, String attributeName, String rawJson) {
try {
- ServerAsset asset;
- User user = identityService.getUser(getAccessToken());
-
- Value value = Values.instance()
- .parse(rawJson)
- .orElse(null); // When parsing literal JSON "null"
-
- AttributeEvent event = new AttributeEvent(new AttributeRef(assetId, attributeName), value);
-
- // TODO: Get this working using camel route
- assetProcessingService.sendAttributeEventWithoutCamel(event, user);
-
- // Note camel SEDA endpoints seem to only support InOnly (if you try and set InOut) it will successfully
- // block and wait for a response but you'll get your original message back so cannot get any exception
- // information or anything.
-// messageBrokerService
-// .getProducerTemplate()
-// .sendBodyAndHeader(ASSET_QUEUE, event, SharedEvent.HEADER_SENDER, user);
- } catch (AssetProcessingException assetProcessingException) {
- switch (assetProcessingException.getReason()) {
- case INSUFFICIENT_ACCESS:
- throw new WebApplicationException(Response.Status.FORBIDDEN);
- case ASSET_NOT_FOUND:
- throw new WebApplicationException(NOT_FOUND);
- case ATTRIBUTE_NOT_FOUND:
- throw new WebApplicationException(NOT_FOUND);
- case INVALID_ACTION:
- throw new WebApplicationException(Response.Status.FORBIDDEN);
- }
- } catch (CamelExecutionException ex) {
- // Unwrap the exception
- Throwable cause = ex.getCause();
- if (cause instanceof AssetProcessingException) {
- AssetProcessingException assetProcessingException = (AssetProcessingException)cause;
- switch (assetProcessingException.getReason()) {
+ // Process update
+ try {
+ Value value = Values.instance()
+ .parse(rawJson)
+ .orElse(null); // When parsing literal JSON "null"
+
+ assetProcessingService.processFromClient(
+ getAuthContext(),
+ new AttributeEvent(new AttributeRef(assetId, attributeName), value)
+ );
+
+ } catch (ValueException ex) {
+ throw new IllegalStateException("Error parsing JSON", ex);
+ } catch (AssetProcessingException ex) {
+ switch (ex.getReason()) {
+ case ILLEGAL_SOURCE:
+ case NO_AUTH_CONTEXT:
case INSUFFICIENT_ACCESS:
throw new WebApplicationException(Response.Status.FORBIDDEN);
case ASSET_NOT_FOUND:
- throw new WebApplicationException(NOT_FOUND);
case ATTRIBUTE_NOT_FOUND:
throw new WebApplicationException(NOT_FOUND);
+ case INVALID_AGENT_LINK:
+ case ILLEGAL_AGENT_UPDATE:
+ case INVALID_ATTRIBUTE_EXECUTE_STATUS:
+ throw new IllegalStateException(ex);
+ default:
+ throw ex;
}
}
- throw new IllegalStateException("Error updating attribute: " + attributeName, ex);
- } catch (Exception ex) {
+
+ } catch (IllegalStateException ex) {
throw new WebApplicationException(ex, Response.Status.BAD_REQUEST);
}
}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetRoute.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetRoute.java
new file mode 100644
index 000000000..d6df89f27
--- /dev/null
+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetRoute.java
@@ -0,0 +1,233 @@
+/*
+ * Copyright 2016, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.manager.server.asset;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.Predicate;
+import org.apache.camel.Processor;
+import org.openremote.agent.protocol.Protocol;
+import org.openremote.container.persistence.PersistenceEvent;
+import org.openremote.container.security.AuthContext;
+import org.openremote.manager.server.agent.AgentService;
+import org.openremote.manager.server.security.ManagerIdentityService;
+import org.openremote.manager.shared.asset.AssetProcessingException;
+import org.openremote.manager.shared.asset.AssetProcessingException.Reason;
+import org.openremote.manager.shared.security.ClientRole;
+import org.openremote.model.Constants;
+import org.openremote.model.asset.Asset;
+import org.openremote.model.asset.AssetAttribute;
+import org.openremote.model.asset.AssetType;
+import org.openremote.model.attribute.AttributeEvent;
+import org.openremote.model.attribute.AttributeEvent.Source;
+import org.openremote.model.attribute.AttributeExecuteStatus;
+import org.openremote.model.value.Values;
+
+import java.util.Optional;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import static org.openremote.model.asset.agent.AgentLink.getAgentLink;
+
+public final class AssetRoute {
+
+ public static final String HEADER_ASSET = AssetRoute.class.getName() + ".ASSET";
+ public static final String HEADER_ATTRIBUTE = AssetRoute.class.getName() + ".ATTRIBUTE";
+
+ public static Predicate isPersistenceEventForEntityType(Class<?> type) {
+ return exchange -> {
+ Class<?> entityType = exchange.getIn().getHeader(PersistenceEvent.HEADER_ENTITY_TYPE, Class.class);
+ return type.isAssignableFrom(entityType);
+ };
+ }
+
+ public static Predicate isPersistenceEventForAssetType(AssetType assetType) {
+ return exchange -> {
+ if (!(exchange.getIn().getBody() instanceof PersistenceEvent))
+ return false;
+ PersistenceEvent persistenceEvent = exchange.getIn().getBody(PersistenceEvent.class);
+ Asset asset = (Asset) persistenceEvent.getEntity();
+ return asset.getWellKnownType() == assetType;
+ };
+ }
+
+ public static Processor extractAttributeEventDetails(AssetStorageService assetStorageService) {
+ return exchange -> {
+ AttributeEvent event = exchange.getIn().getBody(AttributeEvent.class);
+ if (event.getEntityId() == null || event.getEntityId().isEmpty())
+ return;
+ if (event.getAttributeName() == null || event.getAttributeName().isEmpty())
+ return;
+
+ ServerAsset asset;
+ if (exchange.getIn().getHeader(HEADER_ASSET) == null) {
+ asset = assetStorageService.find(event.getEntityId(), true);
+ if (asset == null)
+ return;
+ exchange.getIn().setHeader(HEADER_ASSET, asset);
+ } else {
+ asset = exchange.getIn().getHeader(HEADER_ASSET, ServerAsset.class);
+ }
+
+ AssetAttribute attribute;
+ if (exchange.getIn().getHeader(HEADER_ATTRIBUTE) == null) {
+ attribute = asset.getAttribute(event.getAttributeName()).orElse(null);
+ if (attribute == null)
+ return;
+ exchange.getIn().setHeader(HEADER_ATTRIBUTE, attribute);
+ }
+ };
+ }
+
+ public static Processor validateAttributeEvent() {
+ return exchange -> {
+
+ AttributeEvent event = exchange.getIn().getBody(AttributeEvent.class);
+
+ Source source = exchange.getIn().getHeader(AttributeEvent.HEADER_SOURCE, () -> null, Source.class);
+ if (source == null) {
+ throw new AssetProcessingException(Reason.MISSING_SOURCE);
+ }
+
+ ServerAsset asset = exchange.getIn().getHeader(HEADER_ASSET, ServerAsset.class);
+ if (asset == null) {
+ throw new AssetProcessingException(Reason.ASSET_NOT_FOUND);
+ }
+
+ AssetAttribute attribute = exchange.getIn().getHeader(HEADER_ATTRIBUTE, AssetAttribute.class);
+ if (attribute == null) {
+ throw new AssetProcessingException(Reason.ATTRIBUTE_NOT_FOUND);
+ }
+
+ if (asset.getWellKnownType() == AssetType.AGENT) {
+ throw new AssetProcessingException(Reason.ILLEGAL_AGENT_UPDATE);
+ }
+
+ // For executable attributes, non-sensor sources can set a writable attribute execute status
+ if (attribute.isExecutable() && source != Source.SENSOR) {
+ Optional<AttributeExecuteStatus> status = event.getValue()
+ .flatMap(Values::getString)
+ .flatMap(AttributeExecuteStatus::fromString);
+
+ if (!status.isPresent() && !status.get().isWrite()) {
+ throw new AssetProcessingException(Reason.INVALID_ATTRIBUTE_EXECUTE_STATUS);
+ }
+ }
+ };
+ }
+
+ public static Processor validateAttributeEventFromClient(AssetStorageService assetStorageService,
+ ManagerIdentityService identityService) {
+ return exchange -> {
+
+ AuthContext authContext = exchange.getIn().getHeader(Constants.AUTH_CONTEXT, AuthContext.class);
+ if (authContext == null) {
+ throw new AssetProcessingException(Reason.NO_AUTH_CONTEXT);
+ }
+
+ AttributeEvent event = exchange.getIn().getBody(AttributeEvent.class);
+ ServerAsset asset = exchange.getIn().getHeader(HEADER_ASSET, ServerAsset.class);
+ AssetAttribute attribute = exchange.getIn().getHeader(HEADER_ATTRIBUTE, AssetAttribute.class);
+ Source source = exchange.getIn().getHeader(AttributeEvent.HEADER_SOURCE, () -> null, Source.class);
+
+ if (source != Source.CLIENT) {
+ throw new AssetProcessingException(Reason.ILLEGAL_SOURCE);
+ }
+
+ // Check realm, must be accessible
+ if (!identityService.isTenantActiveAndAccessible(authContext, asset)) {
+ throw new AssetProcessingException(Reason.INSUFFICIENT_ACCESS);
+ }
+
+ // Check read-only
+ if (attribute.isReadOnly() && !authContext.isSuperUser()) {
+ throw new AssetProcessingException(Reason.INSUFFICIENT_ACCESS);
+ }
+
+ // Regular user must have write assets role
+ if (!authContext.hasResourceRoleOrIsSuperUser(ClientRole.WRITE_ASSETS.getValue(), Constants.KEYCLOAK_CLIENT_ID)) {
+ throw new AssetProcessingException(Reason.INSUFFICIENT_ACCESS);
+ }
+
+ // Check restricted user
+ if (identityService.isRestrictedUser(authContext.getUserId())) {
+ // Must be asset linked to user
+ if (!assetStorageService.isUserAsset(authContext.getUserId(), event.getEntityId())) {
+ throw new AssetProcessingException(Reason.INSUFFICIENT_ACCESS);
+ }
+ // Must be protected attributes
+ if (!attribute.isProtected()) {
+ throw new AssetProcessingException(Reason.INSUFFICIENT_ACCESS);
+ }
+ }
+ };
+ }
+
+ public static Processor validateAttributeEventFromSensor(AgentService agentService) {
+ return exchange -> {
+
+ AssetAttribute attribute = exchange.getIn().getHeader(HEADER_ATTRIBUTE, AssetAttribute.class);
+ Source source = exchange.getIn().getHeader(AttributeEvent.HEADER_SOURCE, () -> null, Source.class);
+
+ if (source != Source.SENSOR) {
+ throw new AssetProcessingException(Reason.ILLEGAL_SOURCE);
+ }
+
+ Optional<AssetAttribute> protocolConfiguration =
+ getAgentLink(attribute).flatMap(agentService::getProtocolConfiguration);
+
+ if (!protocolConfiguration.isPresent()) {
+ throw new AssetProcessingException(Reason.INVALID_AGENT_LINK);
+ }
+
+ };
+ }
+
+ public static Processor handleAssetProcessingException(Logger logger) {
+ return exchange -> {
+ AttributeEvent event = exchange.getIn().getBody(AttributeEvent.class);
+ Exception exception = (Exception) exchange.getProperty(Exchange.EXCEPTION_CAUGHT);
+
+ StringBuilder error = new StringBuilder();
+
+ Source source = exchange.getIn().getHeader(AttributeEvent.HEADER_SOURCE, "unknown source", Source.class);
+ if (source != null) {
+ error.append("Error processing from ").append(source);
+ }
+
+ String protocolName = exchange.getIn().getHeader(Protocol.SENSOR_QUEUE_SOURCE_PROTOCOL, String.class);
+ if (protocolName != null) {
+ error.append(" (protocol: ").append(protocolName).append(")");
+ }
+
+ if (exception instanceof AssetProcessingException) {
+ AssetProcessingException processingException = (AssetProcessingException) exception;
+ error.append(" - ").append(processingException.getReason());
+ error.append(": ").append(event.toString());
+ logger.warning(error.toString());
+ } else {
+ error.append(": ").append(event.toString());
+ logger.log(Level.WARNING, error.toString(), exception);
+ }
+
+ // Make the exception available if MEP is InOut
+ exchange.getOut().setBody(exception);
+ };
+ }
+}
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 6d1668d71..43a492fc9 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
@@ -24,21 +24,20 @@ import org.hibernate.Session;
import org.hibernate.jdbc.AbstractReturningWork;
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.security.AuthContext;
import org.openremote.container.timer.TimerService;
import org.openremote.container.web.WebService;
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.manager.shared.security.User;
+import org.openremote.model.Constants;
import org.openremote.model.ValidationFailure;
import org.openremote.model.asset.*;
import org.openremote.model.attribute.AttributeEvent;
-import org.openremote.model.event.shared.SharedEvent;
import org.openremote.model.util.Pair;
import org.openremote.model.value.Value;
import org.postgresql.util.PGobject;
@@ -51,7 +50,7 @@ import java.util.logging.Logger;
import java.util.stream.Collectors;
import static org.openremote.container.persistence.PersistenceEvent.PERSISTENCE_TOPIC;
-import static org.openremote.manager.server.asset.AssetPredicates.isPersistenceEventForEntityType;
+import static org.openremote.manager.server.asset.AssetRoute.isPersistenceEventForEntityType;
import static org.openremote.manager.server.event.EventService.INCOMING_EVENT_TOPIC;
import static org.openremote.manager.server.event.EventService.getSessionKey;
@@ -73,31 +72,33 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
eventService = container.getService(EventService.class);
eventService.addSubscriptionAuthorizer((auth, subscription) -> {
- if (subscription.isEventType(AssetTreeModifiedEvent.class)) {
- // Superuser can get all
- if (auth.isSuperUser())
- return true;
+ if (!subscription.isEventType(AssetTreeModifiedEvent.class))
+ return false;
- // Restricted users get nothing (they don't have asset trees, just a list of linked assets)
- if (managerIdentityService.isRestrictedUser(auth.getUserId()))
- return false;
+ // Superuser can get all
+ if (auth.isSuperUser())
+ return true;
- // User must have role
- auth.isUserInRole(ClientRole.READ_ASSETS.getValue());
+ // Restricted users get nothing (they don't have asset trees, just a list of linked assets)
+ if (managerIdentityService.isRestrictedUser(auth.getUserId()))
+ return false;
- // Ensure filter matches authenticated realm
- if (subscription.getFilter() instanceof AssetTreeModifiedEvent.TenantFilter) {
- AssetTreeModifiedEvent.TenantFilter filter =
- (AssetTreeModifiedEvent.TenantFilter) subscription.getFilter();
+ // User must have role
+ auth.hasResourceRole(ClientRole.READ_ASSETS.getValue(), Constants.KEYCLOAK_CLIENT_ID);
- Tenant authenticatedTenant =
- managerIdentityService.getTenantForRealm(auth.getAuthenticatedRealm());
- if (authenticatedTenant == null)
- return false;
- if (filter.getRealmId().equals(authenticatedTenant.getId()))
- return true;
- }
+ // Ensure filter matches authenticated realm
+ if (subscription.getFilter() instanceof AssetTreeModifiedEvent.TenantFilter) {
+ AssetTreeModifiedEvent.TenantFilter filter =
+ (AssetTreeModifiedEvent.TenantFilter) subscription.getFilter();
+
+ Tenant authenticatedTenant =
+ managerIdentityService.getTenantForRealm(auth.getAuthenticatedRealm());
+ if (authenticatedTenant == null)
+ return false;
+ if (filter.getRealmId().equals(authenticatedTenant.getId()))
+ return true;
}
+
return false;
});
@@ -105,8 +106,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
new AssetResourceImpl(
managerIdentityService,
this,
- container.getService(AssetProcessingService.class),
- container.getService(MessageBrokerService.class)
+ container.getService(AssetProcessingService.class)
)
);
@@ -143,36 +143,47 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
public void configure() throws Exception {
// If any asset was modified in the database, publish events
from(PERSISTENCE_TOPIC)
+ .routeId("AssetPersistenceChanges")
.filter(isPersistenceEventForEntityType(ServerAsset.class))
.process(exchange -> publishModificationEvents(exchange.getIn().getBody(PersistenceEvent.class)));
// React if a client wants to read attribute state
from(INCOMING_EVENT_TOPIC)
+ .routeId("FromClientReadRequests")
.filter(body().isInstanceOf(ReadAssetAttributesEvent.class))
- .filter(header(SharedEvent.HEADER_SENDER).isInstanceOf(User.class))
.process(exchange -> {
- String sessionKey = getSessionKey(exchange);
ReadAssetAttributesEvent event = exchange.getIn().getBody(ReadAssetAttributesEvent.class);
- User user = exchange.getIn().getHeader(SharedEvent.HEADER_SENDER, User.class);
LOG.fine("Handling from client: " + event);
- if (event.getAssetId() == null || event.getAssetId().isEmpty() || user == null)
+ if (event.getAssetId() == null || event.getAssetId().isEmpty())
return;
- if (!user.isSuperUser() && !user.hasRole(ClientRole.READ_ASSETS.getValue())) {
+ String sessionKey = getSessionKey(exchange);
+ AuthContext authContext = exchange.getIn().getHeader(Constants.AUTH_CONTEXT, AuthContext.class);
+
+ // Superuser can get all
+ if (authContext.isSuperUser()) {
+ ServerAsset asset = find(event.getAssetId(), true);
+ if (asset != null)
+ replyWithAttributeEvents(sessionKey, asset, event.getAttributeNames());
+ return;
+ }
+
+ // User must have role
+ if (!authContext.hasResourceRole(ClientRole.READ_ASSETS.getValue(), Constants.KEYCLOAK_CLIENT_ID)) {
return;
}
ServerAsset asset = find(
event.getAssetId(),
true,
- user.isRestricted() // Restricted users get filtered state
+ managerIdentityService.isRestrictedUser(authContext.getUserId()) // Restricted users get filtered state
);
-
if (asset != null) {
replyWithAttributeEvents(sessionKey, asset, event.getAttributeNames());
}
});
+
}
public ServerAsset find(String assetId) {
@@ -682,7 +693,6 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
}
}
-
protected void replyWithAttributeEvents(String sessionKey, ServerAsset asset, String[] attributeNames) {
List<String> names = attributeNames == null ? Collections.emptyList() : Arrays.asList(attributeNames);
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 b79ff3475..ba4533883 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
@@ -25,15 +25,11 @@ 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.security.AuthContext;
import org.openremote.container.timer.TimerService;
-import org.openremote.container.web.socket.WebsocketAuth;
import org.openremote.container.web.socket.WebsocketConstants;
-import org.openremote.manager.server.asset.AssetProcessingService;
-import org.openremote.manager.server.asset.AssetStorageService;
import org.openremote.manager.server.concurrent.ManagerExecutorService;
-import org.openremote.manager.server.security.ManagerIdentityService;
-import org.openremote.manager.shared.security.User;
-import org.openremote.model.attribute.AttributeEvent;
+import org.openremote.model.Constants;
import org.openremote.model.event.shared.CancelEventSubscription;
import org.openremote.model.event.shared.EventSubscription;
import org.openremote.model.event.shared.SharedEvent;
@@ -45,7 +41,6 @@ import java.util.concurrent.CopyOnWriteArraySet;
import java.util.logging.Logger;
import static org.apache.camel.builder.PredicateBuilder.or;
-import static org.openremote.manager.server.asset.AssetProcessingService.ASSET_QUEUE;
/**
* Receives and publishes messages, handles the client/server event bus.
@@ -107,24 +102,17 @@ public class EventService implements ContainerService {
final protected Collection<EventSubscriptionAuthorizer> eventSubscriptionAuthorizers = new CopyOnWriteArraySet<>();
protected MessageBrokerService messageBrokerService;
- protected ManagerIdentityService managerIdentityService;
- protected AssetStorageService assetStorageService;
- protected AssetProcessingService assetProcessingService;
protected EventSubscriptions eventSubscriptions;
@Override
public void init(Container container) throws Exception {
messageBrokerService = container.getService(MessageBrokerService.class);
- managerIdentityService = container.getService(ManagerIdentityService.class);
- assetStorageService = container.getService(AssetStorageService.class);
- assetProcessingService = container.getService(AssetProcessingService.class);
eventSubscriptions = new EventSubscriptions(
container.getService(TimerService.class),
container.getService(ManagerExecutorService.class)
);
-
MessageBrokerSetupService messageBrokerSetupService = container.getService(MessageBrokerSetupService.class);
messageBrokerSetupService.getContext().getTypeConverterRegistry().addTypeConverters(
new EventTypeConverters()
@@ -135,7 +123,7 @@ public class EventService implements ContainerService {
public void configure() throws Exception {
from("websocket://" + WEBSOCKET_EVENTS)
- .routeId("Receive incoming message on WebSocket session(s)")
+ .routeId("FromClientWebsocketEvents")
.choice()
.when(header(WebsocketConstants.SESSION_OPEN))
.process(exchange -> {
@@ -158,13 +146,13 @@ public class EventService implements ContainerService {
.process(exchange -> {
String sessionKey = getSessionKey(exchange);
EventSubscription subscription = exchange.getIn().getBody(EventSubscription.class);
- WebsocketAuth auth = getWebsocketAuth(exchange);
+ AuthContext authContext = exchange.getIn().getHeader(Constants.AUTH_CONTEXT, AuthContext.class);
if (eventSubscriptionAuthorizers.stream()
- .anyMatch(authorizer -> authorizer.apply(auth, subscription))) {
+ .anyMatch(authorizer -> authorizer.apply(authContext, subscription))) {
eventSubscriptions.update(sessionKey, subscription);
} else {
LOG.warning("Unauthorized subscription from '"
- + auth.getUsername() + "' in realm '" + auth.getAuthenticatedRealm()
+ + authContext.getUsername() + "' in realm '" + authContext.getAuthenticatedRealm()
+ "': " + subscription
);
sendToSession(sessionKey, new UnauthorizedEventSubscription(subscription.getEventType()));
@@ -177,25 +165,14 @@ public class EventService implements ContainerService {
eventSubscriptions.cancel(sessionKey, exchange.getIn().getBody(CancelEventSubscription.class));
})
.when(bodyAs(String.class).startsWith(SharedEvent.MESSAGE_PREFIX))
- .convertBodyTo(SharedEvent.class)
- .process(exchange -> {
- WebsocketAuth auth = getWebsocketAuth(exchange);
-
- // Extract user object to use as the sender
- User user = managerIdentityService.getUser(auth.getAccessToken());
- exchange.getIn().setHeader(SharedEvent.HEADER_SENDER, user);
- }).end()
- .choice()
- .when(body().isInstanceOf(AttributeEvent.class))
- .to(ASSET_QUEUE).stop()
- .when(body().isInstanceOf(SharedEvent.class))
- .to(INCOMING_EVENT_TOPIC)
+ .convertBodyTo(SharedEvent.class)
+ .to(EventService.INCOMING_EVENT_TOPIC)
.otherwise()
.process(exchange -> LOG.fine("Unsupported message body: " + exchange.getIn().getBody()))
.end();
from(EventService.OUTGOING_EVENT_QUEUE)
- .routeId("Send outgoing events to WebSocket session(s)")
+ .routeId("ToClientWebsocketEvents")
.choice()
.when(body().isInstanceOf(SharedEvent.class))
.split(method(eventSubscriptions, "splitForSubscribers"))
@@ -246,13 +223,6 @@ public class EventService implements ContainerService {
return exchange.getIn().getHeader(WebsocketConstants.SESSION_KEY, String.class);
}
- public static WebsocketAuth getWebsocketAuth(Exchange exchange) {
- WebsocketAuth auth = exchange.getIn().getHeader(WebsocketConstants.AUTH, WebsocketAuth.class);
- if (auth == null)
- throw new IllegalStateException("No authorization details in websocket exchange");
- return auth;
- }
-
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
diff --git a/manager/server/src/main/java/org/openremote/manager/server/event/EventSubscriptionAuthorizer.java b/manager/server/src/main/java/org/openremote/manager/server/event/EventSubscriptionAuthorizer.java
index 5fe28a5f0..10c6f30ef 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/event/EventSubscriptionAuthorizer.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/event/EventSubscriptionAuthorizer.java
@@ -19,7 +19,7 @@
*/
package org.openremote.manager.server.event;
-import org.openremote.container.web.socket.WebsocketAuth;
+import org.openremote.container.security.AuthContext;
import org.openremote.model.event.shared.EventSubscription;
import java.util.function.BiFunction;
@@ -31,6 +31,6 @@ import java.util.function.BiFunction;
* permissions. It might also fail if the subscription is invalid, for example, if
* a required filter is not supplied or if the filter is not valid.
*/
-public interface EventSubscriptionAuthorizer extends BiFunction<WebsocketAuth, EventSubscription, Boolean> {
+public interface EventSubscriptionAuthorizer extends BiFunction<AuthContext, EventSubscription, Boolean> {
}
\ No newline at end of file
diff --git a/manager/server/src/main/java/org/openremote/manager/server/event/EventSubscriptions.java b/manager/server/src/main/java/org/openremote/manager/server/event/EventSubscriptions.java
index 8f258d55d..b3adeee53 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/event/EventSubscriptions.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/event/EventSubscriptions.java
@@ -122,6 +122,7 @@ public class EventSubscriptions {
}
}
+ @SuppressWarnings("unchecked")
public <T extends SharedEvent> List<Message> splitForSubscribers(Exchange exchange) {
List<Message> messageList = new ArrayList<>();
SharedEvent event = exchange.getIn().getBody(SharedEvent.class);
diff --git a/manager/server/src/main/java/org/openremote/manager/server/map/MapResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/map/MapResourceImpl.java
index 3cc52036e..ef57d3ed9 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/map/MapResourceImpl.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/map/MapResourceImpl.java
@@ -40,7 +40,10 @@ public class MapResourceImpl extends WebResource implements MapResource {
@Override
public ObjectValue getSettings(RequestParams requestParams) {
- return mapService.getMapSettings(getRealm(), identityService.getExternalServerUri().clone());
+ return mapService.getMapSettings(
+ getAuthenticatedRealm(),
+ identityService.getExternalServerUri().clone()
+ );
}
@Override
diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesEngine.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesEngine.java
index a649a988d..dcfca02b8 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesEngine.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesEngine.java
@@ -53,11 +53,11 @@ import org.openremote.manager.shared.rules.AssetRuleset;
import org.openremote.manager.shared.rules.GlobalRuleset;
import org.openremote.manager.shared.rules.Ruleset;
import org.openremote.manager.shared.rules.TenantRuleset;
-import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.asset.AbstractAssetUpdate;
import org.openremote.model.asset.AssetEvent;
import org.openremote.model.asset.AssetQuery;
import org.openremote.model.asset.AssetState;
+import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.notification.AlertNotification;
import org.openremote.model.rules.Assets;
import org.openremote.model.rules.Users;
@@ -635,7 +635,7 @@ public class RulesEngine<T extends Ruleset> {
}
LOG.fine("Dispatching on " + RulesEngine.this + ": " + event);
- assetProcessingService.sendAttributeEvent(event, RulesEngine.this);
+ assetProcessingService.sendAttributeEvent(event, AttributeEvent.Source.INTERNAL);
}
}
};
diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java
index 9a24060a1..8c06ccdd2 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java
@@ -41,6 +41,7 @@ import org.openremote.manager.shared.rules.TenantRuleset;
import org.openremote.manager.shared.security.Tenant;
import org.openremote.model.AbstractValueTimestampHolder;
import org.openremote.model.asset.*;
+import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.util.Pair;
import org.openremote.model.value.ObjectValue;
@@ -54,7 +55,7 @@ import java.util.stream.Stream;
import static org.openremote.container.persistence.PersistenceEvent.PERSISTENCE_TOPIC;
import static org.openremote.container.util.MapAccess.getString;
-import static org.openremote.manager.server.asset.AssetPredicates.isPersistenceEventForEntityType;
+import static org.openremote.manager.server.asset.AssetRoute.isPersistenceEventForEntityType;
import static org.openremote.model.asset.AssetAttribute.attributesFromJson;
/**
@@ -119,6 +120,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
public void configure() throws Exception {
// If any ruleset was modified in the database then check its' status and undeploy, deploy, or update it
from(PERSISTENCE_TOPIC)
+ .routeId("RulesetPersistenceChanges")
.filter(isPersistenceEventForEntityType(Ruleset.class))
.process(exchange -> {
PersistenceEvent persistenceEvent = exchange.getIn().getBody(PersistenceEvent.class);
@@ -128,6 +130,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
// If any tenant was modified in the database then check its' status and undeploy, deploy or update any
// associated rulesets
from(PERSISTENCE_TOPIC)
+ .routeId("RuleEngineTenantChanges")
.filter(isPersistenceEventForEntityType(Tenant.class))
.process(exchange -> {
PersistenceEvent persistenceEvent = exchange.getIn().getBody(PersistenceEvent.class);
@@ -137,6 +140,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
// If any asset was modified in the database, detect changed attributes
from(PERSISTENCE_TOPIC)
+ .routeId("RuleEngineAssetChanges")
.filter(isPersistenceEventForEntityType(Asset.class))
.process(exchange -> {
PersistenceEvent persistenceEvent = exchange.getIn().getBody(PersistenceEvent.class);
@@ -172,7 +176,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
.forEach(pair -> {
ServerAsset asset = pair.key;
pair.value.forEach(ruleAttribute -> {
- AssetState assetState = new AssetState(asset, ruleAttribute, false, false, null);
+ AssetState assetState = new AssetState(asset, ruleAttribute, AttributeEvent.Source.INTERNAL);
// Set the status to completed already so rules cannot interfere with this initial insert
assetState.setProcessingStatus(AssetState.ProcessingStatus.COMPLETED);
updateAssetState(assetState, true);
@@ -252,13 +256,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
// We must load the asset from database (only when required), as the
// persistence event might not contain a completely loaded asset
BiFunction<Asset, AssetAttribute, AssetState> buildAssetState = (loadedAsset, attribute) ->
-
- new AssetState(loadedAsset,
- attribute.deepCopy(),
- false,
- false,
- null
- );
+ new AssetState(loadedAsset, attribute.deepCopy(), AttributeEvent.Source.INTERNAL);
Asset loadedAsset;
@@ -362,7 +360,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
.forEach(attribute -> {
// We can't load the asset again (it was deleted), so don't use buildAssetState() and
// hope that the path of the event asset has been loaded before deletion
- AssetState assetState = new AssetState(asset, attribute, false, false, null);
+ AssetState assetState = new AssetState(asset, attribute, AttributeEvent.Source.INTERNAL);
LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), retracting fact: " + assetState);
retractAssetState(assetState);
});
@@ -430,7 +428,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
assetStorageService,
notificationService,
assetProcessingService,
- identityService,
+ identityService,
GlobalRuleset.class,
ID_GLOBAL_RULES_ENGINE,
rulesEngineListeners
@@ -466,7 +464,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
assetStorageService,
notificationService,
assetProcessingService,
- identityService,
+ identityService,
TenantRuleset.class,
realmId,
rulesEngineListeners
@@ -532,7 +530,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
assetStorageService,
notificationService,
assetProcessingService,
- identityService,
+ identityService,
AssetRuleset.class,
assetId,
rulesEngineListeners
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 953f2b2ef..a9a43221a 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
@@ -23,15 +23,14 @@ import org.apache.camel.ExchangePattern;
import org.keycloak.admin.client.resource.ClientResource;
import org.keycloak.admin.client.resource.ClientsResource;
import org.keycloak.admin.client.resource.RolesResource;
-import org.keycloak.representations.AccessToken;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.representations.idm.RoleRepresentation;
-import org.keycloak.representations.idm.UserRepresentation;
import org.openremote.container.Container;
import org.openremote.container.message.MessageBrokerService;
import org.openremote.container.persistence.PersistenceEvent;
import org.openremote.container.persistence.PersistenceService;
+import org.openremote.container.security.AuthContext;
import org.openremote.container.security.IdentityService;
import org.openremote.container.web.WebService;
import org.openremote.manager.server.event.EventService;
@@ -40,6 +39,7 @@ import org.openremote.manager.shared.security.Tenant;
import org.openremote.manager.shared.security.TenantEmailConfig;
import org.openremote.manager.shared.security.User;
import org.openremote.model.Constants;
+import org.openremote.model.asset.Asset;
import org.openremote.model.asset.AssetTreeModifiedEvent;
import javax.ws.rs.core.UriBuilder;
@@ -47,9 +47,8 @@ import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
-import static org.openremote.manager.server.util.JsonUtil.convert;
import static org.openremote.model.Constants.*;
-import static org.openremote.model.util.TextUtil.requireNonNullAndNonEmpty;
+import static org.openremote.manager.server.util.JsonUtil.convert;
public class ManagerIdentityService extends IdentityService {
@@ -133,6 +132,26 @@ public class ManagerIdentityService extends IdentityService {
});
}
+ public Tenant getAuthenticatedTenant(AuthContext authContext) {
+ return getTenantForRealm(authContext.getAuthenticatedRealm());
+ }
+
+ /**
+ * @return <code>true</code> if the user is the superuser (admin) or if the user is authenticated
+ * in the same realm as the tenant and the tenant is active.
+ */
+ public boolean isTenantActiveAndAccessible(AuthContext authContext, Tenant tenant) {
+ return tenant != null && (authContext.isSuperUser() || (tenant.isActive() && authContext.isRealmAccessibleByUser(tenant.getRealm())));
+ }
+
+ /**
+ * @return <code>true</code> if the user is the superuser (admin) or if the user is authenticated
+ * in the same realm as the assets' realm and the tenant is active.
+ */
+ public boolean isTenantActiveAndAccessible(AuthContext authContext, Asset asset) {
+ return isTenantActiveAndAccessible(authContext, getTenant(asset.getRealmId()));
+ }
+
public String[] getActiveTenantIds() {
return persistenceService.doReturningTransaction(entityManager -> {
@SuppressWarnings("unchecked")
@@ -242,59 +261,6 @@ public class ManagerIdentityService extends IdentityService {
});
}
- // TODO: Have a single getUser method that gets all data in a single query
-
- /**
- * Get user from their Keycloak {@link UserRepresentation}
- */
- public User getUser(String realm, UserRepresentation userRepresentation) {
- User user = convert(Container.JSON, User.class, userRepresentation);
- user.setRealm(realm);
- populateUserConfiguration(user);
- return user;
- }
-
- /**
- * Get user from their Keycloak {@link AccessToken}
- */
- public User getUser(AccessToken accessToken) {
- String realm = accessToken.getIssuer().substring(accessToken.getIssuer().lastIndexOf('/') + 1);
- requireNonNullAndNonEmpty(realm);
- User user = new User();
- user.setId(accessToken.getSubject());
- user.setUsername(accessToken.getPreferredUsername());
- user.setClient(accessToken.getIssuedFor());
- user.setRealm(realm);
- user.setFirstName(accessToken.getGivenName());
- user.setLastName(accessToken.getFamilyName());
- user.setEmail(accessToken.getEmail());
- user.setEnabled(accessToken.isActive()); // If they have an active token then they're enabled
- user.setRealmRoles(new ArrayList<>(accessToken.getRealmAccess().getRoles()));
- accessToken.getResourceAccess()
- .forEach(
- (client, clientRoles) -> {
- user.addClientRoles(client, new ArrayList<>(clientRoles.getRoles()));
- }
- );
- populateUserConfiguration(user);
- return user;
- }
-
- /**
- * Get user from their ID
- */
- // TODO: populate missing data
- public User getUser(String userId, boolean loadComplete) {
- return persistenceService.doReturningTransaction(em -> {
- return em.find(User.class, userId);
- });
- }
-
- protected void populateUserConfiguration(User user) {
- UserConfiguration userConfiguration = getUserConfiguration(user.getId());
- user.setRestricted(userConfiguration.isRestricted());
- }
-
/**
* Use PERSISTENCE_TOPIC and persistence event
*/
diff --git a/manager/server/src/main/java/org/openremote/manager/server/security/UserResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/security/UserResourceImpl.java
index 78f7819b5..d1cb2eb49 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/security/UserResourceImpl.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/security/UserResourceImpl.java
@@ -68,7 +68,7 @@ public class UserResourceImpl extends WebResource implements UserResource {
.realm(realm).users().search(null, 0, Integer.MAX_VALUE);
List<User> users = new ArrayList<>();
for (UserRepresentation userRepresentation : userRepresentations) {
- users.add(identityService.getUser(realm, userRepresentation));
+ users.add(convertUser(realm, userRepresentation));
}
return users.toArray(new User[users.size()]);
} catch (ClientErrorException ex) {
@@ -84,7 +84,7 @@ public class UserResourceImpl extends WebResource implements UserResource {
throw new WebApplicationException(Response.Status.FORBIDDEN);
}
try {
- return identityService.getUser(
+ return convertUser(
realm,
identityService.getRealms(getClientRemoteAddress(), requestParams.getBearerAuth())
.realm(realm).users().get(userId).toRepresentation()
@@ -281,6 +281,12 @@ public class UserResourceImpl extends WebResource implements UserResource {
}
}
+ protected User convertUser(String realm, UserRepresentation userRepresentation) {
+ User user = convert(Container.JSON, User.class, userRepresentation);
+ user.setRealm(realm);
+ return user;
+ }
+
protected ConstraintViolationReport isIllegalMasterAdminUserDeletion(RequestParams requestParams, String realm, String userId) {
if (!realm.equals(MASTER_REALM))
return null;
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 346e6ff5e..8ca42de85 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
@@ -255,54 +255,54 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
AssetAttribute light1PowerConsumptionAttribute = thing.getAttribute("light1PowerConsumption")
.orElseThrow(() -> new RuntimeException("Invalid test data"));
- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, false, false, null));
+ assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR));
light1PowerConsumptionAttribute.setValue(Values.create(0.11), now.minusDays(80).toEpochSecond() * 1000);
- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, false, false, null));
+ assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR));
light1PowerConsumptionAttribute.setValue(Values.create(1.22), now.minusDays(40).toEpochSecond() * 1000);
- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, false, false, null));
+ assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR));
light1PowerConsumptionAttribute.setValue(Values.create(2.33), now.minusDays(20).toEpochSecond() * 1000);
- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, false, false, null));
+ assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR));
light1PowerConsumptionAttribute.setValue(Values.create(3.44), now.minusDays(10).toEpochSecond() * 1000);
- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, false, false, null));
+ assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR));
light1PowerConsumptionAttribute.setValue(Values.create(4.55), now.minusDays(8).toEpochSecond() * 1000);
light1PowerConsumptionAttribute.setValue(Values.create(5.66), now.minusDays(6).toEpochSecond() * 1000);
- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, false, false, null));
+ assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR));
light1PowerConsumptionAttribute.setValue(Values.create(6.77), now.minusDays(3).toEpochSecond() * 1000);
- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, false, false, null));
+ assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR));
light1PowerConsumptionAttribute.setValue(Values.create(7.88), now.minusDays(1).toEpochSecond() * 1000);
- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, false, false, null));
+ assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR));
light1PowerConsumptionAttribute.setValue(Values.create(8.99), now.minusHours(10).toEpochSecond() * 1000);
- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, false, false, null));
+ assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR));
light1PowerConsumptionAttribute.setValue(Values.create(9.11), now.minusHours(5).toEpochSecond() * 1000);
- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, false, false, null));
+ assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR));
light1PowerConsumptionAttribute.setValue(Values.create(10.22), now.minusHours(2).toEpochSecond() * 1000);
- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, false, false, null));
+ assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR));
light1PowerConsumptionAttribute.setValue(Values.create(11.33), now.minusHours(1).toEpochSecond() * 1000);
- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, false, false, null));
+ assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR));
light1PowerConsumptionAttribute.setValue(Values.create(11.44), now.minusMinutes(30).toEpochSecond() * 1000);
- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, false, false, null));
+ assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR));
light1PowerConsumptionAttribute.setValue(Values.create(12.00), now.minusMinutes(5).toEpochSecond() * 1000);
- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, false, false, null));
+ assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR));
light1PowerConsumptionAttribute.setValue(Values.create(12.11), now.minusSeconds(5).toEpochSecond() * 1000);
- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, false, false, null));
+ assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR));
light1PowerConsumptionAttribute.setValue(Values.create(12.22), now.minusSeconds(1).toEpochSecond() * 1000);
- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, false, false, null));
+ assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR));
// ################################ Demo assets for 'customerA' realm ###################################
diff --git a/manager/server/src/main/java/org/openremote/manager/server/web/ManagerWebResource.java b/manager/server/src/main/java/org/openremote/manager/server/web/ManagerWebResource.java
index 93477d6ad..aab089352 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/web/ManagerWebResource.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/web/ManagerWebResource.java
@@ -41,15 +41,11 @@ public class ManagerWebResource extends WebResource {
}
public boolean isTenantActiveAndAccessible(Asset asset) {
- return isTenantActiveAndAccessible(identityService.getTenant(asset.getRealmId()));
+ return identityService.isTenantActiveAndAccessible(this, asset);
}
- /**
- * @return <code>true</code> if the user is the superuser (admin) or if the user is authenticated
- * in the same realm as the tenant and the tenant is active.
- */
public boolean isTenantActiveAndAccessible(Tenant tenant) {
- return tenant != null && (isSuperUser() || (tenant.isActive() && super.isRealmAccessibleByUser(tenant.getRealm())));
+ return identityService.isTenantActiveAndAccessible(this, tenant);
}
}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/asset/AssetProcessingException.java b/manager/shared/src/main/java/org/openremote/manager/shared/asset/AssetProcessingException.java
index b41b4f71e..435cefb16 100644
--- a/manager/shared/src/main/java/org/openremote/manager/shared/asset/AssetProcessingException.java
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/asset/AssetProcessingException.java
@@ -19,12 +19,61 @@
*/
package org.openremote.manager.shared.asset;
+import org.openremote.model.asset.AssetAttribute;
+import org.openremote.model.asset.AssetType;
+import org.openremote.model.attribute.AttributeExecuteStatus;
+
public class AssetProcessingException extends RuntimeException {
+
public enum Reason {
- INSUFFICIENT_ACCESS,
+
+ /**
+ * Missing {@link org.openremote.model.attribute.AttributeEvent.Source}.
+ */
+ MISSING_SOURCE,
+
+ /**
+ * The source of the event does not match the expected source (e.g. expected client message
+ * but received sensor read).
+ */
+ ILLEGAL_SOURCE,
+
+ /**
+ * The asset does not exist.
+ */
ASSET_NOT_FOUND,
+
+ /**
+ * The attribute does not exist.
+ */
ATTRIBUTE_NOT_FOUND,
- INVALID_ACTION
+
+ /**
+ * A sensor update must be for an attribute with a valid agent link.
+ */
+ INVALID_AGENT_LINK,
+
+ /**
+ * Attributes of an {@link AssetType#AGENT} can not be individually updated.
+ */
+ ILLEGAL_AGENT_UPDATE,
+
+ /**
+ * Invalid {@link AttributeExecuteStatus} for {@link AssetAttribute#isExecutable()} attribute,
+ * must be {@link AttributeExecuteStatus#isWrite()}.
+ */
+ INVALID_ATTRIBUTE_EXECUTE_STATUS,
+
+ /**
+ * No authentication/authorization context available.
+ */
+ NO_AUTH_CONTEXT,
+
+ /**
+ * Realm configuration or user privileges do not allow update (e.g. realm inactive, user is
+ * missing required role, attribute is read-only).
+ */
+ INSUFFICIENT_ACCESS
}
protected Reason reason;
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/security/User.java b/manager/shared/src/main/java/org/openremote/manager/shared/security/User.java
index 75dce09ef..c6faede7f 100644
--- a/manager/shared/src/main/java/org/openremote/manager/shared/security/User.java
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/security/User.java
@@ -22,7 +22,6 @@ package org.openremote.manager.shared.security;
import org.hibernate.annotations.Formula;
import org.hibernate.annotations.Subselect;
import org.hibernate.validator.constraints.Email;
-import org.openremote.model.Constants;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -31,7 +30,6 @@ import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
-import java.util.*;
/**
* This can be used (among other things) to query the Keycloak USER_ENTITY table in JPA queries.
@@ -64,21 +62,6 @@ public class User {
@Column(name = "ENABLED")
protected Boolean enabled;
- // TODO: Extract this data from the SQL view when not available in access token
- @Transient
- protected String client;
-
- // TODO: Extract this data from the SQL view when not available in access token
- @Transient
- protected Map<String, List<String>> clientRoles;
-
- // TODO: Extract this data from the SQL view when not available in access token
- @Transient
- protected List<String> realmRoles;
-
- @Formula("(select u.RESTRICTED from USER_CONFIGURATION u where u.USER_ID = ID)")
- protected boolean restricted;
-
public User() {
}
@@ -152,64 +135,6 @@ public class User {
this.enabled = enabled;
}
- public Set<String> getRoles() {
- List<String> roles = clientRoles != null ? clientRoles.get(client) : null;
- return roles != null ? new HashSet<>(roles) : Collections.emptySet();
- }
-
- public Map<String, List<String>> getClientRoles() {
- return clientRoles;
- }
-
- public void setClientRoles(Map<String, List<String>> clientRoles) {
- this.clientRoles = clientRoles;
- }
-
- public void addClientRoles(String client, List<String> roles) {
- if (client != null) {
- if (clientRoles == null) {
- clientRoles = new HashMap<>();
- }
- clientRoles.put(client, roles);
- }
- }
-
- public List<String> getRealmRoles() {
- return realmRoles;
- }
-
- public void setRealmRoles(List<String> realmRoles) {
- this.realmRoles = realmRoles;
- }
-
- public String getClient() {
- return client;
- }
-
- public void setClient(String client) {
- this.client = client;
- }
-
- public boolean isRestricted() {
- return !isSuperUser() && restricted;
- }
-
- public void setRestricted(boolean restricted) {
- this.restricted = restricted;
- }
-
- public boolean isSuperUser() {
- return getRealm().equals(Constants.MASTER_REALM) && hasRealmRole(Constants.REALM_ADMIN_ROLE);
- }
-
- public boolean hasRole(String role) {
- return getRoles() != null && getRoles().contains(role);
- }
-
- public boolean hasRealmRole(String role) {
- return getRealmRoles() != null && getRealmRoles().contains(role);
- }
-
@Override
public String toString() {
return getClass().getName() + "{" +
diff --git a/manager/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy
index 3a3b3ddf0..6c205b416 100644
--- a/manager/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy
@@ -32,7 +32,7 @@ class AssetDatapointTest extends Specification implements ManagerContainerTrait
}
when: "a simulated sensor changes its value several times"
- conditions = new PollingConditions(timeout: 3, initialDelay: 1)
+ conditions = new PollingConditions(timeout: 10, initialDelay: 1)
sleep(10)
simulatorProtocol.putState(managerDemoSetup.thingId, "light1PowerConsumption", Values.create(13.3))
sleep(10)
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 e6c7486f4..1d104bc14 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
@@ -171,7 +171,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
assert asset.getAttribute("geoStreet").get().getValue().get().toJson() == Values.create("Teststreet 123").toJson()
}
- when: "an non-existent attribute is written in the authenticated realm"
+ when: "an non-existent assets attribute is written in the authenticated realm"
assetResource.writeAttributeValue(null, "doesnotexist", "geoStreet", Values.create("Teststreet 123").toJson())
then: "the attribute should be not found"
diff --git a/model/src/main/java/org/openremote/model/Constants.java b/model/src/main/java/org/openremote/model/Constants.java
index ee70f7219..f2459ea68 100644
--- a/model/src/main/java/org/openremote/model/Constants.java
+++ b/model/src/main/java/org/openremote/model/Constants.java
@@ -25,6 +25,7 @@ public interface Constants {
String MASTER_REALM = "master";
String MASTER_REALM_ADMIN_USER = "admin";
String REALM_ADMIN_ROLE = "admin";
+ String AUTH_CONTEXT = "AUTH_CONTEXT";
int ACCESS_TOKEN_LIFESPAN_SECONDS = 300; // 5 minutes
String PERSISTENCE_SEQUENCE_ID_GENERATOR = "SEQUENCE_ID_GENERATOR";
String PERSISTENCE_UNIQUE_ID_GENERATOR = "UNIQUE_ID_GENERATOR";
diff --git a/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java b/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java
index 1dc15a3b7..8cb3aa474 100644
--- a/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java
+++ b/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java
@@ -72,18 +72,13 @@ public abstract class AbstractAssetUpdate {
final protected long oldValueTimestamp;
- final protected boolean southbound;
+ final protected AttributeEvent.Source source;
- final protected boolean sensorUpdate;
-
- final protected Object sender;
-
-
- public AbstractAssetUpdate(Asset asset, AssetAttribute attribute, boolean southbound, boolean sensorUpdate, Object sender) {
- this(asset, attribute, null, 0, southbound, sensorUpdate, sender);
+ public AbstractAssetUpdate(Asset asset, AssetAttribute attribute, AttributeEvent.Source source) {
+ this(asset, attribute, null, 0, source);
}
- public AbstractAssetUpdate(Asset asset, AssetAttribute attribute, Value oldValue, long oldValueTimestamp, boolean southbound, boolean sensorUpdate, Object sender) {
+ public AbstractAssetUpdate(Asset asset, AssetAttribute attribute, Value oldValue, long oldValueTimestamp, AttributeEvent.Source source) {
this(
attribute,
asset.getCreatedOn(),
@@ -101,9 +96,7 @@ public abstract class AbstractAssetUpdate {
asset.getCoordinates(),
oldValue,
oldValueTimestamp,
- southbound,
- sensorUpdate,
- sender
+ source
);
}
@@ -125,9 +118,7 @@ public abstract class AbstractAssetUpdate {
that.coordinates,
that.oldValue,
that.oldValueTimestamp,
- that.southbound,
- that.sensorUpdate,
- that.sender
+ that.source
);
}
@@ -138,9 +129,7 @@ public abstract class AbstractAssetUpdate {
double[] coordinates,
Value oldValue,
long oldValueTimestamp,
- boolean southbound,
- boolean sensorUpdate,
- Object sender) {
+ AttributeEvent.Source source) {
this.attribute = attribute;
this.createdOn = createdOn;
this.id = id;
@@ -160,9 +149,7 @@ public abstract class AbstractAssetUpdate {
this.coordinates = coordinates;
this.oldValue = oldValue;
this.oldValueTimestamp = oldValueTimestamp;
- this.southbound = southbound;
- this.sensorUpdate = sensorUpdate;
- this.sender = sender;
+ this.source = source;
}
public Date getCreatedOn() {
@@ -225,17 +212,8 @@ public abstract class AbstractAssetUpdate {
return oldValueTimestamp;
}
- /**
- * True if the update was initiated by a user/client (and not protocol or internal) and
- * is being processed southbound.
- */
- public boolean isSouthbound() {
- return southbound;
- }
-
-
- public boolean isSensorUpdate() {
- return sensorUpdate;
+ public AttributeEvent.Source getSource() {
+ return source;
}
public Value getValue() {
@@ -337,6 +315,7 @@ public abstract class AbstractAssetUpdate {
", valueTimestamp=" + getValueTimestamp() +
", oldValue='" + (getOldValue() != null ? getOldValue().toJson() : "null") + '\'' +
", oldValueTimestamp=" + getOldValueTimestamp() +
+ ", source=" + getSource() +
'}';
}
}
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 b1c55c376..326c3b241 100644
--- a/model/src/main/java/org/openremote/model/asset/Asset.java
+++ b/model/src/main/java/org/openremote/model/asset/Asset.java
@@ -355,11 +355,10 @@ public class Asset implements IdentifiableEntity {
);
}
+ /**
+ * Replaces existing or adds the attribute if it does not exist.
+ */
public void replaceAttribute(AssetAttribute attribute) throws IllegalArgumentException {
- if (attributes == null) {
- return;
- }
-
if (attribute == null || !attribute.getName().isPresent() || !attribute.getType().isPresent())
throw new IllegalArgumentException("Attribute cannot be null and must have a name and type");
diff --git a/model/src/main/java/org/openremote/model/asset/AssetState.java b/model/src/main/java/org/openremote/model/asset/AssetState.java
index e228f5c2d..5da4e4a66 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetState.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetState.java
@@ -19,6 +19,7 @@
*/
package org.openremote.model.asset;
+import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.value.Value;
/**
@@ -61,12 +62,12 @@ public class AssetState extends AbstractAssetUpdate {
protected Throwable error;
- public AssetState(Asset asset, AssetAttribute attribute, boolean southbound, boolean sensorUpdate, Object sender) {
- super(asset, attribute, southbound, sensorUpdate, sender);
+ public AssetState(Asset asset, AssetAttribute attribute, AttributeEvent.Source source) {
+ super(asset, attribute, source);
}
- public AssetState(Asset asset, AssetAttribute attribute, Value oldValue, long oldValueTimestamp, boolean southbound, boolean sensorUpdate, Object sender) {
- super(asset, attribute, oldValue, oldValueTimestamp, southbound, sensorUpdate, sender);
+ public AssetState(Asset asset, AssetAttribute attribute, Value oldValue, long oldValueTimestamp, AttributeEvent.Source source) {
+ super(asset, attribute, oldValue, oldValueTimestamp, source);
}
public ProcessingStatus getProcessingStatus() {
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 6f5f2491e..d53a0e561 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetType.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetType.java
@@ -77,10 +77,6 @@ public enum AssetType {
AGENT(ASSET_NAMESPACE + ":agent", "gears", null),
- /**
- * When a Thing asset is modified (created, updated, deleted), its attributes are examined
- * and linked to and unlinked from the configured Protocol.
- */
THING(ASSET_NAMESPACE + ":thing", "gear", null);
final protected String value;
diff --git a/model/src/main/java/org/openremote/model/attribute/AttributeEvent.java b/model/src/main/java/org/openremote/model/attribute/AttributeEvent.java
index 4a115a78f..16092a3b4 100644
--- a/model/src/main/java/org/openremote/model/attribute/AttributeEvent.java
+++ b/model/src/main/java/org/openremote/model/attribute/AttributeEvent.java
@@ -31,6 +31,31 @@ import java.util.Optional;
*/
public class AttributeEvent extends SharedEvent {
+ public static final String HEADER_SOURCE = AttributeEvent.class.getName() + ".SOURCE";
+
+ /**
+ * Processing of the attribute event depends on the origin of the event.
+ */
+ public enum Source {
+
+ /**
+ * The event was created by a client, it's a write request by a user.
+ */
+ CLIENT,
+
+ /**
+ * The event was created by internal processing, for example, as a rule
+ * consequence. Protocols can also create events for internal processing,
+ * to update any assets' state.
+ */
+ INTERNAL,
+
+ /**
+ * The event is a value change on a sensor, created by a protocol.
+ */
+ SENSOR
+ }
+
public static class EntityIdFilter extends EventFilter<AttributeEvent> {
public static final String FILTER_TYPE = "attribute-entity-id";
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 751ed5b9e..197ea0720 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
@@ -52,7 +52,6 @@ import org.openremote.model.syslog.SyslogEvent;
)
public abstract class SharedEvent extends Event {
- public static final String HEADER_SENDER = SharedEvent.class.getName() + ".SENDER";
public static final String MESSAGE_PREFIX = "EVENT";
public SharedEvent(long timestamp) {