Skip to content

armgit / core

Public Imported from GitHub
0

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

Agent Service update and attribute classes clean up

Rich Turnerd14641569ce2
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java b/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java
index f04d8b292..71a25948f 100644
--- a/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java
+++ b/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java
@@ -22,17 +22,16 @@ package org.openremote.agent3.protocol;
import org.apache.camel.Predicate;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
+import org.openremote.container.Container;
+import org.openremote.container.message.MessageBrokerContext;
import org.openremote.container.message.MessageBrokerSetupService;
import org.openremote.model.AttributeEvent;
+import org.openremote.model.AttributeRef;
import org.openremote.model.AttributeState;
import org.openremote.model.asset.thing.ThingAttribute;
-import org.openremote.container.Container;
-import org.openremote.container.message.MessageBrokerContext;
-import org.openremote.model.AttributeRef;
import java.util.Collection;
import java.util.HashMap;
-import java.util.Iterator;
import java.util.Map;
import java.util.logging.Logger;
@@ -110,17 +109,19 @@ public abstract class AbstractProtocol implements Protocol {
}
@Override
- public void unlinkAttributes(String thingId) throws Exception {
+ public void unlinkAttributes(Collection<ThingAttribute> attributes) throws Exception {
synchronized (linkedAttributes) {
- Iterator<Map.Entry<AttributeRef, ThingAttribute>> entryIterator = linkedAttributes.entrySet().iterator();
- while (entryIterator.hasNext()) {
- Map.Entry<AttributeRef, ThingAttribute> entry = entryIterator.next();
- if (entry.getKey().getEntityId().equals(thingId)) {
- LOG.fine("Attribute removed on '" + getProtocolName() + "': " + entry.getValue());
- onAttributeRemoved(entry.getValue());
- entryIterator.remove();
- }
- }
+ attributes
+ .stream()
+ .filter(thingAttribute -> linkedAttributes.values()
+ .stream()
+ .anyMatch(linkedAttribute -> linkedAttribute.getAttributeRef().equals(thingAttribute.getAttributeRef()))
+ )
+ .forEach(attributeToRemove -> {
+ linkedAttributes.remove(attributeToRemove.getAttributeRef());
+ LOG.fine("Attribute removed on '" + getProtocolName() + "': " + attributeToRemove);
+ onAttributeRemoved(attributeToRemove);
+ });
}
}
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/Protocol.java b/agent/src/main/java/org/openremote/agent3/protocol/Protocol.java
index cd1839a71..89001bed7 100644
--- a/agent/src/main/java/org/openremote/agent3/protocol/Protocol.java
+++ b/agent/src/main/java/org/openremote/agent3/protocol/Protocol.java
@@ -68,6 +68,6 @@ public interface Protocol extends ContainerService {
void linkAttributes(Collection<ThingAttribute> attributes) throws Exception;
- void unlinkAttributes(String thingId) throws Exception;
+ void unlinkAttributes(Collection<ThingAttribute> attributes) throws Exception;
}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditActivity.java b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditActivity.java
index bb5882e60..a0d3f7125 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditActivity.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditActivity.java
@@ -350,7 +350,7 @@ public class AssetEditActivity
view.getAttributesEditorContainer(),
assetId == null
? asset.getWellKnownType().getDefaultAttributes()
- : new AssetAttributes(asset.getAttributes()),
+ : new AssetAttributes(asset),
assetId == null
);
view.setAttributesEditor(attributesEditor);
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewActivity.java b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewActivity.java
index 1f4d2ec92..0809dad75 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewActivity.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewActivity.java
@@ -180,7 +180,7 @@ public class AssetViewActivity
attributesBrowser = new AttributesBrowser(
environment,
view.getAttributesBrowserContainer(),
- new AssetAttributes(asset.getAttributes())
+ new AssetAttributes(asset)
) {
@Override
protected void readAttributeValue(AssetAttribute attribute, Runnable onSuccess) {
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesEditor.java b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesEditor.java
index a57ff0621..fa50321f3 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesEditor.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesEditor.java
@@ -108,7 +108,7 @@ public class AttributesEditor
/* ####################################################################### */
protected FormGroup createNewAttributeEditor() {
- AssetAttribute attribute = new AssetAttribute();
+ AssetAttribute attribute = new AssetAttribute("NAME", AttributeType.STRING);
FormGroup formGroup = createAttributeNameEditor(attribute);
diff --git a/manager/server/src/main/java/org/openremote/manager/server/Main.java b/manager/server/src/main/java/org/openremote/manager/server/Main.java
index c2cbd449f..4343aba08 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/Main.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/Main.java
@@ -61,11 +61,11 @@ public class Main {
new RulesService(),
new AssetStorageService(),
new AssetDatapointService(),
- new AssetProcessingService(),
- new AgentService()
+ new AssetProcessingService()
));
ServiceLoader.load(Protocol.class).forEach(this::add);
addAll(Arrays.asList(
+ new AgentService(),
new MapService(),
new NotificationService(),
new MessageBrokerService(),
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 bb966e30c..69b56aba2 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
@@ -19,6 +19,7 @@
*/
package org.openremote.manager.server.agent;
+import elemental.json.JsonObject;
import org.apache.camel.builder.RouteBuilder;
import org.openremote.agent3.protocol.Protocol;
import org.openremote.container.Container;
@@ -27,30 +28,28 @@ import org.openremote.container.message.MessageBrokerService;
import org.openremote.container.message.MessageBrokerSetupService;
import org.openremote.container.persistence.PersistenceEvent;
import org.openremote.manager.server.asset.AssetStorageService;
-import org.openremote.model.asset.AssetUpdate;
import org.openremote.manager.server.asset.ServerAsset;
import org.openremote.manager.server.datapoint.AssetDatapointService;
+import org.openremote.model.AbstractValueTimestampHolder;
import org.openremote.model.AttributeRef;
import org.openremote.model.Function;
import org.openremote.model.asset.*;
import org.openremote.model.asset.agent.AgentAttributes;
import org.openremote.model.asset.agent.ProtocolConfiguration;
import org.openremote.model.asset.thing.ThingAttribute;
-import org.openremote.model.asset.thing.ThingAttributes;
+import org.openremote.model.util.JsonUtil;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
+import java.util.*;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
+import java.util.stream.Collectors;
import static org.openremote.agent3.protocol.Protocol.ACTUATOR_TOPIC;
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.model.asset.AssetType.AGENT;
-import static org.openremote.model.asset.AssetType.THING;
/**
* Finds all {@link AssetType#AGENT} and {@link AssetType#THING} assets and starts the protocols for them.
@@ -58,24 +57,17 @@ import static org.openremote.model.asset.AssetType.THING;
public class AgentService extends RouteBuilder implements ContainerService, Consumer<AssetUpdate> {
private static final Logger LOG = Logger.getLogger(AgentService.class.getName());
-
- final protected Function<AttributeRef, ProtocolConfiguration> agentLinkResolver = agentLink -> {
- // Resolve the agent and the protocol configuration
- // TODO This is very inefficient and requires Hibernate second-level caching
- // TODO: Check the realm, the thing must be in the same realm as its agent!
- Asset agent = find(agentLink.getEntityId());
- if (agent != null && agent.getWellKnownType().equals(AGENT)) {
- AgentAttributes agentAttributes = new AgentAttributes(agent);
- return agentAttributes.getProtocolConfiguration(agentLink.getAttributeName());
- }
- LOG.info("No agent/protocol configuration found for thing attribute: " + agentLink);
- return null;
- };
-
protected Container container;
protected AssetStorageService assetStorageService;
protected AssetDatapointService assetDatapointService;
protected MessageBrokerService messageBrokerService;
+ protected Collection<Protocol> protocols; // TODO: Can protocols be added at runtime
+ protected final Map<AttributeRef, ProtocolConfiguration> protocolConfigurations = new HashMap<>();
+ protected Function<AttributeRef, ProtocolConfiguration> protocolConfigurationResolver = (AttributeRef protocolRef) -> {
+ synchronized (protocolConfigurations) {
+ return protocolConfigurations.get(protocolRef);
+ }
+ };
@Override
public void init(Container container) throws Exception {
@@ -88,123 +80,288 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons
@Override
public void start(Container container) throws Exception {
- List<ServerAsset> agents = assetStorageService.findAll(new AssetQuery().type(AssetType.AGENT));
+ protocols = container.getServices(Protocol.class);
+ List<ServerAsset> agents = assetStorageService.findAll(new AssetQuery().select(new AssetQuery.Select(true, false)).type(AssetType.AGENT));
LOG.fine("Deploy all agents in all realms: " + agents.size());
+
for (Asset agent : agents) {
- deployAgent(agent, PersistenceEvent.Cause.UPDATE);
+ // Extract and store protocol configurations for this agent - there won't be any asset attributes
+ // linked yet as agent has just been created
+ // Link the protocol configuration
+ ProtocolConfiguration.getAll(agent)
+ .forEach(this::linkProtocolConfiguration);
}
}
@Override
public void stop(Container container) throws Exception {
+ List<ProtocolConfiguration> protocolConfigs;
+
+ synchronized (protocolConfigurations) {
+ protocolConfigs = Arrays.asList(protocolConfigurations.values().toArray(new ProtocolConfiguration[0]));
+ }
+
+ protocolConfigs.forEach(this::unlinkProtocolConfiguration);
}
@Override
public void configure() throws Exception {
-
- // If any agent or thing was modified in the database, deploy the changes
from(PERSISTENCE_TOPIC)
.filter(isPersistenceEventForEntityType(Asset.class))
.process(exchange -> {
PersistenceEvent persistenceEvent = exchange.getIn().getBody(PersistenceEvent.class);
Asset asset = (Asset) persistenceEvent.getEntity();
if (isPersistenceEventForAssetType(AGENT).matches(exchange)) {
- deployAgent(asset, persistenceEvent.getCause());
- } else if (isPersistenceEventForAssetType(THING).matches(exchange)) {
- deployThing(asset, persistenceEvent.getCause());
+ processAgentChange(asset, persistenceEvent);
+ } else {
+ processAssetChange(asset, persistenceEvent);
}
});
}
- protected void deployAgent(Asset agent, PersistenceEvent.Cause cause) {
- LOG.fine("Deploy agent: " + agent);
- switch (cause) {
+ /**
+ * Looks for new, modified and obsolete protocol configurations and links / unlinks any associated
+ * attributes
+ */
+ protected void processAgentChange(Asset agent, PersistenceEvent persistenceEvent) {
+ LOG.finest("Processing agent persistence event: " + persistenceEvent.getCause());
+
+ switch (persistenceEvent.getCause()) {
+ case INSERT:
+
+ // Link all protocol configurations for this agent
+ ProtocolConfiguration.getAll(agent)
+ .forEach(protocolConfiguration -> {
+ AttributeRef protocolRef = new AttributeRef(agent.getId(), protocolConfiguration.getName());
+ LOG.fine("Agent was persisted (" + persistenceEvent.getCause() + "), linking protocol: " + protocolRef);
+ linkProtocolConfiguration(protocolConfiguration);
+ });
+
+ break;
case UPDATE:
- // TODO: Find everything with this agent ID in the asset tree (only within the same tenant/realm!) not just children
- List<ServerAsset> things = assetStorageService.findAll(new AssetQuery()
- .select(new AssetQuery.Select(true, false))
- .type(THING)
- .parent(new AssetQuery.ParentPredicate(agent.getId()))
- );
- for (Asset thing : things) {
- deployThing(thing, PersistenceEvent.Cause.UPDATE);
+
+ // Check if any protocol config attributes have been added/removed or modified
+ int attributesIndex = Arrays.asList(persistenceEvent.getPropertyNames()).indexOf("attributes");
+ if (attributesIndex < 0) {
+ return;
}
+
+ // Attributes have possibly changed so need to compare old and new state to determine
+ // which protocol configs are affected
+ AgentAttributes oldAttributes = new AgentAttributes(agent.getId(), (JsonObject) persistenceEvent.getPreviousState()[attributesIndex]);
+ AgentAttributes newAttributes = new AgentAttributes(agent.getId(), (JsonObject) persistenceEvent.getCurrentState()[attributesIndex]);
+ List<ProtocolConfiguration> oldProtocolConfigs = ProtocolConfiguration.getAll(oldAttributes.get());
+ List<ProtocolConfiguration> newProtocolConfigs = ProtocolConfiguration.getAll(newAttributes.get());
+
+ // Compare protocol configurations by JSON value
+ // Unlink protocols that are in oldConfigs but not in newConfigs
+ oldProtocolConfigs
+ .stream()
+ .filter(oldProtocolConfig -> newProtocolConfigs
+ .stream()
+ .noneMatch(newProtocolConfig -> JsonUtil.equals(
+ oldProtocolConfig.getJsonObject(),
+ newProtocolConfig.getJsonObject())
+ )
+ )
+ .forEach(obsoleteProtocolConfig -> {
+ AttributeRef protocolRef = new AttributeRef(agent.getId(), obsoleteProtocolConfig.getName());
+ LOG.fine("Agent was persisted (" + persistenceEvent.getCause() + "), unlinking protocol: " + protocolRef);
+ unlinkProtocolConfiguration(obsoleteProtocolConfig);
+ });
+
+ // Link protocols that are in newConfigs but not in oldConfigs
+ newProtocolConfigs
+ .stream()
+ .filter(newConfig -> oldProtocolConfigs
+ .stream()
+ .noneMatch(oldConfig ->
+ JsonUtil.equals(
+ oldConfig.getJsonObject(),
+ newConfig.getJsonObject()
+ )
+ )
+ )
+ .forEach(newProtocolConfig -> {
+ AttributeRef protocolRef = new AttributeRef(agent.getId(), newProtocolConfig.getName());
+ LOG.fine("Agent was persisted (" + persistenceEvent.getCause() + "), linking protocol: " + protocolRef);
+ linkProtocolConfiguration(newProtocolConfig);
+ });
break;
case DELETE:
- // TODO The 'things' children must be deleted first, although we don't have foreign key constraint enforcing this!
- throw new UnsupportedOperationException("TODO not implemented");
+
+ // Unlink any attributes that have an agent link to this agent
+ List<ProtocolConfiguration> protocolConfigurations = ProtocolConfiguration.getAll(agent);
+ protocolConfigurations
+ .forEach(protocolConfig -> {
+ AttributeRef protocolRef = new AttributeRef(agent.getId(), protocolConfig.getName());
+ LOG.fine("Agent was persisted (" + persistenceEvent.getCause() + "), unlinking protocol: " + protocolRef);
+ unlinkProtocolConfiguration(protocolConfig);
+ });
+ break;
}
}
- protected void deployThing(Asset thing, PersistenceEvent.Cause cause) {
- LOG.fine("Deploy thing: " + thing);
- ThingAttributes thingAttributes = new ThingAttributes(thing);
-
- // Attributes grouped by protocol name
- Map<String, List<ThingAttribute>> linkedAttributes = thingAttributes.getLinkedAttributes(
- // Linked attributes have a reference to an agent, and a protocol configuration attribute of that agent
- getAgentLinkResolver()
- );
-
- LOG.fine("Thing has attribute links to " + linkedAttributes.size() + " protocol(s): " + thing);
+ /**
+ * Looks for new, modified and obsolete AGENT_LINK attributes and links / unlinks them
+ * with the protocol
+ */
+ protected void processAssetChange(Asset asset, PersistenceEvent persistenceEvent) {
+ LOG.finest("Processing asset persistence event: " + persistenceEvent.getCause());
- Collection<Protocol> protocols = container.getServices(Protocol.class);
+ switch (persistenceEvent.getCause()) {
+ case INSERT: {
+ // Asset insert persistence events can be fired before the agent insert persistence event
+ // so need to check that all protocol configs exist - any that don't we will exclude here
+ // and handle in agent insert
- switch (cause) {
- case INSERT:
- linkAttributes(thing, protocols, linkedAttributes);
+ // Link any AGENT_LINK attributes to the referenced protocol
+ Map<AttributeRef, List<ThingAttribute>> groupedThingAttributes = ThingAttribute.getAllGroupedByProtocolRef(asset, protocolConfigurationResolver);
+ groupedThingAttributes.forEach((protocolRef, thingAttributes) -> linkAttributes(getProtocol(protocolConfigurationResolver.apply(protocolRef)), thingAttributes));
break;
+ }
case UPDATE:
- // TODO Not very efficient
- unlinkAttributes(thing, protocols, linkedAttributes);
- linkAttributes(thing, protocols, linkedAttributes);
+
+ // Check if attributes of the asset have been modified
+ int attributesIndex = Arrays.asList(persistenceEvent.getPropertyNames()).indexOf("attributes");
+ if (attributesIndex < 0) {
+ return;
+ }
+
+ // Attributes have possibly changed so need to compare old and new state to determine any changes to
+ // AGENT_LINK attributes
+ AssetAttributes oldAttributes = new AssetAttributes(asset.getId(), (JsonObject) persistenceEvent.getPreviousState()[attributesIndex]);
+ AssetAttributes newAttributes = new AssetAttributes(asset.getId(), (JsonObject) persistenceEvent.getCurrentState()[attributesIndex]);
+ List<ThingAttribute> oldThingAttributes = ThingAttribute.getAll(oldAttributes.get(), protocolConfigurationResolver);
+ List<ThingAttribute> newThingAttributes = ThingAttribute.getAll(newAttributes.get(), protocolConfigurationResolver);
+
+ // Unlink thing attributes that are in old but not in new
+ oldThingAttributes
+ .stream()
+ .filter(oldThingAttribute -> newThingAttributes
+ .stream()
+ .noneMatch(newThingAttribute -> JsonUtil.equals( // Ignore the timestamp in comparison
+ oldThingAttribute.getJsonObject(),
+ newThingAttribute.getJsonObject(),
+ Collections.singletonList(AbstractValueTimestampHolder.VALUE_TIMESTAMP_FIELD_NAME))
+ )
+ )
+ .collect(Collectors.groupingBy(thingAttribute -> thingAttribute.getProtocolRef()))
+ .forEach((protocolRef, thingAttributes) ->
+ unlinkAttributes(getProtocol(protocolConfigurationResolver.apply(protocolRef)), thingAttributes)
+ );
+
+ // Link thing attributes that are in new but not in old
+ newThingAttributes
+ .stream()
+ .filter(newThingAttribute -> oldThingAttributes
+ .stream()
+ .noneMatch(oldThingAttribute -> JsonUtil.equals( // Ignore the timestamp in comparison
+ oldThingAttribute.getJsonObject(),
+ newThingAttribute.getJsonObject(),
+ Collections.singletonList(AbstractValueTimestampHolder.VALUE_TIMESTAMP_FIELD_NAME))
+ )
+ )
+ .collect(Collectors.groupingBy(thingAttribute -> thingAttribute.getProtocolRef()))
+ .forEach((protocolRef, thingAttributes) ->
+ linkAttributes(getProtocol(protocolConfigurationResolver.apply(protocolRef)), thingAttributes)
+ );
break;
- case DELETE:
- unlinkAttributes(thing, protocols, linkedAttributes);
+ case DELETE: {
+
+ // Unlink any AGENT_LINK attributes from the referenced protocol
+ Map<AttributeRef, List<ThingAttribute>> groupedThingAttributes = ThingAttribute.getAllGroupedByProtocolRef(asset, protocolConfigurationResolver);
+ groupedThingAttributes.forEach((protocolRef, thingAttributes) -> unlinkAttributes(getProtocol(protocolConfigurationResolver.apply(protocolRef)), thingAttributes));
break;
+ }
}
}
- protected void linkAttributes(Asset thing,
- Collection<Protocol> protocols,
- Map<String, List<ThingAttribute>> attributes) {
- for (String protocolName : attributes.keySet()) {
- for (Protocol protocol : protocols) {
- if (protocol.getProtocolName() == null || protocol.getProtocolName().length() == 0)
- throw new IllegalStateException("Protocol can't have empty name: " + protocol.getClass());
- if (protocol.getProtocolName().equals(protocolName)) {
- try {
- protocol.linkAttributes(attributes.get(protocolName));
- } catch (Exception ex) {
- // TODO: Better error handling?
- LOG.log(Level.WARNING, "Ignoring error on attribute link for: " + thing, ex);
- }
- }
- }
+ protected void linkProtocolConfiguration(ProtocolConfiguration protocolConfiguration) {
+ AttributeRef protocolAttributeRef = protocolConfiguration.getAttributeRef();
+
+ synchronized (protocolConfigurations) {
+ // Store this configuration for easy access later
+ protocolConfigurations.put(protocolAttributeRef, protocolConfiguration);
}
+
+ LOG.finest("Linking all attributes that use protocol configuration: " + protocolAttributeRef);
+
+ // Get all assets that have attributes that use this protocol configuration
+ List<ServerAsset> assets = assetStorageService.findAll(
+ new AssetQuery()
+ .select(new AssetQuery.Select(true, false))
+ .attributeMeta(
+ new AssetQuery.AttributeRefPredicate(
+ AssetMeta.AGENT_LINK,
+ protocolAttributeRef.getEntityId(),
+ protocolAttributeRef.getAttributeName()
+ )
+ )
+ );
+
+ assets.forEach(asset -> {
+ Map<AttributeRef, List<ThingAttribute>> groupedThingAttributes = ThingAttribute.getAllGroupedByProtocolRef(asset, protocolConfigurationResolver);
+ linkAttributes(getProtocol(protocolConfiguration), groupedThingAttributes.get(protocolAttributeRef));
+ });
}
- protected void unlinkAttributes(Asset thing,
- Collection<Protocol> protocols,
- Map<String, List<ThingAttribute>> attributes) {
- for (Protocol protocol : protocols) {
- if (attributes.containsKey(protocol.getProtocolName())) {
- try {
- protocol.unlinkAttributes(thing.getId());
- } catch (Exception ex) {
- // TODO: Better error handling?
- LOG.log(Level.WARNING, "Ignoring error on attribute unlink for: " + thing, ex);
- }
- }
+ protected void unlinkProtocolConfiguration(ProtocolConfiguration protocolConfiguration) {
+ AttributeRef protocolRef = protocolConfiguration.getAttributeRef();
+
+ // Get all assets that have attributes that use this protocol configuration
+ List<ServerAsset> assets = assetStorageService.findAll(
+ new AssetQuery()
+ .select(new AssetQuery.Select(true, false))
+ .attributeMeta(
+ new AssetQuery.AttributeRefPredicate(
+ AssetMeta.AGENT_LINK,
+ protocolRef.getEntityId(),
+ protocolRef.getAttributeName()
+ )
+ )
+ );
+
+ assets.forEach(asset -> {
+ Map<AttributeRef, List<ThingAttribute>> groupedThingAttributes = ThingAttribute.getAllGroupedByProtocolRef(asset, protocolConfigurationResolver);
+ unlinkAttributes(getProtocol(protocolConfiguration), groupedThingAttributes.get(protocolRef));
+ });
+
+ synchronized (protocolConfigurations) {
+ protocolConfigurations.remove(protocolRef);
}
}
- protected Asset find(String id) {
- return assetStorageService.find(id, true, false);
+ protected Protocol getProtocol(ProtocolConfiguration protocolConfiguration) {
+ return protocols
+ .stream()
+ .filter(protocol -> {
+ if (protocol.getProtocolName() == null || protocol.getProtocolName().length() == 0)
+ throw new IllegalStateException("Protocol can't have empty name: " + protocol.getClass());
+ return protocol.getProtocolName().equals(protocolConfiguration.getProtocolName());
+ })
+ .findFirst()
+ .orElse(null);
+ }
+
+ protected void linkAttributes(Protocol protocol, List<ThingAttribute> attributes) {
+ try {
+ LOG.finest("Linking protocol attributes to: " + protocol.getProtocolName());
+ protocol.linkAttributes(attributes);
+ } catch (Exception ex) {
+ // TODO: Better error handling?
+ LOG.log(Level.WARNING, "Ignoring error on linking attributes to protocol: " + protocol.getProtocolName(), ex);
+ }
}
- public Function<AttributeRef, ProtocolConfiguration> getAgentLinkResolver() {
- return agentLinkResolver;
+ protected void unlinkAttributes(Protocol protocol, List<ThingAttribute> attributes) {
+ try {
+ LOG.finest("Unlinking protocol attributes form: " + protocol.getProtocolName());
+ protocol.unlinkAttributes(attributes);
+ } catch (Exception ex) {
+ // TODO: Better error handling?
+ LOG.log(Level.WARNING, "Ignoring error on unlinking attributes from protocol: " + protocol.getProtocolName(), ex);
+ }
}
/**
@@ -215,27 +372,21 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons
* processing of this event by the processing chain, the protocol should raise
* sensor updates as required (i.e. the protocol is responsible for synchronising state)
*
- * @param assetUpdate
*/
@Override
public void accept(AssetUpdate assetUpdate) {
- // Check that asset is a THING
- if (assetUpdate.getType() != THING) {
- LOG.fine("Ignoring asset update as asset is not a THING: " + assetUpdate);
- return;
- }
-
// If update was initiated by a protocol ignore it
if (assetUpdate.isNorthbound()) {
LOG.fine("Ignoring asset update as it came from a protocol:" + assetUpdate);
return;
}
- AttributeRef agentLink = ThingAttribute.getAgentLink(new ThingAttribute(assetUpdate.getAttribute()));
- if (agentLink != null) {
+ AttributeRef protocolRef = ThingAttribute.getProtocolRef(assetUpdate.getAttribute());
+
+ if (protocolRef != null) {
// Check attribute is linked to an actual agent
- ProtocolConfiguration protocolConfiguration = getAgentLinkResolver().apply(agentLink);
+ ProtocolConfiguration protocolConfiguration = protocolConfigurationResolver.apply(protocolRef);
if (protocolConfiguration == null) {
LOG.warning("Cannot process asset update as agent link is invalid:" + assetUpdate);
@@ -258,6 +409,20 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons
assetUpdate.setStatus(AssetUpdate.Status.HANDLED);
}
+ public Function<AttributeRef, ProtocolConfiguration> getProtocolConfigurationResolver() {
+ return protocolConfigurationResolver;
+ }
+
+/*
+ public static List<ThingAttribute> getThingAttributes(Asset asset) {
+ return new AssetAttributes(asset.getAttributes()).get()
+ .stream()
+ .filter(AssetAttribute::isAgentLinked)
+ .map(ThingAttribute::new)
+ .collect(Collectors.toList());
+ }
+*/
+
public String toString() {
return getClass().getSimpleName() + "{" +
'}';
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 876e54747..bca421d87 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
@@ -31,7 +31,6 @@ import org.openremote.model.AttributeEvent;
import org.openremote.model.AttributeState;
import org.openremote.model.asset.*;
import org.openremote.model.asset.thing.ThingAttribute;
-import org.openremote.model.asset.thing.ThingAttributes;
import java.util.ArrayList;
import java.util.List;
@@ -40,7 +39,6 @@ import java.util.logging.Level;
import java.util.logging.Logger;
import static org.openremote.agent3.protocol.Protocol.SENSOR_TOPIC;
-import static org.openremote.model.asset.AssetType.THING;
/**
* Receives {@link AttributeEvent}s and processes them.
@@ -153,9 +151,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
// Sensor updates are processed first by rules, then stored in the asset and datapoint databases
from(SENSOR_TOPIC)
.filter(body().isInstanceOf(AttributeEvent.class))
- .process(exchange -> {
- processSensorUpdate(exchange.getIn().getBody(AttributeEvent.class));
- });
+ .process(exchange -> processSensorUpdate(exchange.getIn().getBody(AttributeEvent.class)));
}
/**
@@ -219,12 +215,13 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
* @param attributeEvent
*/
protected void processSensorUpdate(AttributeEvent attributeEvent) {
- // Must reference a thing asset
ServerAsset thing = assetStorageService.find(attributeEvent.getEntityId(), true);
- if (thing == null || thing.getWellKnownType() != THING) {
- LOG.fine("Ignoring " + attributeEvent + ", not a thing: " + thing);
- return;
- }
+// // Must reference a thing asset
+//
+// if (thing == null || thing.getWellKnownType() != THING) {
+// LOG.fine("Ignoring " + attributeEvent + ", not a thing: " + thing);
+// return;
+// }
LOG.fine("Processing sensor " + attributeEvent + " for thing: " + thing);
@@ -232,10 +229,13 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
// 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)
- ThingAttributes thingAttributes = new ThingAttributes(thing);
- ThingAttribute thingAttribute = thingAttributes.getLinkedAttribute(
- agentService.getAgentLinkResolver(), attributeEvent.getAttributeName()
- );
+ AssetAttributes attributes = new AssetAttributes(thing);
+
+ // Look for a matching thing attribute
+ AssetAttribute attribute = attributes.get(attributeEvent.getAttributeName());
+
+ // Convert this into a thing attribute
+ ThingAttribute thingAttribute = ThingAttribute.get(attribute, agentService.getProtocolConfigurationResolver());
if (thingAttribute == null) {
LOG.warning("Processing sensor update failed attribute not linked to an agent: " + attributeEvent);
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 96359f3dc..0733abde9 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
@@ -208,7 +208,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
throw new WebApplicationException(NOT_FOUND);
// Check attribute exists
- AssetAttributes attributes = new AssetAttributes(asset.getAttributes());
+ AssetAttributes attributes = new AssetAttributes(asset);
if (!attributes.hasAttribute(attributeName))
throw new WebApplicationException(NOT_FOUND);
@@ -258,7 +258,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
throw new WebApplicationException(Response.Status.FORBIDDEN);
}
- AssetAttributes attributes = new AssetAttributes(asset.getAttributes());
+ AssetAttributes attributes = new AssetAttributes(asset);
Attribute attribute = attributes.get(attributeName);
if (attribute == null) {
throw new WebApplicationException(NOT_FOUND);
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 26b3d266f..970e6f611 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
@@ -40,14 +40,10 @@ import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.logging.Logger;
-import java.util.regex.Pattern;
public class AssetStorageService implements ContainerService, Consumer<AssetUpdate> {
private static final Logger LOG = Logger.getLogger(AssetStorageService.class.getName());
-
- protected final Pattern attributeNamePattern = Pattern.compile(Attribute.ATTRIBUTE_NAME_PATTERN);
-
protected PersistenceService persistenceService;
protected ManagerIdentityService managerIdentityService;
protected AssetProcessingService assetProcessingService;
@@ -145,13 +141,6 @@ public class AssetStorageService implements ContainerService, Consumer<AssetUpda
}
// Validate attribute names
AssetAttributes attributes = new AssetAttributes(asset);
- for (Attribute attribute : attributes.get()) {
- if (!attributeNamePattern.matcher(attribute.getName()).matches()) {
- throw new IllegalStateException(
- "Invalid attribute name (must match '" + Attribute.ATTRIBUTE_NAME_PATTERN + "'): " + attribute.getName()
- );
- }
- }
return em.merge(asset);
});
}
@@ -501,7 +490,7 @@ public class AssetStorageService implements ContainerService, Consumer<AssetUpda
try (PreparedStatement statement = connection.prepareStatement(update)) {
// Bind the value (and check we don't have a SQL injection hole in attribute name!)
- if (!attributeNamePattern.matcher(attributeName).matches()) {
+ if (!Attribute.nameIsValid(attributeName)) {
LOG.fine(
"Invalid attribute name (must match '" + Attribute.ATTRIBUTE_NAME_PATTERN + "'): " + attributeName
);
diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/ServerAsset.java b/manager/server/src/main/java/org/openremote/manager/server/asset/ServerAsset.java
index 40fc3f152..7a2427e4f 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/asset/ServerAsset.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/ServerAsset.java
@@ -21,11 +21,9 @@ package org.openremote.manager.server.asset;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.vividsolutions.jts.geom.Coordinate;
-import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
import elemental.json.Json;
-import elemental.json.JsonObject;
import org.geolatte.geom.jts.JTS;
import org.hibernate.annotations.Check;
import org.hibernate.spatial.dialect.postgis.PGGeometryTypeDescriptor;
diff --git a/manager/server/src/main/java/org/openremote/manager/server/notification/DeviceNotificationToken.java b/manager/server/src/main/java/org/openremote/manager/server/notification/DeviceNotificationToken.java
index f1b45009c..8311fad18 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/notification/DeviceNotificationToken.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/notification/DeviceNotificationToken.java
@@ -44,8 +44,7 @@ public class DeviceNotificationToken {
Id id = (Id) o;
- if (!deviceId.equals(id.deviceId)) return false;
- return userId.equals(id.userId);
+ return deviceId.equals(id.deviceId) && userId.equals(id.userId);
}
@Override
diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulePersistence.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulePersistence.java
index d3c7bec8e..07905f35c 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulePersistence.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulePersistence.java
@@ -23,7 +23,7 @@ public class RulePersistence {
public String readData(String key, String defaultValue) {
LOG.fine("Reading '" + key + "', default: " + defaultValue);
- return data.containsKey(key) ? data.get(key) : defaultValue;
+ return data.getOrDefault(key, defaultValue);
}
public void deleteData(String key) {
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 5505d04e4..c8538f58c 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
@@ -240,87 +240,114 @@ 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<String, AssetAttribute, AssetUpdate> buildUpdateFunction = (assetId, attribute) -> {
- final Asset loadedAsset = assetStorageService.find(assetId, true);
- return new AssetUpdate(loadedAsset,
+ BiFunction<Asset, AssetAttribute, AssetUpdate> buildUpdateFunction = (loadedAsset, attribute) ->
+ new AssetUpdate(loadedAsset,
new AssetAttribute(loadedAsset.getId(),
attribute.getName(),
attribute.getJsonObject()));
- };
+ Asset loadedAsset = null;
switch (persistenceEvent.getCause()) {
case INSERT:
// New asset has been created so get attributes that have RULES_FACT meta
AssetAttributes addedAttributes = new AssetAttributes(asset);
+ List<AssetAttribute> ruleAttributes = addedAttributes.get()
+ .stream()
+ .filter(AssetAttribute::isRulesFact)
+ .collect(Collectors.toList());
- addedAttributes.get().stream()
- .filter(AssetAttribute::isRulesFact)
- .forEach(attribute -> {
- AssetUpdate update = buildUpdateFunction.apply(asset.getId(), attribute);
- // Set the status to completed already so rules cannot interfere with this initial insert
- update.setStatus(AssetUpdate.Status.COMPLETED);
- LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), inserting fact: " + update);
- updateFact(update, true);
- });
+ if (ruleAttributes.size() == 0) {
+ return;
+ }
+
+ // Fully load the asset
+ loadedAsset = assetStorageService.find(asset.getId(), true);
+ Asset finalLoadedAsset = loadedAsset;
+
+ ruleAttributes.forEach(attribute -> {
+ AssetUpdate update = buildUpdateFunction.apply(finalLoadedAsset, attribute);
+ // Set the status to completed already so rules cannot interfere with this initial insert
+ update.setStatus(AssetUpdate.Status.COMPLETED);
+ LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), inserting fact: " + update);
+ updateFact(update, true);
+ });
break;
case UPDATE:
int attributesIndex = Arrays.asList(persistenceEvent.getPropertyNames()).indexOf("attributes");
- if (attributesIndex >= 0) {
- // Attributes have possibly changed so need to compare old and new state to determine
- // which facts to retract and which to insert
- AssetAttributes oldAttributes = new AssetAttributes((JsonObject) persistenceEvent.getPreviousState()[attributesIndex]);
- AssetAttributes newAttributes = new AssetAttributes((JsonObject) persistenceEvent.getCurrentState()[attributesIndex]);
+ if (attributesIndex < 0) {
+ return;
+ }
+
+ // Attributes have possibly changed so need to compare old and new state to determine
+ // which facts to retract and which to insert
+ AssetAttributes oldAttributes = new AssetAttributes(asset.getId(), (JsonObject) persistenceEvent.getPreviousState()[attributesIndex]);
+ AssetAttributes newAttributes = new AssetAttributes(asset.getId(), (JsonObject) persistenceEvent.getCurrentState()[attributesIndex]);
- List<AssetAttribute> oldFactAttributes = oldAttributes.get().stream()
+ List<AssetAttribute> oldFactAttributes = oldAttributes.get().stream()
.filter(AssetAttribute::isRulesFact)
.collect(Collectors.toList());
- List<AssetAttribute> newFactAttributes = newAttributes.get().stream()
+ List<AssetAttribute> newFactAttributes = newAttributes.get().stream()
.filter(AssetAttribute::isRulesFact)
.collect(Collectors.toList());
- // Compare attributes by JSON value
- // Retract facts for attributes that are in oldFactAttributes but not in newFactAttributes
-
- oldFactAttributes
+ // Compare attributes by JSON value
+ // Retract facts for attributes that are in oldFactAttributes but not in newFactAttributes
+ List<AssetAttribute> processAttributes = oldFactAttributes
.stream()
.filter(oldFactAttribute -> newFactAttributes
- .stream()
- .noneMatch(newFactAttribute -> JsonUtil.equals( // Ignore the timestamp in comparison
- oldFactAttribute.getJsonObject(),
- newFactAttribute.getJsonObject(),
- Collections.singletonList(AbstractValueTimestampHolder.VALUE_TIMESTAMP_FIELD_NAME))
- )
+ .stream()
+ .noneMatch(newFactAttribute -> JsonUtil.equals( // Ignore the timestamp in comparison
+ oldFactAttribute.getJsonObject(),
+ newFactAttribute.getJsonObject(),
+ Collections.singletonList(AbstractValueTimestampHolder.VALUE_TIMESTAMP_FIELD_NAME))
+ )
)
- .forEach(obsoleteFactAttribute -> {
- AssetUpdate update = buildUpdateFunction.apply(asset.getId(), obsoleteFactAttribute);
- LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), retracting fact: " + update);
- retractFact(update);
- });
+ .collect(Collectors.toList());
- // Insert facts for attributes that are in newFactAttributes but not in oldFactAttributes
- newFactAttributes
+ if (processAttributes.size() > 0) {
+ // Fully load the asset
+ loadedAsset = assetStorageService.find(asset.getId(), true);
+ Asset finalLoadedAsset1 = loadedAsset;
+ processAttributes.forEach(obsoleteFactAttribute -> {
+ AssetUpdate update = buildUpdateFunction.apply(finalLoadedAsset1, obsoleteFactAttribute);
+ LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), retracting fact: " + update);
+ retractFact(update);
+ });
+ }
+
+ // Insert facts for attributes that are in newFactAttributes but not in oldFactAttributes
+ processAttributes = newFactAttributes
.stream()
.filter(newFactAttribute -> oldFactAttributes
- .stream()
- .noneMatch(oldFactAttribute ->
- JsonUtil.equals( // Ignore the timestamp in comparison
- oldFactAttribute.getJsonObject(),
- newFactAttribute.getJsonObject(),
- Collections.singletonList(AbstractValueTimestampHolder.VALUE_TIMESTAMP_FIELD_NAME)
+ .stream()
+ .noneMatch(oldFactAttribute ->
+ JsonUtil.equals( // Ignore the timestamp in comparison
+ oldFactAttribute.getJsonObject(),
+ newFactAttribute.getJsonObject(),
+ Collections.singletonList(AbstractValueTimestampHolder.VALUE_TIMESTAMP_FIELD_NAME)
+ )
)
- )
)
- .forEach(newFactAttribute -> {
- AssetUpdate update = buildUpdateFunction.apply(asset.getId(), newFactAttribute);
- // Set the status to completed already so rules cannot interfere with this initial insert
- update.setStatus(AssetUpdate.Status.COMPLETED);
- LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), inserting fact: " + update);
- updateFact(update, true);
- });
+ .collect(Collectors.toList());
+
+ if (processAttributes.size() > 0) {
+ if (loadedAsset == null) {
+ // Fully load the asset
+ loadedAsset = assetStorageService.find(asset.getId(), true);
+ }
+
+ Asset finalLoadedAsset2 = loadedAsset;
+ processAttributes.forEach(newFactAttribute -> {
+ AssetUpdate update = buildUpdateFunction.apply(finalLoadedAsset2, newFactAttribute);
+ // Set the status to completed already so rules cannot interfere with this initial insert
+ update.setStatus(AssetUpdate.Status.COMPLETED);
+ LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), inserting fact: " + update);
+ updateFact(update, true);
+ });
}
break;
case DELETE:
@@ -536,7 +563,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
if (!skipStatusCheck) {
// Check that all engines in the scope are not in ERROR state
- if (rulesDeployments.stream().anyMatch(rd -> rd.isError())) {
+ if (rulesDeployments.stream().anyMatch(RulesDeployment::isError)) {
LOG.severe("At least one rule engine is in an error state so cannot process update:" + assetUpdate);
assetUpdate.setStatus(AssetUpdate.Status.ERROR);
return;
diff --git a/manager/server/src/main/java/org/openremote/manager/server/web/ManagerFileServlet.java b/manager/server/src/main/java/org/openremote/manager/server/web/ManagerFileServlet.java
index 0af82a87e..c4af67030 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/web/ManagerFileServlet.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/web/ManagerFileServlet.java
@@ -97,7 +97,7 @@ public class ManagerFileServlet extends FileServlet {
}
ManagerFileServlet fileServlet = new ManagerFileServlet(devMode, docRoot.toFile(), requiredRoles);
- ServletInfo servletInfo = Servlets.servlet("Manager File Servlet", FileServlet.class, () -> new ImmediateInstanceHandle<Servlet>(fileServlet));
+ ServletInfo servletInfo = Servlets.servlet("Manager File Servlet", FileServlet.class, () -> new ImmediateInstanceHandle<>(fileServlet));
servletInfo.addMapping("/*");
Filter gzipFilter = new GzipResponseFilter(MIME_TYPES_TO_ZIP);
diff --git a/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy b/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy
index e5a7bf657..d33c70603 100644
--- a/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy
+++ b/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy
@@ -36,8 +36,8 @@ trait ManagerContainerTrait extends ContainerTrait {
new AssetStorageService(),
new AssetDatapointService(),
new AssetProcessingService(),
- new AgentService(),
*Lists.newArrayList(ServiceLoader.load(Protocol.class)),
+ new AgentService(),
new MapService(),
new NotificationService(),
new MessageBrokerService(),
diff --git a/manager/test/src/test/groovy/org/openremote/test/agent/AgentDeploymentTest.groovy b/manager/test/src/test/groovy/org/openremote/test/agent/AgentDeploymentTest.groovy
index 55b171be2..25bd94a28 100644
--- a/manager/test/src/test/groovy/org/openremote/test/agent/AgentDeploymentTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/agent/AgentDeploymentTest.groovy
@@ -48,7 +48,7 @@ class AgentDeploymentTest extends Specification implements ManagerContainerTrait
conditions.eventually {
assert simulatorProtocol.getState(managerDemoSetup.thingId, "light1Dimmer").asNumber() == 66
def thing = assetStorageService.find(managerDemoSetup.thingId, true)
- def attributes = new AssetAttributes(thing.getAttributes())
+ def attributes = new AssetAttributes(thing)
assert attributes.get("light1Dimmer").getValue().getType() == JsonType.NUMBER
assert attributes.get("light1Dimmer").getValueAsInteger() == 66
}
@@ -60,7 +60,7 @@ class AgentDeploymentTest extends Specification implements ManagerContainerTrait
then: "the thing attribute value should be updated"
conditions.eventually {
def thing = assetStorageService.find(managerDemoSetup.thingId, true)
- def attributes = new AssetAttributes(thing.getAttributes())
+ def attributes = new AssetAttributes(thing)
assert attributes.get("light1Dimmer").getValue().getType() == JsonType.NUMBER
assert attributes.get("light1Dimmer").getValueAsInteger() == 77
}
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 815750807..f7afe5fed 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
@@ -45,7 +45,7 @@ class AssetDatapointTest extends Specification implements ManagerContainerTrait
then: "the thing attribute value should be updated and the datapoints stored"
conditions.eventually {
def thing = assetStorageService.find(managerDemoSetup.thingId, true)
- def attributes = new AssetAttributes(thing.getAttributes())
+ def attributes = new AssetAttributes(thing)
assert attributes.get("light1PowerConsumption").getValueAsDecimal() == 15.5d
def datapoints = assetDatapointService.getDatapoints(new AttributeRef(managerDemoSetup.thingId, "light1PowerConsumption"))
datapoints.size() == 3
diff --git a/manager/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy
index f478abc4a..5667939a5 100644
--- a/manager/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy
@@ -6,6 +6,7 @@ import org.openremote.manager.server.setup.SetupService
import org.openremote.manager.server.setup.builtin.ManagerDemoSetup
import org.openremote.manager.server.setup.builtin.KeycloakDemoSetup
import org.openremote.manager.shared.asset.AssetResource
+import org.openremote.manager.shared.http.BadRequestException
import org.openremote.model.Attribute
import org.openremote.model.Attributes
import org.openremote.model.asset.Asset
@@ -17,6 +18,7 @@ import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
import javax.ws.rs.WebApplicationException
+import javax.xml.ws.WebServiceException
import static org.openremote.container.util.MapAccess.getString
import static org.openremote.manager.server.setup.AbstractKeycloakSetup.SETUP_KEYCLOAK_ADMIN_PASSWORD
@@ -58,15 +60,13 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTrait
testAsset.realmId == keycloakDemoSetup.masterTenant.id
testAsset.parentId == null
- when: "an asset is stored with an illegal attribute name"
- def attributes = new AssetAttributes(testAsset.getAttributes())
- attributes.put(new AssetAttribute(testAsset.id, "illegal- Attribute:name&&&"))
+ when: "an asset is created with an illegal attribute name"
+ def attributes = new AssetAttributes(testAsset)
+ attributes.put(new AssetAttribute(testAsset.id, "illegal- Attribute:name&&&", AttributeType.STRING))
testAsset.setAttributes(attributes.getJsonObject())
- assetResource.update(null, testAsset.id, testAsset)
then: "the request should be bad"
- WebApplicationException ex = thrown()
- ex.response.status == 400
+ thrown(IllegalArgumentException)
when: "an asset is stored with a non-empty attribute value"
testAsset = assetResource.get(null, testAsset.getId())
@@ -77,14 +77,14 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTrait
testAsset = assetResource.get(null, testAsset.getId())
then: "the attribute should exist"
- new AssetAttributes(testAsset.getAttributes()).get("foo").getValueAsString() == "bar"
+ new AssetAttributes(testAsset).get("foo").getValueAsString() == "bar"
when: "an asset attribute value is written directly"
assetResource.writeAttributeValue(null, testAsset.getId(), "foo", "\"bar2\"")
testAsset = assetResource.get(null, testAsset.getId())
then: "the attribute value should match"
- new AssetAttributes(testAsset.getAttributes()).get("foo").getValueAsString() == "bar2"
+ new AssetAttributes(testAsset).get("foo").getValueAsString() == "bar2"
assetResource.readAttributeValue(null, testAsset.getId(), "foo") == "\"bar2\""
when: "an asset attribute value null is written directly"
@@ -92,7 +92,7 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTrait
testAsset = assetResource.get(null, testAsset.getId())
then: "the attribute value should match"
- !new AssetAttributes(testAsset.getAttributes()).get("foo").hasValue()
+ !new AssetAttributes(testAsset).get("foo").hasValue()
assetResource.readAttributeValue(null, testAsset.getId(), "foo") == "null"
when: "an asset is updated with a different type"
@@ -109,7 +109,7 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTrait
assetResource.update(null, testAsset.id, testAsset)
then: "the request should be bad"
- ex = thrown()
+ WebApplicationException ex = thrown()
ex.response.status == 400
when: "an asset is updated with a non-existent parent"
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 de47999b9..7de46140d 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
@@ -562,7 +562,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
apartment1LivingroomThermostat.id == managerDemoSetup.apartment1LivingroomThermostatId
apartment1LivingroomThermostat.name == "Livingroom Thermostat"
- AssetAttributes protectedAttributes = new AssetAttributes(apartment1LivingroomThermostat.attributes)
+ AssetAttributes protectedAttributes = new AssetAttributes(apartment1LivingroomThermostat)
protectedAttributes.size() == 2
protectedAttributes.get("currentTemperature")
protectedAttributes.get("currentTemperature").getType() == AttributeType.DECIMAL
diff --git a/manager/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy
index 9b96b8a3d..edac53e5f 100644
--- a/manager/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy
@@ -101,7 +101,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
asset.coordinates.length == 2
asset.path.length == 1
asset.path[0] == managerDemoSetup.smartOfficeId
- new AssetAttributes(asset.attributes).get("geoStreet").valueAsString == "Torenallee 20"
+ new AssetAttributes(asset).get("geoStreet").valueAsString == "Torenallee 20"
when: "a query is executed"
def assets = assetStorageService.findAll(
@@ -151,7 +151,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
assets.get(0).coordinates.length == 2
assets.get(0).path.length == 1
assets.get(0).path[0] == managerDemoSetup.smartOfficeId
- new AssetAttributes(assets.get(0).attributes).get("geoStreet").valueAsString == "Torenallee 20"
+ new AssetAttributes(assets.get(0)).get("geoStreet").valueAsString == "Torenallee 20"
when: "a query is executed"
assets = assetStorageService.findAll(
@@ -248,11 +248,11 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
assets.get(0).id == managerDemoSetup.apartment1Id
assets.get(1).id == managerDemoSetup.apartment1LivingroomId
assets.get(2).id == managerDemoSetup.apartment1LivingroomThermostatId
- new AssetAttributes(assets.get(2).attributes).size() == 2
- new AssetAttributes(assets.get(2).attributes).get("currentTemperature").valueAsDecimal == null
- new AssetAttributes(assets.get(2).attributes).get("currentTemperature").meta.size() == 3
- new AssetAttributes(assets.get(2).attributes).get("comfortTemperature").valueAsDecimal == null
- new AssetAttributes(assets.get(2).attributes).get("comfortTemperature").meta.size() == 2
+ new AssetAttributes(assets.get(2)).size() == 2
+ new AssetAttributes(assets.get(2)).get("currentTemperature").valueAsDecimal == null
+ new AssetAttributes(assets.get(2)).get("currentTemperature").meta.size() == 3
+ new AssetAttributes(assets.get(2)).get("comfortTemperature").valueAsDecimal == null
+ new AssetAttributes(assets.get(2)).get("comfortTemperature").meta.size() == 2
assets.get(3).id == managerDemoSetup.apartment2Id
when: "a query is executed"
diff --git a/manager/test/src/test/groovy/org/openremote/test/rules/ApartmentActionsTest.groovy b/manager/test/src/test/groovy/org/openremote/test/rules/ApartmentActionsTest.groovy
index 0d1cac9d1..224f69f78 100644
--- a/manager/test/src/test/groovy/org/openremote/test/rules/ApartmentActionsTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/rules/ApartmentActionsTest.groovy
@@ -51,7 +51,7 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai
and: "the room lights in an apartment to be on"
def livingRoomAsset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)
- assert new AssetAttributes(livingRoomAsset.getAttributes()).get("lightSwitch").valueAsBoolean
+ assert new AssetAttributes(livingRoomAsset).get("lightSwitch").valueAsBoolean
when: "the ALL LIGHTS OFF switch is set to off for an apartment"
def apartment1AllLightsOffChange = new AttributeEvent(
@@ -62,7 +62,7 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai
then: "the room lights in the apartment should be off"
conditions.eventually {
livingRoomAsset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)
- assert !new AssetAttributes(livingRoomAsset.getAttributes()).get("lightSwitch").valueAsBoolean
+ assert !new AssetAttributes(livingRoomAsset).get("lightSwitch").valueAsBoolean
}
cleanup: "the server should be stopped"
diff --git a/model/src/main/java/org/openremote/model/AbstractValueHolder.java b/model/src/main/java/org/openremote/model/AbstractValueHolder.java
index 34a37023a..344f03c06 100644
--- a/model/src/main/java/org/openremote/model/AbstractValueHolder.java
+++ b/model/src/main/java/org/openremote/model/AbstractValueHolder.java
@@ -149,6 +149,14 @@ public abstract class AbstractValueHolder<CHILD extends AbstractValueHolder> {
return value != null; // Don't allow literal nulls
}
+ /**
+ * Indicate that the jsonObject contains the mandatory data for this type of attribute
+ * override in attribute sub classes as required
+ */
+ public boolean isValid() {
+ return true;
+ }
+
@Override
public String toString() {
return jsonObject.toJson();
diff --git a/model/src/main/java/org/openremote/model/Attribute.java b/model/src/main/java/org/openremote/model/Attribute.java
index ab2ff5306..f72a9f382 100644
--- a/model/src/main/java/org/openremote/model/Attribute.java
+++ b/model/src/main/java/org/openremote/model/Attribute.java
@@ -19,6 +19,7 @@
*/
package org.openremote.model;
+import com.google.gwt.regexp.shared.RegExp;
import elemental.json.Json;
import elemental.json.JsonObject;
import elemental.json.JsonValue;
@@ -32,39 +33,44 @@ import java.util.NoSuchElementException;
*/
public abstract class Attribute<CHILD extends Attribute<CHILD>> extends AbstractValueTimestampHolder<CHILD> {
+ public static final String TYPE_FIELD_NAME = "type";
+ public static final String META_FIELD_NAME = "meta";
+
/**
* Attribute names should be very simple, as we use them in SQL path expressions, etc. and must manually escape.
*/
public static final String ATTRIBUTE_NAME_PATTERN = "^\\w+$";
+ protected static final RegExp attributeNamePattern = RegExp.compile(Attribute.ATTRIBUTE_NAME_PATTERN);
protected String name;
- public Attribute() {
- super(Json.createObject());
- }
-
- public Attribute(String name) {
+ protected Attribute(String name) {
this(name, Json.createObject());
}
- public Attribute(String name, AttributeType type) {
- this(name);
+ protected Attribute(String name, AttributeType type) {
+ super(Json.createObject());
+ setName(name);
setType(type);
}
- public Attribute(String name, JsonObject jsonObject) {
+ protected Attribute(String name, JsonObject jsonObject) {
super(jsonObject);
- this.name = name;
+ setName(name);
+
+ // Verify jsonObject is valid
+ if (!isValid()) {
+ throw new IllegalArgumentException("Supplied JSON object is not valid for this type of attribute: " + jsonObject.toJson());
+ }
}
- public Attribute(String name, AttributeType type, JsonValue value) {
- this(name, Json.createObject());
- setType(type);
+ protected Attribute(String name, AttributeType type, JsonValue value) {
+ this(name, type);
setValue(value);
}
- public Attribute(CHILD attribute) {
- this(attribute.getName(), attribute.getJsonObject());
+ protected Attribute(CHILD attribute) {
+ this(attribute.getName(), attribute.getType(), attribute.getJsonObject());
}
@Override
@@ -75,6 +81,11 @@ public abstract class Attribute<CHILD extends Attribute<CHILD>> extends Abstract
}
public void setName(String name) {
+ if (!Attribute.nameIsValid(name)) {
+ throw new IllegalArgumentException(
+ "Invalid attribute name (must match '" + Attribute.ATTRIBUTE_NAME_PATTERN + "'): " + name
+ );
+ }
this.name = name;
}
@@ -87,34 +98,34 @@ public abstract class Attribute<CHILD extends Attribute<CHILD>> extends Abstract
}
public AttributeType getType() {
- String typeName = jsonObject.hasKey("type") ? jsonObject.get("type").asString() : null;
+ String typeName = jsonObject.hasKey(TYPE_FIELD_NAME) ? jsonObject.get(TYPE_FIELD_NAME).asString() : null;
return typeName != null ? AttributeType.fromValue(typeName) : null;
}
@SuppressWarnings("unchecked")
public CHILD setType(AttributeType type) {
if (type != null) {
- jsonObject.put("type", Json.create(type.getValue()));
- } else if (jsonObject.hasKey("type")) {
- jsonObject.remove("type");
- }
+ jsonObject.put(TYPE_FIELD_NAME, Json.create(type.getValue()));
+ }/* else if (jsonObject.hasKey(TYPE_FIELD_NAME)) {
+ jsonObject.remove(TYPE_FIELD_NAME);
+ }*/
return (CHILD)this;
}
public boolean hasMeta() {
- return jsonObject.hasKey("meta");
+ return jsonObject.hasKey(META_FIELD_NAME);
}
public Meta getMeta() {
- return hasMeta() ? new Meta(jsonObject.getArray("meta")) : null;
+ return hasMeta() ? new Meta(jsonObject.getArray(META_FIELD_NAME)) : null;
}
@SuppressWarnings("unchecked")
public CHILD setMeta(Meta meta) {
if (meta != null) {
- jsonObject.put("meta", meta.getJsonArray());
- } else if (jsonObject.hasKey("meta")) {
- jsonObject.remove("meta");
+ jsonObject.put(META_FIELD_NAME, meta.getJsonArray());
+ } else if (jsonObject.hasKey(META_FIELD_NAME)) {
+ jsonObject.remove(META_FIELD_NAME);
}
return (CHILD) this;
}
@@ -133,8 +144,13 @@ public abstract class Attribute<CHILD extends Attribute<CHILD>> extends Abstract
return firstMetaItem(name);
}
+ public static boolean nameIsValid(String name) {
+ return name != null && name.length() > 0 && attributeNamePattern.test(name);
+ }
+
+ @Override
public boolean isValid() {
- return getName() != null && getName().length() > 0 && getType() != null;
+ return super.isValid() && nameIsValid(name) && getType() != null;
}
public abstract CHILD copy();
diff --git a/model/src/main/java/org/openremote/model/Attributes.java b/model/src/main/java/org/openremote/model/Attributes.java
index 58fc4b697..b65e85f4b 100644
--- a/model/src/main/java/org/openremote/model/Attributes.java
+++ b/model/src/main/java/org/openremote/model/Attributes.java
@@ -109,7 +109,7 @@ public abstract class Attributes<CHILD extends Attributes<CHILD, A>, A extends A
abstract public CHILD copy();
- abstract protected A createAttribute(String name, JsonObject jsonObject);
+ abstract protected A createAttribute(String name, JsonObject jsonObject) throws IllegalArgumentException;
@Override
public String toString() {
diff --git a/model/src/main/java/org/openremote/model/Meta.java b/model/src/main/java/org/openremote/model/Meta.java
index ddf4260d7..0bf9dcd89 100644
--- a/model/src/main/java/org/openremote/model/Meta.java
+++ b/model/src/main/java/org/openremote/model/Meta.java
@@ -105,6 +105,10 @@ public class Meta {
return this;
}
+ public Meta removeAll(AssetMeta assetMeta) {
+ return removeAll(assetMeta.getName());
+ }
+
public Meta removeAll(String name) {
for (int i = 0; i < jsonArray.length(); i++) {
JsonObject jsonObject = jsonArray.getObject(i);
diff --git a/model/src/main/java/org/openremote/model/asset/AbstractAssetAttribute.java b/model/src/main/java/org/openremote/model/asset/AbstractAssetAttribute.java
index 7e6a5c0d9..f4f90bc6a 100644
--- a/model/src/main/java/org/openremote/model/asset/AbstractAssetAttribute.java
+++ b/model/src/main/java/org/openremote/model/asset/AbstractAssetAttribute.java
@@ -29,57 +29,28 @@ public abstract class AbstractAssetAttribute<CHILD extends AbstractAssetAttribut
final public String assetId;
- public AbstractAssetAttribute() {
- this.assetId = null;
- }
-
- public AbstractAssetAttribute(String assetId) {
- this.assetId = assetId;
- }
-
- public AbstractAssetAttribute(String name, AttributeType type) {
+ protected AbstractAssetAttribute(String assetId, String name, AttributeType type) {
super(name, type);
- this.assetId = null;
- }
-
- public AbstractAssetAttribute(String name, JsonObject jsonObject) {
- super(name, jsonObject);
- this.assetId = null;
- }
-
- public AbstractAssetAttribute(String name, AttributeType type, JsonValue value) {
- super(name, type, value);
- this.assetId = null;
- }
-
- public AbstractAssetAttribute(String assetId, String name) {
- super(name);
this.assetId = assetId;
}
- public AbstractAssetAttribute(String assetId, String name, AttributeType type) {
- super(name, type);
+ protected AbstractAssetAttribute(String assetId, String name, AttributeType type, JsonValue value) {
+ super(name, type, value);
this.assetId = assetId;
}
- public AbstractAssetAttribute(String assetId, String name, JsonObject jsonObject) {
+ protected AbstractAssetAttribute(String assetId, String name, JsonObject jsonObject) {
super(name, jsonObject);
this.assetId = assetId;
}
- public AbstractAssetAttribute(String assetId, String name, AttributeType type, JsonValue value) {
- super(name, type, value);
- this.assetId = assetId;
- }
-
- public AbstractAssetAttribute(AbstractAssetAttribute attribute) {
- this(attribute.assetId, attribute.getName(), attribute.getJsonObject());
+ // Bypass the valid check as asset attribute would have already been validated
+ protected AbstractAssetAttribute(AbstractAssetAttribute assetAttribute) {
+ super(assetAttribute.getName(), assetAttribute.getJsonObject());
+ this.assetId = assetAttribute.assetId;
}
public String getAssetId() {
- if (assetId == null) {
- throw new IllegalStateException("Asset identifier not set on: " + this);
- }
return assetId;
}
@@ -92,8 +63,8 @@ public abstract class AbstractAssetAttribute<CHILD extends AbstractAssetAttribut
*/
public AttributeState getState() {
return new AttributeState(
- getAttributeRef(),
- getValue()
+ getAttributeRef(),
+ getValue()
);
}
@@ -102,8 +73,8 @@ public abstract class AbstractAssetAttribute<CHILD extends AbstractAssetAttribut
*/
public AttributeEvent getStateEvent() {
return new AttributeEvent(
- getState(),
- getValueTimestamp()
+ getState(),
+ getValueTimestamp()
);
}
@@ -139,4 +110,7 @@ public abstract class AbstractAssetAttribute<CHILD extends AbstractAssetAttribut
return hasMetaItem(RULES_EVENT_EXPIRES) ? firstMetaItem(RULES_EVENT_EXPIRES).getValueAsString() : null;
}
+ public boolean isAgentLinked() {
+ return hasMetaItem(AGENT_LINK);
+ }
}
diff --git a/model/src/main/java/org/openremote/model/asset/AssetAttribute.java b/model/src/main/java/org/openremote/model/asset/AssetAttribute.java
index 5b2586bcc..8bbad4334 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetAttribute.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetAttribute.java
@@ -22,52 +22,35 @@ package org.openremote.model.asset;
import elemental.json.Json;
import elemental.json.JsonObject;
import elemental.json.JsonValue;
-import org.openremote.model.AttributeType;
+import org.openremote.model.*;
public class AssetAttribute extends AbstractAssetAttribute<AssetAttribute> {
-
- public AssetAttribute() {
- }
-
- public AssetAttribute(String assetId) {
- super(assetId);
- }
-
public AssetAttribute(String name, AttributeType type) {
- super(name, type);
- }
-
- public AssetAttribute(String name, JsonObject jsonObject) {
- super(name, jsonObject);
+ super(null, name, type);
}
public AssetAttribute(String name, AttributeType type, JsonValue value) {
- super(name, type, value);
+ super(null, name, type, value);
}
- public AssetAttribute(String assetId, String name) {
- super(assetId, name);
+ public AssetAttribute(String name, JsonObject jsonObject) {
+ super(null, name, jsonObject);
}
public AssetAttribute(String assetId, String name, AttributeType type) {
super(assetId, name, type);
}
- public AssetAttribute(String assetId, String name, JsonObject jsonObject) {
- super(assetId, name, jsonObject);
- }
-
public AssetAttribute(String assetId, String name, AttributeType type, JsonValue value) {
super(assetId, name, type, value);
}
- public AssetAttribute(AbstractAssetAttribute attribute) {
- super(attribute);
+ public AssetAttribute(String assetId, String name, JsonObject jsonObject) {
+ super(assetId, name, jsonObject);
}
@Override
public AssetAttribute copy() {
return new AssetAttribute(assetId, getName(), Json.parse(getJsonObject().toJson()));
}
-
}
diff --git a/model/src/main/java/org/openremote/model/asset/AssetAttributes.java b/model/src/main/java/org/openremote/model/asset/AssetAttributes.java
index 53354ee13..5e1e81a27 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetAttributes.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetAttributes.java
@@ -59,7 +59,7 @@ public class AssetAttributes extends AbstractAssetAttributes<AssetAttributes, As
@SuppressWarnings("unchecked")
@Override
- protected AssetAttribute createAttribute(String name, JsonObject jsonObject) {
+ protected AssetAttribute createAttribute(String name, JsonObject jsonObject) throws IllegalArgumentException {
return new AssetAttribute(assetId, name, jsonObject);
}
}
diff --git a/model/src/main/java/org/openremote/model/asset/AssetMeta.java b/model/src/main/java/org/openremote/model/asset/AssetMeta.java
index 45727bdbd..4b5cd6a9f 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetMeta.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetMeta.java
@@ -129,7 +129,12 @@ public enum AssetMeta {
* facts from the rules sessions if they are older than this value (using event source timestamp, not event
* processing time).
*/
- RULES_EVENT_EXPIRES(ASSET_META_NAMESPACE + ":rulesEventExpires", new Access(true, false, true), JsonType.NUMBER);
+ RULES_EVENT_EXPIRES(ASSET_META_NAMESPACE + ":rulesEventExpires", new Access(true, false, true), JsonType.NUMBER),
+
+ /**
+ * Enable flag to be used by asset attributes that could require this functionality (e.g. ProtocolConfiguration)
+ */
+ ENABLED(ASSET_META_NAMESPACE + ":enabled", new Access(true, false, true), JsonType.BOOLEAN);
final protected String name;
final protected Access access;
diff --git a/model/src/main/java/org/openremote/model/asset/agent/AgentAttribute.java b/model/src/main/java/org/openremote/model/asset/agent/AgentAttribute.java
index 81dc00840..2591eb9bc 100644
--- a/model/src/main/java/org/openremote/model/asset/agent/AgentAttribute.java
+++ b/model/src/main/java/org/openremote/model/asset/agent/AgentAttribute.java
@@ -24,52 +24,31 @@ import elemental.json.JsonObject;
import elemental.json.JsonValue;
import org.openremote.model.AttributeType;
import org.openremote.model.asset.AbstractAssetAttribute;
+import org.openremote.model.asset.AssetAttribute;
-public class AgentAttribute<CHILD extends AgentAttribute<CHILD>> extends AbstractAssetAttribute<CHILD> {
-
- public AgentAttribute() {
- }
-
- public AgentAttribute(String assetId) {
- super(assetId);
- }
-
- public AgentAttribute(String name, AttributeType type) {
- super(name, type);
- }
-
- public AgentAttribute(String name, JsonObject jsonObject) {
- super(name, jsonObject);
- }
-
- public AgentAttribute(String name, AttributeType type, JsonValue value) {
- super(name, type, value);
- }
+import static org.openremote.model.asset.AssetMeta.RULES_FACT;
- public AgentAttribute(String assetId, String name) {
- super(assetId, name);
- }
+public class AgentAttribute<CHILD extends AgentAttribute<CHILD>> extends AbstractAssetAttribute<CHILD> {
public AgentAttribute(String assetId, String name, AttributeType type) {
super(assetId, name, type);
}
- public AgentAttribute(String assetId, String name, JsonObject jsonObject) {
- super(assetId, name, jsonObject);
- }
-
public AgentAttribute(String assetId, String name, AttributeType type, JsonValue value) {
super(assetId, name, type, value);
}
- public AgentAttribute(AbstractAssetAttribute attribute) {
- super(attribute);
+ public AgentAttribute(String assetId, String name, JsonObject jsonObject) {
+ super(assetId, name, jsonObject);
}
@SuppressWarnings("unchecked")
@Override
public CHILD copy() {
- return (CHILD) new AgentAttribute<CHILD>(getName(), Json.parse(getJsonObject().toJson()));
+ return (CHILD) new AgentAttribute<CHILD>(assetId, getName(), Json.parse(getJsonObject().toJson()));
}
+ public boolean isProtocolConfiguration() {
+ return ProtocolConfiguration.isProtocolConfiguration(this);
+ }
}
diff --git a/model/src/main/java/org/openremote/model/asset/agent/ProtocolConfiguration.java b/model/src/main/java/org/openremote/model/asset/agent/ProtocolConfiguration.java
index ff979dcfd..5b391fc84 100644
--- a/model/src/main/java/org/openremote/model/asset/agent/ProtocolConfiguration.java
+++ b/model/src/main/java/org/openremote/model/asset/agent/ProtocolConfiguration.java
@@ -22,11 +22,16 @@ package org.openremote.model.asset.agent;
import elemental.json.Json;
import elemental.json.JsonObject;
import elemental.json.JsonValue;
-import org.openremote.model.AttributeType;
-import org.openremote.model.Meta;
+import org.openremote.model.*;
import org.openremote.model.asset.AbstractAssetAttribute;
+import org.openremote.model.asset.Asset;
+import org.openremote.model.asset.AssetAttribute;
+import org.openremote.model.asset.AssetMeta;
+import org.openremote.model.asset.thing.ThingAttribute;
+import java.util.List;
import java.util.Locale;
+import java.util.stream.Collectors;
/**
* Agent attributes can be named protocol configurations, the value is a protocol URN.
@@ -35,65 +40,80 @@ import java.util.Locale;
*/
public class ProtocolConfiguration extends AgentAttribute<ProtocolConfiguration> {
- /**
- * A protocol configuration attribute value must be a URN string representation starting with "urn:".
- */
- public static boolean isProtocolConfiguration(AgentAttribute attribute) {
- return attribute.getType() == AttributeType.STRING
- && attribute.hasValue()
- && attribute.getValueAsString().toLowerCase(Locale.ROOT).startsWith("urn:");
- }
-
- public ProtocolConfiguration() {
+ public ProtocolConfiguration(String name, String protocol) {
+ super(null, name, AttributeType.STRING, Json.create(protocol));
}
- public ProtocolConfiguration(String assetId) {
- super(assetId);
+ public ProtocolConfiguration(String assetId, String name, String protocol) {
+ super(assetId, name, AttributeType.STRING, Json.create(protocol));
}
- public ProtocolConfiguration(String name, AttributeType type) {
- super(name, type);
+ public ProtocolConfiguration(String assetId, String name, JsonObject jsonObject) {
+ super(assetId, name, jsonObject);
}
- public ProtocolConfiguration(String name, JsonObject jsonObject) {
- super(name, jsonObject);
+ public ProtocolConfiguration(AbstractAssetAttribute attribute) {
+ this(attribute.getAssetId(), attribute.getName(), attribute.getJsonObject());
}
- public ProtocolConfiguration(String name, AttributeType type, JsonValue value) {
- super(name, type, value);
+ public boolean isEnabled() {
+ MetaItem enabled = firstMetaItem(AssetMeta.ENABLED);
+ return enabled != null ? enabled.getValueAsBoolean() : true;
}
- public ProtocolConfiguration(String name, String protocol) {
- super(name, AttributeType.STRING, Json.create(protocol));
+ public void setEnabled(boolean enabled) {
+ Meta meta = getMeta();
+ meta.removeAll(AssetMeta.ENABLED.getName());
+ meta.add(new MetaItem(AssetMeta.ENABLED, Json.create(enabled)));
+ setMeta(meta);
}
- public ProtocolConfiguration(String assetId, String name, AttributeType type) {
- super(assetId, name, type);
+ @Override
+ public ProtocolConfiguration setValue(JsonValue value) throws IllegalArgumentException {
+ super.setValue(value);
+ if (!isValueValid()) {
+ throw new IllegalArgumentException("Protocol configuration value should contain a protocol URN");
+ }
+ return this;
}
- public ProtocolConfiguration(String assetId, String name, JsonObject jsonObject) {
- super(assetId, name, jsonObject);
+ public String getProtocolName() {
+ return getValueAsString();
}
- public ProtocolConfiguration(String assetId, String name, AttributeType type, JsonValue value) {
- super(assetId, name, type, value);
+ public boolean isValueValid() {
+ return getType() == AttributeType.STRING && getValueAsString() != null && getValueAsString().startsWith(Constants.PROTOCOL_NAMESPACE);
}
- public ProtocolConfiguration(ProtocolConfiguration attribute) {
- super(attribute);
+ @Override
+ public boolean isValid() {
+ return super.isValid() && isValueValid();
}
- public ProtocolConfiguration(AbstractAssetAttribute attribute) {
- super(attribute);
+ /**
+ * A protocol configuration attribute value must be a URN string representation starting with {@link Constants#PROTOCOL_NAMESPACE}.
+ */
+ public static boolean isProtocolConfiguration(AbstractAssetAttribute attribute) {
+ return attribute.getType() == AttributeType.STRING
+ && attribute.hasValue()
+ && attribute.getValueAsString().toLowerCase(Locale.ROOT).startsWith(Constants.PROTOCOL_NAMESPACE);
}
- @Override
- public ProtocolConfiguration copy() {
- return new ProtocolConfiguration(getName(), Json.parse(getJsonObject().toJson()));
+ /**
+ * Get all protocol configuration attributes from the asset
+ */
+ public static List<ProtocolConfiguration> getAll(Asset agent) {
+ return getAll(new AgentAttributes(agent).get());
}
- public String getProtocolName() {
- return getValueAsString();
+ /**
+ * Get all protocol configuration attributes from the agent attributes
+ */
+ public static List<ProtocolConfiguration> getAll(List<AgentAttribute> attributes) {
+ return attributes
+ .stream()
+ .filter(ProtocolConfiguration::isProtocolConfiguration)
+ .map(ProtocolConfiguration::new)
+ .collect(Collectors.toList());
}
-
}
diff --git a/model/src/main/java/org/openremote/model/asset/thing/ThingAttribute.java b/model/src/main/java/org/openremote/model/asset/thing/ThingAttribute.java
index 9156b2462..696934c89 100644
--- a/model/src/main/java/org/openremote/model/asset/thing/ThingAttribute.java
+++ b/model/src/main/java/org/openremote/model/asset/thing/ThingAttribute.java
@@ -23,86 +23,137 @@ import elemental.json.Json;
import elemental.json.JsonArray;
import elemental.json.JsonObject;
import elemental.json.JsonValue;
-import org.openremote.model.AttributeRef;
-import org.openremote.model.AttributeType;
-import org.openremote.model.asset.AbstractAssetAttribute;
-import org.openremote.model.asset.AssetMeta;
+import org.openremote.model.*;
+import org.openremote.model.asset.*;
import org.openremote.model.asset.agent.ProtocolConfiguration;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
public class ThingAttribute extends AbstractAssetAttribute<ThingAttribute> {
protected ProtocolConfiguration protocolConfiguration;
- public static boolean isLinkedAttribute(ThingAttribute attribute) {
- return getAgentLink(attribute) != null;
+ public ThingAttribute(ProtocolConfiguration protocolConfiguration, AssetAttribute attribute) {
+ this(protocolConfiguration, attribute.getAssetId(), attribute.getName(), attribute.getJsonObject());
}
- static public AttributeRef getAgentLink(ThingAttribute attribute) {
- JsonArray array = attribute.hasMetaItem(AssetMeta.AGENT_LINK)
- ? attribute.firstMetaItem(AssetMeta.AGENT_LINK).getValueAsArray()
- : null;
- if (array == null || array.length() != 2)
- return null;
- return new AttributeRef(array);
+ public ThingAttribute(ProtocolConfiguration protocolConfiguration, AttributeRef protocolRef, String assetId, String name, AttributeType type, JsonValue value) {
+ super(assetId, name, type, value);
+ setProtocolRef(protocolRef);
+ this.protocolConfiguration = protocolConfiguration;
}
- public ThingAttribute() {
- }
+ public ThingAttribute(ProtocolConfiguration protocolConfiguration, String assetId, String name, JsonObject jsonObject) {
+ super(assetId, name, jsonObject);
+ this.protocolConfiguration = protocolConfiguration;
- public ThingAttribute(String assetId) {
- super(assetId);
+ // Verify jsonObject is valid
+ if (!isValid()) {
+ throw new IllegalArgumentException("Supplied JSON object is not valid for this type of attribute: " + jsonObject.toJson());
+ }
}
- public ThingAttribute(String name, AttributeType type) {
- super(name, type);
+ @Override
+ public ThingAttribute copy() {
+ return new ThingAttribute(protocolConfiguration.copy(), assetId, getName(), Json.parse(getJsonObject().toJson()));
}
- public ThingAttribute(String name, JsonObject jsonObject) {
- super(name, jsonObject);
+ public ProtocolConfiguration getProtocolConfiguration() {
+ return protocolConfiguration;
}
- public ThingAttribute(String name, AttributeType type, JsonValue value) {
- super(name, type, value);
+ /**
+ * Get the referenced protocol configuration for this thing attribute; if it is not populated then use the supplied
+ * resolver to go and populate it before returning the value
+ */
+ public ProtocolConfiguration getProtocolConfiguration(Function<AttributeRef, ProtocolConfiguration> protocolConfigurationResolver) {
+ if (protocolConfiguration == null && protocolConfigurationResolver != null) {
+ protocolConfiguration = protocolConfigurationResolver.apply(getProtocolRef(this));
+ }
+ return protocolConfiguration;
}
- public ThingAttribute(String assetId, String name) {
- super(assetId, name);
+ public AttributeRef getProtocolRef() {
+ return getProtocolRef(this);
}
- public ThingAttribute(String assetId, String name, AttributeType type) {
- super(assetId, name, type);
- }
+ protected void setProtocolRef(AttributeRef attributeRef) {
+ if (attributeRef == null) {
+ throw new IllegalArgumentException("AttributeRef cannot be null");
+ }
- public ThingAttribute(String assetId, String name, JsonObject jsonObject) {
- super(assetId, name, jsonObject);
+ Meta meta = hasMeta() ? getMeta() : new Meta();
+ meta.removeAll(AssetMeta.AGENT_LINK);
+ meta.add(new MetaItem(AssetMeta.AGENT_LINK, attributeRef.asJsonValue()));
+ setMeta(meta);
+ protocolConfiguration = null;
}
- public ThingAttribute(String assetId, String name, AttributeType type, JsonValue value) {
- super(assetId, name, type, value);
+ /**
+ * Does super class checks and also checks for valid Protocol Ref
+ */
+ @Override
+ public boolean isValid() {
+ return super.isValid() && getProtocolRef(this) != null;
}
- public ThingAttribute(AbstractAssetAttribute attribute) {
- this(attribute, null);
+ public static AttributeRef getProtocolRef(AbstractAssetAttribute attribute) {
+ MetaItem metaItem = attribute.firstMetaItem(AssetMeta.AGENT_LINK);
+ JsonArray array = metaItem != null ? metaItem.getValueAsArray() : null;
+ return array != null && array.length() == 2 ? new AttributeRef(array) : null;
}
- public ThingAttribute(AbstractAssetAttribute attribute, ProtocolConfiguration protocolConfiguration) {
- this(attribute.assetId, protocolConfiguration, attribute.getName(), attribute.getJsonObject());
+ /**
+ * Gets all thing attributes from the asset and groups them by ProtocolRef
+ */
+ public static Map<AttributeRef, List<ThingAttribute>> getAllGroupedByProtocolRef(Asset asset, Function<AttributeRef, ProtocolConfiguration> protocolConfigurationResolver) {
+ return getAllGroupedByProtocolRef(new AssetAttributes(asset).get(), protocolConfigurationResolver);
}
- public ThingAttribute(String assetId, ProtocolConfiguration protocolConfiguration, String name, JsonObject jsonObject) {
- super(assetId, name, jsonObject);
- this.protocolConfiguration = protocolConfiguration;
+ /**
+ * Gets all thing attributes from the asset and groups them by ProtocolRef
+ */
+ public static Map<AttributeRef, List<ThingAttribute>> getAllGroupedByProtocolRef(List<AssetAttribute> attributes, Function<AttributeRef, ProtocolConfiguration> protocolConfigurationResolver) {
+ return attributes
+ .stream()
+ .filter(AssetAttribute::isAgentLinked)
+ .map(attribute -> get(attribute, protocolConfigurationResolver))
+ .filter(thingAttribute -> thingAttribute != null)
+ .collect(Collectors.groupingBy(thingAttribute -> thingAttribute.getProtocolRef()));
}
- @Override
- public ThingAttribute copy() {
- return new ThingAttribute(assetId, protocolConfiguration, getName(), Json.parse(getJsonObject().toJson()));
+ /**
+ * Gets all thing attributes from the asset
+ */
+ public static List<ThingAttribute> getAll(Asset asset, Function<AttributeRef, ProtocolConfiguration> protocolConfigurationResolver) {
+ return getAll(new AssetAttributes(asset).get(), protocolConfigurationResolver);
}
/**
- * Linked thing attributes have a protocol configuration of their agent after they are resolved.
+ * Gets all thing attributes from the asset
*/
- public ProtocolConfiguration getProtocolConfiguration() {
- return protocolConfiguration;
+ public static List<ThingAttribute> getAll(List<AssetAttribute> attributes, Function<AttributeRef, ProtocolConfiguration> protocolConfigurationResolver) {
+ return attributes
+ .stream()
+ .filter(AssetAttribute::isAgentLinked)
+ .filter(thingAttribute -> thingAttribute != null)
+ .map(attribute -> get(attribute, protocolConfigurationResolver))
+ .collect(Collectors.toList());
+ }
+
+ public static ThingAttribute get(AssetAttribute attribute, Function<AttributeRef, ProtocolConfiguration> protocolConfigurationResolver) {
+ AttributeRef protocolRef = getProtocolRef(attribute);
+ if (protocolRef == null) {
+ return null;
+ }
+ ProtocolConfiguration protocolConfiguration = protocolConfigurationResolver.apply(protocolRef);
+
+ if (protocolConfiguration == null) {
+ return null;
+ }
+
+ return new ThingAttribute(protocolConfiguration, attribute);
}
}
diff --git a/model/src/main/java/org/openremote/model/asset/thing/ThingAttributes.java b/model/src/main/java/org/openremote/model/asset/thing/ThingAttributes.java
index 53f507611..b7343ba6f 100644
--- a/model/src/main/java/org/openremote/model/asset/thing/ThingAttributes.java
+++ b/model/src/main/java/org/openremote/model/asset/thing/ThingAttributes.java
@@ -33,10 +33,6 @@ import java.util.List;
import java.util.Map;
public class ThingAttributes extends AbstractAssetAttributes<ThingAttributes, ThingAttribute> {
-
- public ThingAttributes() {
- }
-
public ThingAttributes(String assetId) {
super(assetId);
}
@@ -61,52 +57,7 @@ public class ThingAttributes extends AbstractAssetAttributes<ThingAttributes, Th
@SuppressWarnings("unchecked")
@Override
- protected ThingAttribute createAttribute(String name, JsonObject jsonObject) {
- return new ThingAttribute(assetId, null, name, jsonObject);
- }
-
- /**
- * Get all attributes which are linked to an agent, grouped by protocol name.
- */
- public Map<String, List<ThingAttribute>> getLinkedAttributes(Function<AttributeRef, ProtocolConfiguration> linkResolver) {
- List<ThingAttribute> attributes = super.get();
-
- // Resolve all which are linked to an agent
- List<ThingAttribute> linkedAttributes = new ArrayList<>();
- for (ThingAttribute attribute : attributes) {
- ThingAttribute linkedAttribute = getLinkedAttribute(linkResolver, attribute.getName());
- if (linkedAttribute != null) {
- linkedAttributes.add(linkedAttribute);
- }
- }
-
- // Group by protocol name
- Map<String, List<ThingAttribute>> result = new HashMap<>();
- for (ThingAttribute linkedAttribute : linkedAttributes) {
- String protocolName = linkedAttribute.getProtocolConfiguration().getProtocolName();
- if (!result.containsKey(protocolName)) {
- result.put(protocolName, new ArrayList<>());
- }
- result.get(protocolName).add(linkedAttribute);
- }
- return result;
- }
-
- public ThingAttribute getLinkedAttribute(Function<AttributeRef, ProtocolConfiguration> linkResolver,
- String attributeName) {
- ThingAttribute attribute = get(attributeName);
- if (attribute == null || !ThingAttribute.isLinkedAttribute(attribute))
- return null;
-
- AttributeRef agentLink = ThingAttribute.getAgentLink(attribute);
- if (agentLink == null)
- return null;
-
- ProtocolConfiguration protocolConfiguration = linkResolver.apply(agentLink);
- if (protocolConfiguration == null) {
- return null;
- }
-
- return new ThingAttribute(attribute, protocolConfiguration);
+ protected ThingAttribute createAttribute(String name, JsonObject jsonObject) throws IllegalArgumentException {
+ return new ThingAttribute(null, assetId, name, jsonObject);
}
}