100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Cleanup of attribute classes Removed Attribute collection classes (use list now) Replaced AssetAttribute sub classes with wrapper mechanism Introduced Runtime Resolver
Rich Turner5ef8f9afc15e
diff --git a/agent/src/main/java/org/openremote/agent/AgentService.java b/agent/src/main/java/org/openremote/agent/AgentService.javaindex 6dfc8a3c0..97197b179 100644--- a/agent/src/main/java/org/openremote/agent/AgentService.java+++ b/agent/src/main/java/org/openremote/agent/AgentService.java@@ -54,6 +54,11 @@ public class AgentService implements ContainerService {}}+ @Override+ public void allStarted(Container container) throws Exception {++ }+@Overridepublic void stop(Container container) throws Exception {if (agentContext != null) {diff --git a/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java b/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.javaindex 2491b95e9..321087a55 100644--- a/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java+++ b/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java@@ -24,11 +24,13 @@ 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.MessageBrokerService;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.model.asset.AssetAttribute;+import org.openremote.model.asset.agent.ProtocolConfiguration;import java.util.Collection;import java.util.HashMap;@@ -48,21 +50,25 @@ public abstract class AbstractProtocol implements Protocol {};}- final protected Map<AttributeRef, ThingAttribute> linkedAttributes = new HashMap<>();+ final protected Map<AttributeRef, AssetAttribute> linkedAttributes = new HashMap<>();protected MessageBrokerContext messageBrokerContext;protected ProducerTemplate producerTemplate;@Overridepublic void init(Container container) throws Exception {LOG.info("Initializing protocol: " + getProtocolName());- this.messageBrokerContext = container.getService(MessageBrokerSetupService.class).getContext();- this.producerTemplate = messageBrokerContext.createProducerTemplate();}@Overridepublic void start(Container container) throws Exception {+ LOG.fine("Starting protocol: " + getProtocolName());+ this.messageBrokerContext = container.getService(MessageBrokerSetupService.class).getContext();+ this.producerTemplate = container.getService(MessageBrokerService.class).getProducerTemplate();+ }++ @Override+ public void allStarted(Container container) throws Exception {synchronized (linkedAttributes) {- LOG.fine("Starting: " + getProtocolName());messageBrokerContext.addRoutes(new RouteBuilder() {@Overridepublic void configure() throws Exception {@@ -92,40 +98,45 @@ public abstract class AbstractProtocol implements Protocol {}@Override- public void linkAttributes(Collection<ThingAttribute> attributes) throws Exception {+ public void linkAttributes(Collection<AssetAttribute> attributes, ProtocolConfiguration protocolConfiguration) throws Exception {synchronized (linkedAttributes) {- for (ThingAttribute attribute : attributes) {+ attributes.forEach(attribute -> {if (linkedAttributes.containsKey(attribute.getReference())) {LOG.fine("Attribute updated on '" + getProtocolName() + "': " + attribute);- onAttributeUpdated(attribute);+ onAttributeUpdated(attribute, protocolConfiguration);linkedAttributes.put(attribute.getReference(), attribute);} else {LOG.fine("Attribute added on '" + getProtocolName() + "': " + attribute);- onAttributeAdded(attribute);+ onAttributeAdded(attribute, protocolConfiguration);linkedAttributes.put(attribute.getReference(), attribute);}- }+ });}}@Override- public void unlinkAttributes(Collection<ThingAttribute> attributes) throws Exception {+ public void unlinkAttributes(Collection<AssetAttribute> attributes, ProtocolConfiguration protocolConfiguration) throws Exception {synchronized (linkedAttributes) {attributes.stream()- .filter(thingAttribute -> linkedAttributes.values()+ .filter(attribute -> linkedAttributes.values().stream()- .anyMatch(linkedAttribute -> linkedAttribute.getReference().equals(thingAttribute.getReference()))+ .anyMatch(linkedAttribute ->+ linkedAttribute+ .getReference()+ .equals(attribute.getReference()))).forEach(attributeToRemove -> {- linkedAttributes.remove(attributeToRemove.getReference());+ AttributeRef agentLinkedAttributeRef = attributeToRemove.getReference();++ linkedAttributes.remove(agentLinkedAttributeRef);LOG.fine("Attribute removed on '" + getProtocolName() + "': " + attributeToRemove);- onAttributeRemoved(attributeToRemove);+ onAttributeRemoved(attributeToRemove, protocolConfiguration);});}}- protected ThingAttribute getLinkedAttribute(AttributeRef attributeRef) {+ protected AssetAttribute getLinkedAttribute(AttributeRef attributeRef) {synchronized (linkedAttributes) {return linkedAttributes.get(attributeRef);}@@ -151,10 +162,9 @@ public abstract class AbstractProtocol implements Protocol {abstract protected void sendToActuator(AttributeEvent event);- abstract protected void onAttributeAdded(ThingAttribute attribute);-- abstract protected void onAttributeUpdated(ThingAttribute attribute);+ abstract protected void onAttributeAdded(AssetAttribute attribute, ProtocolConfiguration protocolConfiguration);- abstract protected void onAttributeRemoved(ThingAttribute attribute);+ abstract protected void onAttributeUpdated(AssetAttribute attribute, ProtocolConfiguration protocolConfiguration);+ abstract protected void onAttributeRemoved(AssetAttribute attribute, ProtocolConfiguration protocolConfiguration);}diff --git a/agent/src/main/java/org/openremote/agent3/protocol/Protocol.java b/agent/src/main/java/org/openremote/agent3/protocol/Protocol.javaindex 6aa82baaf..092b350ce 100644--- a/agent/src/main/java/org/openremote/agent3/protocol/Protocol.java+++ b/agent/src/main/java/org/openremote/agent3/protocol/Protocol.java@@ -22,7 +22,8 @@ package org.openremote.agent3.protocol;import org.openremote.container.ContainerService;import org.openremote.model.AttributeEvent;import org.openremote.model.Constants;-import org.openremote.model.asset.thing.ThingAttribute;+import org.openremote.model.asset.AssetAttribute;+import org.openremote.model.asset.agent.ProtocolConfiguration;import java.util.Collection;@@ -38,7 +39,7 @@ import java.util.Collection;* <p>* The linked attributes of a protocol provide the model for the protocol to perform these operations. How* attributes and value changes map to actual device and service calls is up to the implementation. The method- * {@link #linkAttributes(Collection)} is first called during startup of the protocol, after+ * {@link #linkAttributes(Collection, ProtocolConfiguration)} is first called during startup of the protocol, after* {@link #init} and before {@link #start}.* <p>* The linked protocol handles south-bound read and write of the attribute value: If the user writes@@ -66,8 +67,8 @@ public interface Protocol extends ContainerService {String getProtocolName();- void linkAttributes(Collection<ThingAttribute> attributes) throws Exception;+ void linkAttributes(Collection<AssetAttribute> attributes, ProtocolConfiguration protocolConfiguration) throws Exception;- void unlinkAttributes(Collection<ThingAttribute> attributes) throws Exception;+ void unlinkAttributes(Collection<AssetAttribute> attributes, ProtocolConfiguration protocolConfiguration) throws Exception;}diff --git a/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroProtocol.java b/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroProtocol.javaindex 315266dc6..9341fcf4d 100644--- a/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroProtocol.java+++ b/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroProtocol.java@@ -23,10 +23,11 @@ import elemental.json.JsonValue;import org.openremote.agent3.protocol.AbstractProtocol;import org.openremote.container.Container;import org.openremote.model.*;+import org.openremote.model.asset.AssetAttribute;+import org.openremote.model.asset.agent.ProtocolConfiguration;import org.openremote.model.asset.macro.MacroAction;-import org.openremote.model.asset.macro.MacroAttribute;import org.openremote.model.asset.macro.MacroAttributeCommand;-import org.openremote.model.asset.thing.ThingAttribute;+import org.openremote.model.asset.macro.MacroConfiguration;import java.util.Collections;import java.util.HashMap;@@ -156,7 +157,7 @@ public class MacroProtocol extends AbstractProtocol {@Overridepublic String getProtocolName() {- return MacroAttribute.PROTOCOL_NAME;+ return MacroConfiguration.PROTOCOL_NAME;}@Override@@ -205,13 +206,13 @@ public class MacroProtocol extends AbstractProtocol {}@Override- protected void onAttributeAdded(ThingAttribute attribute) {- // Protocol configuration is actually a MacroAttribute- MacroAttribute macroAttribute = new MacroAttribute(attribute.getProtocolConfiguration());+ protected void onAttributeAdded(AssetAttribute attribute, ProtocolConfiguration protocolConfiguration) {+ // Protocol configuration is actually a Macro+ MacroConfiguration macroConfiguration = new MacroConfiguration(protocolConfiguration.getAttribute());// Store the macro actions for later execution requestsAttributeRef reference = attribute.getReference();- List<MacroAction> actions = macroAttribute.getActions();+ List<MacroAction> actions = macroConfiguration.getActions();synchronized (actionMap) {actionMap.put(reference, actions);@@ -219,12 +220,12 @@ public class MacroProtocol extends AbstractProtocol {}@Override- protected void onAttributeUpdated(ThingAttribute attribute) {- onAttributeAdded(attribute);+ protected void onAttributeUpdated(AssetAttribute attribute, ProtocolConfiguration protocolConfiguration) {+ onAttributeAdded(attribute, protocolConfiguration);}@Override- protected void onAttributeRemoved(ThingAttribute attribute) {+ protected void onAttributeRemoved(AssetAttribute attribute, ProtocolConfiguration protocolConfiguration) {// Store the macro actions for later execution requestsAttributeRef reference = attribute.getReference();diff --git a/agent/src/main/java/org/openremote/agent3/protocol/simulator/SimulatorProtocol.java b/agent/src/main/java/org/openremote/agent3/protocol/simulator/SimulatorProtocol.javaindex 610274a20..0f9620ee0 100644--- a/agent/src/main/java/org/openremote/agent3/protocol/simulator/SimulatorProtocol.java+++ b/agent/src/main/java/org/openremote/agent3/protocol/simulator/SimulatorProtocol.java@@ -22,9 +22,12 @@ package org.openremote.agent3.protocol.simulator;import elemental.json.JsonValue;import org.openremote.agent3.protocol.AbstractProtocol;import org.openremote.agent3.protocol.simulator.element.*;-import org.openremote.model.*;+import org.openremote.model.AttributeEvent;+import org.openremote.model.AttributeRef;+import org.openremote.model.AttributeState;+import org.openremote.model.MetaItem;+import org.openremote.model.asset.AssetAttribute;import org.openremote.model.asset.agent.ProtocolConfiguration;-import org.openremote.model.asset.thing.ThingAttribute;import java.util.HashMap;import java.util.Locale;@@ -111,16 +114,15 @@ public class SimulatorProtocol extends AbstractProtocol {}@Override- protected void onAttributeAdded(ThingAttribute attribute) {+ protected void onAttributeAdded(AssetAttribute attribute, ProtocolConfiguration protocolConfiguration) {String elementType = attribute.firstMetaItemOrThrow(SIMULATOR_ELEMENT).getValueAsString();- ProtocolConfiguration config = attribute.getProtocolConfiguration();- String configName = config.getName();+ String protocolConfigurationName = protocolConfiguration.getAttribute().getName();- Instance instance = instances.get(configName);+ Instance instance = instances.get(protocolConfigurationName);if (instance == null) {- MetaItem configModeMeta = config.firstMetaItem(CONFIG_MODE);- MetaItem configDelayMeta = config.firstMetaItem(CONFIG_WRITE_DELAY_MILLISECONDS);+ MetaItem configModeMeta = protocolConfiguration.getAttribute().firstMetaItem(CONFIG_MODE);+ MetaItem configDelayMeta = protocolConfiguration.getAttribute().firstMetaItem(CONFIG_WRITE_DELAY_MILLISECONDS);Mode mode = Mode.WRITE_THROUGH_IMMEDIATE;if (configModeMeta != null) {@@ -137,7 +139,7 @@ public class SimulatorProtocol extends AbstractProtocol {}instance = new Instance(mode, writeDelay);- instances.put(configName, instance);+ instances.put(protocolConfigurationName, instance);}SimulatorElement element = createElement(elementType, attribute);@@ -149,16 +151,16 @@ public class SimulatorProtocol extends AbstractProtocol {LOG.info("Putting element '" + element + "' for: " + attribute);elements.put(attribute.getReference(), element);- attributeInstanceMap.put(attribute.getReference(), configName);+ attributeInstanceMap.put(attribute.getReference(), protocolConfigurationName);}@Override- protected void onAttributeUpdated(ThingAttribute attribute) {- onAttributeAdded(attribute);+ protected void onAttributeUpdated(AssetAttribute attribute, ProtocolConfiguration protocolConfiguration) {+ onAttributeAdded(attribute, protocolConfiguration);}@Override- protected void onAttributeRemoved(ThingAttribute attribute) {+ protected void onAttributeRemoved(AssetAttribute attribute, ProtocolConfiguration protocolConfiguration) {elements.remove(attribute.getReference());attributeInstanceMap.remove(attribute.getReference());}@@ -275,7 +277,7 @@ public class SimulatorProtocol extends AbstractProtocol {}}- protected SimulatorElement createElement(String elementType, ThingAttribute attribute) {+ protected SimulatorElement createElement(String elementType, AssetAttribute attribute) {switch (elementType.toLowerCase(Locale.ROOT)) {case SwitchSimulatorElement.ELEMENT_NAME:return new SwitchSimulatorElement();diff --git a/container/src/main/java/org/openremote/container/Container.java b/container/src/main/java/org/openremote/container/Container.javaindex dd92c7662..72a21020e 100644--- a/container/src/main/java/org/openremote/container/Container.java+++ b/container/src/main/java/org/openremote/container/Container.java@@ -115,6 +115,10 @@ public class Container {LOG.fine("Starting service: " + service);service.start(Container.this);}+ for (ContainerService service : getServices()) {+ LOG.fine("Notifying service all started: " + service);+ service.allStarted(Container.this);+ }} catch (RuntimeException ex) {throw ex;} catch (Exception ex) {diff --git a/container/src/main/java/org/openremote/container/ContainerService.java b/container/src/main/java/org/openremote/container/ContainerService.javaindex d2ee6eb4d..995ce5010 100644--- a/container/src/main/java/org/openremote/container/ContainerService.java+++ b/container/src/main/java/org/openremote/container/ContainerService.java@@ -47,6 +47,11 @@ public interface ContainerService {*/void start(Container container) throws Exception;+ /**+ * Called once the container has finished starting all services+ */+ void allStarted(Container container) throws Exception;+/*** When the container is shutting down, it stops all services in the reverse order they have been added to container.*/diff --git a/container/src/main/java/org/openremote/container/message/MessageBrokerService.java b/container/src/main/java/org/openremote/container/message/MessageBrokerService.javaindex f1410fbfe..5983d050a 100644--- a/container/src/main/java/org/openremote/container/message/MessageBrokerService.java+++ b/container/src/main/java/org/openremote/container/message/MessageBrokerService.java@@ -45,6 +45,11 @@ public class MessageBrokerService implements ContainerService {messageBrokerSetupService.getContext().start();}+ @Override+ public void allStarted(Container container) throws Exception {++ }+@Overridepublic void stop(Container container) throws Exception {}diff --git a/container/src/main/java/org/openremote/container/message/MessageBrokerSetupService.java b/container/src/main/java/org/openremote/container/message/MessageBrokerSetupService.javaindex 55db6f22a..c74e0f1c2 100644--- a/container/src/main/java/org/openremote/container/message/MessageBrokerSetupService.java+++ b/container/src/main/java/org/openremote/container/message/MessageBrokerSetupService.java@@ -97,6 +97,11 @@ public class MessageBrokerSetupService implements ContainerService {// 4. WebService#init() - configures HTTP routing paths, giving Camel routes a chance to add routes before}+ @Override+ public void allStarted(Container container) throws Exception {++ }+@Overridepublic void stop(Container container) throws Exception {if (context != null) {diff --git a/container/src/main/java/org/openremote/container/persistence/PersistenceService.java b/container/src/main/java/org/openremote/container/persistence/PersistenceService.javaindex c50248d2b..dc99f12c5 100644--- a/container/src/main/java/org/openremote/container/persistence/PersistenceService.java+++ b/container/src/main/java/org/openremote/container/persistence/PersistenceService.java@@ -106,6 +106,11 @@ public class PersistenceService implements ContainerService {Persistence.createEntityManagerFactory(persistenceUnitName, persistenceUnitProperties);}+ @Override+ public void allStarted(Container container) throws Exception {++ }+@Overridepublic void stop(Container container) throws Exception {LOG.info("Stopping persistence service...");diff --git a/container/src/main/java/org/openremote/container/security/IdentityService.java b/container/src/main/java/org/openremote/container/security/IdentityService.javaindex b70a5b428..901d5b32b 100644--- a/container/src/main/java/org/openremote/container/security/IdentityService.java+++ b/container/src/main/java/org/openremote/container/security/IdentityService.java@@ -79,6 +79,7 @@ public abstract class IdentityService implements ContainerService {public static final int KEYCLOAK_PORT_DEFAULT = 8081;public static final String KEYCLOAK_CONNECT_TIMEOUT = "KEYCLOAK_CONNECT_TIMEOUT";public static final int KEYCLOAK_CONNECT_TIMEOUT_DEFAULT = 2000;+public static final String KEYCLOAK_REQUEST_TIMEOUT = "KEYCLOAK_REQUEST_TIMEOUT";public static final int KEYCLOAK_REQUEST_TIMEOUT_DEFAULT = 10000;public static final String KEYCLOAK_CLIENT_POOL_SIZE = "KEYCLOAK_CLIENT_POOL_SIZE";@@ -197,6 +198,11 @@ public abstract class IdentityService implements ContainerService {LOG.info("Keycloak identity provider available: " + keycloakServiceUri.build());}+ @Override+ public void allStarted(Container container) throws Exception {++ }+@Overridepublic void stop(Container container) throws Exception {if (getHttpClient() != null)diff --git a/container/src/main/java/org/openremote/container/web/WebService.java b/container/src/main/java/org/openremote/container/web/WebService.javaindex 539674725..d53d5e92a 100644--- a/container/src/main/java/org/openremote/container/web/WebService.java+++ b/container/src/main/java/org/openremote/container/web/WebService.java@@ -122,6 +122,11 @@ public abstract class WebService implements ContainerService {}}+ @Override+ public void allStarted(Container container) throws Exception {++ }+@Overridepublic void stop(Container container) throws Exception {if (undertow != null) {diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditActivity.java b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditActivity.javaindex 858851000..710a91dd2 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@@ -35,12 +35,13 @@ import org.openremote.manager.shared.security.Tenant;import org.openremote.manager.shared.validation.ConstraintViolation;import org.openremote.model.Consumer;import org.openremote.model.asset.Asset;-import org.openremote.model.asset.AssetAttributes;import org.openremote.model.asset.AssetType;import org.openremote.model.event.bus.EventBus;import org.openremote.model.event.bus.EventRegistration;import javax.inject.Inject;+import java.util.ArrayList;+import java.util.Arrays;import java.util.Collection;import static org.openremote.manager.client.http.RequestExceptionHandler.handleRequestException;@@ -331,8 +332,8 @@ public class AssetEditActivityenvironment,view.getAttributesEditorContainer(),assetId == null- ? asset.getWellKnownType().getDefaultAttributes()- : new AssetAttributes(asset),+ ? Arrays.asList(asset.getWellKnownType().getDefaultAttributes())+ : new ArrayList<>(),assetId == null);view.setAttributesEditor(attributesEditor);@@ -355,7 +356,7 @@ public class AssetEditActivityasset.setCoordinates(selectedCoordinates);}asset.setAttributes(- attributesEditor != null ? attributesEditor.getAttributes().getJsonObject() : null+ attributesEditor != null ? attributesEditor.getAttributes() : null);}diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesBrowser.java b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesBrowser.javaindex 3cdb63bfd..fa20cf226 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesBrowser.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesBrowser.java@@ -31,7 +31,6 @@ import org.openremote.model.Consumer;import org.openremote.model.ReadAttributesEvent;import org.openremote.model.asset.Asset;import org.openremote.model.asset.AssetAttribute;-import org.openremote.model.asset.AssetAttributes;import org.openremote.model.datapoint.DatapointInterval;import org.openremote.model.datapoint.NumberDatapoint;import org.openremote.model.event.bus.EventRegistration;@@ -41,7 +40,7 @@ import java.util.List;import java.util.logging.Logger;public abstract class AttributesBrowser- extends AttributesView<AttributesBrowser.Container, AttributesBrowser.Style, AssetAttributes, AssetAttribute> {+ extends AttributesView<AttributesBrowser.Container, AttributesBrowser.Style> {private static final Logger LOG = Logger.getLogger(AttributesBrowser.class.getName());@@ -60,7 +59,7 @@ public abstract class AttributesBrowserprotected EventRegistration<AttributeEvent> eventRegistration;public AttributesBrowser(Environment environment, Container container, Asset asset) {- super(environment, container, new AssetAttributes(asset));+ super(environment, container, asset.getAttributes());this.asset = asset;eventRegistration = environment.getEventBus().register(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.javaindex 6d9177022..3dce1f22d 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@@ -21,7 +21,6 @@ package org.openremote.manager.client.assets.attributes;import com.google.gwt.dom.client.Document;import com.google.gwt.event.dom.client.DomEvent;-import com.google.gwt.regexp.shared.RegExp;import com.google.gwt.user.client.ui.FlowPanel;import com.google.gwt.user.client.ui.IsWidget;import elemental.json.Json;@@ -32,13 +31,12 @@ import org.openremote.manager.client.util.JsUtil;import org.openremote.manager.client.widget.*;import org.openremote.model.*;import org.openremote.model.asset.AssetAttribute;-import org.openremote.model.asset.AssetAttributes;import org.openremote.model.asset.AssetMeta;+import org.openremote.model.util.AttributeUtil;+import java.util.List;public class AttributesEditor- extends AttributesView<AttributesEditor.Container, AttributesEditor.Style, AssetAttributes, AssetAttribute> {-- protected final RegExp attributeNameRegExp = RegExp.compile(Attribute.ATTRIBUTE_NAME_PATTERN);+ extends AttributesView<AttributesEditor.Container, AttributesEditor.Style> {public interface Container extends AttributesView.Container<AttributesEditor.Style> {@@ -51,7 +49,7 @@ public class AttributesEditorfinal protected boolean isCreate;protected FormGroup newAttributeGroup;- public AttributesEditor(Environment environment, Container container, AssetAttributes attributes, boolean isCreate) {+ public AttributesEditor(Environment environment, Container container, List<AssetAttribute> attributes, boolean isCreate) {super(environment, container, attributes);this.isCreate = isCreate;}@@ -128,7 +126,7 @@ public class AttributesEditor// TODO This is necessary because JSON elemental behavior is weirdAssetAttribute att2 =new AssetAttribute(attribute.getName(), Json.parse(attribute.getJsonObject().toJson()));- getAttributes().put(att2);+ getAttributes().add(att2);showInfo(environment.getMessages().attributeAdded(attribute.getName()));build();} else {@@ -155,7 +153,7 @@ public class AttributesEditorFormInputText nameInput = createFormInputText(container.getStyle().stringEditor());nameInput.setPlaceholder(environment.getMessages().attributeName());nameInput.addValueChangeHandler(event -> {- if (!attributeNameRegExp.test(event.getValue())) {+ if (!AttributeUtil.nameIsValid(event.getValue())) {formGroup.setError(true);showValidationError(environment.getMessages().invalidAttributeName());} else {@@ -207,15 +205,15 @@ public class AttributesEditorprotected void buildItemList() {itemListPanel.clear();- if (!attribute.hasMeta() || attribute.getMeta().all().length == 0) {+ if (!attribute.hasMeta() || attribute.getMeta().all().size() == 0) {itemListSectionLabel.setVisible(false);return;}itemListSectionLabel.setVisible(true);- MetaItem[] items = attribute.getMeta().all();- for (int i = 0; i < items.length; i++) {- MetaItem item = items[i];+ List<MetaItem> items = attribute.getMeta().all();+ for (int i = 0; i < items.size(); i++) {+ MetaItem item = items.get(i);FormGroup formGroup = new FormGroup();FormLabel label = new FormLabel(item.getName());diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesView.java b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesView.javaindex bb861f04d..136333de4 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesView.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesView.java@@ -32,22 +32,17 @@ import org.openremote.manager.client.event.ShowSuccessEvent;import org.openremote.manager.client.i18n.ManagerMessages;import org.openremote.manager.client.util.CollectionsUtil;import org.openremote.manager.client.widget.*;-import org.openremote.model.AttributeType;-import org.openremote.model.Constants;-import org.openremote.model.Consumer;-import org.openremote.model.MetaItem;-import org.openremote.model.asset.AbstractAssetAttribute;-import org.openremote.model.asset.AbstractAssetAttributes;+import org.openremote.model.*;+import org.openremote.model.asset.AssetAttribute;import org.openremote.model.asset.AssetMeta;+import org.openremote.model.util.AttributeUtil;import org.openremote.model.util.TextUtil;import java.util.*;public abstract class AttributesView<C extends AttributesView.Container<S>,- S extends AttributesView.Style,- ATTRIBUTES extends AbstractAssetAttributes<?, A>,- A extends AbstractAssetAttribute+ S extends AttributesView.Style> {public interface Container<S extends AttributesView.Style> {@@ -97,17 +92,17 @@ public abstract class AttributesView<final protected Environment environment;final protected C container;- final protected ATTRIBUTES attributes;+ final protected List<AssetAttribute> attributes;final protected Map<String, AttributeEditor> editors = new HashMap<>();- final protected LinkedHashMap<A, FormGroup> attributeGroups = new LinkedHashMap<>();+ final protected LinkedHashMap<AssetAttribute, FormGroup> attributeGroups = new LinkedHashMap<>();- public AttributesView(Environment environment, C container, ATTRIBUTES attributes) {+ public AttributesView(Environment environment, C container, List<AssetAttribute> attributes) {this.environment = environment;this.container = container;this.attributes = attributes;}- public ATTRIBUTES getAttributes() {+ public List<AssetAttribute> getAttributes() {return attributes;}@@ -136,21 +131,21 @@ public abstract class AttributesView</* ####################################################################### */- protected void addAttributeActions(A attribute,+ protected void addAttributeActions(AssetAttribute attribute,FormGroup formGroup,FormField formField,FormGroupActions formGroupActions,IsWidget editor) {}- protected void addAttributeExtensions(A attribute,+ protected void addAttributeExtensions(AssetAttribute attribute,FormGroup formGroup) {}/* ####################################################################### */protected void createAttributeGroups() {- for (A attribute : attributes.get()) {+ for (AssetAttribute attribute : attributes) {FormGroup formGroup = createAttributeGroup(attribute);if (formGroup != null) {attributeGroups.put(attribute, formGroup);@@ -164,7 +159,7 @@ public abstract class AttributesView<}}- protected FormGroup createAttributeGroup(A attribute) {+ protected FormGroup createAttributeGroup(AssetAttribute attribute) {FormGroup formGroup = new FormGroup();@@ -198,14 +193,14 @@ public abstract class AttributesView<return formGroup;}- protected FormLabel createAttributeLabel(A attribute) {+ protected FormLabel createAttributeLabel(AssetAttribute attribute) {String label = getAttributeLabel(attribute);FormLabel formLabel = new FormLabel(TextUtil.ellipsize(label, 30));formLabel.addStyleName("larger");return formLabel;}- protected String getAttributeLabel(A attribute) {+ protected String getAttributeLabel(AssetAttribute attribute) {String label = attribute.getName();MetaItem labelItem = attribute.firstMetaItem(AssetMeta.LABEL);if (labelItem != null) {@@ -214,7 +209,7 @@ public abstract class AttributesView<return label;}- protected String getAttributeDescription(A attribute) {+ protected String getAttributeDescription(AssetAttribute attribute) {MetaItem description = attribute.firstMetaItem(AssetMeta.DESCRIPTION);if (description != null) {return description.getValueAsString();@@ -222,7 +217,7 @@ public abstract class AttributesView<return null;}- protected AttributeEditor createEditor(A attribute, FormGroup formGroup) {+ protected AttributeEditor createEditor(AssetAttribute attribute, FormGroup formGroup) {MetaItem defaultValueItem = attribute.firstMetaItem(AssetMeta.DEFAULT);S style = container.getStyle();@@ -241,7 +236,7 @@ public abstract class AttributesView<return attributeEditor;}- protected AttributeEditor createUnsupportedEditor(A attribute) {+ protected AttributeEditor createUnsupportedEditor(AssetAttribute attribute) {FormField unsupportedField = new FormField();unsupportedField.add(new FormOutputText(environment.getMessages().unsupportedAttributeType(attribute.getType().getValue())@@ -249,7 +244,7 @@ public abstract class AttributesView<return () -> unsupportedField;}- protected AttributeEditor createStringEditor(A attribute, MetaItem defaultValueItem, S style, FormGroup formGroup) {+ protected AttributeEditor createStringEditor(AssetAttribute attribute, MetaItem defaultValueItem, S style, FormGroup formGroup) {String currentValue = attribute.getValueAsString();String defaultValue = defaultValueItem != null ? defaultValueItem.getValueAsString() : null;@@ -296,7 +291,7 @@ public abstract class AttributesView<return input;}- protected AttributeEditor createIntegerEditor(A attribute, MetaItem defaultValueItem, S style, FormGroup formGroup) {+ protected AttributeEditor createIntegerEditor(AssetAttribute attribute, MetaItem defaultValueItem, S style, FormGroup formGroup) {String currentValue = attribute.getValueAsString();String defaultValue = defaultValueItem != null ? defaultValueItem.getValueAsString() : null;Consumer<String> updateConsumer = isReadOnly(attribute) ? null : value -> {@@ -353,7 +348,7 @@ public abstract class AttributesView<return input;}- protected AttributeEditor createDecimalEditor(A attribute, MetaItem defaultValueItem, S style, FormGroup formGroup) {+ protected AttributeEditor createDecimalEditor(AssetAttribute attribute, MetaItem defaultValueItem, S style, FormGroup formGroup) {String currentValue = attribute.getValueAsString();String defaultValue = defaultValueItem != null ? defaultValueItem.getValueAsString() : null;Consumer<String> updateConsumer = isReadOnly(attribute) ? null : value -> {@@ -410,7 +405,7 @@ public abstract class AttributesView<return input;}- protected AttributeEditor createBooleanEditor(A attribute, MetaItem defaultValueItem, S style, FormGroup formGroup) {+ protected AttributeEditor createBooleanEditor(AssetAttribute attribute, MetaItem defaultValueItem, S style, FormGroup formGroup) {Boolean currentValue = attribute.getValueAsBoolean();Boolean defaultValue = defaultValueItem != null ? defaultValueItem.getValueAsBoolean() : null;Consumer<Boolean> updateConsumer = isReadOnly(attribute) ? null : value -> {@@ -471,16 +466,16 @@ public abstract class AttributesView<return input;}- protected boolean isReadOnly(A attribute) {+ protected boolean isReadOnly(AssetAttribute attribute) {return attribute.isReadOnly();}- protected boolean isShowTimestamp(A attribute) {+ protected boolean isShowTimestamp(AssetAttribute attribute) {return true;}- protected void removeAttribute(A attribute) {- attributes.remove(attribute.getName());+ protected void removeAttribute(AssetAttribute attribute) {+ AttributeUtil.remove(attributes, attribute.getName());editors.remove(attribute.getName());int attributeGroupIndex = container.getPanel().getWidgetIndex(attributeGroups.get(attribute));container.getPanel().remove(attributeGroupIndex);diff --git a/manager/client/src/main/java/org/openremote/manager/client/map/MapActivity.java b/manager/client/src/main/java/org/openremote/manager/client/map/MapActivity.javaindex b291837ea..54a85566a 100644--- a/manager/client/src/main/java/org/openremote/manager/client/map/MapActivity.java+++ b/manager/client/src/main/java/org/openremote/manager/client/map/MapActivity.java@@ -37,7 +37,6 @@ import org.openremote.model.AttributeEvent;import org.openremote.model.Pair;import org.openremote.model.asset.Asset;import org.openremote.model.asset.AssetAttribute;-import org.openremote.model.asset.AssetAttributes;import org.openremote.model.event.bus.EventBus;import org.openremote.model.event.bus.EventRegistration;import org.openremote.model.geo.GeoJSON;@@ -159,7 +158,7 @@ public class MapActivity extends AssetBrowsingActivity<MapPlace> implements MapVif (assetId != null) {assetBrowserPresenter.loadAsset(assetId, loadedAsset -> {this.asset = loadedAsset;- this.dashboardAttributes = new AssetAttributes(asset).get().stream()+ this.dashboardAttributes = asset.getAttributes().stream().filter(AssetAttribute::isShowOnDashboard).collect(Collectors.toList());assetBrowserPresenter.selectAsset(asset);view.setAssetViewHistoryToken(environment.getPlaceHistoryMapper().getToken(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.javaindex 4343aba08..6a2858ddc 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@@ -19,7 +19,6 @@*/package org.openremote.manager.server;-import org.openremote.agent3.protocol.Protocol;import org.openremote.container.Container;import org.openremote.container.ContainerService;import org.openremote.container.message.MessageBrokerService;@@ -33,17 +32,17 @@ import org.openremote.manager.server.datapoint.AssetDatapointService;import org.openremote.manager.server.event.EventService;import org.openremote.manager.server.i18n.I18NService;import org.openremote.manager.server.map.MapService;+import org.openremote.manager.server.notification.NotificationService;import org.openremote.manager.server.rules.RulesService;import org.openremote.manager.server.rules.RulesetStorageService;-import org.openremote.manager.server.notification.NotificationService;import org.openremote.manager.server.security.ManagerIdentityService;+import org.openremote.manager.server.setup.RuntimeResolverService;import org.openremote.manager.server.setup.SetupService;import org.openremote.manager.server.web.ManagerWebService;import java.util.ArrayList;import java.util.Arrays;import java.util.List;-import java.util.ServiceLoader;public class Main {@@ -51,6 +50,7 @@ public class Main {List<ContainerService> services = new ArrayList<ContainerService>() {{addAll(Arrays.asList(+ new RuntimeResolverService(),new I18NService(),new PersistenceService(),new MessageBrokerSetupService(),@@ -61,10 +61,7 @@ public class Main {new RulesService(),new AssetStorageService(),new AssetDatapointService(),- new AssetProcessingService()- ));- ServiceLoader.load(Protocol.class).forEach(this::add);- addAll(Arrays.asList(+ new AssetProcessingService(),new AgentService(),new MapService(),new NotificationService(),diff --git a/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.javaindex 641274ff4..5f2048b98 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@@ -30,13 +30,14 @@ import org.openremote.container.persistence.PersistenceEvent;import org.openremote.manager.server.asset.AssetStorageService;import org.openremote.manager.server.asset.ServerAsset;import org.openremote.manager.server.datapoint.AssetDatapointService;+import org.openremote.manager.server.setup.RuntimeResolverService;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.agent.AgentProtocolLink;+import org.openremote.model.util.AttributeUtil;import org.openremote.model.util.JsonUtil;import java.util.*;@@ -61,8 +62,10 @@ public class AgentService extends RouteBuilder implements ContainerService, Consprotected AssetStorageService assetStorageService;protected AssetDatapointService assetDatapointService;protected MessageBrokerService messageBrokerService;- protected Collection<Protocol> protocols; // TODO: Can protocols be added at runtime+ protected RuntimeResolverService resolverService;protected final Map<AttributeRef, ProtocolConfiguration> protocolConfigurations = new HashMap<>();+ protected AgentProtocolLink.Filter agentLinkFilter;+ protected ProtocolConfiguration.Filter protocolConfigFilter;protected Function<AttributeRef, ProtocolConfiguration> protocolConfigurationResolver = (AttributeRef protocolRef) -> {synchronized (protocolConfigurations) {return protocolConfigurations.get(protocolRef);@@ -75,33 +78,34 @@ public class AgentService extends RouteBuilder implements ContainerService, ConsassetStorageService = container.getService(AssetStorageService.class);assetDatapointService = container.getService(AssetDatapointService.class);messageBrokerService = container.getService(MessageBrokerService.class);- container.getService(MessageBrokerSetupService.class).getContext().addRoutes(this);+ resolverService = container.getService(RuntimeResolverService.class);}@Overridepublic void start(Container container) throws Exception {- protocols = container.getServices(Protocol.class);+ container.getService(MessageBrokerSetupService.class).getContext().addRoutes(this);+ agentLinkFilter = resolverService.resolve(AgentProtocolLink.Filter.class);+ protocolConfigFilter = resolverService.resolve(ProtocolConfiguration.Filter.class);+ }++ @Override+ public void allStarted(Container container) throws Exception {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) {- // 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);+ /// Link protocols for all attributes that are valid ProtocolAttributeWrappers+ protocolConfigFilter.getAllWrapped(agent.getAttributes(), true)+ .forEach(this::linkProtocol);}}@Overridepublic void stop(Container container) throws Exception {- List<ProtocolConfiguration> protocolConfigs;-synchronized (protocolConfigurations) {- protocolConfigs = Arrays.asList(protocolConfigurations.values().toArray(new ProtocolConfiguration[0]));+ new ArrayList<>(protocolConfigurations.values())+ .forEach(this::unlinkProtocol);}-- protocolConfigs.forEach(this::unlinkProtocolConfiguration);}@Override@@ -129,14 +133,9 @@ public class AgentService extends RouteBuilder implements ContainerService, Consswitch (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);- });-+ // Link protocols for all attributes that are valid ProtocolAttributeWrappers+ protocolConfigFilter.getAllWrapped(agent.getAttributes(), true)+ .forEach(this::linkProtocol);break;case UPDATE:@@ -148,56 +147,43 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons// 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());+ List<AssetAttribute> oldAttributes = AttributeUtil.getAssetAttributesFromJson(agent.getId(), (JsonObject) persistenceEvent.getPreviousState()[attributesIndex]);+ List<AssetAttribute> newAttributes = AttributeUtil.getAssetAttributesFromJson(agent.getId(), (JsonObject) persistenceEvent.getCurrentState()[attributesIndex]);+ List<ProtocolConfiguration> oldProtocolConfigurations = protocolConfigFilter.getAllWrapped(oldAttributes, true);+ List<ProtocolConfiguration> newProtocolConfigurations = protocolConfigFilter.getAllWrapped(newAttributes, true);// Compare protocol configurations by JSON value// Unlink protocols that are in oldConfigs but not in newConfigs- oldProtocolConfigs+ oldProtocolConfigurations.stream()- .filter(oldProtocolConfig -> newProtocolConfigs+ .filter(oldProtocolAttribute -> newProtocolConfigurations.stream()- .noneMatch(newProtocolConfig -> JsonUtil.equals(- oldProtocolConfig.getJsonObject(),- newProtocolConfig.getJsonObject())+ .noneMatch(newProtocolAttribute -> JsonUtil.equals(+ oldProtocolAttribute.getAttribute().getJsonObject(),+ newProtocolAttribute.getAttribute().getJsonObject())))- .forEach(obsoleteProtocolConfig -> {- AttributeRef protocolRef = new AttributeRef(agent.getId(), obsoleteProtocolConfig.getName());- LOG.fine("Agent was persisted (" + persistenceEvent.getCause() + "), unlinking protocol: " + protocolRef);- unlinkProtocolConfiguration(obsoleteProtocolConfig);- });+ .forEach(this::unlinkProtocol);// Link protocols that are in newConfigs but not in oldConfigs- newProtocolConfigs+ newProtocolConfigurations.stream()- .filter(newConfig -> oldProtocolConfigs+ .filter(newProtocolAttribute -> oldProtocolConfigurations.stream()- .noneMatch(oldConfig ->+ .noneMatch(oldProtocolAttribute ->JsonUtil.equals(- oldConfig.getJsonObject(),- newConfig.getJsonObject()+ oldProtocolAttribute.getAttribute().getJsonObject(),+ newProtocolAttribute.getAttribute().getJsonObject())))- .forEach(newProtocolConfig -> {- AttributeRef protocolRef = new AttributeRef(agent.getId(), newProtocolConfig.getName());- LOG.fine("Agent was persisted (" + persistenceEvent.getCause() + "), linking protocol: " + protocolRef);- linkProtocolConfiguration(newProtocolConfig);- });+ .forEach(this::linkProtocol);break;case DELETE:// 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);- });+ protocolConfigFilter.getAllWrapped(agent.getAttributes(), true)+ .forEach(this::unlinkProtocol);break;}}@@ -216,8 +202,8 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons// and handle in agent insert// 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));+ Map<ProtocolConfiguration, List<AssetAttribute>> groupedAgentLinksAttributes = getGroupedAgentLinkAttributes(asset.getAttributes());+ groupedAgentLinksAttributes.forEach(this::linkAttributes);break;}case UPDATE:@@ -230,84 +216,92 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons// 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);+ List<AssetAttribute> oldAttributes = AttributeUtil.getAssetAttributesFromJson(asset.getId(), (JsonObject) persistenceEvent.getPreviousState()[attributesIndex]);+ List<AssetAttribute> newAttributes = AttributeUtil.getAssetAttributesFromJson(asset.getId(), (JsonObject) persistenceEvent.getCurrentState()[attributesIndex]);+ List<AssetAttribute> oldAgentLinkedAttributes = agentLinkFilter.getAll(oldAttributes, true);+ List<AssetAttribute> newAgentLinkedAttributes = agentLinkFilter.getAll(newAttributes, true);// Unlink thing attributes that are in old but not in new- oldThingAttributes+ List<AssetAttribute> attributesToUnlink = oldAgentLinkedAttributes+ .stream()+ .filter(oldAgentLinkedAttribute -> newAgentLinkedAttributes.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))- )+ .noneMatch(newAgentLinkedAttribute -> JsonUtil.equals( // Ignore the timestamp in comparison+ oldAgentLinkedAttribute.getJsonObject(),+ newAgentLinkedAttribute.getJsonObject(),+ Collections.singletonList(AbstractValueTimestampHolder.VALUE_TIMESTAMP_FIELD_NAME)))- .collect(Collectors.groupingBy(thingAttribute -> thingAttribute.getProtocolRef()))- .forEach((protocolRef, thingAttributes) ->- unlinkAttributes(getProtocol(protocolConfigurationResolver.apply(protocolRef)), thingAttributes)- );+ )+ .collect(Collectors.toList());++ getGroupedAgentLinkAttributes(attributesToUnlink)+ .forEach(+ this::unlinkAttributes+ );// 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)- );+ List<AssetAttribute> attributesToLink = newAgentLinkedAttributes+ .stream()+ .filter(newThingAttribute -> oldAgentLinkedAttributes+ .stream()+ .noneMatch(oldThingAttribute -> JsonUtil.equals( // Ignore the timestamp in comparison+ oldThingAttribute.getJsonObject(),+ newThingAttribute.getJsonObject(),+ Collections.singletonList(AbstractValueTimestampHolder.VALUE_TIMESTAMP_FIELD_NAME))+ )+ )+ .collect(Collectors.toList());++ getGroupedAgentLinkAttributes(attributesToLink)+ .forEach(+ this::linkAttributes+ );break;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));+ Map<ProtocolConfiguration, List<AssetAttribute>> groupedAgentLinkAndProtocolAttributes = getGroupedAgentLinkAttributes(asset.getAttributes());+ groupedAgentLinkAndProtocolAttributes+ .forEach(+ this::unlinkAttributes+ );break;}}}- protected void linkProtocolConfiguration(ProtocolConfiguration protocolConfiguration) {- AttributeRef protocolAttributeRef = protocolConfiguration.getReference();+ protected void linkProtocol(ProtocolConfiguration protocolConfiguration) {+ AttributeRef protocolAttributeRef = protocolConfiguration.getAttributeReference();synchronized (protocolConfigurations) {- // Store this configuration for easy access later+ // Store this protocol configuration for easy access laterprotocolConfigurations.put(protocolAttributeRef, protocolConfiguration);}- LOG.finest("Linking all attributes that use protocol configuration: " + protocolAttributeRef);+ LOG.finest("Linking all attributes that use protocol attribute: " + protocolAttributeRef);// Get all assets that have attributes that use this protocol configurationList<ServerAsset> assets = assetStorageService.findAll(- new AssetQuery()- .select(new AssetQuery.Select(true, false))- .attributeMeta(- new AssetQuery.AttributeRefPredicate(- AssetMeta.AGENT_LINK,- protocolAttributeRef.getEntityId(),- protocolAttributeRef.getAttributeName()- )+ 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));- });+ assets.forEach(+ asset ->+ getGroupedAgentLinkAttributes(asset.getAttributes())+ .forEach(this::linkAttributes)+ );}- protected void unlinkProtocolConfiguration(ProtocolConfiguration protocolConfiguration) {- AttributeRef protocolRef = protocolConfiguration.getReference();+ protected void unlinkProtocol(ProtocolConfiguration protocolConfiguration) {+ AttributeRef protocolAttributeRef = protocolConfiguration.getAttribute().getReference();// Get all assets that have attributes that use this protocol configurationList<ServerAsset> assets = assetStorageService.findAll(@@ -316,23 +310,25 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons.attributeMeta(new AssetQuery.AttributeRefPredicate(AssetMeta.AGENT_LINK,- protocolRef.getEntityId(),- protocolRef.getAttributeName()+ protocolAttributeRef.getEntityId(),+ protocolAttributeRef.getAttributeName())));- assets.forEach(asset -> {- Map<AttributeRef, List<ThingAttribute>> groupedThingAttributes = ThingAttribute.getAllGroupedByProtocolRef(asset, protocolConfigurationResolver);- unlinkAttributes(getProtocol(protocolConfiguration), groupedThingAttributes.get(protocolRef));- });+ assets.forEach(+ asset ->+ getGroupedAgentLinkAttributes(asset.getAttributes())+ .forEach(this::unlinkAttributes)+ );synchronized (protocolConfigurations) {- protocolConfigurations.remove(protocolRef);+ protocolConfigurations.remove(protocolAttributeRef);}}protected Protocol getProtocol(ProtocolConfiguration protocolConfiguration) {+ Collection<Protocol> protocols = container.getServices(Protocol.class);return protocols.stream().filter(protocol -> {@@ -344,7 +340,9 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons.orElse(null);}- protected void linkAttributes(Protocol protocol, List<ThingAttribute> attributes) {+ protected void linkAttributes(ProtocolConfiguration protocolConfiguration, Collection<AssetAttribute> agentLinkedAttributes) {+ Protocol protocol = getProtocol(protocolConfiguration);+if (protocol == null) {LOG.severe("Cannot link protocol attributes as protocol is null");return;@@ -352,14 +350,16 @@ public class AgentService extends RouteBuilder implements ContainerService, Constry {LOG.finest("Linking protocol attributes to: " + protocol.getProtocolName());- protocol.linkAttributes(attributes);+ protocol.linkAttributes(agentLinkedAttributes, protocolConfiguration);} catch (Exception ex) {// TODO: Better error handling?LOG.log(Level.WARNING, "Ignoring error on linking attributes to protocol: " + protocol.getProtocolName(), ex);}}- protected void unlinkAttributes(Protocol protocol, List<ThingAttribute> attributes) {+ protected void unlinkAttributes(ProtocolConfiguration protocolConfiguration, Collection<AssetAttribute> attributes) {+ Protocol protocol = getProtocol(protocolConfiguration);+if (protocol == null) {LOG.severe("Cannot link protocol attributes as protocol is null");return;@@ -367,7 +367,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Constry {LOG.finest("Unlinking protocol attributes form: " + protocol.getProtocolName());- protocol.unlinkAttributes(attributes);+ protocol.unlinkAttributes(attributes, protocolConfiguration);} catch (Exception ex) {// TODO: Better error handling?LOG.log(Level.WARNING, "Ignoring error on unlinking attributes from protocol: " + protocol.getProtocolName(), ex);@@ -391,8 +391,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Consreturn;}-- AttributeRef protocolRef = ThingAttribute.getProtocolRef(assetState.getAttribute());+ AttributeRef protocolRef = AgentProtocolLink.getLink(assetState.getAttribute());if (protocolRef != null) {// Check attribute is linked to an actual agent@@ -423,15 +422,29 @@ public class AgentService extends RouteBuilder implements ContainerService, Consreturn protocolConfigurationResolver;}-/*- public static List<ThingAttribute> getThingAttributes(Asset asset) {- return new AssetAttributes(asset.getAttributes()).get()- .stream()- .filter(AssetAttribute::isAgentLinked)- .map(ThingAttribute::new)- .collect(Collectors.toList());+ /**+ * Gets all agent link attributes and their linked protocol configuration and groups them by Protocol Configuration+ */+ protected Map<ProtocolConfiguration, List<AssetAttribute>> getGroupedAgentLinkAttributes(List<AssetAttribute> agentLinkAttributes) {+ AgentProtocolLink.Filter filter = resolverService.resolve(AgentProtocolLink.Filter.class);+ Map<ProtocolConfiguration, List<AssetAttribute>> map = new HashMap<>();++ filter.getAll(agentLinkAttributes, true)+ .forEach(agentLinkAttribute -> {+ AttributeRef agentLink = AgentProtocolLink.getLink(agentLinkAttribute);+ ProtocolConfiguration protocolConfiguration = protocolConfigurationResolver.apply(agentLink);++ if (protocolConfiguration == null) {+ LOG.warning("Invalid agent link '" + agentLink + "' on attribute '" + agentLinkAttribute.getReference() + "'");+ }+ else {+ map.computeIfAbsent(protocolConfiguration, newProtocolConfiguration -> new ArrayList<>())+ .add(agentLinkAttribute);+ }+ });++ return map;}-*/public String toString() {return getClass().getSimpleName() + "{" +diff --git a/manager/server/src/main/java/org/openremote/manager/server/apps/ConsoleAppService.java b/manager/server/src/main/java/org/openremote/manager/server/apps/ConsoleAppService.javaindex a9af07131..d915b6179 100644--- a/manager/server/src/main/java/org/openremote/manager/server/apps/ConsoleAppService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/apps/ConsoleAppService.java@@ -53,6 +53,11 @@ public class ConsoleAppService implements ContainerService {public void start(Container container) throws Exception {}+ @Override+ public void allStarted(Container container) throws Exception {++ }+@Overridepublic void stop(Container container) throws Exception {}diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.javaindex ce05baa4b..c5b463ff7 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@@ -33,7 +33,9 @@ import org.openremote.manager.server.security.ManagerIdentityService;import org.openremote.manager.shared.security.ClientRole;import org.openremote.model.AttributeEvent;import org.openremote.model.asset.*;-import org.openremote.model.asset.thing.ThingAttribute;+import org.openremote.model.asset.agent.ProtocolConfiguration;+import org.openremote.model.asset.agent.AgentProtocolLink;+import org.openremote.model.util.AttributeUtil;import java.util.ArrayList;import java.util.List;@@ -191,6 +193,11 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer}+ @Override+ public void allStarted(Container container) throws Exception {++ }+@Overridepublic void stop(Container container) throws Exception {@@ -260,7 +267,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSerreturn;// Attribute must exist- if (!new AssetAttributes(asset).hasAttribute(event.getAttributeName()))+ if (!AttributeUtil.contains(asset.getAttributes(), event.getAttributeName()))return;// Regular users can only write attribute events for assets in their realm@@ -312,8 +319,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer// Pass attribute event through the processing chainLOG.fine("Processing " + attributeEvent + " for: " + asset);- AssetAttributes attributes = new AssetAttributes(asset);- AssetAttribute attribute = attributes.get(attributeEvent.getAttributeName());+ AssetAttribute attribute = AttributeUtil.getAttributeByName(asset.getAttributes(), attributeEvent.getAttributeName());if (attribute == null) {LOG.warning("Ignoring " + attributeEvent + ", attribute doesn't exist on asset: " + asset);@@ -333,44 +339,35 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer/*** We get here if a protocol pushes a sensor update message.*- * @param attributeEvent*/protected void processSensorUpdate(AttributeEvent attributeEvent) {- ServerAsset thing = assetStorageService.find(attributeEvent.getEntityId(), true);-// // Must reference a thing asset-//-// if (thing == null || thing.getWellKnownType() != THING) {-// LOG.fine("Ignoring " + attributeEvent + ", not a thing: " + thing);-// return;-// }+ ServerAsset asset = assetStorageService.find(attributeEvent.getEntityId(), true);- LOG.fine("Processing sensor " + attributeEvent + " for thing: " + thing);+ LOG.fine("Processing sensor " + attributeEvent + " for asset: " + asset);// 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)- AssetAttributes attributes = new AssetAttributes(thing);- // Look for a matching thing attribute- AssetAttribute attribute = attributes.get(attributeEvent.getAttributeName());+ // Look for a matching attribute+ AssetAttribute attribute = AttributeUtil.getAttributeByName(asset.getAttributes(), attributeEvent.getAttributeName());- // Convert this into a thing attribute- ThingAttribute thingAttribute = ThingAttribute.get(attribute, agentService.getProtocolConfigurationResolver());+ // Wrap this as an agent link attribute and ensure that the protocol can be resolved+ AgentProtocolLink agentProtocolLink = new AgentProtocolLink(attribute);+ ProtocolConfiguration protocolConfiguration = agentService.getProtocolConfigurationResolver().apply(agentProtocolLink.getLink());- if (thingAttribute == null) {- LOG.warning("Processing sensor update failed attribute not linked to an agent: " + attributeEvent);+ if (!agentProtocolLink.isValid() || protocolConfiguration == null) {+ LOG.warning("Processing sensor update failed attribute not linked to an agent or invalid agent link: " + attributeEvent);return;}- // Protocols can write to readonly attributes (i.e. sensor attributes)- // So no need to check readonly flag-- processUpdate(thing, thingAttribute, attributeEvent, true);+ // Protocols can write to readonly attributes (i.e. sensor attributes) so no need to check readonly flag+ processUpdate(asset, attribute, attributeEvent, true);}protected void processUpdate(ServerAsset asset,- AbstractAssetAttribute attribute,+ AssetAttribute attribute,AttributeEvent attributeEvent,boolean northbound) {// Ensure timestamp of event is not in the future as that would essentially block access todiff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.javaindex 9d5f570f7..f0625f7a1 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@@ -29,8 +29,9 @@ import org.openremote.manager.shared.security.Tenant;import org.openremote.model.AttributeEvent;import org.openremote.model.AttributeRef;import org.openremote.model.asset.Asset;-import org.openremote.model.asset.AssetAttributes;+import org.openremote.model.asset.AssetAttribute;import org.openremote.model.asset.AssetQuery;+import org.openremote.model.util.AttributeUtil;import javax.ws.rs.WebApplicationException;import javax.ws.rs.core.Response;@@ -243,10 +244,10 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResourthrow new WebApplicationException(NOT_FOUND);}- // Check attribute exists- AssetAttributes attributes = new AssetAttributes(asset);+ List<AssetAttribute> attributes = asset.getAttributes();- if (!attributes.hasAttribute(attributeName))+ // Check attribute exists+ if (!AttributeUtil.contains(attributes, attributeName))throw new WebApplicationException(NOT_FOUND);// Check realm, must be accessible@@ -256,7 +257,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour}// Check read-only- if (!isSuperUser() && attributes.get(attributeName).isReadOnly()) {+ if (!isSuperUser() && AttributeUtil.getAttributeByName(attributes, attributeName).isReadOnly()) {throw new WebApplicationException(Response.Status.FORBIDDEN);}diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.javaindex 77cf1aaa1..c635e9256 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@@ -35,11 +35,11 @@ import org.openremote.manager.server.event.EventService;import org.openremote.manager.server.security.ManagerIdentityService;import org.openremote.manager.shared.security.ClientRole;import org.openremote.manager.shared.security.Tenant;-import org.openremote.model.Attribute;import org.openremote.model.AttributeEvent;import org.openremote.model.Pair;import org.openremote.model.ReadAttributesEvent;import org.openremote.model.asset.*;+import org.openremote.model.util.AttributeUtil;import org.postgresql.util.PGobject;import javax.persistence.EntityManager;@@ -115,6 +115,11 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicpublic void start(Container container) throws Exception {}+ @Override+ public void allStarted(Container container) throws Exception {++ }+@Overridepublic void stop(Container container) throws Exception {@@ -203,7 +208,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicpublic ServerAsset find(String assetId, boolean loadComplete, boolean filterProtected) {if (assetId == null)throw new IllegalArgumentException("Can't query null asset identifier");- return find(new AssetQuery().select(new AssetQuery.Select(loadComplete, filterProtected)).id(assetId));+ return find(new AssetQuery().select(new AssetQuery.Select(loadComplete, filterProtected)).id(assetId));}public ServerAsset find(AssetQuery query) {@@ -239,8 +244,12 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicif (parent.pathContains(asset.getId()))throw new IllegalStateException("Invalid parent");}+// Validate attribute names- AssetAttributes attributes = new AssetAttributes(asset);+ if (!asset.getAttributes().stream().allMatch(AssetAttribute::isValid)) {+ throw new IllegalStateException("One or more attributes are not valid");+ }+return em.merge(asset);});}@@ -587,9 +596,9 @@ public class AssetStorageService extends RouteBuilder implements ContainerServictry (PreparedStatement statement = connection.prepareStatement(update)) {// Bind the value (and check we don't have a SQL injection hole in attribute name!)- if (!Attribute.nameIsValid(attributeName)) {+ if (!AttributeUtil.nameIsValid(attributeName)) {LOG.fine(- "Invalid attribute name (must match '" + Attribute.ATTRIBUTE_NAME_PATTERN + "'): " + attributeName+ "Invalid attribute name (must match '" + AttributeUtil.ATTRIBUTE_NAME_PATTERN + "'): " + attributeName);return false;}@@ -648,7 +657,6 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic);break;}- ;// Did the parent change?String previousParentId = persistenceEvent.getPreviousState("parentId");@@ -659,7 +667,6 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic);break;}- ;// Did the realm change?String previousRealmId = persistenceEvent.getPreviousState("realmId");@@ -670,7 +677,6 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic);break;}- ;break;case DELETE:@@ -682,17 +688,17 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic}protected void replyWithAttributeEvents(String sessionKey, ServerAsset asset, String[] attributeNames) {- AssetAttributes attributes = new AssetAttributes(asset);+ List<AssetAttribute> attributes = asset.getAttributes();// Client may want to read a subset or all attributes of the assetList<String> names = attributeNames != null && attributeNames.length > 0? Arrays.asList(attributeNames)- : attributes.names();+ : AttributeUtil.getNames(attributes);LOG.fine("For client session '" + sessionKey + "', reading asset attributes " + names + " on: " + asset);- List<AttributeEvent> events = attributes.get().stream()+ List<AttributeEvent> events = attributes.stream().filter(assetAttribute -> names.contains(assetAttribute.getName()))- .map(AbstractAssetAttribute::getStateEvent)+ .map(AssetAttribute::getStateEvent).collect(Collectors.toList());eventService.sendToSession(sessionKey, events.toArray(new AttributeEvent[events.size()]));diff --git a/manager/server/src/main/java/org/openremote/manager/server/datapoint/AssetDatapointResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/datapoint/AssetDatapointResourceImpl.javaindex e6e8db030..7aa4cf53e 100644--- a/manager/server/src/main/java/org/openremote/manager/server/datapoint/AssetDatapointResourceImpl.java+++ b/manager/server/src/main/java/org/openremote/manager/server/datapoint/AssetDatapointResourceImpl.java@@ -26,13 +26,15 @@ import org.openremote.manager.server.web.ManagerWebResource;import org.openremote.manager.shared.datapoint.AssetDatapointResource;import org.openremote.manager.shared.http.RequestParams;import org.openremote.model.AttributeRef;-import org.openremote.model.asset.AssetAttributes;+import org.openremote.model.asset.AssetAttribute;import org.openremote.model.datapoint.DatapointInterval;import org.openremote.model.datapoint.NumberDatapoint;+import org.openremote.model.util.AttributeUtil;import javax.ws.rs.BeanParam;import javax.ws.rs.WebApplicationException;import javax.ws.rs.core.Response;+import java.util.List;public class AssetDatapointResourceImpl extends ManagerWebResource implements AssetDatapointResource {@@ -56,11 +58,12 @@ public class AssetDatapointResourceImpl extends ManagerWebResource implements Astry {// TODO Security etc.ServerAsset asset = assetStorageService.find(assetId, true);- AssetAttributes assetAttributes = new AssetAttributes(asset);- if (!assetAttributes.hasAttribute(attributeName)) {+ List<AssetAttribute> assetAttributes = asset.getAttributes();++ if (!AttributeUtil.contains(assetAttributes, attributeName)) {throw new WebApplicationException(Response.Status.NOT_FOUND);}- if (!assetAttributes.get(attributeName).isStoreDatapoints()) {+ if (!AttributeUtil.getAttributeByName(assetAttributes, attributeName).isStoreDatapoints()) {throw new WebApplicationException(Response.Status.NOT_FOUND);}diff --git a/manager/server/src/main/java/org/openremote/manager/server/datapoint/AssetDatapointService.java b/manager/server/src/main/java/org/openremote/manager/server/datapoint/AssetDatapointService.javaindex 62d0b153b..0dd19c1e1 100644--- a/manager/server/src/main/java/org/openremote/manager/server/datapoint/AssetDatapointService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/datapoint/AssetDatapointService.java@@ -51,6 +51,11 @@ public class AssetDatapointService implements ContainerService, Consumer<AssetStpublic void start(Container container) throws Exception {}+ @Override+ public void allStarted(Container container) throws Exception {++ }+@Overridepublic void stop(Container container) throws Exception {}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.javaindex 07072ff3c..59c13d2f8 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@@ -185,6 +185,11 @@ public class EventService implements ContainerService {}+ @Override+ public void allStarted(Container container) throws Exception {++ }+@Overridepublic void stop(Container container) {diff --git a/manager/server/src/main/java/org/openremote/manager/server/i18n/I18NService.java b/manager/server/src/main/java/org/openremote/manager/server/i18n/I18NService.javaindex 7f2252eef..e143abbb7 100644--- a/manager/server/src/main/java/org/openremote/manager/server/i18n/I18NService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/i18n/I18NService.java@@ -22,6 +22,11 @@ public class I18NService implements ContainerService {}+ @Override+ public void allStarted(Container container) throws Exception {++ }+@Overridepublic void stop(Container container) throws Exception {diff --git a/manager/server/src/main/java/org/openremote/manager/server/map/MapService.java b/manager/server/src/main/java/org/openremote/manager/server/map/MapService.javaindex ac4afaa7a..74f63ee8d 100644--- a/manager/server/src/main/java/org/openremote/manager/server/map/MapService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/map/MapService.java@@ -85,6 +85,11 @@ public class MapService implements ContainerService {connection = DriverManager.getConnection("jdbc:sqlite:" + mapTilesPath.toAbsolutePath());}+ @Override+ public void allStarted(Container container) throws Exception {++ }+@Overridepublic void stop(Container container) throws Exception {LOG.info("Stopping map service...");diff --git a/manager/server/src/main/java/org/openremote/manager/server/notification/NotificationService.java b/manager/server/src/main/java/org/openremote/manager/server/notification/NotificationService.javaindex 350b45e80..e454bc942 100644--- a/manager/server/src/main/java/org/openremote/manager/server/notification/NotificationService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/notification/NotificationService.java@@ -70,6 +70,11 @@ public class NotificationService implements ContainerService {public void start(Container container) throws Exception {}+ @Override+ public void allStarted(Container container) throws Exception {++ }+@Overridepublic void stop(Container container) throws Exception {}diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.javaindex c48561323..91159d6eb 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.security.Tenant;import org.openremote.model.AbstractValueTimestampHolder;import org.openremote.model.asset.*;import org.openremote.model.asset.AssetEvent;+import org.openremote.model.util.AttributeUtil;import org.openremote.model.util.JsonUtil;import java.util.*;@@ -136,6 +137,11 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons@Overridepublic void start(Container container) throws Exception {++ }++ @Override+ public void allStarted(Container container) throws Exception {LOG.info("Deploying global rulesets");rulesetStorageService.findEnabledGlobalRulesets().forEach(this::deployGlobalRuleset);@@ -153,7 +159,7 @@ public class RulesService extends RouteBuilder implements ContainerService, ConsdeployAssetRulesets(rulesetStorageService.findEnabledAssetRulesets());LOG.info("Loading all assets with fact attributes to initialize state of rules engines");- List<Pair<ServerAsset, List<AssetAttribute>>> assetRuleAttributesList = findRuleStateAttributes(null, null);+ List<Pair<ServerAsset, List<AssetAttribute>>> assetRuleAttributesList = findRuleStateAttributes();// Push each rule attribute as an asset update through the rule engine chain// that will ensure the insert only happens to the engines in scope@@ -253,8 +259,8 @@ public class RulesService extends RouteBuilder implements ContainerService, Conscase INSERT:// New asset has been created so get attributes that have RULE_STATE meta- AssetAttributes addedAttributes = new AssetAttributes(asset);- List<AssetAttribute> ruleAttributes = addedAttributes.get()+ List<AssetAttribute> addedAttributes = asset.getAttributes();+ List<AssetAttribute> ruleAttributes = addedAttributes.stream().filter(AssetAttribute::isRuleState).collect(Collectors.toList());@@ -285,14 +291,14 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons// 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> oldAttributes = AttributeUtil.getAssetAttributesFromJson(asset.getId(), (JsonObject) persistenceEvent.getPreviousState()[attributesIndex]);+ List<AssetAttribute> newAttributes = AttributeUtil.getAssetAttributesFromJson(asset.getId(), (JsonObject) persistenceEvent.getCurrentState()[attributesIndex]);- List<AssetAttribute> oldFactAttributes = oldAttributes.get().stream()+ List<AssetAttribute> oldFactAttributes = oldAttributes.stream().filter(AssetAttribute::isRuleState).collect(Collectors.toList());- List<AssetAttribute> newFactAttributes = newAttributes.get().stream()+ List<AssetAttribute> newFactAttributes = newAttributes.stream().filter(AssetAttribute::isRuleState).collect(Collectors.toList());@@ -354,8 +360,8 @@ public class RulesService extends RouteBuilder implements ContainerService, Consbreak;case DELETE:// Retract any facts that were associated with this asset- AssetAttributes removedAttributes = new AssetAttributes(asset);- removedAttributes.get().stream()+ List<AssetAttribute> removedAttributes = asset.getAttributes();+ removedAttributes.stream().filter(AssetAttribute::isRuleState).forEach(attribute -> {// We can't load the asset again (it was deleted), so don't use buildAssetState() and@@ -652,21 +658,19 @@ public class RulesService extends RouteBuilder implements ContainerService, Consreturn rulesDeployments;}- protected List<Pair<ServerAsset, List<AssetAttribute>>> findRuleStateAttributes(AssetQuery.TenantPredicate tenantPredicate, AssetQuery.ParentPredicate parentPredicate) {+ protected List<Pair<ServerAsset, List<AssetAttribute>>> findRuleStateAttributes() {List<ServerAsset> assets = assetStorageService.findAll(new AssetQuery().select(new AssetQuery.Select(true))- .parent(parentPredicate)- .tenant(tenantPredicate).attributeMeta(new AssetQuery.AttributeMetaPredicate(AssetMeta.RULE_STATE,new AssetQuery.BooleanPredicate(true))));- return assets.stream().map(asset -> {- AssetAttributes attributes = new AssetAttributes(asset);- List<AssetAttribute> ruleAttributes = attributes.get().stream()+ return assets.stream().map((ServerAsset asset) -> {+ List<AssetAttribute> attributes = asset.getAttributes();+ List<AssetAttribute> ruleAttributes = attributes.stream().filter(AssetAttribute::isRuleState).collect(Collectors.toList());return new Pair<>(asset, ruleAttributes);diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesetStorageService.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesetStorageService.javaindex caf6e72dd..850036a44 100644--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesetStorageService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesetStorageService.java@@ -55,6 +55,11 @@ public class RulesetStorageService implements ContainerService {public void start(Container container) throws Exception {}+ @Override+ public void allStarted(Container container) throws Exception {++ }+@Overridepublic void stop(Container container) throws Exception {diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/RuntimeResolverService.java b/manager/server/src/main/java/org/openremote/manager/server/setup/RuntimeResolverService.javanew file mode 100644index 000000000..c6fd27344--- /dev/null+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/RuntimeResolverService.java@@ -0,0 +1,104 @@+/*+ * Copyright 2017, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.manager.server.setup;++import org.openremote.agent3.protocol.Protocol;+import org.openremote.container.Container;+import org.openremote.container.ContainerService;+import org.openremote.model.asset.AttributeWrapperFilter;++import java.util.*;+import java.util.logging.Logger;+import java.util.stream.Collectors;++/**+ * This is for resolving objects that are loaded at startup+ * e.g. protocols and attribute wrappers. It uses the standard+ * Java {@link ServiceLoader} to load the list of types defined+ * here.+ */+public class RuntimeResolverService implements ContainerService {+ private static final Logger LOG = Logger.getLogger(RuntimeResolverService.class.getName());+ protected static final List<Class> types;+ protected static final Map<Class, Object> instances = new HashMap<>();++ static {+ types = Arrays.asList(+ Protocol.class,+ AttributeWrapperFilter.class+ );+ }++ @Override+ public void init(Container container) throws Exception {+ // Load each type+ for (Class type : types) {+ ServiceLoader+ .load(type)+ .forEach(instance -> {+ instances.put(instance.getClass(), instance);+ });+ }++ for (Object instance : instances.values()) {+ // if it is a Container Service initialise it and pass it to the+ // container; the container will then call start+ if (instance instanceof ContainerService) {+ ContainerService service = (ContainerService)instance;+ container.addService(service);+ LOG.fine("Initializing service: " + service);+ service.init(container);+ }+ }+ }++ @SuppressWarnings("unchecked")+ @Override+ public void start(Container container) throws Exception {+ }++ @Override+ public void allStarted(Container container) throws Exception {++ }++ @Override+ public void stop(Container container) throws Exception {+ }++ @SuppressWarnings("unchecked")+ public <T> T resolve(Class<T> clazz) {+ synchronized (instances) {+ return (T)instances.get(clazz);+ }+ }++ public <T> List<T> resolveAll(Class<T> clazz) {+ synchronized (instances) {+ return instances+ .values()+ .stream()+ .filter(instance -> clazz.isAssignableFrom(instance.getClass()))+ .map(instance -> (T)instance)+ .collect(Collectors.toList());++ }+ }+}diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/SetupService.java b/manager/server/src/main/java/org/openremote/manager/server/setup/SetupService.javaindex 35b0f9690..eb29a0310 100644--- a/manager/server/src/main/java/org/openremote/manager/server/setup/SetupService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/SetupService.java@@ -90,6 +90,11 @@ public class SetupService implements ContainerService {}}+ @Override+ public void allStarted(Container container) throws Exception {++ }+@Overridepublic void stop(Container container) {}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.javaindex 141a18845..13e39b5ac 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@@ -31,16 +31,23 @@ import org.openremote.manager.server.asset.ServerAsset;import org.openremote.manager.server.setup.AbstractManagerSetup;import org.openremote.manager.shared.security.Tenant;import org.openremote.model.*;-import org.openremote.model.asset.*;-import org.openremote.model.asset.agent.AgentAttributes;+import org.openremote.model.asset.AssetAttribute;+import org.openremote.model.asset.AssetMeta;+import org.openremote.model.asset.AssetState;+import org.openremote.model.asset.AssetType;import org.openremote.model.asset.agent.ProtocolConfiguration;import org.openremote.model.units.AttributeUnits;import org.openremote.model.units.ColorRGB;+import org.openremote.model.util.AttributeUtil;import java.time.LocalDateTime;import java.time.ZoneId;import java.time.ZonedDateTime;+import java.util.Arrays;+import java.util.Collections;+import java.util.List;+import static org.openremote.model.AttributeType.*;import static org.openremote.model.asset.AssetMeta.*;import static org.openremote.model.asset.AssetType.*;@@ -72,7 +79,6 @@ public class ManagerDemoSetup extends AbstractManagerSetup {KeycloakDemoSetup keycloakDemoSetup = setupService.getTaskOfType(KeycloakDemoSetup.class);Tenant masterTenant = keycloakDemoSetup.masterTenant;Tenant customerATenant = keycloakDemoSetup.customerATenant;- Tenant customerBTenant = keycloakDemoSetup.customerBTenant;// ################################ Demo assets for 'master' realm ###################################@@ -82,8 +88,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {smartOffice.setName("Smart Office");smartOffice.setLocation(geometryFactory.createPoint(new Coordinate(5.460315214821094, 51.44541688237109)));smartOffice.setType(BUILDING);- AssetAttributes smartOfficeAttributes = new AssetAttributes();- smartOfficeAttributes.put(+ List<AssetAttribute> smartOfficeAttributes = Arrays.asList(new AssetAttribute("geoStreet", STRING, Json.create("Torenallee 20")).setMeta(new Meta().add(createMetaItem(LABEL, Json.create("Street")))@@ -105,7 +110,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {.add(createMetaItem(ABOUT, Json.create("http://project-haystack.org/tag/geoCountry")))));- smartOffice.setAttributes(smartOfficeAttributes.getJsonObject());+ smartOffice.setAttributes(smartOfficeAttributes);smartOffice = assetStorageService.merge(smartOffice);smartOfficeId = smartOffice.getId();@@ -127,21 +132,21 @@ public class ManagerDemoSetup extends AbstractManagerSetup {agent.setName("Demo Agent");agent.setLocation(geometryFactory.createPoint(new Coordinate(5.460315214821094, 51.44541688237109)));agent.setType(AssetType.AGENT);- AgentAttributes agentAttributes = new AgentAttributes();- ProtocolConfiguration protocolConfigSimulator123 = new ProtocolConfiguration(agentProtocolConfigName, SimulatorProtocol.PROTOCOL_NAME);- protocolConfigSimulator123.setMeta(new Meta()- .add(new MetaItem(- SimulatorProtocol.CONFIG_MODE,- Json.create(SimulatorProtocol.Mode.WRITE_THROUGH_DELAYED.toString())- )- )- .add(new MetaItem(- SimulatorProtocol.CONFIG_WRITE_DELAY_MILLISECONDS,- Json.create(500)- )- ));- agentAttributes.put(protocolConfigSimulator123);- agent.setAttributes(agentAttributes.getJsonObject());+ List<AssetAttribute> agentAttributes = Collections.singletonList(+ new ProtocolConfiguration(agentProtocolConfigName, SimulatorProtocol.PROTOCOL_NAME)+ .getAttribute()+ .setMeta(new Meta()+ .add(new MetaItem(+ SimulatorProtocol.CONFIG_MODE,+ Json.create(SimulatorProtocol.Mode.WRITE_THROUGH_DELAYED.toString())+ )+ )+ .add(new MetaItem(+ SimulatorProtocol.CONFIG_WRITE_DELAY_MILLISECONDS,+ Json.create(500)+ )+ )));+ agent.setAttributes(agentAttributes);agent = assetStorageService.merge(agent);agentId = agent.getId();@@ -149,8 +154,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {thing.setName("Demo Thing");thing.setLocation(geometryFactory.createPoint(new Coordinate(5.460315214821094, 51.44541688237109)));thing.setType(AssetType.THING);- AssetAttributes thingAttributes = new AssetAttributes(thing);- thingAttributes.put(+ List<AssetAttribute> thingAttributes = Arrays.asList(new AssetAttribute("light1Toggle", BOOLEAN, Json.create(true)).setMeta(new Meta().add(new MetaItem(@@ -238,54 +242,54 @@ public class ManagerDemoSetup extends AbstractManagerSetup {))));- thing.setAttributes(thingAttributes.getJsonObject());+ thing.setAttributes(thingAttributes);thing = assetStorageService.merge(thing);thingId = thing.getId();// Some sample datapointsthing = assetStorageService.find(thingId, true);- thingAttributes = new AssetAttributes(thing);+ thingAttributes = thing.getAttributes();ZonedDateTime now = LocalDateTime.now().atZone(ZoneId.systemDefault());- assetDatapointService.accept(new AssetState(thing, thingAttributes.get("light1PowerConsumption")));- assetDatapointService.accept(new AssetState(thing, thingAttributes.get("light1PowerConsumption")+ assetDatapointService.accept(new AssetState(thing, AttributeUtil.getAttributeByName(thingAttributes, "light1PowerConsumption")));+ assetDatapointService.accept(new AssetState(thing, AttributeUtil.getAttributeByName(thingAttributes, "light1PowerConsumption").setValueAsDecimal(0.11).setValueTimestamp(now.minusDays(80).toEpochSecond() * 1000)));- assetDatapointService.accept(new AssetState(thing, thingAttributes.get("light1PowerConsumption")+ assetDatapointService.accept(new AssetState(thing, AttributeUtil.getAttributeByName(thingAttributes, "light1PowerConsumption").setValueAsDecimal(1.22).setValueTimestamp(now.minusDays(40).toEpochSecond() * 1000)));- assetDatapointService.accept(new AssetState(thing, thingAttributes.get("light1PowerConsumption")+ assetDatapointService.accept(new AssetState(thing, AttributeUtil.getAttributeByName(thingAttributes, "light1PowerConsumption").setValueAsDecimal(2.33).setValueTimestamp(now.minusDays(20).toEpochSecond() * 1000)));- assetDatapointService.accept(new AssetState(thing, thingAttributes.get("light1PowerConsumption")+ assetDatapointService.accept(new AssetState(thing, AttributeUtil.getAttributeByName(thingAttributes, "light1PowerConsumption").setValueAsDecimal(3.44).setValueTimestamp(now.minusDays(10).toEpochSecond() * 1000)));- assetDatapointService.accept(new AssetState(thing, thingAttributes.get("light1PowerConsumption")+ assetDatapointService.accept(new AssetState(thing, AttributeUtil.getAttributeByName(thingAttributes, "light1PowerConsumption").setValueAsDecimal(4.55).setValueTimestamp(now.minusDays(8).toEpochSecond() * 1000)));- assetDatapointService.accept(new AssetState(thing, thingAttributes.get("light1PowerConsumption")+ assetDatapointService.accept(new AssetState(thing, AttributeUtil.getAttributeByName(thingAttributes, "light1PowerConsumption").setValueAsDecimal(5.66).setValueTimestamp(now.minusDays(6).toEpochSecond() * 1000)));- assetDatapointService.accept(new AssetState(thing, thingAttributes.get("light1PowerConsumption")+ assetDatapointService.accept(new AssetState(thing, AttributeUtil.getAttributeByName(thingAttributes, "light1PowerConsumption").setValueAsDecimal(6.77).setValueTimestamp(now.minusDays(3).toEpochSecond() * 1000)));- assetDatapointService.accept(new AssetState(thing, thingAttributes.get("light1PowerConsumption")+ assetDatapointService.accept(new AssetState(thing, AttributeUtil.getAttributeByName(thingAttributes, "light1PowerConsumption").setValueAsDecimal(7.88).setValueTimestamp(now.minusDays(1).toEpochSecond() * 1000)));- assetDatapointService.accept(new AssetState(thing, thingAttributes.get("light1PowerConsumption")+ assetDatapointService.accept(new AssetState(thing, AttributeUtil.getAttributeByName(thingAttributes, "light1PowerConsumption").setValueAsDecimal(8.99).setValueTimestamp(now.minusHours(10).toEpochSecond() * 1000)));- assetDatapointService.accept(new AssetState(thing, thingAttributes.get("light1PowerConsumption")+ assetDatapointService.accept(new AssetState(thing, AttributeUtil.getAttributeByName(thingAttributes, "light1PowerConsumption").setValueAsDecimal(9.11).setValueTimestamp(now.minusHours(5).toEpochSecond() * 1000)));- assetDatapointService.accept(new AssetState(thing, thingAttributes.get("light1PowerConsumption")+ assetDatapointService.accept(new AssetState(thing, AttributeUtil.getAttributeByName(thingAttributes, "light1PowerConsumption").setValueAsDecimal(10.22).setValueTimestamp(now.minusHours(2).toEpochSecond() * 1000)));- assetDatapointService.accept(new AssetState(thing, thingAttributes.get("light1PowerConsumption")+ assetDatapointService.accept(new AssetState(thing, AttributeUtil.getAttributeByName(thingAttributes, "light1PowerConsumption").setValueAsDecimal(11.33).setValueTimestamp(now.minusHours(1).toEpochSecond() * 1000)));- assetDatapointService.accept(new AssetState(thing, thingAttributes.get("light1PowerConsumption")+ assetDatapointService.accept(new AssetState(thing, AttributeUtil.getAttributeByName(thingAttributes, "light1PowerConsumption").setValueAsDecimal(11.44).setValueTimestamp(now.minusMinutes(30).toEpochSecond() * 1000)));- assetDatapointService.accept(new AssetState(thing, thingAttributes.get("light1PowerConsumption")+ assetDatapointService.accept(new AssetState(thing, AttributeUtil.getAttributeByName(thingAttributes, "light1PowerConsumption").setValueAsDecimal(11.55).setValueTimestamp(now.minusMinutes(15).toEpochSecond() * 1000)));- assetDatapointService.accept(new AssetState(thing, thingAttributes.get("light1PowerConsumption")+ assetDatapointService.accept(new AssetState(thing, AttributeUtil.getAttributeByName(thingAttributes, "light1PowerConsumption").setValueAsDecimal(11.66).setValueTimestamp(now.minusMinutes(6).toEpochSecond() * 1000)));- assetDatapointService.accept(new AssetState(thing, thingAttributes.get("light1PowerConsumption")+ assetDatapointService.accept(new AssetState(thing, AttributeUtil.getAttributeByName(thingAttributes, "light1PowerConsumption").setValueAsDecimal(11.77).setValueTimestamp(now.minusMinutes(3).toEpochSecond() * 1000)));- assetDatapointService.accept(new AssetState(thing, thingAttributes.get("light1PowerConsumption")+ assetDatapointService.accept(new AssetState(thing, AttributeUtil.getAttributeByName(thingAttributes, "light1PowerConsumption").setValueAsDecimal(11.88).setValueTimestamp(now.minusSeconds(30).toEpochSecond() * 1000)));- assetDatapointService.accept(new AssetState(thing, thingAttributes.get("light1PowerConsumption")+ assetDatapointService.accept(new AssetState(thing, AttributeUtil.getAttributeByName(thingAttributes, "light1PowerConsumption").setValueAsDecimal(11.99).setValueTimestamp(now.minusSeconds(15).toEpochSecond() * 1000)));- assetDatapointService.accept(new AssetState(thing, thingAttributes.get("light1PowerConsumption")+ assetDatapointService.accept(new AssetState(thing, AttributeUtil.getAttributeByName(thingAttributes, "light1PowerConsumption").setValueAsDecimal(12.00).setValueTimestamp(now.minusSeconds(1).toEpochSecond() * 1000)));- assetDatapointService.accept(new AssetState(thing, thingAttributes.get("light1PowerConsumption")+ assetDatapointService.accept(new AssetState(thing, AttributeUtil.getAttributeByName(thingAttributes, "light1PowerConsumption").setValueAsDecimal(12.01).setValueTimestamp(now.toEpochSecond() * 1000 - 500)));// ################################ Demo assets for 'customerA' realm ###################################@@ -295,8 +299,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {smartHome.setName("Smart Home");smartHome.setLocation(geometryFactory.createPoint(new Coordinate(5.470945, 51.438000)));smartHome.setType(BUILDING);- AssetAttributes smartHomeAttributes = new AssetAttributes();- smartHomeAttributes.put(+ List<AssetAttribute> smartHomeAttributes = Arrays.asList(new AssetAttribute("geoStreet", STRING, Json.create("Wilhelminaplein 21C")).setMeta(new Meta().add(createMetaItem(LABEL, Json.create("Street")))@@ -318,7 +321,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {.add(createMetaItem(ABOUT, Json.create("http://project-haystack.org/tag/geoCountry")))));- smartHome.setAttributes(smartHomeAttributes.getJsonObject());+ smartHome.setAttributes(smartHomeAttributes);smartHome = assetStorageService.merge(smartHome);smartHomeId = smartHome.getId();@@ -326,8 +329,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {apartment1.setName("Apartment 1");apartment1.setLocation(geometryFactory.createPoint(new Coordinate(5.470945, 51.438000)));apartment1.setType(RESIDENCE);- AssetAttributes apartment1Attributes = new AssetAttributes();- apartment1Attributes.put(+ List<AssetAttribute> apartment1Attributes = Arrays.asList(new AssetAttribute("allLightsOffSwitch", AttributeType.BOOLEAN, Json.create(true)).setMeta(new Meta().add(@@ -339,8 +341,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {).add(new MetaItem(AssetMeta.RULE_EVENT_EXPIRES, Json.create("10s")))- )- ).put(+ ),new AssetAttribute("vacationDays", AttributeType.INTEGER, Json.createNull()).setMeta(new Meta().add(@@ -352,7 +353,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {)));- apartment1.setAttributes(apartment1Attributes.getJsonObject());+ apartment1.setAttributes(apartment1Attributes);apartment1 = assetStorageService.merge(apartment1);apartment1Id = apartment1.getId();@@ -360,8 +361,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {apartment1Livingroom.setName("Livingroom");apartment1Livingroom.setLocation(geometryFactory.createPoint(new Coordinate(5.470945, 51.438000)));apartment1Livingroom.setType(ROOM);- AssetAttributes apartment1LivingroomAttributes = new AssetAttributes();- apartment1LivingroomAttributes.put(+ List<AssetAttribute> apartment1LivingroomAttributes = Arrays.asList(new AssetAttribute("presenceSensor", AttributeType.BOOLEAN, Json.create(false)).setMeta(new Meta().add(@@ -401,15 +401,14 @@ public class ManagerDemoSetup extends AbstractManagerSetup {)));- apartment1Livingroom.setAttributes(apartment1LivingroomAttributes.getJsonObject());+ apartment1Livingroom.setAttributes(apartment1LivingroomAttributes);apartment1Livingroom = assetStorageService.merge(apartment1Livingroom);apartment1LivingroomId = apartment1Livingroom.getId();ServerAsset apartment1LivingroomThermostat = new ServerAsset(apartment1Livingroom);apartment1LivingroomThermostat.setName("Livingroom Thermostat");apartment1LivingroomThermostat.setType(AssetType.THING);- AssetAttributes apartment1LivingroomThermostatAttributes = new AssetAttributes(apartment1LivingroomThermostat);- apartment1LivingroomThermostatAttributes.put(+ List<AssetAttribute> apartment1LivingroomThermostatAttributes = Arrays.asList(new AssetAttribute("currentTemperature", DECIMAL, Json.createNull()).setMeta(new Meta().add(new MetaItem(@@ -461,7 +460,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {));- apartment1LivingroomThermostat.setAttributes(apartment1LivingroomThermostatAttributes.getJsonObject());+ apartment1LivingroomThermostat.setAttributes(apartment1LivingroomThermostatAttributes);apartment1LivingroomThermostat = assetStorageService.merge(apartment1LivingroomThermostat);apartment1LivingroomThermostatId = apartment1LivingroomThermostat.getId();@@ -469,8 +468,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {apartment2.setName("Apartment 2");apartment2.setLocation(geometryFactory.createPoint(new Coordinate(5.470945, 51.438000)));apartment2.setType(RESIDENCE);- AssetAttributes apartment2Attributes = new AssetAttributes();- apartment2Attributes.put(+ List<AssetAttribute> apartment2Attributes = Collections.singletonList(new AssetAttribute("allLightsOffSwitch", AttributeType.BOOLEAN, Json.create(false)).setMeta(new Meta().add(@@ -482,7 +480,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {)));- apartment2.setAttributes(apartment2Attributes.getJsonObject());+ apartment2.setAttributes(apartment2Attributes);apartment2 = assetStorageService.merge(apartment2);apartment2Id = apartment2.getId();@@ -490,8 +488,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {apartment2Livingroom.setName("Livingroom");apartment2Livingroom.setLocation(geometryFactory.createPoint(new Coordinate(5.470945, 51.438000)));apartment2Livingroom.setType(ROOM);- AssetAttributes apartment2LivingroomAttributes = new AssetAttributes();- apartment2LivingroomAttributes.put(+ List<AssetAttribute> apartment2LivingroomAttributes = Arrays.asList(new AssetAttribute("presenceSensor", AttributeType.BOOLEAN, Json.create(false)).setMeta(new Meta().add(@@ -523,7 +520,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {)));- apartment2Livingroom.setAttributes(apartment2LivingroomAttributes.getJsonObject());+ apartment2Livingroom.setAttributes(apartment2LivingroomAttributes);apartment2Livingroom = assetStorageService.merge(apartment2Livingroom);apartment2LivingroomId = apartment2Livingroom.getId();@@ -531,8 +528,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {apartment3.setName("Apartment 3");apartment3.setLocation(geometryFactory.createPoint(new Coordinate(5.470945, 51.438000)));apartment3.setType(RESIDENCE);- AssetAttributes apartment3Attributes = new AssetAttributes();- apartment3Attributes.put(+ List<AssetAttribute> apartment3Attributes = Collections.singletonList(new AssetAttribute("allLightsOffSwitch", AttributeType.BOOLEAN, Json.create(false)).setMeta(new Meta().add(@@ -544,7 +540,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {)));- apartment3.setAttributes(apartment3Attributes.getJsonObject());+ apartment3.setAttributes(apartment3Attributes);apartment3 = assetStorageService.merge(apartment3);apartment3Id = apartment3.getId();@@ -552,8 +548,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {apartment3Livingroom.setName("Livingroom");apartment3Livingroom.setLocation(geometryFactory.createPoint(new Coordinate(5.470945, 51.438000)));apartment3Livingroom.setType(ROOM);- AssetAttributes apartment3LivingroomAttributes = new AssetAttributes();- apartment3LivingroomAttributes.put(+ List<AssetAttribute> apartment3LivingroomAttributes = Arrays.asList(new AssetAttribute("presenceSensor", AttributeType.BOOLEAN, Json.create(false)).setMeta(new Meta().add(@@ -585,7 +580,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {)));- apartment3Livingroom.setAttributes(apartment3LivingroomAttributes.getJsonObject());+ apartment3Livingroom.setAttributes(apartment3LivingroomAttributes);apartment3Livingroom = assetStorageService.merge(apartment3Livingroom);apartment3LivingroomId = apartment3Livingroom.getId();diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/device/Capability.java b/manager/shared/src/main/java/org/openremote/manager/shared/device/Capability.javaindex 83c1a3ed9..95fa999ce 100644--- a/manager/shared/src/main/java/org/openremote/manager/shared/device/Capability.java+++ b/manager/shared/src/main/java/org/openremote/manager/shared/device/Capability.java@@ -1,6 +1,8 @@package org.openremote.manager.shared.device;-import org.openremote.model.Attributes;+import org.openremote.model.Attribute;++import java.util.List;/*** Analogous to an Object in LWM2M; note the mandatory field@@ -19,7 +21,7 @@ public class Capability implements CapabilityDefinition {protected String type;protected String name;protected String description;- protected Attributes resources;+ protected List<Attribute> resources;@Overridepublic String getType() {@@ -38,7 +40,7 @@ public class Capability implements CapabilityDefinition {return description;}- public Attributes getResources() {+ public List<Attribute> getResources() {return resources;}@@ -50,7 +52,7 @@ public class Capability implements CapabilityDefinition {this.description = description;}- public void setResources(Attributes resources) {+ public void setResources(List<Attribute> resources) {this.resources = resources;}}diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/device/CapabilityDefinition.java b/manager/shared/src/main/java/org/openremote/manager/shared/device/CapabilityDefinition.javaindex 2423eb9dd..d2fed53ec 100644--- a/manager/shared/src/main/java/org/openremote/manager/shared/device/CapabilityDefinition.java+++ b/manager/shared/src/main/java/org/openremote/manager/shared/device/CapabilityDefinition.java@@ -1,6 +1,8 @@package org.openremote.manager.shared.device;-import org.openremote.model.Attributes;+import org.openremote.model.Attribute;++import java.util.List;// TODO Not usedpublic interface CapabilityDefinition {@@ -8,5 +10,5 @@ public interface CapabilityDefinition {String getDescription();- Attributes getResources();+ List<Attribute> getResources();}diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/device/CapabilityRef.java b/manager/shared/src/main/java/org/openremote/manager/shared/device/CapabilityRef.javaindex e13bb8fb5..74024f7a7 100644--- a/manager/shared/src/main/java/org/openremote/manager/shared/device/CapabilityRef.java+++ b/manager/shared/src/main/java/org/openremote/manager/shared/device/CapabilityRef.java@@ -1,10 +1,5 @@package org.openremote.manager.shared.device;-import elemental.json.JsonObject;-import org.openremote.model.Attribute;-import org.openremote.model.AttributeType;-import org.openremote.model.Attributes;-// TODO Not usedpublic class CapabilityRef {/*extends Attribute {diff --git a/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy b/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovyindex aba588e43..1c511546c 100644--- a/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy+++ b/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy@@ -1,9 +1,7 @@package org.openremote.test-import com.google.common.collect.Listsimport org.drools.core.time.impl.PseudoClockSchedulerimport org.kie.api.runtime.conf.ClockTypeOption-import org.openremote.agent3.protocol.Protocolimport org.openremote.container.Containerimport org.openremote.container.ContainerServiceimport org.openremote.container.message.MessageBrokerService@@ -22,6 +20,7 @@ import org.openremote.manager.server.rules.RulesDeploymentimport org.openremote.manager.server.rules.RulesServiceimport org.openremote.manager.server.rules.RulesetStorageServiceimport org.openremote.manager.server.security.ManagerIdentityService+import org.openremote.manager.server.setup.RuntimeResolverServiceimport org.openremote.manager.server.setup.SetupServiceimport org.openremote.manager.server.web.ManagerWebService@@ -31,6 +30,7 @@ trait ManagerContainerTrait extends ContainerTrait {static Iterable<ContainerService> defaultServices(Iterable<ContainerService> additionalServices) {[+ new RuntimeResolverService(),new I18NService(),new PersistenceService(),new MessageBrokerSetupService(),@@ -42,7 +42,6 @@ trait ManagerContainerTrait extends ContainerTrait {new AssetStorageService(),new AssetDatapointService(),new AssetProcessingService(),- *Lists.newArrayList(ServiceLoader.load(Protocol.class)),new AgentService(),new MapService(),new NotificationService(),diff --git a/manager/test/src/test/groovy/org/openremote/test/agent/AgentDeploymentTest.groovy b/manager/test/src/test/groovy/org/openremote/test/agent/AgentDeploymentTest.groovyindex 966b44d64..329bdb25c 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@@ -9,8 +9,8 @@ import org.openremote.manager.server.asset.AssetProcessingServiceimport org.openremote.manager.server.setup.SetupServiceimport org.openremote.manager.server.setup.builtin.ManagerDemoSetupimport org.openremote.model.AttributeEvent-import org.openremote.model.asset.AssetAttributesimport org.openremote.model.units.ColorRGB+import org.openremote.model.util.AttributeUtilimport org.openremote.test.ManagerContainerTraitimport spock.lang.Specificationimport spock.util.concurrent.PollingConditions@@ -50,9 +50,9 @@ class AgentDeploymentTest extends Specification implements ManagerContainerTraitconditions.eventually {assert simulatorProtocol.getState(managerDemoSetup.thingId, "light1Dimmer").asNumber() == 66def thing = assetStorageService.find(managerDemoSetup.thingId, true)- def attributes = new AssetAttributes(thing)- assert attributes.get("light1Dimmer").getValue().getType() == JsonType.NUMBER- assert attributes.get("light1Dimmer").getValueAsInteger() == 66+ def attributes = thing.getAttributes()+ assert AttributeUtil.getAttributeByName(attributes, "light1Dimmer").getValue().getType() == JsonType.NUMBER+ assert AttributeUtil.getAttributeByName(attributes, "light1Dimmer").getValueAsInteger() == 66}when: "a simulated sensor changes its value"@@ -62,9 +62,9 @@ class AgentDeploymentTest extends Specification implements ManagerContainerTraitthen: "the thing attribute value should be updated"conditions.eventually {def thing = assetStorageService.find(managerDemoSetup.thingId, true)- def attributes = new AssetAttributes(thing)- assert attributes.get("light1Dimmer").getValue().getType() == JsonType.NUMBER- assert attributes.get("light1Dimmer").getValueAsInteger() == 77+ def attributes = thing.getAttributes()+ assert AttributeUtil.getAttributeByName(attributes, "light1Dimmer").getValue().getType() == JsonType.NUMBER+ assert AttributeUtil.getAttributeByName(attributes, "light1Dimmer").getValueAsInteger() == 77}cleanup: "the server should be stopped"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.groovyindex 112013d7a..9eae1aa97 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@@ -7,7 +7,7 @@ import org.openremote.manager.server.datapoint.AssetDatapointServiceimport org.openremote.manager.server.setup.SetupServiceimport org.openremote.manager.server.setup.builtin.ManagerDemoSetupimport org.openremote.model.AttributeRef-import org.openremote.model.asset.AssetAttributes+import org.openremote.model.util.AttributeUtilimport org.openremote.test.ManagerContainerTraitimport spock.lang.Specificationimport spock.util.concurrent.PollingConditions@@ -44,8 +44,8 @@ class AssetDatapointTest extends Specification implements ManagerContainerTraitthen: "the thing attribute value should be updated and the datapoints stored"conditions.eventually {def thing = assetStorageService.find(managerDemoSetup.thingId, true)- def attributes = new AssetAttributes(thing)- assert attributes.get("light1PowerConsumption").getValueAsDecimal() == 15.5d+ def attributes = thing.getAttributes()+ assert AttributeUtil.getAttributeByName(attributes, "light1PowerConsumption").getValueAsDecimal() == 15.5ddef datapoints = assetDatapointService.getDatapoints(new AttributeRef(managerDemoSetup.thingId, "light1PowerConsumption"))datapoints.size() > 3datapoints.get(0).value.asNumber() == 13.3ddiff --git a/manager/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovyindex 88c6a7557..89170ebaf 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@@ -3,23 +3,19 @@ package org.openremote.test.assetsimport elemental.json.Jsonimport org.openremote.container.util.IdentifierUtilimport org.openremote.manager.server.setup.SetupService-import org.openremote.manager.server.setup.builtin.ManagerDemoSetupimport org.openremote.manager.server.setup.builtin.KeycloakDemoSetup+import org.openremote.manager.server.setup.builtin.ManagerDemoSetupimport 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.AttributeTypeimport org.openremote.model.asset.Assetimport org.openremote.model.asset.AssetAttribute-import org.openremote.model.asset.AssetAttributesimport org.openremote.model.asset.AssetType-import org.openremote.model.AttributeType+import org.openremote.model.util.AttributeUtilimport org.openremote.test.ManagerContainerTraitimport spock.lang.Specificationimport spock.util.concurrent.PollingConditionsimport javax.ws.rs.WebApplicationException-import javax.xml.ws.WebServiceExceptionimport static org.openremote.container.util.MapAccess.getStringimport static org.openremote.manager.server.setup.AbstractKeycloakSetup.SETUP_KEYCLOAK_ADMIN_PASSWORD@@ -61,23 +57,22 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTraittestAsset.parentId == nullwhen: "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())+ def attributes = testAsset.getAttributes()+ attributes.add(new AssetAttribute(testAsset.id, "illegal- Attribute:name&&&", AttributeType.STRING))+ testAsset.setAttributes(attributes)then: "the request should be bad"thrown(IllegalArgumentException)when: "an asset is stored with a non-empty attribute value"testAsset = assetResource.get(null, testAsset.getId())- testAsset.setAttributes(- new AssetAttributes().put(new AssetAttribute("foo", AttributeType.STRING, Json.create("bar"))).getJsonObject()- )+ testAsset.setAttributes([new AssetAttribute("foo", AttributeType.STRING, Json.create("bar"))])assetResource.update(null, testAsset.id, testAsset)testAsset = assetResource.get(null, testAsset.getId())then: "the attribute should exist"- new AssetAttributes(testAsset).get("foo").getValueAsString() == "bar"+ AttributeUtil.getAttributeByName(testAsset.getAttributes(), "foo") != null+ AttributeUtil.getAttributeByName(testAsset.getAttributes(), "foo").getValueAsString() == "bar"when: "an asset attribute value is written directly"assetResource.writeAttributeValue(null, testAsset.getId(), "foo", "\"bar2\"")@@ -85,7 +80,7 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTraitthen: "the attribute value should match"new PollingConditions(delay: 1, timeout: 5).eventually {def asset = assetResource.get(null, testAsset.getId())- new AssetAttributes(asset).get("foo").getValueAsString() == "bar2"+ assert AttributeUtil.getAttributeByName(asset.getAttributes(), "foo").getValueAsString() == "bar2"}when: "an asset attribute value null is written directly"@@ -94,7 +89,7 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTraitthen: "the attribute value should match"new PollingConditions(delay: 1, timeout: 5).eventually {def asset = assetResource.get(null, testAsset.getId())- !new AssetAttributes(asset).get("foo").hasValue()+ assert AttributeUtil.getAttributeByName(asset.getAttributes(), "foo").hasValue() == false}when: "an asset is updated with a different type"diff --git a/manager/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovyindex ed0511de6..8b1ee48b9 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@@ -9,9 +9,9 @@ import org.openremote.manager.shared.asset.AssetResourceimport org.openremote.model.AttributeTypeimport org.openremote.model.Metaimport org.openremote.model.asset.Asset-import org.openremote.model.asset.AssetAttributesimport org.openremote.model.asset.AssetMetaimport org.openremote.model.asset.AssetType+import org.openremote.model.util.AttributeUtilimport org.openremote.test.ManagerContainerTraitimport spock.lang.Specificationimport spock.util.concurrent.PollingConditions@@ -167,7 +167,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraidef assetconditions.eventually {asset = assetResource.get(null, managerDemoSetup.smartOfficeId)- new AssetAttributes(asset).get("geoStreet").getValue().toJson() == Json.create("Teststreet 123").toJson()+ assert AttributeUtil.getAttributeByName(asset.getAttributes(), "geoStreet").getValue().toJson() == Json.create("Teststreet 123").toJson()}when: "an non-existent attribute is written in the authenticated realm"@@ -190,7 +190,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraithen: "result should match"conditions.eventually {asset = assetResource.get(null, managerDemoSetup.smartHomeId)- new AssetAttributes(asset).get("geoStreet").getValue().toJson() == Json.create("Teststreet 456").toJson()+ assert AttributeUtil.getAttributeByName(asset.getAttributes(), "geoStreet").getValue().toJson() == Json.create("Teststreet 456").toJson()}cleanup: "the server should be stopped"@@ -228,7 +228,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraiassets[0].id == managerDemoSetup.smartOfficeId// Assets should not be completely loadedassets[0].path == null- assets[0].attributes == null+ assets[0].attributes.size() == 0when: "the root assets of the authenticated realm are retrieved"assets = assetResource.getRoot(null, keycloakDemoSetup.masterTenant.id)@@ -339,7 +339,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraidef assetconditions.eventually {asset = assetResource.get(null, managerDemoSetup.smartOfficeId)- new AssetAttributes(asset).get("geoStreet").getValue().toJson() == Json.create("Teststreet 123").toJson()+ assert AttributeUtil.getAttributeByName(asset.getAttributes(), "geoStreet").getValue().toJson() == Json.create("Teststreet 123").toJson()}when: "an asset attribute is written in a foreign realm"@@ -359,7 +359,6 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraidef container = startContainerWithoutDemoRules(defaultConfig(serverPort), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)- def conditions = new PollingConditions(delay: 1, timeout: 5)and: "an authenticated test user"def accessToken = authenticate(@@ -383,7 +382,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraiassets[0].id == managerDemoSetup.smartHomeId// Assets should not be completely loadedassets[0].path == null- assets[0].attributes == null+ assets[0].attributes.size() == 0when: "the root assets of a foreign realm are retrieved"assets = assetResource.getRoot(null, keycloakDemoSetup.masterTenant.id)@@ -522,7 +521,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraiapartment1.coordinates[0] == 5.470945dapartment1.coordinates[1] == 51.438dapartment1.path == null- apartment1.attributes == null+ apartment1.attributes.size() == 0Asset apartment1Livingroom = assets[1]apartment1Livingroom.id == managerDemoSetup.apartment1LivingroomId@@ -585,13 +584,13 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraithen: "the protected asset details should be available"apartment1LivingroomThermostat.id == managerDemoSetup.apartment1LivingroomThermostatIdapartment1LivingroomThermostat.name == "Livingroom Thermostat"- AssetAttributes protectedAttributes = new AssetAttributes(apartment1LivingroomThermostat)+ def protectedAttributes = apartment1LivingroomThermostat.getAttributes()protectedAttributes.size() == 2- protectedAttributes.get("currentTemperature")- protectedAttributes.get("currentTemperature").getType() == AttributeType.DECIMAL- protectedAttributes.get("currentTemperature").getValueAsDecimal() == null- Meta protectedMeta = protectedAttributes.get("currentTemperature").getMeta()- protectedMeta.all().length == 3+ assert AttributeUtil.getAttributeByName(protectedAttributes, "currentTemperature") != null+ AttributeUtil.getAttributeByName(protectedAttributes, "currentTemperature").getType() == AttributeType.DECIMAL+ AttributeUtil.getAttributeByName(protectedAttributes, "currentTemperature").getValueAsDecimal() == null+ Meta protectedMeta = AttributeUtil.getAttributeByName(protectedAttributes, "currentTemperature").getMeta()+ protectedMeta.all().size() == 3protectedMeta.first(AssetMeta.LABEL).getValueAsString() == "Current Temperature"protectedMeta.first(AssetMeta.READ_ONLY).getValueAsBoolean()protectedMeta.first(AssetMeta.RULE_STATE).getValueAsBoolean()@@ -666,7 +665,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraithen: "result should match"conditions.eventually {def asset = assetResource.get(null, managerDemoSetup.apartment1LivingroomThermostatId)- new AssetAttributes(asset).get("comfortTemperature").getValue().toJson() == Json.create(22.123).toJson()+ assert AttributeUtil.getAttributeByName(asset.getAttributes(), "comfortTemperature").getValue().toJson() == Json.create(22.123).toJson()}when: "an attribute is written on a non-existent user asset"diff --git a/manager/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovyindex 0f3002158..fda859b6c 100644--- a/manager/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy@@ -4,16 +4,17 @@ import elemental.json.Jsonimport org.openremote.agent3.protocol.AbstractProtocolimport org.openremote.manager.server.asset.AssetProcessingServiceimport org.openremote.manager.server.asset.AssetStorageService-import org.openremote.manager.server.rules.RulesServiceimport org.openremote.manager.server.asset.ServerAsset+import org.openremote.manager.server.rules.RulesServiceimport org.openremote.manager.server.setup.SetupServiceimport org.openremote.manager.server.setup.builtin.KeycloakDemoSetupimport org.openremote.manager.server.setup.builtin.ManagerDemoSetupimport org.openremote.model.*-import org.openremote.model.asset.*-import org.openremote.model.asset.agent.AgentAttributes+import org.openremote.model.asset.AssetAttribute+import org.openremote.model.asset.AssetMeta+import org.openremote.model.asset.AssetState+import org.openremote.model.asset.AssetTypeimport org.openremote.model.asset.agent.ProtocolConfiguration-import org.openremote.model.asset.thing.ThingAttributeimport org.openremote.test.ManagerContainerTraitimport spock.lang.Specificationimport spock.util.concurrent.PollingConditions@@ -52,18 +53,18 @@ class AssetProcessingTest extends Specification implements ManagerContainerTrait}@Override- protected void onAttributeAdded(ThingAttribute attribute) {+ protected void onAttributeAdded(AssetAttribute attribute, ProtocolConfiguration protocolConfiguration) {protocolDeployed = trueLOG.info("Mock Protocol: onAttributeAdded")}@Override- protected void onAttributeUpdated(ThingAttribute attribute) {+ protected void onAttributeUpdated(AssetAttribute attribute, ProtocolConfiguration protocolConfiguration) {LOG.info("Mock Protocol: onAttributeUpdated")}@Override- protected void onAttributeRemoved(ThingAttribute attribute) {+ protected void onAttributeRemoved(AssetAttribute attribute, ProtocolConfiguration protocolConfiguration) {LOG.info("Mock Protocol: onAttributeRemoved")}@@ -122,10 +123,8 @@ class AssetProcessingTest extends Specification implements ManagerContainerTraitdef mockAgent = new ServerAsset()mockAgent.setName("Mock Agent")mockAgent.setType(AssetType.AGENT)- AgentAttributes agentAttributes = new AgentAttributes()- ProtocolConfiguration mockProtocolConfig = new ProtocolConfiguration("mock123", mockProtocolName)- agentAttributes.put(mockProtocolConfig)- mockAgent.setAttributes(agentAttributes.getJsonObject())+ def mockProtocolConfig = new ProtocolConfiguration("mock123", mockProtocolName)+ mockAgent.setAttributes(Collections.singletonList(mockProtocolConfig.getAttribute()))mockAgent.setRealmId(keycloakDemoSetup.masterTenant.id)mockAgent = assetStorageService.merge(mockAgent)//endregion@@ -135,8 +134,7 @@ class AssetProcessingTest extends Specification implements ManagerContainerTraitdef mockThing = new ServerAsset(mockAgent)mockThing.setName("Mock Thing Asset")mockThing.setType(AssetType.THING)- def mockThingAttributes = new AssetAttributes(mockThing)- mockThingAttributes.put(+ def mockThingAttributes = [new AssetAttribute("light1Toggle", AttributeType.BOOLEAN, Json.create(false)).setMeta(new Meta().add(new MetaItem(@@ -170,8 +168,8 @@ class AssetProcessingTest extends Specification implements ManagerContainerTraitJson.create("A plain string attribute for storing information"))))- )- mockThing.setAttributes(mockThingAttributes.getJsonObject())+ ]+ mockThing.setAttributes(mockThingAttributes)mockThing = assetStorageService.merge(mockThing)//endregiondiff --git a/manager/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovyindex 6c8a805fc..999187c00 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@@ -6,10 +6,10 @@ import org.openremote.manager.server.asset.ServerAssetimport org.openremote.manager.server.setup.SetupServiceimport org.openremote.manager.server.setup.builtin.KeycloakDemoSetupimport org.openremote.manager.server.setup.builtin.ManagerDemoSetup-import org.openremote.model.asset.AssetAttributesimport org.openremote.model.asset.AssetMetaimport org.openremote.model.asset.AssetQueryimport org.openremote.model.asset.AssetType+import org.openremote.model.util.AttributeUtilimport org.openremote.test.ManagerContainerTraitimport spock.lang.Specification@@ -55,7 +55,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {asset.path.length == 2asset.path[0] == managerDemoSetup.apartment1Idasset.path[1] == managerDemoSetup.smartHomeId- asset.attributes.keys().length > 0+ asset.attributes.size() > 0when: "a query is executed"asset = assetStorageService.find(@@ -77,7 +77,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {asset.tenantDisplayName == keycloakDemoSetup.masterTenant.displayNameasset.coordinates.length == 2asset.path == null- asset.attributes == null+ asset.attributes.size() == 0when: "a query is executed"asset = assetStorageService.find(@@ -101,7 +101,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {asset.coordinates.length == 2asset.path.length == 1asset.path[0] == managerDemoSetup.smartOfficeId- new AssetAttributes(asset).get("geoStreet").valueAsString == "Torenallee 20"+ AttributeUtil.getAttributeByName(asset.getAttributes(), "geoStreet").valueAsString == "Torenallee 20"when: "a query is executed"def assets = assetStorageService.findAll(@@ -125,7 +125,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {assets.get(0).tenantDisplayName == keycloakDemoSetup.masterTenant.displayNameassets.get(0).coordinates.length == 2assets.get(0).path == null- assets.get(0).attributes == null+ assets.get(0).attributes.size() == 0when: "a query is executed"assets = assetStorageService.findAll(@@ -151,7 +151,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {assets.get(0).coordinates.length == 2assets.get(0).path.length == 1assets.get(0).path[0] == managerDemoSetup.smartOfficeId- new AssetAttributes(assets.get(0)).get("geoStreet").valueAsString == "Torenallee 20"+ AttributeUtil.getAttributeByName(assets.get(0).getAttributes(), "geoStreet").valueAsString == "Torenallee 20"when: "a query is executed"assets = assetStorageService.findAll(@@ -174,7 +174,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {assets.get(0).tenantDisplayName == keycloakDemoSetup.customerATenant.displayNameassets.get(0).coordinates.length == 2assets.get(0).path == null- assets.get(0).attributes == null+ assets.get(0).attributes.size() == 0assets.get(1).id == managerDemoSetup.apartment2Idassets.get(2).id == managerDemoSetup.apartment3Id@@ -248,11 +248,11 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {assets.get(0).id == managerDemoSetup.apartment1Idassets.get(1).id == managerDemoSetup.apartment1LivingroomIdassets.get(2).id == managerDemoSetup.apartment1LivingroomThermostatId- 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(2).getAttributes().size() == 2+ AttributeUtil.getAttributeByName(assets.get(2).getAttributes(), "currentTemperature").valueAsDecimal == null+ AttributeUtil.getAttributeByName(assets.get(2).getAttributes(), "currentTemperature").meta.size() == 3+ AttributeUtil.getAttributeByName(assets.get(2).getAttributes(), "comfortTemperature").valueAsDecimal == null+ AttributeUtil.getAttributeByName(assets.get(2).getAttributes(), "comfortTemperature").meta.size() == 2assets.get(3).id == managerDemoSetup.apartment2Idwhen: "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.groovyindex 56521e0c1..42427edca 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@@ -10,7 +10,7 @@ import org.openremote.manager.server.setup.builtin.KeycloakDemoSetupimport org.openremote.manager.server.setup.builtin.ManagerDemoSetupimport org.openremote.manager.server.setup.builtin.RulesDemoSetupimport org.openremote.model.AttributeEvent-import org.openremote.model.asset.AssetAttributes+import org.openremote.model.util.AttributeUtilimport org.openremote.test.ManagerContainerTraitimport spock.lang.Specificationimport spock.util.concurrent.PollingConditions@@ -50,7 +50,7 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTraiand: "the room lights in an apartment to be on"def livingRoomAsset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)- assert new AssetAttributes(livingRoomAsset).get("lightSwitch").valueAsBoolean+ assert AttributeUtil.getAttributeByName(livingRoomAsset.getAttributes(), "lightSwitch").valueAsBooleanwhen: "the ALL LIGHTS OFF switch is pressed for an apartment"def apartment1AllLightsOffChange = new AttributeEvent(@@ -62,7 +62,7 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTraiconditions.eventually {assert customerAEngine.knowledgeSession.factCount == 10livingRoomAsset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)- assert !new AssetAttributes(livingRoomAsset).get("lightSwitch").valueAsBoolean+ assert !AttributeUtil.getAttributeByName(livingRoomAsset.getAttributes(), "lightSwitch").valueAsBoolean}when: "time advanced"@@ -103,11 +103,11 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTraiand: "the presence latch of the room should not be set"def livingRoomAsset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)- assert !new AssetAttributes(livingRoomAsset.getAttributes()).get("presenceDetected").valueAsBoolean+ assert !AttributeUtil.getAttributeByName(livingRoomAsset.getAttributes(), "presenceDetected").valueAsBooleanand: "the presence latch of the other room should not be set"def otherLivingRoomAsset = assetStorageService.find(managerDemoSetup.apartment2LivingroomId, true)- assert !new AssetAttributes(otherLivingRoomAsset.getAttributes()).get("presenceDetected").valueAsBoolean+ assert !AttributeUtil.getAttributeByName(otherLivingRoomAsset.getAttributes(), "presenceDetected").valueAsBooleanand: "several presence sensor events are triggered in the room"for (i in 0..2) {@@ -138,13 +138,13 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTraiand: "the presence latch of the room should be set"conditions.eventually {def asset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)- assert new AssetAttributes(asset.getAttributes()).get("presenceDetected").valueAsBoolean+ assert AttributeUtil.getAttributeByName(asset.getAttributes(), "presenceDetected").valueAsBoolean}and: "the presence latch of the other room should NOT be set"conditions.eventually {def asset = assetStorageService.find(managerDemoSetup.apartment2LivingroomId, true)- assert !new AssetAttributes(asset.getAttributes()).get("presenceDetected").valueAsBoolean+ assert !AttributeUtil.getAttributeByName(asset.getAttributes(), "presenceDetected").valueAsBoolean}when: "time is advanced enough to trigger event expiration"@@ -197,7 +197,7 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTraithen: "that value should be stored"conditions.eventually {def asset = assetStorageService.find(managerDemoSetup.apartment1Id, true)- assert new AssetAttributes(asset).get("vacationDays").valueAsInteger == 5+ assert AttributeUtil.getAttributeByName(asset.getAttributes(), "vacationDays").valueAsInteger == 5}when: "time advanced to the next day, which should trigger the cron rule"@@ -206,7 +206,7 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTraithen: "the vacation days should be decremented"conditions.eventually {def asset = assetStorageService.find(managerDemoSetup.apartment1Id, true)- assert new AssetAttributes(asset).get("vacationDays").valueAsInteger == 4+ assert AttributeUtil.getAttributeByName(asset.getAttributes(), "vacationDays").valueAsInteger == 4}when: "time advanced again (to test that the rule only fires once per day)"@@ -215,7 +215,7 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTraithen: "the vacation days should NOT be decremented"new PollingConditions(initialDelay: 2).eventually {def asset = assetStorageService.find(managerDemoSetup.apartment1Id, true)- assert new AssetAttributes(asset).get("vacationDays").valueAsInteger == 4+ assert AttributeUtil.getAttributeByName(asset.getAttributes(), "vacationDays").valueAsInteger == 4}expect: "the remaining vacation days to be decremented with each passing day"@@ -228,7 +228,7 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTraiconditions.eventually {def asset = assetStorageService.find(managerDemoSetup.apartment1Id, true)- assert new AssetAttributes(asset).get("vacationDays").valueAsInteger == remainingDays+ assert AttributeUtil.getAttributeByName(asset.getAttributes(), "vacationDays").valueAsInteger == remainingDays}}diff --git a/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy b/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovyindex 3525e5eda..9983ab063 100644--- a/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy@@ -18,7 +18,6 @@ import org.openremote.model.AttributeTypeimport org.openremote.model.Metaimport org.openremote.model.MetaItemimport org.openremote.model.asset.AssetAttribute-import org.openremote.model.asset.AssetAttributesimport org.openremote.model.asset.AssetMetaimport org.openremote.model.asset.AssetTypeimport org.openremote.test.ManagerContainerTrait@@ -301,14 +300,13 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerasset.setRealmId(keycloakDemoSetup.customerATenant.getId())asset.setType(AssetType.ROOM)asset.setName("Kitchen")- AssetAttributes attributes = new AssetAttributes()- attributes.put(+ def attributes = [new AssetAttribute("testString", AttributeType.STRING, Json.create("test")).setMeta(new Meta().add(new MetaItem(AssetMeta.RULE_STATE, Json.create(true))))- )- asset.setAttributes(attributes.getJsonObject())+ ]+ asset.setAttributes(attributes)asset = assetStorageService.merge(asset)then: "after a few seconds the engines in scope should not have fired any rules but the facts should have been inserted"@@ -329,16 +327,15 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerwhen: "the Kitchen room asset is modified to add a new attribute but RULE_STATE = true meta is not changed"resetRuleExecutionLoggers()- attributes = new AssetAttributes()- attributes.put(+ attributes = [new AssetAttribute("testString", AttributeType.STRING, Json.create("test")).setMeta(new Meta().add(new MetaItem(AssetMeta.RULE_STATE, Json.create(true)))),new AssetAttribute("testInteger", AttributeType.INTEGER, Json.create(0))- )- asset.setAttributes(attributes.getJsonObject())+ ]+ asset.setAttributes(attributes)asset = assetStorageService.merge(asset)then: "after a few seconds the fact count shouldn't change and no rules should have fired"@@ -358,16 +355,15 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer}when: "the Kitchen room asset is modified to set the RULE_STATE to false"- attributes = new AssetAttributes()- attributes.put(+ attributes = [new AssetAttribute("testString", AttributeType.STRING, Json.create("test")).setMeta(new Meta().add(new MetaItem(AssetMeta.RULE_STATE, Json.create(false)))),new AssetAttribute("testInteger", AttributeType.INTEGER, Json.create(0))- )- asset.setAttributes(attributes.getJsonObject())+ ]+ asset.setAttributes(attributes)asset = assetStorageService.merge(asset)then: "the facts should be removed from the rule engines and no rules should have fired"@@ -388,8 +384,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerwhen: "the Kitchen room asset is modified to set all attributes to RULE_STATE = true"resetRuleExecutionLoggers()- attributes = new AssetAttributes()- attributes.put(+ attributes = [new AssetAttribute("testString", AttributeType.STRING, Json.create("test")).setMeta(new Meta()@@ -400,8 +395,8 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainernew Meta().add(new MetaItem(AssetMeta.RULE_STATE, Json.create(true))))- )- asset.setAttributes(attributes.getJsonObject())+ ]+ asset.setAttributes(attributes)asset = assetStorageService.merge(asset)then: "the facts should be added to the rule engines and no rules should have fired"diff --git a/model/src/main/java/org/openremote/model/Attribute.java b/model/src/main/java/org/openremote/model/Attribute.javaindex f72a9f382..1d70292f1 100644--- a/model/src/main/java/org/openremote/model/Attribute.java+++ b/model/src/main/java/org/openremote/model/Attribute.java@@ -19,29 +19,23 @@*/package org.openremote.model;-import com.google.gwt.regexp.shared.RegExp;import elemental.json.Json;import elemental.json.JsonObject;import elemental.json.JsonValue;+import org.openremote.model.util.AttributeUtil;+import java.util.Collections;+import java.util.List;import java.util.NoSuchElementException;+import java.util.function.Predicate;/*** Convenience overlay API for {@link JsonObject}.- * <p>- * Modifies the given or an empty object.*/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;protected Attribute(String name) {@@ -81,9 +75,9 @@ public abstract class Attribute<CHILD extends Attribute<CHILD>> extends Abstract}public void setName(String name) {- if (!Attribute.nameIsValid(name)) {+ if (!AttributeUtil.nameIsValid(name)) {throw new IllegalArgumentException(- "Invalid attribute name (must match '" + Attribute.ATTRIBUTE_NAME_PATTERN + "'): " + name+ "Invalid attribute name (must match '" + AttributeUtil.ATTRIBUTE_NAME_PATTERN + "'): " + name);}this.name = name;@@ -117,7 +111,7 @@ public abstract class Attribute<CHILD extends Attribute<CHILD>> extends Abstract}public Meta getMeta() {- return hasMeta() ? new Meta(jsonObject.getArray(META_FIELD_NAME)) : null;+ return hasMeta() ? new Meta(jsonObject.getArray(META_FIELD_NAME)) : new Meta();}@SuppressWarnings("unchecked")@@ -134,24 +128,60 @@ public abstract class Attribute<CHILD extends Attribute<CHILD>> extends Abstractreturn hasMeta() && getMeta().contains(name);}+ public boolean hasMetaItem(String name, JsonValue value) {+ return hasMeta() && getMeta().contains(name, value);+ }+public MetaItem firstMetaItem(String name) {return hasMetaItem(name) ? getMeta().first(name) : null;}+ public MetaItem firstMetaItem(String name, JsonValue value) {+ return hasMeta() ? getMeta().first(name, value) : null;+ }+public MetaItem firstMetaItemOrThrow(String name) throws NoSuchElementException {if (!hasMetaItem(name))throw new NoSuchElementException("Missing item: " + name);return firstMetaItem(name);}- public static boolean nameIsValid(String name) {- return name != null && name.length() > 0 && attributeNamePattern.test(name);+ public MetaItem firstMetaItemOrThrow(String name, JsonValue value) throws NoSuchElementException {+ if (!hasMeta())+ throw new NoSuchElementException("Missing item: " + name);+ MetaItem metaItem = getMeta().first(name, value);+ if (metaItem == null)+ throw new NoSuchElementException("Missing item: " + name);++ return metaItem;+ }++ public List<MetaItem> getMetaItems(String name) {+ if (!hasMeta()) {+ return Collections.emptyList();+ }++ return getMeta().get(name);+ }++ public List<MetaItem> getMetaItems(String name, JsonValue value) {+ if (!hasMeta()) {+ return Collections.emptyList();+ }++ return getMeta().get(name, value);+ }++ public List<MetaItem> getMetaItems(Predicate<MetaItem> filter) {+ if (!hasMeta()) {+ return Collections.emptyList();+ }++ return getMeta().get(filter);}@Overridepublic boolean isValid() {- return super.isValid() && nameIsValid(name) && getType() != null;+ return super.isValid() && AttributeUtil.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.javadeleted file mode 100644index b65e85f4b..000000000--- a/model/src/main/java/org/openremote/model/Attributes.java+++ /dev/null@@ -1,118 +0,0 @@-/*- * Copyright 2016, OpenRemote Inc.- *- * See the CONTRIBUTORS.txt file in the distribution for a- * full listing of individual contributors.- *- * This program is free software: you can redistribute it and/or modify- * it under the terms of the GNU Affero General Public License as- * published by the Free Software Foundation, either version 3 of the- * License, or (at your option) any later version.- *- * This program is distributed in the hope that it will be useful,- * but WITHOUT ANY WARRANTY; without even the implied warranty of- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the- * GNU Affero General Public License for more details.- *- * You should have received a copy of the GNU Affero General Public License- * along with this program. If not, see <http://www.gnu.org/licenses/>.- */-package org.openremote.model;--import elemental.json.Json;-import elemental.json.JsonObject;--import java.util.ArrayList;-import java.util.Arrays;-import java.util.Collections;-import java.util.List;--/**- * Convenience overlay API for {@link JsonObject}.- *- * Modifies the given or an empty object.- */-public abstract class Attributes<CHILD extends Attributes<CHILD, A>, A extends Attribute> {-- final protected JsonObject jsonObject;-- public Attributes() {- this(Json.createObject());- }-- // TODO @JsonCreator(mode = JsonCreator.Mode.DELEGATING)- public Attributes(JsonObject jsonObject) {- this.jsonObject = jsonObject != null ? jsonObject : Json.createObject();- }-- public Attributes(CHILD attributes) {- this.jsonObject = attributes != null && attributes.getJsonObject() != null ? attributes.getJsonObject() : Json.createObject();- }-- public JsonObject getJsonObject() {- return jsonObject;- }-- public boolean hasAttribute(String name) {- return jsonObject.hasKey(name);- }-- public List<String> names() {- return Collections.unmodifiableList(Arrays.asList(jsonObject.keys()));- }-- public int size() {- return jsonObject.keys().length;- }-- public List<A> get() {- List<A> attributes = new ArrayList<>();- String[] keys = jsonObject.keys();- for (String key : keys) {- attributes.add(createAttribute(key, jsonObject.getObject(key)));- }- return Collections.unmodifiableList(attributes);- }-- public A get(String name) {- return hasAttribute(name) ? createAttribute(name, jsonObject.getObject(name)) : null;- }-- @SuppressWarnings("unchecked")- public CHILD put(A... attributes) {- if (attributes != null)- for (A attribute : attributes) {- jsonObject.put(attribute.getName(), attribute.getJsonObject());- }- return (CHILD) this;- }-- @SuppressWarnings("unchecked")- public CHILD remove(String name) {- if (hasAttribute(name)) {- jsonObject.remove(name);- }- return (CHILD) this;- }-- @SuppressWarnings("unchecked")- public CHILD clear(String... excludeAttributes) {- List<String> excluded =- excludeAttributes != null ? Arrays.asList(excludeAttributes) : new ArrayList<>();- for (A attribute : get()) {- if (!excluded.contains(attribute.getName())) {- remove(attribute.getName());- }- }- return (CHILD) this;- }-- abstract public CHILD copy();-- abstract protected A createAttribute(String name, JsonObject jsonObject) throws IllegalArgumentException;-- @Override- public String toString() {- return jsonObject.toJson();- }-}diff --git a/model/src/main/java/org/openremote/model/Meta.java b/model/src/main/java/org/openremote/model/Meta.javaindex 0bf9dcd89..1d532262c 100644--- a/model/src/main/java/org/openremote/model/Meta.java+++ b/model/src/main/java/org/openremote/model/Meta.java@@ -22,10 +22,13 @@ package org.openremote.model;import elemental.json.Json;import elemental.json.JsonArray;import elemental.json.JsonObject;+import elemental.json.JsonValue;import org.openremote.model.asset.AssetMeta;+import org.openremote.model.util.JsonUtil;import java.util.ArrayList;import java.util.List;+import java.util.function.Predicate;/*** An array of {@link MetaItem} elements.@@ -52,16 +55,32 @@ public class Meta {return getJsonArray().length();}- public MetaItem[] all() {- List<MetaItem> list = asList();- return list.toArray(new MetaItem[list.size()]);+ public List<MetaItem> all() {+ return get((Predicate<MetaItem>) null);}- public MetaItem[] get(String name) {- List<MetaItem> list = asList(+ public List<MetaItem> get(String name) {+ return get(item -> item.getName().equals(name));- return list.toArray(new MetaItem[list.size()]);+ }++ public List<MetaItem> get(String name, JsonValue value) {+ return get(metaItem -> metaItem.getName().equals(name) && JsonUtil.equals(metaItem.getValue(), value));+ }++ public List<MetaItem> get(Predicate<MetaItem> filter) {+ List<MetaItem> list = new ArrayList<>();+ for (int i = 0; i < jsonArray.length(); i++) {+ JsonObject jsonObject = jsonArray.getObject(i);+ MetaItem item = new MetaItem(jsonObject);+ if (filter == null) {+ list.add(item);+ } else if (filter.test(item)) {+ list.add(item);+ }+ }+ return list;}public MetaItem get(int index) {@@ -75,7 +94,16 @@ public class Meta {}public MetaItem first(String name) {- List<MetaItem> list = asList();+ List<MetaItem> list = all();+ for (MetaItem item : list) {+ if (item.getName().equals(name))+ return item;+ }+ return null;+ }++ public MetaItem first(String name, JsonValue value) {+ List<MetaItem> list = all();for (MetaItem item : list) {if (item.getName().equals(name))return item;@@ -91,9 +119,14 @@ public class Meta {return first(name) != null;}- public int indexOf(MetaItem item) {- List<MetaItem> list = asList();- for (int i = 0; i < list.size(); i++) {+ public boolean contains(String name, JsonValue value) {+ MetaItem metaItem = first(name);+ return metaItem != null && JsonUtil.equals(metaItem.getValue(), value);+ }++ public int firstIndexOf(MetaItem item, int startIndex) {+ List<MetaItem> list = all();+ for (int i = startIndex; i < list.size(); i++) {if (list.get(i).getName().equals(item.getName()))return i;}@@ -129,24 +162,6 @@ public class Meta {return new Meta((JsonArray) Json.parse(getJsonArray().toJson()));}- protected List<MetaItem> asList() {- return asList(null);- }-- protected List<MetaItem> asList(Function<MetaItem, Boolean> filter) {- List<MetaItem> list = new ArrayList<>();- for (int i = 0; i < jsonArray.length(); i++) {- JsonObject jsonObject = jsonArray.getObject(i);- MetaItem item = new MetaItem(jsonObject);- if (filter == null) {- list.add(item);- } else if (filter.apply(item)) {- list.add(item);- }- }- return list;- }-@Overridepublic String toString() {return jsonArray.toJson();diff --git a/model/src/main/java/org/openremote/model/asset/AbstractAssetAttribute.java b/model/src/main/java/org/openremote/model/asset/AbstractAssetAttribute.javadeleted file mode 100644index f6b232ccb..000000000--- a/model/src/main/java/org/openremote/model/asset/AbstractAssetAttribute.java+++ /dev/null@@ -1,128 +0,0 @@-/*- * Copyright 2017, OpenRemote Inc.- *- * See the CONTRIBUTORS.txt file in the distribution for a- * full listing of individual contributors.- *- * This program is free software: you can redistribute it and/or modify- * it under the terms of the GNU Affero General Public License as- * published by the Free Software Foundation, either version 3 of the- * License, or (at your option) any later version.- *- * This program is distributed in the hope that it will be useful,- * but WITHOUT ANY WARRANTY; without even the implied warranty of- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the- * GNU Affero General Public License for more details.- *- * You should have received a copy of the GNU Affero General Public License- * along with this program. If not, see <http://www.gnu.org/licenses/>.- */-package org.openremote.model.asset;--import elemental.json.JsonObject;-import elemental.json.JsonValue;-import org.openremote.model.*;--import static org.openremote.model.asset.AssetMeta.*;--public abstract class AbstractAssetAttribute<CHILD extends AbstractAssetAttribute<CHILD>> extends Attribute<CHILD> {-- final public String assetId;-- protected AbstractAssetAttribute(String assetId, String name, AttributeType type) {- super(name, type);- this.assetId = assetId;- }-- protected AbstractAssetAttribute(String assetId, String name, AttributeType type, JsonValue value) {- super(name, type, value);- this.assetId = assetId;- }-- protected AbstractAssetAttribute(String assetId, String name, JsonObject jsonObject) {- super(name, jsonObject);- this.assetId = assetId;- }-- // 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() {- return assetId;- }-- public AttributeRef getReference() {- return new AttributeRef(getAssetId(), getName());- }-- /**- * @return The current value.- */- public AttributeState getState() {- return new AttributeState(- getReference(),- getValue()- );- }-- /**- * @return The current value and its timestamp represented as an attribute event.- */- public AttributeEvent getStateEvent() {- return new AttributeEvent(- getState(),- getValueTimestamp()- );- }-- public boolean hasMetaItem(AssetMeta assetMeta) {- return hasMetaItem(assetMeta.getName());- }-- public MetaItem firstMetaItem(AssetMeta assetMeta) {- return firstMetaItem(assetMeta.getName());- }-- public String getLabel() {- return hasMetaItem(LABEL) ? firstMetaItem(LABEL).getValueAsString() : getName();- }-- public String getFormat() {- return hasMetaItem(FORMAT) ? firstMetaItem(FORMAT).getValueAsString() : null;- }-- public boolean isShowOnDashboard() {- return hasMetaItem(SHOWN_ON_DASHBOARD) && firstMetaItem(SHOWN_ON_DASHBOARD).isValueTrue();- }-- public boolean isProtected() {- return hasMetaItem(PROTECTED) && firstMetaItem(PROTECTED).isValueTrue();- }-- public boolean isReadOnly() {- return hasMetaItem(READ_ONLY) && firstMetaItem(READ_ONLY).isValueTrue();- }-- public boolean isStoreDatapoints() {- return hasMetaItem(STORE_DATA_POINTS) && firstMetaItem(STORE_DATA_POINTS).isValueTrue();- }-- public boolean isRuleState() {- return hasMetaItem(RULE_STATE) && firstMetaItem(RULE_STATE).isValueTrue();- }-- public boolean isRuleEvent() {- return hasMetaItem(RULE_EVENT) && firstMetaItem(RULE_EVENT).isValueTrue();- }-- public String getRuleEventExpires() {- return hasMetaItem(RULE_EVENT_EXPIRES) ? firstMetaItem(RULE_EVENT_EXPIRES).getValueAsString() : null;- }-- public boolean isAgentLinked() {- return hasMetaItem(AGENT_LINK);- }-}diff --git a/model/src/main/java/org/openremote/model/asset/AbstractAssetAttributes.java b/model/src/main/java/org/openremote/model/asset/AbstractAssetAttributes.javadeleted file mode 100644index 0e3952fb3..000000000--- a/model/src/main/java/org/openremote/model/asset/AbstractAssetAttributes.java+++ /dev/null@@ -1,119 +0,0 @@-/*- * Copyright 2017, OpenRemote Inc.- *- * See the CONTRIBUTORS.txt file in the distribution for a- * full listing of individual contributors.- *- * This program is free software: you can redistribute it and/or modify- * it under the terms of the GNU Affero General Public License as- * published by the Free Software Foundation, either version 3 of the- * License, or (at your option) any later version.- *- * This program is distributed in the hope that it will be useful,- * but WITHOUT ANY WARRANTY; without even the implied warranty of- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the- * GNU Affero General Public License for more details.- *- * You should have received a copy of the GNU Affero General Public License- * along with this program. If not, see <http://www.gnu.org/licenses/>.- */-package org.openremote.model.asset;--import elemental.json.JsonObject;-import org.openremote.model.Attributes;-import org.openremote.model.Meta;-import org.openremote.model.MetaItem;--import static org.openremote.model.Constants.NAMESPACE;--public abstract class AbstractAssetAttributes<CHILD extends AbstractAssetAttributes<CHILD, A>, A extends AbstractAssetAttribute> extends Attributes<CHILD, A> {-- final public String assetId;-- public AbstractAssetAttributes() {- this.assetId = null;- }-- public AbstractAssetAttributes(JsonObject jsonObject) {- super(jsonObject);- this.assetId = null;- }-- public AbstractAssetAttributes(CHILD attributes) {- super(attributes);- this.assetId = null;- }-- public AbstractAssetAttributes(String assetId) {- this.assetId = assetId;- }-- public AbstractAssetAttributes(String assetId, JsonObject jsonObject) {- super(jsonObject);- this.assetId = assetId;- }-- public AbstractAssetAttributes(String assetId, CHILD attributes) {- super(attributes);- this.assetId = assetId;- }-- public AbstractAssetAttributes(Asset asset) {- super(asset.getAttributes());- this.assetId = asset.getId();- }-- public String getAssetId() {- if (assetId == null) {- throw new IllegalStateException("Asset identifier not set on: " + this);- }- return assetId;- }-- /* TODO Do we need an "enabled" attribute on many asset types?- @SuppressWarnings("unchecked")- public CHILD setEnabled(boolean enabled) {- if (hasAttribute("enabled")) {- get("enabled").setValueAsBoolean(enabled);- } else {- A enabledAttribute = createAttribute("enabled", Json.createObject());- enabledAttribute.setType(AttributeType.BOOLEAN);- enabledAttribute.setValue(Json.create(enabled));- put(enabledAttribute);- }- return (CHILD) this;- }- */-- /**- * Remove all attributes and meta items that are private.- */- public void filterProtected() {- for (A attribute : get()) {-- if (!attribute.isProtected()) {- remove(attribute.getName());- continue;- }-- if (!attribute.hasMeta())- continue;-- // Any meta item of the attribute, if it's in our namespace, must be protected READ to be included- Meta protectedMeta = new Meta();- for (MetaItem metaItem : attribute.getMeta().all()) {- if (!metaItem.getName().startsWith(NAMESPACE))- continue;-- AssetMeta wellKnownMeta = AssetMeta.byName(metaItem.getName());- if (wellKnownMeta != null && wellKnownMeta.getAccess().protectedRead) {- protectedMeta.add(- new MetaItem(metaItem.getName(), metaItem.getValue())- );- }- }- if (protectedMeta.size() > 0)- attribute.setMeta(protectedMeta);- }- }-}diff --git a/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java b/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.javaindex c569a268f..595691c86 100644--- a/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java+++ b/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java@@ -20,7 +20,9 @@package org.openremote.model.asset;import elemental.json.JsonValue;+import org.openremote.model.AttributeEvent;import org.openremote.model.AttributeRef;+import org.openremote.model.AttributeState;import org.openremote.model.AttributeType;import org.openremote.model.util.JsonUtil;@@ -34,7 +36,7 @@ import java.util.Date;*/public abstract class AbstractAssetUpdate {- final protected AbstractAssetAttribute attribute;+ final protected AssetAttribute attribute;final protected Date createdOn;@@ -69,11 +71,11 @@ public abstract class AbstractAssetUpdate {// True if the update was initiated by a protocol and is being processed northboundprotected boolean northbound;- public AbstractAssetUpdate(Asset asset, AbstractAssetAttribute attribute) {+ public AbstractAssetUpdate(Asset asset, AssetAttribute attribute) {this(asset, attribute, null, 0, false);}- public AbstractAssetUpdate(Asset asset, AbstractAssetAttribute attribute, JsonValue oldValue, long oldValueTimestamp, boolean northbound) {+ public AbstractAssetUpdate(Asset asset, AssetAttribute attribute, JsonValue oldValue, long oldValueTimestamp, boolean northbound) {this(attribute,asset.getCreatedOn(),@@ -117,7 +119,7 @@ public abstract class AbstractAssetUpdate {);}- protected AbstractAssetUpdate(AbstractAssetAttribute attribute,+ protected AbstractAssetUpdate(AssetAttribute attribute,Date createdOn, String id, String name, String typeString, AssetType type,String[] pathFromRoot, String parentId, String parentName, String parentTypeString, AssetType parentType,String realmId, String tenantRealm,@@ -227,6 +229,10 @@ public abstract class AbstractAssetUpdate {return attribute.getType();}+ public AttributeEvent getStateEvent() {+ return new AttributeEvent(new AttributeState(getAttributeRef(), attribute.getValue()), attribute.getValueTimestamp());+ }+public boolean isValueChanged() {return !JsonUtil.equals(attribute.getValue(), oldValue);}@@ -239,8 +245,7 @@ public abstract class AbstractAssetUpdate {* This is here because {@link #attribute} is not always publicly accessible*/public boolean attributeRefsEqual(AbstractAssetUpdate assetUpdate) {- return !(assetUpdate == null || assetUpdate.attribute == null)- && assetUpdate.attribute.getReference().equals(attribute.getReference());+ return assetUpdate != null && assetUpdate.getAttributeRef().equals(getAttributeRef());}@Overridediff --git a/model/src/main/java/org/openremote/model/asset/AbstractAttributeWrapper.java b/model/src/main/java/org/openremote/model/asset/AbstractAttributeWrapper.javanew file mode 100644index 000000000..f4f1e0cca--- /dev/null+++ b/model/src/main/java/org/openremote/model/asset/AbstractAttributeWrapper.java@@ -0,0 +1,96 @@+/*+ * Copyright 2017, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.model.asset;++import org.openremote.model.AttributeRef;+import org.openremote.model.Meta;+import org.openremote.model.util.AttributeUtil;++/**+ * This is a wrapper for AssetAttribute that can provide convenience+ * methods for getting/setting the attribute value and/or meta items+ * that should be in the dynamic part of the attribute class.+ *+ * It is deliberately minimal as any standard attribute manipulation+ * should be done on the attribute class itself.+ *+ */+public abstract class AbstractAttributeWrapper<CHILD extends AbstractAttributeWrapper> {++ AssetAttribute attribute;++ /**+ * Default constructor will also initialise the attribute, subclasses+ * should provide both constructors for convenience and consistency.+ *+ */+ protected AbstractAttributeWrapper(AssetAttribute attribute) {+ this(attribute, true);+ }++ /**+ * Should optionally initialise the attribute by calling initialise method.+ */+ protected AbstractAttributeWrapper(AssetAttribute attribute, boolean initialise) {+ this.attribute = attribute;+ if (initialise) {+ initialise();+ }+ }++ public AssetAttribute getAttribute() {+ return attribute;+ }++ public AttributeRef getAttributeReference() {+ return attribute.getReference();+ }++ public Meta getMeta() {+ return attribute.getMeta();+ }++ public void setMeta(Meta meta) {+ attribute.setMeta(meta);+ }++ /**+ * Indicates whether or not the attribute is valid for this wrapper type. Should be overridden in sub classes+ * where needed.+ */+ public boolean isValid() {+ return isValid(getAttribute());+ }++ /**+ * Initialise this attribute with all the static data relating to+ * this attribute wrapper type.+ */+ public abstract void initialise();++ /**+ * @return a static filter for this wrapper type+ */+ public abstract AttributeWrapperFilter<CHILD> getFilter();++ public static boolean isValid(AssetAttribute assetAttribute) {+ return AttributeUtil.nameIsValid(assetAttribute.getName()) && assetAttribute.getType() != null;+ }+}diff --git a/model/src/main/java/org/openremote/model/asset/Asset.java b/model/src/main/java/org/openremote/model/asset/Asset.javaindex 37f9d4d82..326c001b0 100644--- a/model/src/main/java/org/openremote/model/asset/Asset.java+++ b/model/src/main/java/org/openremote/model/asset/Asset.java@@ -19,6 +19,8 @@*/package org.openremote.model.asset;+import com.fasterxml.jackson.annotation.JsonIgnore;+import com.fasterxml.jackson.annotation.JsonProperty;import elemental.json.JsonObject;import org.hibernate.annotations.Formula;import org.openremote.model.IdentifiableEntity;@@ -26,6 +28,7 @@ import org.openremote.model.geo.GeoJSON;import org.openremote.model.geo.GeoJSONFeature;import org.openremote.model.geo.GeoJSONGeometry;import org.openremote.model.util.TextUtil;+import org.openremote.model.util.AttributeUtil;import javax.persistence.*;import javax.validation.constraints.NotNull;@@ -34,6 +37,7 @@ import java.math.BigDecimal;import java.math.RoundingMode;import java.util.Arrays;import java.util.Date;+import java.util.List;import static org.openremote.model.Constants.PERSISTENCE_JSON_OBJECT_TYPE;import static org.openremote.model.Constants.PERSISTENCE_UNIQUE_ID_GENERATOR;@@ -69,8 +73,8 @@ import static org.openremote.model.Constants.PERSISTENCE_UNIQUE_ID_GENERATOR;* <p>* The {@link #coordinates} are a pair of LNG/LAT values with the location of the asset.* <p>- * An asset may have dynamically-typed {@link #attributes} with an underlying- * {@link elemental.json.JsonObject} model. Use the {@link org.openremote.model.Attributes}+ * An asset may have dynamically-typed {@link #attrs} with an underlying+ * {@link elemental.json.JsonObject} model. Use the {@link org.openremote.model.util.AttributeUtil}* class to work with this API. This property can be empty when certain optimized loading* operations are used.* <p>@@ -266,7 +270,9 @@ public class Asset implements IdentifiableEntity {@Column(name = "ATTRIBUTES", columnDefinition = "jsonb")@org.hibernate.annotations.Type(type = PERSISTENCE_JSON_OBJECT_TYPE)- protected JsonObject attributes;+ @JsonProperty+ // We have to use a different name to the getter/setter because GWT Jackson ignores it otherwise+ public JsonObject attrs;public Asset() {}@@ -303,12 +309,12 @@ public class Asset implements IdentifiableEntity {this.tenantDisplayName = tenantDisplayName;this.path = path;- if (filterProtectedAttributes && attributes != null) {- AbstractAssetAttributes assetAttributes = new AssetAttributes(this.id, attributes);- assetAttributes.filterProtected();- this.attributes = assetAttributes.size() > 0 ? assetAttributes.getJsonObject() : null;+ if (filterProtectedAttributes) {+ List<AssetAttribute> assetAttributes = AttributeUtil.getAssetAttributesFromJson(id, attributes);+ assetAttributes = AttributeUtil.filterByProtected(assetAttributes);+ this.attrs = assetAttributes.size() > 0 ? AttributeUtil.getAssetAttributesAsJson(assetAttributes) : null;} else {- this.attributes = attributes;+ this.attrs = attributes;}}@@ -474,12 +480,15 @@ public class Asset implements IdentifiableEntity {return path != null && Arrays.asList(getPath()).contains(assetId);}- public JsonObject getAttributes() {- return attributes;+ @JsonIgnore+ public List<AssetAttribute> getAttributes() {+ return AttributeUtil.getAssetAttributesFromJson(id, attrs);}- public void setAttributes(JsonObject attributes) {- this.attributes = attributes;+ @JsonIgnore+ public void setAttributes(List<AssetAttribute> attributes) {+ // TODO: need to verify there are no duplicate attribute names+ this.attrs = AttributeUtil.getAssetAttributesAsJson(attributes);}/**@@ -532,7 +541,7 @@ public class Asset implements IdentifiableEntity {", tenantDisplayName='" + tenantDisplayName + '\'' +", coordinates=" + Arrays.toString(coordinates) +", path=" + Arrays.toString(path) +- ", attributes=" + attributes ++ ", attributes=" + attrs +'}';}}diff --git a/model/src/main/java/org/openremote/model/asset/AssetAttribute.java b/model/src/main/java/org/openremote/model/asset/AssetAttribute.javaindex 8bbad4334..7c49dde75 100644--- a/model/src/main/java/org/openremote/model/asset/AssetAttribute.java+++ b/model/src/main/java/org/openremote/model/asset/AssetAttribute.java@@ -19,38 +19,127 @@*/package org.openremote.model.asset;-import elemental.json.Json;import elemental.json.JsonObject;import elemental.json.JsonValue;import org.openremote.model.*;-public class AssetAttribute extends AbstractAssetAttribute<AssetAttribute> {+import java.util.List;++import static org.openremote.model.asset.AssetMeta.*;+import static org.openremote.model.asset.AssetMeta.AGENT_LINK;++public class AssetAttribute extends Attribute<AssetAttribute> {+ final protected String assetId;+public AssetAttribute(String name, AttributeType type) {- super(null, name, type);+ this(null, name, type);}public AssetAttribute(String name, AttributeType type, JsonValue value) {- super(null, name, type, value);+ this(null, name, type, value);}public AssetAttribute(String name, JsonObject jsonObject) {- super(null, name, jsonObject);+ this(null, name, jsonObject);}public AssetAttribute(String assetId, String name, AttributeType type) {- super(assetId, name, type);+ super(name, type);+ this.assetId = assetId;}public AssetAttribute(String assetId, String name, AttributeType type, JsonValue value) {- super(assetId, name, type, value);+ super(name, type, value);+ this.assetId = assetId;}public AssetAttribute(String assetId, String name, JsonObject jsonObject) {- super(assetId, name, jsonObject);+ super(name, jsonObject);+ this.assetId = assetId;+ }++ public AssetAttribute(AssetAttribute assetAttribute) {+ super(assetAttribute);+ this.assetId = assetAttribute.getAssetId();+ }++ public String getAssetId() {+ return assetId;+ }++ public AttributeRef getReference() {+ return new AttributeRef(getAssetId(), getName());+ }++ /**+ * @return The current value.+ */+ public AttributeState getState() {+ return new AttributeState(+ getReference(),+ getValue()+ );+ }++ /**+ * @return The current value and its timestamp represented as an attribute event.+ */+ public AttributeEvent getStateEvent() {+ return new AttributeEvent(+ getState(),+ getValueTimestamp()+ );+ }++ public boolean hasMetaItem(AssetMeta assetMeta) {+ return hasMetaItem(assetMeta.getName());+ }++ public MetaItem firstMetaItem(AssetMeta assetMeta) {+ return firstMetaItem(assetMeta.getName());+ }++ public List<MetaItem> getMetaItems(AssetMeta assetMeta) {+ return getMetaItems(assetMeta.getName());+ }++ public String getLabel() {+ return hasMetaItem(LABEL) ? firstMetaItem(LABEL).getValueAsString() : getName();+ }++ public String getFormat() {+ return hasMetaItem(FORMAT) ? firstMetaItem(FORMAT).getValueAsString() : null;+ }++ public boolean isShowOnDashboard() {+ return hasMetaItem(SHOWN_ON_DASHBOARD) && firstMetaItem(SHOWN_ON_DASHBOARD).isValueTrue();+ }++ public boolean isProtected() {+ return hasMetaItem(PROTECTED) && firstMetaItem(PROTECTED).isValueTrue();+ }++ public boolean isReadOnly() {+ return hasMetaItem(READ_ONLY) && firstMetaItem(READ_ONLY).isValueTrue();+ }++ public boolean isStoreDatapoints() {+ return hasMetaItem(STORE_DATA_POINTS) && firstMetaItem(STORE_DATA_POINTS).isValueTrue();+ }++ public boolean isRuleState() {+ return hasMetaItem(RULE_STATE) && firstMetaItem(RULE_STATE).isValueTrue();+ }++ public boolean isRuleEvent() {+ return hasMetaItem(RULE_EVENT) && firstMetaItem(RULE_EVENT).isValueTrue();+ }++ public String getRuleEventExpires() {+ return hasMetaItem(RULE_EVENT_EXPIRES) ? firstMetaItem(RULE_EVENT_EXPIRES).getValueAsString() : null;}- @Override- public AssetAttribute copy() {- return new AssetAttribute(assetId, getName(), Json.parse(getJsonObject().toJson()));+ public boolean isAgentLinked() {+ return hasMetaItem(AGENT_LINK);}}diff --git a/model/src/main/java/org/openremote/model/asset/AssetAttributes.java b/model/src/main/java/org/openremote/model/asset/AssetAttributes.javadeleted file mode 100644index 5e1e81a27..000000000--- a/model/src/main/java/org/openremote/model/asset/AssetAttributes.java+++ /dev/null@@ -1,65 +0,0 @@-/*- * Copyright 2017, OpenRemote Inc.- *- * See the CONTRIBUTORS.txt file in the distribution for a- * full listing of individual contributors.- *- * This program is free software: you can redistribute it and/or modify- * it under the terms of the GNU Affero General Public License as- * published by the Free Software Foundation, either version 3 of the- * License, or (at your option) any later version.- *- * This program is distributed in the hope that it will be useful,- * but WITHOUT ANY WARRANTY; without even the implied warranty of- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the- * GNU Affero General Public License for more details.- *- * You should have received a copy of the GNU Affero General Public License- * along with this program. If not, see <http://www.gnu.org/licenses/>.- */-package org.openremote.model.asset;--import elemental.json.Json;-import elemental.json.JsonObject;--public class AssetAttributes extends AbstractAssetAttributes<AssetAttributes, AssetAttribute> {-- public AssetAttributes() {- }-- public AssetAttributes(JsonObject jsonObject) {- super(jsonObject);- }-- public AssetAttributes(AssetAttributes attributes) {- super(attributes);- }-- public AssetAttributes(String assetId) {- super(assetId);- }-- public AssetAttributes(String assetId, JsonObject jsonObject) {- super(assetId, jsonObject);- }-- public AssetAttributes(String assetId, AssetAttributes attributes) {- super(assetId, attributes);- }-- public AssetAttributes(Asset asset) {- super(asset);- }-- @SuppressWarnings("unchecked")- @Override- public AssetAttributes copy() {- return new AssetAttributes(assetId, Json.parse(getJsonObject().toJson()));- }-- @SuppressWarnings("unchecked")- @Override- 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/AssetState.java b/model/src/main/java/org/openremote/model/asset/AssetState.javaindex ff6a15792..5f911f923 100644--- a/model/src/main/java/org/openremote/model/asset/AssetState.java+++ b/model/src/main/java/org/openremote/model/asset/AssetState.java@@ -66,11 +66,11 @@ public class AssetState extends AbstractAssetUpdate {protected Throwable error;- public AssetState(Asset asset, AbstractAssetAttribute attribute) {+ public AssetState(Asset asset, AssetAttribute attribute) {super(asset, attribute);}- public AssetState(Asset asset, AbstractAssetAttribute attribute, JsonValue oldValue, long oldValueTimestamp, boolean northbound) {+ public AssetState(Asset asset, AssetAttribute attribute, JsonValue oldValue, long oldValueTimestamp, boolean northbound) {super(asset, attribute, oldValue, oldValueTimestamp, northbound);}@@ -93,7 +93,7 @@ public class AssetState extends AbstractAssetUpdate {// GETTERS AND SETTERS BELOW CAN ONLY BE USED WHEN STATUS IS NOT COMPLETED/////////////////////////////////////////////////////////////////- public AbstractAssetAttribute getAttribute() {+ public AssetAttribute getAttribute() {if (!isCompleted()) {return attribute;}diff --git a/model/src/main/java/org/openremote/model/asset/AssetType.java b/model/src/main/java/org/openremote/model/asset/AssetType.javaindex 735942bcd..a20ebf212 100644--- a/model/src/main/java/org/openremote/model/asset/AssetType.java+++ b/model/src/main/java/org/openremote/model/asset/AssetType.java@@ -43,34 +43,33 @@ public enum AssetType {CUSTOM(null, true, null),- BUILDING(ASSET_NAMESPACE + ":building", true, new AssetAttributes().put(+ BUILDING(ASSET_NAMESPACE + ":building", true, Arrays.asList(new AssetAttribute("area", INTEGER).setMeta(new Meta()- .add(createMetaItem(LABEL, Json.create("Surface area")))- .add(createMetaItem(DESCRIPTION, Json.create("Floor area of building measured in m²")))- .add(createMetaItem(ABOUT, Json.create("http://project-haystack.org/tag/area")))- ),+ .add(createMetaItem(LABEL, Json.create("Surface area")))+ .add(createMetaItem(DESCRIPTION, Json.create("Floor area of building measured in m²")))+ .add(createMetaItem(ABOUT, Json.create("http://project-haystack.org/tag/area")))+ ),new AssetAttribute("geoStreet", STRING).setMeta(new Meta()- .add(createMetaItem(LABEL, Json.create("Street")))- .add(createMetaItem(ABOUT, Json.create("http://project-haystack.org/tag/geoStreet")))- ),+ .add(createMetaItem(LABEL, Json.create("Street")))+ .add(createMetaItem(ABOUT, Json.create("http://project-haystack.org/tag/geoStreet")))+ ),new AssetAttribute("geoPostalCode", AttributeType.INTEGER).setMeta(new Meta()- .add(createMetaItem(LABEL, Json.create("Postal Code")))- .add(createMetaItem(ABOUT, Json.create("http://project-haystack.org/tag/geoPostalCode")))- ),+ .add(createMetaItem(LABEL, Json.create("Postal Code")))+ .add(createMetaItem(ABOUT, Json.create("http://project-haystack.org/tag/geoPostalCode")))+ ),new AssetAttribute("geoCity", STRING).setMeta(new Meta()- .add(createMetaItem(LABEL, Json.create("City")))- .add(createMetaItem(ABOUT, Json.create("http://project-haystack.org/tag/geoCity")))- ),+ .add(createMetaItem(LABEL, Json.create("City")))+ .add(createMetaItem(ABOUT, Json.create("http://project-haystack.org/tag/geoCity")))+ ),new AssetAttribute("geoCountry", STRING).setMeta(new Meta()- .add(createMetaItem(LABEL, Json.create("Country")))- .add(createMetaItem(ABOUT, Json.create("http://project-haystack.org/tag/geoCountry")))- )- )),+ .add(createMetaItem(LABEL, Json.create("Country")))+ .add(createMetaItem(ABOUT, Json.create("http://project-haystack.org/tag/geoCountry")))+ ))),FLOOR(ASSET_NAMESPACE + ":floor", true, null),@@ -87,19 +86,19 @@ public enum AssetType {THING(ASSET_NAMESPACE + ":thing", true, null);final protected String value;- final protected AssetAttributes defaultAttributes;+ final protected List<AssetAttribute> defaultAttributes;- AssetType(String value, boolean editable, AssetAttributes defaultAttributes) {+ AssetType(String value, boolean editable, List<AssetAttribute> defaultAttributes) {this.value = value;- this.defaultAttributes = defaultAttributes != null ? defaultAttributes : new AssetAttributes();+ this.defaultAttributes = defaultAttributes;}public String getValue() {return value;}- public AssetAttributes getDefaultAttributes() {- return defaultAttributes;+ public AssetAttribute[] getDefaultAttributes() {+ return defaultAttributes != null ? defaultAttributes.toArray(new AssetAttribute[0]) : new AssetAttribute[0];}public static AssetType[] valuesSorted() {diff --git a/model/src/main/java/org/openremote/model/asset/AttributeWrapperFilter.java b/model/src/main/java/org/openremote/model/asset/AttributeWrapperFilter.javanew file mode 100644index 000000000..5a4bff85d--- /dev/null+++ b/model/src/main/java/org/openremote/model/asset/AttributeWrapperFilter.java@@ -0,0 +1,28 @@+/*+ * Copyright 2017, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.model.asset;++import java.util.List;++public interface AttributeWrapperFilter<CHILD> {+ List<CHILD> getAllWrapped(List<AssetAttribute> assetAttributes, boolean excludeInvalid);++ List<AssetAttribute> getAll(List<AssetAttribute> assetAttributes, boolean excludeInvalid);+}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.javadeleted file mode 100644index 1460ec02d..000000000--- a/model/src/main/java/org/openremote/model/asset/agent/AgentAttribute.java+++ /dev/null@@ -1,51 +0,0 @@-/*- * Copyright 2017, OpenRemote Inc.- *- * See the CONTRIBUTORS.txt file in the distribution for a- * full listing of individual contributors.- *- * This program is free software: you can redistribute it and/or modify- * it under the terms of the GNU Affero General Public License as- * published by the Free Software Foundation, either version 3 of the- * License, or (at your option) any later version.- *- * This program is distributed in the hope that it will be useful,- * but WITHOUT ANY WARRANTY; without even the implied warranty of- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the- * GNU Affero General Public License for more details.- *- * You should have received a copy of the GNU Affero General Public License- * along with this program. If not, see <http://www.gnu.org/licenses/>.- */-package org.openremote.model.asset.agent;--import elemental.json.Json;-import elemental.json.JsonObject;-import elemental.json.JsonValue;-import org.openremote.model.AttributeType;-import org.openremote.model.asset.AbstractAssetAttribute;--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, AttributeType type, JsonValue value) {- super(assetId, name, type, value);- }-- public AgentAttribute(String assetId, String name, JsonObject jsonObject) {- super(assetId, name, jsonObject);- }-- @SuppressWarnings("unchecked")- @Override- public CHILD copy() {- 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/AgentAttributes.java b/model/src/main/java/org/openremote/model/asset/agent/AgentAttributes.javadeleted file mode 100644index c04a59ec5..000000000--- a/model/src/main/java/org/openremote/model/asset/agent/AgentAttributes.java+++ /dev/null@@ -1,82 +0,0 @@-/*- * Copyright 2017, OpenRemote Inc.- *- * See the CONTRIBUTORS.txt file in the distribution for a- * full listing of individual contributors.- *- * This program is free software: you can redistribute it and/or modify- * it under the terms of the GNU Affero General Public License as- * published by the Free Software Foundation, either version 3 of the- * License, or (at your option) any later version.- *- * This program is distributed in the hope that it will be useful,- * but WITHOUT ANY WARRANTY; without even the implied warranty of- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the- * GNU Affero General Public License for more details.- *- * You should have received a copy of the GNU Affero General Public License- * along with this program. If not, see <http://www.gnu.org/licenses/>.- */-package org.openremote.model.asset.agent;--import elemental.json.Json;-import elemental.json.JsonObject;-import org.openremote.model.asset.AbstractAssetAttributes;-import org.openremote.model.asset.Asset;--import java.util.ArrayList;-import java.util.Collections;-import java.util.List;--public class AgentAttributes extends AbstractAssetAttributes<AgentAttributes, AgentAttribute> {-- public AgentAttributes() {- }-- public AgentAttributes(String assetId) {- super(assetId);- }-- public AgentAttributes(String assetId, JsonObject jsonObject) {- super(assetId, jsonObject);- }-- public AgentAttributes(AgentAttributes attributes) {- super(attributes);- }-- public AgentAttributes(Asset asset) {- super(asset);- }-- @SuppressWarnings("unchecked")- @Override- public AgentAttributes copy() {- return new AgentAttributes(assetId, Json.parse(getJsonObject().toJson()));- }-- @SuppressWarnings("unchecked")- @Override- protected AgentAttribute createAttribute(String name, JsonObject jsonObject) {- return new AgentAttribute(assetId, name, jsonObject);- }-- public List<ProtocolConfiguration> getProtocolConfigurations() {- List<AgentAttribute> attributes = super.get();- List<ProtocolConfiguration> protocolConfigurations = new ArrayList<>();- for (AgentAttribute attribute : attributes) {- if (ProtocolConfiguration.isProtocolConfiguration(attribute)) {- protocolConfigurations.add(new ProtocolConfiguration(attribute));- }- }- return Collections.unmodifiableList(protocolConfigurations);- }-- public ProtocolConfiguration getProtocolConfiguration(String name) {- AgentAttribute attribute = super.get(name);- if (attribute == null || !ProtocolConfiguration.isProtocolConfiguration(attribute))- return null;- return new ProtocolConfiguration(attribute);- }--}diff --git a/model/src/main/java/org/openremote/model/asset/agent/AgentProtocolLink.java b/model/src/main/java/org/openremote/model/asset/agent/AgentProtocolLink.javanew file mode 100644index 000000000..f8816d060--- /dev/null+++ b/model/src/main/java/org/openremote/model/asset/agent/AgentProtocolLink.java@@ -0,0 +1,116 @@+/*+ * Copyright 2017, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.model.asset.agent;++import elemental.json.JsonArray;+import org.openremote.model.AttributeRef;+import org.openremote.model.Meta;+import org.openremote.model.MetaItem;+import org.openremote.model.asset.AbstractAttributeWrapper;+import org.openremote.model.asset.AttributeWrapperFilter;+import org.openremote.model.asset.AssetAttribute;+import org.openremote.model.asset.AssetMeta;++import java.util.List;+import java.util.stream.Collectors;++public class AgentProtocolLink extends AbstractAttributeWrapper <AgentProtocolLink> {+ public static class Filter implements AttributeWrapperFilter<AgentProtocolLink> {+ @Override+ public List<AgentProtocolLink> getAllWrapped(List<AssetAttribute> assetAttributes, boolean excludeInvalid) {+ return getAll(assetAttributes, excludeInvalid)+ .stream()+ .map(assetAttribute -> new AgentProtocolLink(assetAttribute, false))+ .collect(Collectors.toList());+ }++ @Override+ public List<AssetAttribute> getAll(List<AssetAttribute> assetAttributes, boolean excludeInvalid) {+ // Agent Linked Attribute wrappers should have protocol URN as the attribute value+ return assetAttributes+ .stream()+ .filter(attribute ->+ AgentProtocolLink.hasAgentProtocolLink(attribute) && (!excludeInvalid || AgentProtocolLink.isValid(attribute))+ )+ .collect(Collectors.toList());+ }+ }++ protected static final AttributeWrapperFilter<AgentProtocolLink> filter = new Filter();++ public AgentProtocolLink(AssetAttribute attribute) {+ super(attribute);+ }++ public AgentProtocolLink(AssetAttribute attribute, boolean initialise) {+ super(attribute, initialise);+ }++ public AttributeRef getLink() {+ return getLink(getAttribute());+ }++ protected void setLink(AttributeRef attributeRef) {+ if (attributeRef == null) {+ throw new IllegalArgumentException("AttributeRef cannot be null");+ }++ Meta meta = getMeta().removeAll(AssetMeta.AGENT_LINK);+ meta.add(new MetaItem(AssetMeta.AGENT_LINK, attributeRef.asJsonValue()));+ setMeta(meta);+ }++ protected void removeAgentProtocolLink() {+ Meta meta = getMeta().removeAll(AssetMeta.AGENT_LINK);+ setMeta(meta);+ }++ @Override+ public void initialise() {+ // Nothing to do here+ }++ @Override+ public AttributeWrapperFilter<AgentProtocolLink> getFilter() {+ return null;+ }++ /**+ * Does super class checks and also checks for valid Protocol Ref+ */+ @Override+ public boolean isValid() {+ return isValid(getAttribute());+ }++ public static boolean isValid(AssetAttribute assetAttribute) {+ return AbstractAttributeWrapper.isValid(assetAttribute) && hasAgentProtocolLink(assetAttribute);+ }++ public static AttributeRef getLink(AssetAttribute assetAttribute) {+ MetaItem metaItem = assetAttribute.firstMetaItem(AssetMeta.AGENT_LINK);+ JsonArray array = metaItem != null ? metaItem.getValueAsArray() : null;+ return array != null && array.length() == 2 ? new AttributeRef(array) : null;+ }++ public static boolean hasAgentProtocolLink(AssetAttribute assetAttribute) {+ return getLink(assetAttribute) != null;+ }+}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.javaindex 5b391fc84..b06c1fa68 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@@ -20,14 +20,14 @@package org.openremote.model.asset.agent;import elemental.json.Json;-import elemental.json.JsonObject;-import elemental.json.JsonValue;-import org.openremote.model.*;-import org.openremote.model.asset.AbstractAssetAttribute;-import org.openremote.model.asset.Asset;+import org.openremote.model.AttributeType;+import org.openremote.model.Constants;+import org.openremote.model.Meta;+import org.openremote.model.MetaItem;+import org.openremote.model.asset.AbstractAttributeWrapper;+import org.openremote.model.asset.AttributeWrapperFilter;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;@@ -38,26 +38,59 @@ import java.util.stream.Collectors;* <p>* Configuration details are managed as {@link Meta} of the attribute.*/-public class ProtocolConfiguration extends AgentAttribute<ProtocolConfiguration> {+public class ProtocolConfiguration extends AbstractAttributeWrapper<ProtocolConfiguration> {+ public static class Filter implements AttributeWrapperFilter<ProtocolConfiguration> {+ @Override+ public List<ProtocolConfiguration> getAllWrapped(List<AssetAttribute> assetAttributes, boolean excludeInvalid) {+ return getAll(assetAttributes, excludeInvalid)+ .stream()+ .map(assetAttribute -> new ProtocolConfiguration(assetAttribute, false))+ .collect(Collectors.toList());+ }- public ProtocolConfiguration(String name, String protocol) {- super(null, name, AttributeType.STRING, Json.create(protocol));+ @Override+ public List<AssetAttribute> getAll(List<AssetAttribute> assetAttributes, boolean excludeInvalid) {+ // Macro Attribute wrappers should have macro protocol name as the attribute value+ return assetAttributes+ .stream()+ .filter(attribute ->+ ProtocolConfiguration.valueIsProtocolUrn(attribute)+ && (!excludeInvalid || ProtocolConfiguration.isValid(attribute)))+ .collect(Collectors.toList());+ }}- public ProtocolConfiguration(String assetId, String name, String protocol) {- super(assetId, name, AttributeType.STRING, Json.create(protocol));+ public static final AttributeWrapperFilter<ProtocolConfiguration> filter = new Filter();++ @Override+ public void initialise() {+ // Push enabled flag as true by default+ if (!getAttribute().hasMetaItem(AssetMeta.ENABLED)) {+ Meta meta = getAttribute().getMeta().add(new MetaItem(AssetMeta.ENABLED, Json.create(true)));+ getAttribute().setMeta(meta);+ }+ }++ @Override+ public AttributeWrapperFilter<ProtocolConfiguration> getFilter() {+ return null;}- public ProtocolConfiguration(String assetId, String name, JsonObject jsonObject) {- super(assetId, name, jsonObject);+ public ProtocolConfiguration(String attributeName, String protocolName) {+ this(new AssetAttribute(attributeName, AttributeType.STRING));+ setProtocolName(protocolName);}- public ProtocolConfiguration(AbstractAssetAttribute attribute) {- this(attribute.getAssetId(), attribute.getName(), attribute.getJsonObject());+ public ProtocolConfiguration(AssetAttribute attribute) {+ super(attribute);+ }++ public ProtocolConfiguration(AssetAttribute attribute, boolean initialise) {+ super(attribute, initialise);}public boolean isEnabled() {- MetaItem enabled = firstMetaItem(AssetMeta.ENABLED);+ MetaItem enabled = getMeta().first(AssetMeta.ENABLED);return enabled != null ? enabled.getValueAsBoolean() : true;}@@ -68,52 +101,39 @@ public class ProtocolConfiguration extends AgentAttribute<ProtocolConfiguration>setMeta(meta);}- @Override- public ProtocolConfiguration setValue(JsonValue value) throws IllegalArgumentException {- super.setValue(value);- if (!isValueValid()) {+ public ProtocolConfiguration setProtocolName(String protocolName) throws IllegalArgumentException {++ if (!valueIsProtocolUrn(protocolName)) {throw new IllegalArgumentException("Protocol configuration value should contain a protocol URN");}++ getAttribute().setValue(Json.create(protocolName));return this;}public String getProtocolName() {- return getValueAsString();- }-- public boolean isValueValid() {- return getType() == AttributeType.STRING && getValueAsString() != null && getValueAsString().startsWith(Constants.PROTOCOL_NAMESPACE);+ return getAttribute().getValueAsString();}@Overridepublic boolean isValid() {- return super.isValid() && isValueValid();+ return super.isValid() && isValid(getAttribute());}/*** 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);+ public static boolean isValid(AssetAttribute assetAttribute) {+ // Value must be protocol name and must be at least one macro action+ return assetAttribute.getType() == AttributeType.STRING && valueIsProtocolUrn(assetAttribute);}- /**- * Get all protocol configuration attributes from the asset- */- public static List<ProtocolConfiguration> getAll(Asset agent) {- return getAll(new AgentAttributes(agent).get());+ protected static boolean valueIsProtocolUrn(AssetAttribute assetAttribute) {+ String value = assetAttribute.getValueAsString();+ return valueIsProtocolUrn(value);}- /**- * 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());+ protected static boolean valueIsProtocolUrn(String value) {+ return value != null && value.toLowerCase(Locale.ROOT).startsWith(Constants.PROTOCOL_NAMESPACE);}}diff --git a/model/src/main/java/org/openremote/model/asset/macro/MacroAttribute.java b/model/src/main/java/org/openremote/model/asset/macro/MacroAttribute.javadeleted file mode 100644index a13245cfb..000000000--- a/model/src/main/java/org/openremote/model/asset/macro/MacroAttribute.java+++ /dev/null@@ -1,92 +0,0 @@-/*- * Copyright 2017, OpenRemote Inc.- *- * See the CONTRIBUTORS.txt file in the distribution for a- * full listing of individual contributors.- *- * This program is free software: you can redistribute it and/or modify- * it under the terms of the GNU Affero General Public License as- * published by the Free Software Foundation, either version 3 of the- * License, or (at your option) any later version.- *- * This program is distributed in the hope that it will be useful,- * but WITHOUT ANY WARRANTY; without even the implied warranty of- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the- * GNU Affero General Public License for more details.- *- * You should have received a copy of the GNU Affero General Public License- * along with this program. If not, see <http://www.gnu.org/licenses/>.- */-package org.openremote.model.asset.macro;--import elemental.json.JsonObject;-import org.openremote.model.Meta;-import org.openremote.model.MetaItem;-import org.openremote.model.asset.AbstractAssetAttribute;-import org.openremote.model.asset.AssetMeta;-import org.openremote.model.asset.agent.ProtocolConfiguration;-import org.openremote.model.util.JsonUtil;--import java.util.Arrays;-import java.util.List;-import java.util.stream.Collectors;-import java.util.stream.IntStream;--import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;--public class MacroAttribute extends ProtocolConfiguration {- public static final String PROTOCOL_NAME = PROTOCOL_NAMESPACE + ":macro";-- public MacroAttribute(String name) {- super(name, PROTOCOL_NAME);- }-- public MacroAttribute(String assetId, String name) {- super(assetId, name, PROTOCOL_NAME);- }-- public MacroAttribute(String assetId, String name, JsonObject jsonObject) {- super(assetId, name, jsonObject);- }-- public MacroAttribute(ProtocolConfiguration protocolConfiguration) {- super(protocolConfiguration);- }-- public List<MacroAction> getActions() {- return Arrays.stream(getMeta().all())- .filter(metaItem -> metaItem.getName().equals(AssetMeta.MACRO_ACTION.getName()))- .map(metaItem -> new MacroAction(metaItem.getValueAsObject()))- .collect(Collectors.toList());- }-- public void setActions(List<MacroAction> actions) {- Meta meta = getMeta() != null ? getMeta() : new Meta();- meta = meta.removeAll(AssetMeta.MACRO_ACTION);- Meta finalMeta = meta;- actions.forEach(action -> finalMeta.add(action.asMetaItem()));- }-- public void addAction(MacroAction action) {- Meta meta = getMeta() != null ? getMeta() : new Meta();- meta.add(action.asMetaItem());- setMeta(meta);- }-- public void removeAction(MacroAction action) {- if (!hasMeta()) {- return;- }-- MetaItem[] metaItems = getMeta().all();- IntStream.range(0, metaItems.length)- .filter(i -> metaItems[i].getName().equals(AssetMeta.MACRO_ACTION.getName()))- .filter(i -> JsonUtil.equals(metaItems[i].getValueAsObject(), action.asJsonValue()))- .forEach(i -> getMeta().remove(i));- }-- @Override- public String getProtocolName() {- return PROTOCOL_NAME;- }-}diff --git a/model/src/main/java/org/openremote/model/asset/macro/MacroConfiguration.java b/model/src/main/java/org/openremote/model/asset/macro/MacroConfiguration.javanew file mode 100644index 000000000..4141bd089--- /dev/null+++ b/model/src/main/java/org/openremote/model/asset/macro/MacroConfiguration.java@@ -0,0 +1,138 @@+/*+ * Copyright 2017, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.model.asset.macro;++import elemental.json.Json;+import org.openremote.model.AttributeType;+import org.openremote.model.Meta;+import org.openremote.model.MetaItem;+import org.openremote.model.asset.AbstractAttributeWrapper;+import org.openremote.model.asset.AttributeWrapperFilter;+import org.openremote.model.asset.AssetAttribute;+import org.openremote.model.asset.AssetMeta;+import org.openremote.model.util.JsonUtil;++import java.util.List;+import java.util.stream.Collectors;+import java.util.stream.IntStream;++import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;++public class MacroConfiguration extends AbstractAttributeWrapper<MacroConfiguration> {+ public static class Filter implements AttributeWrapperFilter<MacroConfiguration> {+ @Override+ public List<MacroConfiguration> getAllWrapped(List<AssetAttribute> assetAttributes, boolean excludeInvalid) {+ return getAll(assetAttributes, excludeInvalid)+ .stream()+ .map(assetAttribute -> new MacroConfiguration(assetAttribute, false))+ .collect(Collectors.toList());+ }++ @Override+ public List<AssetAttribute> getAll(List<AssetAttribute> assetAttributes, boolean excludeInvalid) {+ // Macro Attribute wrappers should have macro protocol name as the attribute value+ return assetAttributes+ .stream()+ .filter(attribute ->+ MacroConfiguration.valueIsProtocolName(attribute) && (!excludeInvalid || MacroConfiguration.isValid(attribute))+ )+ .collect(Collectors.toList());+ }+ }++ public static final String PROTOCOL_NAME = PROTOCOL_NAMESPACE + ":macro";+ protected static final AttributeWrapperFilter<MacroConfiguration> filter = new Filter();++ public MacroConfiguration(String attributeName) {+ this(new AssetAttribute(attributeName, AttributeType.STRING, Json.create(PROTOCOL_NAME)));+ }++ public MacroConfiguration(AssetAttribute attribute) {+ super(attribute);+ }++ public MacroConfiguration(AssetAttribute attribute, boolean initialise) {+ super(attribute, initialise);+ }++ @Override+ public boolean isValid() {+ return super.isValid() && isValid(getAttribute());+ }++ @Override+ public void initialise() {+ // Set value as protocol name+ getAttribute().setValue(Json.create(PROTOCOL_NAME));+ }++ @Override+ public AttributeWrapperFilter<MacroConfiguration> getFilter() {+ return filter;+ }++ public List<MacroAction> getActions() {+ return getAttribute().getMeta().all()+ .stream()+ .filter(metaItem -> metaItem.getName().equals(AssetMeta.MACRO_ACTION.getName()))+ .map(metaItem -> new MacroAction(metaItem.getValueAsObject()))+ .collect(Collectors.toList());+ }++ public void setActions(List<MacroAction> actions) {+ Meta meta = getAttribute().getMeta() != null ? getAttribute().getMeta() : new Meta();+ meta = meta.removeAll(AssetMeta.MACRO_ACTION);+ Meta finalMeta = meta;+ actions.forEach(action -> finalMeta.add(action.asMetaItem()));+ }++ public void addAction(MacroAction action) {+ Meta meta = getAttribute().getMeta() != null ? getAttribute().getMeta() : new Meta();+ meta.add(action.asMetaItem());+ getAttribute().setMeta(meta);+ }++ public void removeAction(MacroAction action) {+ if (!getAttribute().hasMeta()) {+ return;+ }++ List<MetaItem> metaItems = getAttribute().getMeta().all();+ IntStream.range(0, metaItems.size())+ .filter(i -> metaItems.get(i).getName().equals(AssetMeta.MACRO_ACTION.getName()))+ .filter(i -> JsonUtil.equals(metaItems.get(i).getValueAsObject(), action.asJsonValue()))+ .forEach(i -> getAttribute().getMeta().remove(i));+ }++ public String getProtocolName() {+ return PROTOCOL_NAME;+ }++ public static boolean isValid(AssetAttribute assetAttribute) {+ MetaItem item = assetAttribute.firstMetaItem(AssetMeta.MACRO_ACTION);+ return AbstractAttributeWrapper.isValid(assetAttribute) && valueIsProtocolName(assetAttribute) && item != null;+ }++ public static boolean valueIsProtocolName(AssetAttribute assetAttribute) {+ // Value must be protocol name and must be at least one macro action+ String value = assetAttribute.getValueAsString();+ return value != null && value.equals(PROTOCOL_NAME);+ }+}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.javadeleted file mode 100644index 696934c89..000000000--- a/model/src/main/java/org/openremote/model/asset/thing/ThingAttribute.java+++ /dev/null@@ -1,159 +0,0 @@-/*- * Copyright 2017, OpenRemote Inc.- *- * See the CONTRIBUTORS.txt file in the distribution for a- * full listing of individual contributors.- *- * This program is free software: you can redistribute it and/or modify- * it under the terms of the GNU Affero General Public License as- * published by the Free Software Foundation, either version 3 of the- * License, or (at your option) any later version.- *- * This program is distributed in the hope that it will be useful,- * but WITHOUT ANY WARRANTY; without even the implied warranty of- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the- * GNU Affero General Public License for more details.- *- * You should have received a copy of the GNU Affero General Public License- * along with this program. If not, see <http://www.gnu.org/licenses/>.- */-package org.openremote.model.asset.thing;--import elemental.json.Json;-import elemental.json.JsonArray;-import elemental.json.JsonObject;-import elemental.json.JsonValue;-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 ThingAttribute(ProtocolConfiguration protocolConfiguration, AssetAttribute attribute) {- this(protocolConfiguration, attribute.getAssetId(), attribute.getName(), attribute.getJsonObject());- }-- 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(ProtocolConfiguration protocolConfiguration, String assetId, String name, JsonObject jsonObject) {- super(assetId, name, jsonObject);- this.protocolConfiguration = protocolConfiguration;-- // Verify jsonObject is valid- if (!isValid()) {- throw new IllegalArgumentException("Supplied JSON object is not valid for this type of attribute: " + jsonObject.toJson());- }- }-- @Override- public ThingAttribute copy() {- return new ThingAttribute(protocolConfiguration.copy(), assetId, getName(), Json.parse(getJsonObject().toJson()));- }-- public ProtocolConfiguration getProtocolConfiguration() {- return protocolConfiguration;- }-- /**- * 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 AttributeRef getProtocolRef() {- return getProtocolRef(this);- }-- protected void setProtocolRef(AttributeRef attributeRef) {- if (attributeRef == null) {- throw new IllegalArgumentException("AttributeRef cannot be null");- }-- Meta meta = hasMeta() ? getMeta() : new Meta();- meta.removeAll(AssetMeta.AGENT_LINK);- meta.add(new MetaItem(AssetMeta.AGENT_LINK, attributeRef.asJsonValue()));- setMeta(meta);- protocolConfiguration = null;- }-- /**- * Does super class checks and also checks for valid Protocol Ref- */- @Override- public boolean isValid() {- return super.isValid() && getProtocolRef(this) != 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;- }-- /**- * 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);- }-- /**- * 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()));- }-- /**- * 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);- }-- /**- * Gets all thing attributes from the asset- */- 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.javadeleted file mode 100644index b7343ba6f..000000000--- a/model/src/main/java/org/openremote/model/asset/thing/ThingAttributes.java+++ /dev/null@@ -1,63 +0,0 @@-/*- * Copyright 2017, OpenRemote Inc.- *- * See the CONTRIBUTORS.txt file in the distribution for a- * full listing of individual contributors.- *- * This program is free software: you can redistribute it and/or modify- * it under the terms of the GNU Affero General Public License as- * published by the Free Software Foundation, either version 3 of the- * License, or (at your option) any later version.- *- * This program is distributed in the hope that it will be useful,- * but WITHOUT ANY WARRANTY; without even the implied warranty of- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the- * GNU Affero General Public License for more details.- *- * You should have received a copy of the GNU Affero General Public License- * along with this program. If not, see <http://www.gnu.org/licenses/>.- */-package org.openremote.model.asset.thing;--import elemental.json.Json;-import elemental.json.JsonObject;-import org.openremote.model.AttributeRef;-import org.openremote.model.Function;-import org.openremote.model.asset.AbstractAssetAttributes;-import org.openremote.model.asset.Asset;-import org.openremote.model.asset.agent.ProtocolConfiguration;--import java.util.ArrayList;-import java.util.HashMap;-import java.util.List;-import java.util.Map;--public class ThingAttributes extends AbstractAssetAttributes<ThingAttributes, ThingAttribute> {- public ThingAttributes(String assetId) {- super(assetId);- }-- public ThingAttributes(String assetId, JsonObject jsonObject) {- super(assetId, jsonObject);- }-- public ThingAttributes(ThingAttributes attributes) {- super(attributes);- }-- public ThingAttributes(Asset asset) {- super(asset);- }-- @SuppressWarnings("unchecked")- @Override- public ThingAttributes copy() {- return new ThingAttributes(assetId, Json.parse(getJsonObject().toJson()));- }-- @SuppressWarnings("unchecked")- @Override- protected ThingAttribute createAttribute(String name, JsonObject jsonObject) throws IllegalArgumentException {- return new ThingAttribute(null, assetId, name, jsonObject);- }-}diff --git a/model/src/main/java/org/openremote/model/util/AttributeUtil.java b/model/src/main/java/org/openremote/model/util/AttributeUtil.javanew file mode 100644index 000000000..4b4dcad19--- /dev/null+++ b/model/src/main/java/org/openremote/model/util/AttributeUtil.java@@ -0,0 +1,193 @@+/*+ * Copyright 2017, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.model.util;++import com.google.gwt.regexp.shared.RegExp;+import elemental.json.Json;+import elemental.json.JsonObject;+import elemental.json.JsonValue;+import org.openremote.model.AttributeRef;+import org.openremote.model.Meta;+import org.openremote.model.MetaItem;+import org.openremote.model.asset.AbstractAttributeWrapper;+import org.openremote.model.asset.AttributeWrapperFilter;+import org.openremote.model.asset.AssetAttribute;+import org.openremote.model.asset.AssetMeta;++import java.util.*;+import java.util.stream.Collectors;++import static org.openremote.model.Constants.NAMESPACE;++public class AttributeUtil {+ /**+ * 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_NAME_PATTERN);++ private AttributeUtil() {+ }++ /**+ * Returns only attributes and meta that are not private.+ */+ public static List<AssetAttribute> filterByProtected(List<AssetAttribute> attributes) {+ if (attributes == null) {+ return Collections.emptyList();+ }++ List<AssetAttribute> filteredAttributes = new ArrayList<>(attributes);++ for (AssetAttribute attribute : attributes) {++ if (!attribute.isProtected()) {+ filteredAttributes.remove(attribute);+ continue;+ }++ if (!attribute.hasMeta())+ continue;++ // Any meta item of the attribute, if it's in our namespace, must be protected READ to be included+ Meta protectedMeta = new Meta();+ for (MetaItem metaItem : attribute.getMeta().all()) {+ if (!metaItem.getName().startsWith(NAMESPACE))+ continue;++ AssetMeta wellKnownMeta = AssetMeta.byName(metaItem.getName());+ if (wellKnownMeta != null && wellKnownMeta.getAccess().protectedRead) {+ protectedMeta.add(+ new MetaItem(metaItem.getName(), metaItem.getValue())+ );+ }+ }+ if (protectedMeta.size() > 0)+ attribute.setMeta(protectedMeta);+ }++ return filteredAttributes;+ }++ public static List<AssetAttribute> getAssetAttributesFromJson(String assetId, JsonObject jsonObject) {+ if (jsonObject == null || jsonObject.keys().length == 0) {+ return new ArrayList<>();+ }++ List<AssetAttribute> assetAttributes = new ArrayList<>();+ String[] keys = jsonObject.keys();+ for (String key : keys) {+ assetAttributes.add(new AssetAttribute(assetId, key, jsonObject.getObject(key)));+ }+ return assetAttributes;+ }++ public static JsonObject getAssetAttributesAsJson(List<AssetAttribute> attributes) {+ if (attributes == null) {+ return null;+ }++ JsonObject jsonObject = Json.createObject();+ for (AssetAttribute attribute : attributes) {+ jsonObject.put(attribute.getName(), attribute.getJsonObject());+ }++ return jsonObject;+ }++ public static boolean nameIsValid(String name) {+ return name != null && name.length() > 0 && attributeNamePattern.test(name);+ }+++ /**+ * Filter attributes that contain one or more meta items of the specified asset meta type.+ */+ public static List<AssetAttribute> filterByMeta(List<AssetAttribute> attributes, AssetMeta meta) {+ return filterByMeta(attributes, meta.getName());+ }++ /**+ * Filter attributes that contain one or more meta items with the specified name.+ */+ public static List<AssetAttribute> filterByMeta(List<AssetAttribute> attributes, String metaName) {+ return attributes+ .stream()+ .filter(assetAttribute -> assetAttribute.hasMetaItem(metaName))+ .collect(Collectors.toList());+ }++ /**+ * Filter attributes that contain one or more meta items of the specified asset meta type and with the+ * specified value.+ *+ * Value equality uses {@link JsonUtil#equals(JsonValue, JsonValue)} method.+ */+ public static List<AssetAttribute> filterByMeta(List<AssetAttribute> attributes, AssetMeta meta, JsonValue value) {+ return filterByMeta(attributes, meta.getName(), value);+ }++ /**+ * Filter attributes that contain one or more meta items with the specified name and value.+ *+ * Value equality uses {@link JsonUtil#equals(JsonValue, JsonValue)} method.+ */+ public static List<AssetAttribute> filterByMeta(List<AssetAttribute> attributes, String metaName, JsonValue value) {+ return attributes+ .stream()+ .filter(assetAttribute -> assetAttribute.getMetaItems(metaName, value).size() > 0)+ .collect(Collectors.toList());+ }++ public static boolean contains(List<AssetAttribute> attributes, String attributeName) {+ return attributes.stream().anyMatch(assetAttribute -> assetAttribute.getName().equals(attributeName));+ }++ public static AssetAttribute getAttributeByName(List<AssetAttribute> attributes, String attributeName) {+ if (attributes == null || attributeName == null) {+ return null;+ }++ return attributes+ .stream()+ .filter(assetAttribute -> assetAttribute.getName().equals(attributeName))+ .findFirst()+ .orElse(null);+ }++ public static void remove(List<AssetAttribute> attributes, String name) {+ attributes.removeIf(assetAttribute -> assetAttribute.getName().equals(name));+ }++ public static AttributeRef getAttributeRef(String assetId, String attributeName) {+ return new AttributeRef(assetId, attributeName);+ }++ public static AttributeRef getAttributeRef(String assetId, AbstractAttributeWrapper attributeWrapper) {+ return getAttributeRef(assetId, attributeWrapper.getAttribute().getName());+ }++ public static List<String> getNames(List<AssetAttribute> attributes) {+ return attributes+ .stream()+ .map(attribute -> attribute.getName())+ .collect(Collectors.toList());+ }+}diff --git a/model/src/main/resources/META-INF/services/org.openremote.model.asset.AttributeWrapperFilter b/model/src/main/resources/META-INF/services/org.openremote.model.asset.AttributeWrapperFilternew file mode 100644index 000000000..0b3c9b23e--- /dev/null+++ b/model/src/main/resources/META-INF/services/org.openremote.model.asset.AttributeWrapperFilter@@ -0,0 +1,3 @@+org.openremote.model.asset.agent.ProtocolConfiguration$Filter+org.openremote.model.asset.macro.MacroConfiguration$Filter+org.openremote.model.asset.agent.AgentProtocolLink$Filter\ No newline at end of file