Skip to content

armgit / core

Public Imported from GitHub
0

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

Attribute related functions and NULL attribute type

Rich Turner15ba2c7341c7
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroConfiguration.java b/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroConfiguration.java
index 9443babf6..e6ca3f2d3 100644
--- a/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroConfiguration.java
+++ b/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroConfiguration.java
@@ -33,11 +33,9 @@ import java.util.function.UnaryOperator;
import java.util.stream.IntStream;
import java.util.stream.Stream;
-import static org.openremote.agent3.protocol.macro.MacroAction.MACRO_ACTION;
-import static org.openremote.model.Attribute.*;
+import static org.openremote.model.Attribute.Functions.*;
import static org.openremote.model.AttributeType.STRING;
-import static org.openremote.model.asset.AssetAttribute.hasMetaItem;
-import static org.openremote.model.asset.AssetAttribute.isAssetMetaItem;
+import static org.openremote.model.MetaItem.matches;
/**
* Agent attributes can be macro configurations.
@@ -53,28 +51,28 @@ final public class MacroConfiguration {
public static UnaryOperator<AssetAttribute> initMacroConfiguration() {
return attribute -> {
attribute.setType(AttributeType.STRING);
- attribute.setValue(Json.create(MacroProtocol.MACRO_PROTOCOL_NAME));
+ attribute.setValue(Json.create(MacroProtocol.PROTOCOL_NAME));
return attribute;
};
}
- public static Predicate<Attribute> isMacroConfiguration() {
+ public static <A extends Attribute> Predicate<A> isMacroConfiguration() {
return attribute -> {
String value = attribute.getValueAsString();
- return value != null && value.equals(MacroProtocol.MACRO_PROTOCOL_NAME);
+ return value != null && value.equals(MacroProtocol.PROTOCOL_NAME);
};
}
- public static Predicate<Attribute> isValidMacroConfiguration() {
- return isAttributeValid()
- .and(isAttributeType(STRING))
+ public static <A extends Attribute> Predicate<A> isValidMacroConfiguration() {
+ return (Predicate<A>) isValid()
+ .and(isOfType(STRING))
.and(isMacroConfiguration())
- .and(hasMetaItem(MACRO_ACTION)); // Must have at least one macro action
+ .and(hasMetaItem(MacroAction.MACRO_ACTION)); // Must have at least one macro action
}
public static Function<AssetAttribute, Stream<MacroAction>> getMacroActions() {
return attribute -> attribute.getMetaItemStream()
- .filter(isMetaItem(MACRO_ACTION))
+ .filter(matches(MacroAction.MACRO_ACTION))
.map(MacroAction.getMacroActionFromMetaItem());
}
@@ -89,9 +87,9 @@ final public class MacroConfiguration {
if (!attribute.hasMeta()) {
return attribute;
}
- List<MetaItem> metaItems = attribute.getMeta().all();
+ List<MetaItem> metaItems = attribute.getMeta().getAll();
IntStream.range(0, metaItems.size())
- .filter(i -> isMetaItem(MACRO_ACTION).test(metaItems.get(i)))
+ .filter(i -> matches(MacroAction.MACRO_ACTION).test(metaItems.get(i)))
.filter(i -> JsonUtil.equals(metaItems.get(i).getValueAsObject(), action.asJsonValue()))
.forEach(i -> attribute.getMeta().remove(i));
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.java
index 8153d5ddb..d6bb93d62 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
@@ -50,7 +50,7 @@ import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;
*/
public class MacroProtocol extends AbstractProtocol {
- public static final String MACRO_PROTOCOL_NAME = PROTOCOL_NAMESPACE + ":macro";
+ public static final String PROTOCOL_NAME = PROTOCOL_NAMESPACE + ":macro";
class MacroExecutionTask {
AttributeRef attributeRef;
@@ -141,7 +141,7 @@ public class MacroProtocol extends AbstractProtocol {
@Override
public String getProtocolName() {
- return MACRO_PROTOCOL_NAME;
+ return PROTOCOL_NAME;
}
@Override
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/simulator/SimulatorProtocol.java b/agent/src/main/java/org/openremote/agent3/protocol/simulator/SimulatorProtocol.java
index d56f083e6..8e5d4004f 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
@@ -114,7 +114,7 @@ public class SimulatorProtocol extends AbstractProtocol {
@Override
protected void onAttributeAdded(AssetAttribute attribute, AssetAttribute protocolConfiguration) {
- String elementType = attribute.firstMetaItem(SIMULATOR_ELEMENT)
+ String elementType = attribute.getMetaItem(SIMULATOR_ELEMENT)
.map(AbstractValueHolder::getValueAsString).orElseThrow(
() -> new IllegalArgumentException(
"Can't configure simulator, missing " + SIMULATOR_ELEMENT + " meta item on: " + attribute
@@ -125,7 +125,7 @@ public class SimulatorProtocol extends AbstractProtocol {
Instance instance = instances.get(protocolConfigurationName);
if (instance == null) {
- Mode mode = protocolConfiguration.firstMetaItem(CONFIG_MODE)
+ Mode mode = protocolConfiguration.getMetaItem(CONFIG_MODE)
.map(item -> {
try {
return Mode.valueOf(item.getValueAsString());
@@ -136,7 +136,7 @@ public class SimulatorProtocol extends AbstractProtocol {
})
.orElse(Mode.WRITE_THROUGH_IMMEDIATE);
- int writeDelay = protocolConfiguration.firstMetaItem(CONFIG_WRITE_DELAY_MILLISECONDS)
+ int writeDelay = protocolConfiguration.getMetaItem(CONFIG_WRITE_DELAY_MILLISECONDS)
.map(AbstractValueHolder::getValueAsInteger)
.orElse(DEFAULT_WRITE_DELAY);
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesBrowser.java b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesBrowser.java
index 064885e0f..8ec43882c 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
@@ -254,8 +254,7 @@ public abstract class AttributesBrowser
protected DatapointBrowser createDatapointBrowser(AssetAttribute attribute) {
if (!attribute.isStoreDatapoints())
return null;
- if (!attribute.getType().isPresent()
- || !(attribute.getType().get() == AttributeType.DECIMAL || attribute.getType().get() == AttributeType.INTEGER))
+ if (!(attribute.getType() == AttributeType.DECIMAL || attribute.getType() == AttributeType.INTEGER))
return null;
return new DatapointBrowser(environment.getMessages(), 850, 250) {
@Override
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesEditor.java b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesEditor.java
index c5ea3202f..8a69f7829 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
@@ -212,13 +212,13 @@ public class AttributesEditor
protected void buildItemList() {
itemListPanel.clear();
- if (!attribute.hasMeta() || attribute.getMeta().all().size() == 0) {
+ if (!attribute.hasMeta() || !attribute.getMeta().any()) {
itemListSectionLabel.setVisible(false);
return;
}
itemListSectionLabel.setVisible(true);
- List<MetaItem> items = attribute.getMeta().all();
+ List<MetaItem> items = attribute.getMeta().getAll();
for (int i = 0; i < items.size(); i++) {
MetaItem item = items.get(i);
FormGroup formGroup = new FormGroup();
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.java
index 40a591b86..0a2964fed 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
@@ -207,7 +207,7 @@ public abstract class AttributesView<
S style = container.getStyle();
AttributeEditor attributeEditor;
- AttributeType attributeType = attribute.getType().orElse(AttributeType.STRING);
+ AttributeType attributeType = attribute.getType();
if (attributeType == AttributeType.STRING) {
attributeEditor = createStringEditor(attribute, defaultValueItem, style, formGroup);
} else if (attributeType == AttributeType.INTEGER) {
@@ -226,7 +226,7 @@ public abstract class AttributesView<
FormField unsupportedField = new FormField();
unsupportedField.add(new FormOutputText(
environment.getMessages().unsupportedAttributeType(
- attribute.getType().map(AttributeType::getValue).orElse(null)
+ attribute.getType().getValue()
)
));
return () -> unsupportedField;
@@ -457,7 +457,7 @@ public abstract class AttributesView<
}
protected void removeAttribute(AssetAttribute attribute) {
- Attribute.removeAttribute(attributes, attribute.getName());
+ Attribute.Functions.removeAttribute(attributes, attribute.getName());
editors.remove(attribute.getName());
int attributeGroupIndex = container.getPanel().getWidgetIndex(attributeGroups.get(attribute));
container.getPanel().remove(attributeGroupIndex);
diff --git a/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java
index f43d16109..29cb4df3f 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
@@ -49,7 +49,7 @@ import static org.openremote.agent3.protocol.Protocol.ACTUATOR_TOPIC;
import static org.openremote.container.persistence.PersistenceEvent.PERSISTENCE_TOPIC;
import static org.openremote.manager.server.asset.AssetPredicates.isPersistenceEventForAssetType;
import static org.openremote.manager.server.asset.AssetPredicates.isPersistenceEventForEntityType;
-import static org.openremote.model.asset.AssetAttribute.getAssetAttributesFromJson;
+import static org.openremote.model.asset.AssetAttribute.Functions.getAssetAttributesFromJson;
import static org.openremote.model.asset.AssetType.AGENT;
import static org.openremote.model.asset.agent.AgentLink.*;
import static org.openremote.model.asset.agent.ProtocolConfiguration.getProtocolName;
diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java
index 4aae54054..10b108e97 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
@@ -47,7 +47,7 @@ import java.util.logging.Logger;
import static org.openremote.agent3.protocol.Protocol.SENSOR_QUEUE;
import static org.openremote.manager.server.event.EventService.INCOMING_EVENT_TOPIC;
import static org.openremote.manager.server.event.EventService.getWebsocketAuth;
-import static org.openremote.model.asset.AssetAttribute.*;
+import static org.openremote.model.asset.AssetAttribute.Functions.matches;
import static org.openremote.model.asset.agent.AgentLink.getAgentLink;
import static org.openremote.model.asset.agent.AgentLink.isValidAgentLink;
@@ -266,7 +266,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
return;
// Attribute must exist
- if (!containsAssetAttributeNamed(event.getAttributeName()).test(asset))
+ if (!asset.hasAttribute(event.getAttributeName()))
return;
// Regular users can only write attribute events for assets in their realm
@@ -317,7 +317,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
// Pass attribute event through the processing chain
LOG.fine("Processing " + attributeEvent + " for: " + asset);
- Optional<AssetAttribute> attribute = findAssetAttribute(attributeEvent.getAttributeName()).apply(asset);
+ Optional<AssetAttribute> attribute = asset.getAttribute(attributeEvent.getAttributeName());
if (!attribute.isPresent()) {
LOG.warning("Ignoring " + attributeEvent + ", attribute doesn't exist on asset: " + asset);
@@ -363,7 +363,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
// consider a protocol that receives a batch of messages because a gateway was offline
// for a day)
AssetAttribute attribute = asset.getAttributeStream()
- .filter(isMatchingAttributeEvent(attributeEvent))
+ .filter(matches(attributeEvent))
.filter(isValidAgentLink())
.findFirst()
.orElse(null);
diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java
index 6d53ba027..4c30e366f 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
@@ -40,8 +40,6 @@ import java.util.logging.Logger;
import static javax.ws.rs.core.Response.Status.BAD_REQUEST;
import static javax.ws.rs.core.Response.Status.NOT_FOUND;
-import static org.openremote.model.asset.AssetAttribute.containsAssetAttributeNamed;
-import static org.openremote.model.asset.AssetAttribute.isAssetAttribute;
public class AssetResourceImpl extends ManagerWebResource implements AssetResource {
@@ -246,7 +244,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
}
// Check attribute exists
- if (!containsAssetAttributeNamed(attributeName).test(asset))
+ if (!asset.hasAttribute(attributeName))
throw new WebApplicationException(NOT_FOUND);
// Check realm, must be accessible
@@ -256,7 +254,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
}
// Check read-only
- if (!isSuperUser() && isAssetAttribute(attributeName, AssetAttribute::isReadOnly).test(asset)) {
+ if (!isSuperUser() && asset.hasAttribute(attributeName, AssetAttribute::isReadOnly)) {
throw new WebApplicationException(Response.Status.FORBIDDEN);
}
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.java
index 9dbf9d138..db91ba5f0 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
@@ -34,8 +34,6 @@ import javax.ws.rs.BeanParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
-import static org.openremote.model.asset.AssetAttribute.isAssetAttribute;
-
public class AssetDatapointResourceImpl extends ManagerWebResource implements AssetDatapointResource {
protected final AssetStorageService assetStorageService;
@@ -59,7 +57,7 @@ public class AssetDatapointResourceImpl extends ManagerWebResource implements As
// TODO Security etc.
ServerAsset asset = assetStorageService.find(assetId, true);
- if (!isAssetAttribute(attributeName, AssetAttribute::isStoreDatapoints).test(asset)) {
+ if (!asset.hasAttribute(attributeName, AssetAttribute::isStoreDatapoints)) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java
index f97e295c5..a4e00c393 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
@@ -52,7 +52,7 @@ import java.util.stream.Stream;
import static org.openremote.container.persistence.PersistenceEvent.PERSISTENCE_TOPIC;
import static org.openremote.container.util.MapAccess.getString;
import static org.openremote.manager.server.asset.AssetPredicates.isPersistenceEventForEntityType;
-import static org.openremote.model.asset.AssetAttribute.getAssetAttributesFromJson;
+import static org.openremote.model.asset.AssetAttribute.Functions.getAssetAttributesFromJson;
/**
* Responsible for creating Drools knowledge sessions for the rulesets
diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java
index 9ac5ae4b1..84c3b8ae6 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
@@ -35,7 +35,6 @@ 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;
@@ -48,7 +47,6 @@ import java.util.List;
import java.util.stream.Stream;
import static org.openremote.model.AttributeType.*;
-import static org.openremote.model.asset.AssetAttribute.findAssetAttribute;
import static org.openremote.model.asset.AssetMeta.*;
import static org.openremote.model.asset.AssetType.*;
import static org.openremote.model.asset.agent.ProtocolConfiguration.initProtocolConfiguration;
@@ -255,7 +253,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
thing = assetStorageService.find(thingId, true);
ZonedDateTime now = LocalDateTime.now().atZone(ZoneId.systemDefault());
- AssetAttribute light1PowerConsumptionAttribute = findAssetAttribute("light1PowerConsumption").apply(thing).get();
+ AssetAttribute light1PowerConsumptionAttribute = thing.getAttribute("light1PowerConsumption").get();
assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute));
diff --git a/manager/test/src/test/groovy/org/openremote/test/agent/AgentDeploymentTest.groovy b/manager/test/src/test/groovy/org/openremote/test/agent/AgentDeploymentTest.groovy
index f62d28393..d03c9fca1 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
@@ -4,18 +4,17 @@ import elemental.json.Json
import elemental.json.JsonArray
import elemental.json.JsonType
import org.openremote.agent3.protocol.simulator.SimulatorProtocol
-import org.openremote.manager.server.asset.AssetStorageService
import org.openremote.manager.server.asset.AssetProcessingService
+import org.openremote.manager.server.asset.AssetStorageService
import org.openremote.manager.server.setup.SetupService
import org.openremote.manager.server.setup.builtin.ManagerDemoSetup
import org.openremote.model.AttributeEvent
import org.openremote.model.units.ColorRGB
-
import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
-import static org.openremote.model.Attribute.*
+import static org.openremote.model.Attribute.Functions.getAttribute
class AgentDeploymentTest extends Specification implements ManagerContainerTrait {
@@ -53,7 +52,7 @@ class AgentDeploymentTest extends Specification implements ManagerContainerTrait
assert simulatorProtocol.getState(managerDemoSetup.thingId, "light1Dimmer").asNumber() == 66
def thing = assetStorageService.find(managerDemoSetup.thingId, true)
def attributes = thing.getAttributeStream()
- def attribute = findAttribute("light1Dimmer").apply(attributes)
+ def attribute = getAttribute("light1Dimmer").apply(attributes)
assert attribute.get().getValue().getType() == JsonType.NUMBER
assert attribute.get().getValueAsInteger() == 66
}
@@ -66,7 +65,7 @@ class AgentDeploymentTest extends Specification implements ManagerContainerTrait
conditions.eventually {
def thing = assetStorageService.find(managerDemoSetup.thingId, true)
def attributes = thing.getAttributeStream()
- def attribute = findAttribute("light1Dimmer").apply(attributes)
+ def attribute = getAttribute("light1Dimmer").apply(attributes)
assert attribute.get().getValue().getType() == JsonType.NUMBER
assert attribute.get().getValueAsInteger() == 77
}
diff --git a/manager/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy
index 43f45bafc..fd8bc81df 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
@@ -11,7 +11,7 @@ import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
-import static org.openremote.model.asset.AssetAttribute.findAssetAttribute
+import static org.openremote.model.asset.Asset.getAttribute
class AssetDatapointTest extends Specification implements ManagerContainerTrait {
@@ -45,7 +45,7 @@ class AssetDatapointTest extends Specification implements ManagerContainerTrait
then: "the thing attribute value should be updated and the datapoints stored"
conditions.eventually {
def thing = assetStorageService.find(managerDemoSetup.thingId, true)
- assert findAssetAttribute("light1PowerConsumption").apply(thing).get().getValueAsDecimal() == 15.5d
+ assert thing.getAttribute("light1PowerConsumption").get().getValueAsDecimal() == 15.5d
def datapoints = assetDatapointService.getDatapoints(new AttributeRef(managerDemoSetup.thingId, "light1PowerConsumption"))
datapoints.size() > 3
datapoints.get(0).value.asNumber() == 13.3d
diff --git a/manager/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy
index cc3746fcb..8998ad664 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
@@ -10,7 +10,6 @@ import org.openremote.model.AttributeType
import org.openremote.model.asset.Asset
import org.openremote.model.asset.AssetAttribute
import org.openremote.model.asset.AssetType
-
import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
@@ -21,7 +20,7 @@ import static org.openremote.container.util.MapAccess.getString
import static org.openremote.manager.server.setup.AbstractKeycloakSetup.SETUP_KEYCLOAK_ADMIN_PASSWORD
import static org.openremote.manager.server.setup.AbstractKeycloakSetup.SETUP_KEYCLOAK_ADMIN_PASSWORD_DEFAULT
import static org.openremote.model.Constants.*
-import static org.openremote.model.asset.AssetAttribute.findAssetAttribute
+import static org.openremote.model.asset.Asset.getAttribute
class AssetIntegrityTest extends Specification implements ManagerContainerTrait {
@@ -75,8 +74,8 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTrait
testAsset = assetResource.get(null, testAsset.getId())
then: "the attribute should exist"
- findAssetAttribute("foo").apply(testAsset) != null
- findAssetAttribute("foo").apply(testAsset).get().getValueAsString() == "bar"
+ testAsset.getAttribute("foo") != null
+ testAsset.getAttribute("foo").get().getValueAsString() == "bar"
when: "an asset attribute value is written directly"
assetResource.writeAttributeValue(null, testAsset.getId(), "foo", "\"bar2\"")
@@ -84,7 +83,7 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTrait
then: "the attribute value should match"
new PollingConditions(delay: 1, timeout: 5).eventually {
def asset = assetResource.get(null, testAsset.getId())
- assert findAssetAttribute("foo").apply(asset).get().getValueAsString() == "bar2"
+ assert asset.getAttribute("foo").get().getValueAsString() == "bar2"
}
when: "an asset attribute value null is written directly"
@@ -93,7 +92,7 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTrait
then: "the attribute value should match"
new PollingConditions(delay: 1, timeout: 5).eventually {
def asset = assetResource.get(null, testAsset.getId())
- assert findAssetAttribute("foo").apply(asset).get().hasValue() == false
+ assert asset.getAttribute("foo").get().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.groovy
index 4b2553ade..9c11983b8 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
@@ -11,7 +11,6 @@ import org.openremote.model.Meta
import org.openremote.model.asset.Asset
import org.openremote.model.asset.AssetMeta
import org.openremote.model.asset.AssetType
-
import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
@@ -22,7 +21,6 @@ import static org.openremote.container.util.MapAccess.getString
import static org.openremote.manager.server.setup.AbstractKeycloakSetup.SETUP_KEYCLOAK_ADMIN_PASSWORD
import static org.openremote.manager.server.setup.AbstractKeycloakSetup.SETUP_KEYCLOAK_ADMIN_PASSWORD_DEFAULT
import static org.openremote.model.Constants.*
-import static org.openremote.model.asset.AssetAttribute.findAssetAttribute
class AssetPermissionsTest extends Specification implements ManagerContainerTrait {
@@ -168,7 +166,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
def asset
conditions.eventually {
asset = assetResource.get(null, managerDemoSetup.smartOfficeId)
- assert findAssetAttribute("geoStreet").apply(asset).get().getValue().toJson() == Json.create("Teststreet 123").toJson()
+ assert asset.getAttribute("geoStreet").get().getValue().toJson() == Json.create("Teststreet 123").toJson()
}
when: "an non-existent attribute is written in the authenticated realm"
@@ -191,7 +189,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
then: "result should match"
conditions.eventually {
asset = assetResource.get(null, managerDemoSetup.smartHomeId)
- assert findAssetAttribute("geoStreet").apply(asset).get().getValue().toJson() == Json.create("Teststreet 456").toJson()
+ assert asset.getAttribute("geoStreet").get().getValue().toJson() == Json.create("Teststreet 456").toJson()
}
cleanup: "the server should be stopped"
@@ -340,7 +338,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
def asset
conditions.eventually {
asset = assetResource.get(null, managerDemoSetup.smartOfficeId)
- assert findAssetAttribute("geoStreet").apply(asset).get().getValue().toJson() == Json.create("Teststreet 123").toJson()
+ assert asset.getAttribute("geoStreet").get().getValue().toJson() == Json.create("Teststreet 123").toJson()
}
when: "an asset attribute is written in a foreign realm"
@@ -587,14 +585,14 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
apartment1LivingroomThermostat.name == "Livingroom Thermostat"
def protectedAttributes = apartment1LivingroomThermostat.getAttributeList()
protectedAttributes.size() == 2
- def currentTemperature = findAssetAttribute("currentTemperature").apply(apartment1LivingroomThermostat)
- currentTemperature.get().getType().get() == AttributeType.DECIMAL
+ def currentTemperature = apartment1LivingroomThermostat.getAttribute("currentTemperature")
+ currentTemperature.get().getType() == AttributeType.DECIMAL
currentTemperature.get().getValueAsDecimal() == null
Meta protectedMeta = currentTemperature.get().getMeta()
- protectedMeta.all().size() == 3
- protectedMeta.first(AssetMeta.LABEL).get().getValueAsString() == "Current Temperature"
- protectedMeta.first(AssetMeta.READ_ONLY).get().getValueAsBoolean()
- protectedMeta.first(AssetMeta.RULE_STATE).get().getValueAsBoolean()
+ protectedMeta.getAll().size() == 3
+ protectedMeta.get(AssetMeta.LABEL).get().getValueAsString() == "Current Temperature"
+ protectedMeta.get(AssetMeta.READ_ONLY).get().getValueAsBoolean()
+ protectedMeta.get(AssetMeta.RULE_STATE).get().getValueAsBoolean()
when: "an asset is retrieved by ID in a foreign realm"
assetResource.get(null, managerDemoSetup.thingId)
@@ -666,7 +664,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
then: "result should match"
conditions.eventually {
def asset = assetResource.get(null, managerDemoSetup.apartment1LivingroomThermostatId)
- assert findAssetAttribute("comfortTemperature").apply(asset).get().getValue().toJson() == Json.create(22.123).toJson()
+ assert asset.getAttribute("comfortTemperature").get().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/AssetQueryTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy
index 46e5a4ac3..81266333d 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
@@ -9,19 +9,17 @@ import org.openremote.manager.server.setup.builtin.ManagerDemoSetup
import org.openremote.model.asset.AssetMeta
import org.openremote.model.asset.AssetQuery
import org.openremote.model.asset.AssetType
-
import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
import javax.persistence.EntityManager
import java.util.function.Function
+import static org.openremote.model.asset.Asset.getAttribute
import static org.openremote.model.asset.AssetQuery.*
import static org.openremote.model.asset.AssetQuery.OrderBy.Property.NAME
import static org.openremote.model.asset.AssetType.THING
-import static org.openremote.model.asset.AssetAttribute.*
-
class AssetQueryTest extends Specification implements ManagerContainerTrait {
def "Query assets"() {
@@ -103,7 +101,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
asset.coordinates.length == 2
asset.path.length == 1
asset.path[0] == managerDemoSetup.smartOfficeId
- findAssetAttribute("geoStreet").apply(asset).get().valueAsString == "Torenallee 20"
+ asset.getAttribute("geoStreet").get().valueAsString == "Torenallee 20"
when: "a query is executed"
def assets = assetStorageService.findAll(
@@ -153,7 +151,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
assets.get(0).coordinates.length == 2
assets.get(0).path.length == 1
assets.get(0).path[0] == managerDemoSetup.smartOfficeId
- findAssetAttribute("geoStreet").apply(assets.get(0)).get().valueAsString == "Torenallee 20"
+ assets.get(0).getAttribute("geoStreet").get().valueAsString == "Torenallee 20"
when: "a query is executed"
assets = assetStorageService.findAll(
@@ -251,10 +249,10 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
assets.get(1).id == managerDemoSetup.apartment1LivingroomId
assets.get(2).id == managerDemoSetup.apartment1LivingroomThermostatId
assets.get(2).getAttributeList().size() == 2
- findAssetAttribute("currentTemperature").apply(assets.get(2)).get().valueAsDecimal == null
- findAssetAttribute("currentTemperature").apply(assets.get(2)).get().meta.size() == 3
- findAssetAttribute("comfortTemperature").apply(assets.get(2)).get().valueAsDecimal == null
- findAssetAttribute("comfortTemperature").apply(assets.get(2)).get().meta.size() == 2
+ assets.get(2).getAttribute("currentTemperature").get().valueAsDecimal == null
+ assets.get(2).getAttribute("currentTemperature").get().meta.size() == 3
+ assets.get(2).getAttribute("comfortTemperature").get().valueAsDecimal == null
+ assets.get(2).getAttribute("comfortTemperature").get().meta.size() == 2
assets.get(3).id == managerDemoSetup.apartment2Id
when: "a query is executed"
diff --git a/manager/test/src/test/groovy/org/openremote/test/rules/ApartmentActionsTest.groovy b/manager/test/src/test/groovy/org/openremote/test/rules/ApartmentActionsTest.groovy
index 7f04539d6..c3bf3eb6c 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
@@ -14,7 +14,7 @@ import spock.lang.Specification
import spock.util.concurrent.PollingConditions
import static java.util.concurrent.TimeUnit.*
-import static org.openremote.model.asset.AssetAttribute.findAssetAttribute
+import static org.openremote.model.asset.Asset.getAttribute
class ApartmentActionsTest extends Specification implements ManagerContainerTrait {
@@ -48,7 +48,7 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai
and: "the room lights in an apartment to be on"
def livingRoomAsset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)
- assert findAssetAttribute("lightSwitch").apply(livingRoomAsset).get().valueAsBoolean
+ assert livingRoomAsset.getAttribute("lightSwitch").get().valueAsBoolean
when: "the ALL LIGHTS OFF switch is pressed for an apartment"
def apartment1AllLightsOffChange = new AttributeEvent(
@@ -60,7 +60,7 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai
conditions.eventually {
assert customerAEngine.knowledgeSession.factCount == 10
livingRoomAsset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)
- assert !findAssetAttribute("lightSwitch").apply(livingRoomAsset).get().valueAsBoolean
+ assert !livingRoomAsset.getAttribute("lightSwitch").get().valueAsBoolean
}
when: "time advanced"
@@ -100,11 +100,11 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai
and: "the presence latch of the room should not be set"
def livingRoomAsset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)
- assert !findAssetAttribute("presenceDetected").apply(livingRoomAsset).get().valueAsBoolean
+ assert !livingRoomAsset.getAttribute("presenceDetected").get().valueAsBoolean
and: "the presence latch of the other room should not be set"
def otherLivingRoomAsset = assetStorageService.find(managerDemoSetup.apartment2LivingroomId, true)
- assert !findAssetAttribute("presenceDetected").apply(otherLivingRoomAsset).get().valueAsBoolean
+ assert !otherLivingRoomAsset.getAttribute("presenceDetected").get().valueAsBoolean
and: "several presence sensor events are triggered in the room"
for (i in 0..2) {
@@ -135,13 +135,13 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai
and: "the presence latch of the room should be set"
conditions.eventually {
def asset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)
- assert findAssetAttribute("presenceDetected").apply(asset).get().valueAsBoolean
+ assert asset.getAttribute("presenceDetected").get().valueAsBoolean
}
and: "the presence latch of the other room should NOT be set"
conditions.eventually {
def asset = assetStorageService.find(managerDemoSetup.apartment2LivingroomId, true)
- assert !findAssetAttribute("presenceDetected").apply(asset).get().valueAsBoolean
+ assert !asset.getAttribute("presenceDetected").get().valueAsBoolean
}
when: "time is advanced enough to trigger event expiration"
@@ -193,7 +193,7 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai
then: "that value should be stored"
conditions.eventually {
def asset = assetStorageService.find(managerDemoSetup.apartment1Id, true)
- assert findAssetAttribute("vacationDays").apply(asset).get().valueAsInteger == 5
+ assert asset.getAttribute("vacationDays").get().valueAsInteger == 5
}
when: "time advanced to the next day, which should trigger the cron rule"
@@ -202,7 +202,7 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai
then: "the vacation days should be decremented"
conditions.eventually {
def asset = assetStorageService.find(managerDemoSetup.apartment1Id, true)
- assert findAssetAttribute("vacationDays").apply(asset).get().valueAsInteger == 4
+ assert asset.getAttribute("vacationDays").get().valueAsInteger == 4
}
when: "time advanced again (to test that the rule only fires once per day)"
@@ -211,7 +211,7 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai
then: "the vacation days should NOT be decremented"
new PollingConditions(initialDelay: 2).eventually {
def asset = assetStorageService.find(managerDemoSetup.apartment1Id, true)
- assert findAssetAttribute("vacationDays").apply(asset).get().valueAsInteger == 4
+ assert asset.getAttribute("vacationDays").get().valueAsInteger == 4
}
expect: "the remaining vacation days to be decremented with each passing day"
@@ -224,7 +224,7 @@ class ApartmentActionsTest extends Specification implements ManagerContainerTrai
conditions.eventually {
def asset = assetStorageService.find(managerDemoSetup.apartment1Id, true)
- assert findAssetAttribute("vacationDays").apply(asset).get().valueAsInteger == remainingDays
+ assert asset.getAttribute("vacationDays").get().valueAsInteger == remainingDays
}
}
diff --git a/model/src/main/java/org/openremote/model/Attribute.java b/model/src/main/java/org/openremote/model/Attribute.java
index ea6abe385..b4dc2f4e8 100644
--- a/model/src/main/java/org/openremote/model/Attribute.java
+++ b/model/src/main/java/org/openremote/model/Attribute.java
@@ -24,9 +24,11 @@ import elemental.json.Json;
import elemental.json.JsonObject;
import elemental.json.JsonType;
import elemental.json.JsonValue;
-import org.openremote.model.asset.AssetMeta;
+import org.openremote.model.util.JsonUtil;
+import java.util.Collections;
import java.util.List;
+import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
@@ -38,6 +40,113 @@ import java.util.stream.Stream;
*/
public abstract class Attribute extends AbstractValueTimestampHolder {
+ public static final class Functions {
+
+ private Functions() {}
+
+ public static <A extends Attribute> List<A> removeAttribute(List<A> attributes, String name) {
+ attributes.removeIf(attribute -> attribute.getName().equals(name));
+ return attributes;
+ }
+
+ public static <A extends Attribute> Optional<A> getAttribute(List<A> attributes, String name) {
+ return attributes
+ .stream()
+ .filter(attribute -> attribute.getName().equals(name))
+ .findFirst();
+ }
+
+ public static Function<Stream<? extends Attribute>, Optional<? extends Attribute>> getAttribute(String name) {
+ return attributeStream -> attributeStream
+ .filter(attribute -> attribute.getName().equals(name))
+ .findFirst();
+ }
+
+ public static <A extends Attribute> Function<A, Optional<AttributeRef>> getAttributeLink(String metaName) {
+ return attribute -> attribute.getMetaItem(metaName)
+ .filter(item -> item.getValue().getType() == JsonType.ARRAY)
+ .map(AbstractValueHolder::getValueAsArray)
+ .map(AttributeRef::new);
+ }
+
+ @SuppressWarnings("unchecked")
+ public static <A extends Attribute> UnaryOperator<A> setAttributeLink(String metaName, AttributeRef attributeRef) {
+ return attribute -> {
+ if (attributeRef == null) {
+ throw new IllegalArgumentException(
+ "Attribute reference cannot be null for '" + metaName + "' on: " + attribute
+ );
+ }
+ return (A)attribute.setMeta(
+ attribute.getMeta().replace(metaName, new MetaItem(metaName, attributeRef.asJsonValue()))
+ );
+ };
+ }
+
+ @SuppressWarnings("unchecked")
+ public static <A extends Attribute> UnaryOperator<A> removeAttributeLink(String metaName) {
+ return attribute -> (A)attribute.setMeta(attribute.getMeta().removeAll(metaName));
+ }
+
+ public static <A extends Attribute> Predicate<A> isAttributeLink(String metaName) {
+ return attribute -> getAttributeLink(metaName)
+ .apply(attribute)
+ .isPresent();
+ }
+
+ public static <A extends Attribute> Predicate<A> isValid() {
+ return A::isValid;
+ }
+
+ public static <A extends Attribute> Predicate<A> notValid() {
+ return attribute -> !attribute.isValid();
+ }
+
+ public static <A extends Attribute> Predicate<A> isOfType(AttributeType attributeType) {
+ return attribute -> attribute.getType().equals(attributeType);
+ }
+
+ public static <A extends Attribute> Predicate<A> isValueEqualTo(JsonValue value) {
+ return attribute -> JsonUtil.equals(attribute.getValue(), value);
+ }
+
+ public static <A extends Attribute> Predicate<A> hasMetaItem(String metaName) {
+ return attribute -> attribute.hasMetaItem(metaName);
+ }
+
+ public static <A extends Attribute> Predicate<A> hasMetaItem(String metaName, JsonValue value) {
+ return attribute -> attribute.hasMetaItem(metaName, value);
+ }
+
+ public static <A extends Attribute, T extends JsonValue> Predicate<A> hasMetaItem(String metaName, Class<T> clazz) {
+ return attribute -> attribute.hasMetaItem(metaName, clazz);
+ }
+
+ public static <A extends Attribute> Function<A, Optional<MetaItem>> getMetaItem(String metaName) {
+ return attribute -> attribute.getMetaItem(metaName);
+ }
+
+ public static <A extends Attribute> Function<A, Optional<MetaItem>> getMetaItem(String metaName, JsonValue value) {
+ return attribute -> attribute.getMetaItem(metaName, value);
+ }
+
+ public static <A extends Attribute, T extends JsonValue> Function<A, Optional<MetaItem>> getMetaItem(String metaName, Class<T> clazz) {
+ return attribute -> attribute.getMetaItem(metaName, clazz);
+ }
+
+ public static <A extends Attribute> Function<A, List<MetaItem>> getMetaItems(String metaName) {
+ return attribute -> attribute.getMetaItems(metaName);
+ }
+
+ public static <A extends Attribute> Function<A, List<MetaItem>> getMetaItems(String metaName, JsonValue value) {
+ return attribute -> attribute.getMetaItems(metaName, value);
+ }
+
+ public static <A extends Attribute, T extends JsonValue> Function<A, List<MetaItem>> getMetaItems(String metaName, Class<T> clazz) {
+ return attribute -> attribute.getMetaItems(metaName, clazz);
+ }
+ }
+
/**
* Attribute names should be very simple, as we use them in SQL path
* expressions, etc. and must manually escape.
@@ -73,14 +182,12 @@ public abstract class Attribute extends AbstractValueTimestampHolder {
}
protected Attribute(Attribute attribute) {
- this(attribute.getName(), attribute.getType().orElse(null), attribute.getJsonObject());
+ this(attribute.getName(), attribute.getType(), attribute.getJsonObject());
}
@Override
protected boolean isValidValue(JsonValue value) {
- return getType().isPresent()
- ? getType().get().isValid(value)
- : super.isValidValue(value);
+ return getType().isValid(value);
}
public void setName(String name) {
@@ -95,16 +202,25 @@ public abstract class Attribute extends AbstractValueTimestampHolder {
return jsonObject;
}
- public Optional<AttributeType> getType() {
+ public AttributeType getType() {
String typeName = jsonObject.hasKey(TYPE_FIELD_NAME) ? jsonObject.get(TYPE_FIELD_NAME).asString() : null;
- return Optional.ofNullable(typeName != null ? AttributeType.fromValue(typeName) : null);
+ return typeName != null ? AttributeType.fromValue(typeName) : AttributeType.NULL;
}
- @SuppressWarnings("unchecked")
public void setType(AttributeType type) {
- if (type != null) {
- jsonObject.put(TYPE_FIELD_NAME, Json.create(type.getValue()));
+ if (type == null) {
+ type = AttributeType.NULL;
+ }
+
+ if (getType() == type) {
+ return;
}
+
+ jsonObject.put(TYPE_FIELD_NAME, Json.create(type.getValue()));
+
+ // Remove the old value and timestamp
+ jsonObject.remove(VALUE_TIMESTAMP_FIELD_NAME);
+ setValueUnchecked(Json.createNull());
}
public boolean hasMeta() {
@@ -115,10 +231,6 @@ public abstract class Attribute extends AbstractValueTimestampHolder {
return hasMeta() ? new Meta(jsonObject.getArray(META_FIELD_NAME)) : new Meta();
}
- public Stream<MetaItem> getMetaItemStream() {
- return getMeta().stream();
- }
-
@SuppressWarnings("unchecked")
public Attribute setMeta(Meta meta) {
if (meta != null) {
@@ -129,74 +241,164 @@ public abstract class Attribute extends AbstractValueTimestampHolder {
return this;
}
- public Optional<MetaItem> firstMetaItem(String name) {
- return getMeta().first(name);
+ public Stream<MetaItem> getMetaItemStream() {
+ return getMeta().stream();
}
- @Override
- public boolean isValid() {
- return super.isValid() && ATTRIBUTE_NAME_VALIDATOR.test(name) && getType().isPresent();
+ public List<MetaItem> getMetaItems(String name) {
+ return hasMeta() ? getMeta().getAll(name) : Collections.emptyList();
}
- public static Predicate<Attribute> isAttributeValid() {
- return Attribute::isValid;
+ public List<MetaItem> getMetaItems(String name, JsonValue value) {
+ return hasMeta() ? getMeta().getAll(name, value) : Collections.emptyList();
}
- public static Predicate<Attribute> isAttributeType(AttributeType attributeType) {
- return attribute -> attribute.getType().map(at -> at.equals(attributeType)).orElse(false);
+ public <T extends JsonValue> List<MetaItem> getMetaItems(String name, Class<T> clazz) {
+ return hasMeta() ? getMeta().getAll(name, clazz) : Collections.emptyList();
}
- public static Predicate<Attribute> hasMetaItem(String name) {
- return attribute -> attribute.firstMetaItem(name).isPresent();
+ public List<MetaItem> getMetaItems(Predicate<MetaItem> filter) {
+ return hasMeta() ? getMeta().getAll(filter) : Collections.emptyList();
}
- public static Predicate<MetaItem> isMetaItem(String name) {
- return metaItem -> metaItem.getName().equals(name);
+ public Optional<MetaItem> getMetaItem(int index) {
+ return hasMeta() ? getMeta().get(index) : Optional.empty();
}
- public static Function<Stream<? extends Attribute>, Optional<? extends Attribute>> findAttribute(String name) {
- return attributeStream -> attributeStream
- .filter(attribute -> attribute.getName().equals(name))
- .findFirst();
+ public Optional<MetaItem> getMetaItem(String name) {
+ return hasMeta() ? getMeta().get(name) : Optional.empty();
}
- public static Predicate<Stream<? extends Attribute>> containsAttributeNamed(String name) {
- return attributeStream -> findAttribute(name).apply(attributeStream).isPresent();
+ public Optional<MetaItem> getMetaItem(String name, int startIndex) {
+ return hasMeta() ? getMeta().get(name, startIndex) : Optional.empty();
}
- public static Function<Attribute, Optional<AttributeRef>> getAttributeLink(String metaName) {
- return attribute -> attribute.firstMetaItem(metaName)
- .filter(item -> item.getValue().getType() == JsonType.ARRAY)
- .map(AbstractValueHolder::getValueAsArray)
- .map(AttributeRef::new);
+ public Optional<MetaItem> getMetaItem(String name, JsonValue value) {
+ return hasMeta() ? getMeta().get(name, value) : Optional.empty();
}
- public static void removeAttribute(List<? extends Attribute> attributes, String name) {
- attributes.removeIf(attribute -> attribute.getName().equals(name));
+ public Optional<MetaItem> getMetaItem(String name, JsonValue value, int startIndex) {
+ return hasMeta() ? getMeta().get(name, value, startIndex) : Optional.empty();
}
- public static <A extends Attribute> Optional<A> findAttribute(List<A> attributes, String name) {
- for (A attribute : attributes) {
- if (attribute.getName().equals(name))
- return Optional.of(attribute);
+ public <T extends JsonValue> Optional<MetaItem> getMetaItem(String name, Class<T> clazz) {
+ return hasMeta() ? getMeta().get(name, clazz) : Optional.empty();
+ }
+
+ public <T extends JsonValue> Optional<MetaItem> getMetaItem(String name, Class<T> clazz, int startIndex) {
+ return hasMeta() ? getMeta().get(name, clazz, startIndex) : Optional.empty();
+ }
+
+ public MetaItem getMetaItemOrThrow(int index) throws NoSuchElementException {
+ MetaItem item = getMetaItem(index).orElse(null);
+
+ if (item == null) {
+ throw new NoSuchElementException("Missing item: " + index);
}
- return Optional.empty();
+
+ return item;
}
- public static UnaryOperator<Attribute> setAttributeLink(String metaName, AttributeRef attributeRef) {
- return attribute -> {
- if (attributeRef == null) {
- throw new IllegalArgumentException(
- "Attribute reference cannot be null for '" + metaName + "' on: " + attribute
- );
- }
- return attribute.setMeta(
- attribute.getMeta().replace(metaName, new MetaItem(metaName, attributeRef.asJsonValue()))
- );
- };
+ public MetaItem getMetaItemOrThrow(MetaItem item) throws NoSuchElementException {
+ return getMetaItemOrThrow(item.getName(), item.getValue(), 0);
+ }
+
+ public MetaItem getMetaItemOrThrow(MetaItem item, int startIndex) throws NoSuchElementException {
+ return getMetaItemOrThrow(item.getName(), item.getValue(), startIndex);
+ }
+
+ public MetaItem getMetaItemOrThrow(String name) throws NoSuchElementException {
+ return getMetaItemOrThrow(name, 0);
+ }
+
+ public MetaItem getMetaItemOrThrow(String name, int startIndex) throws NoSuchElementException {
+ MetaItem item = getMetaItem(name, startIndex).orElse(null);
+
+ if (item == null) {
+ throw new NoSuchElementException("Missing item: " + name);
+ }
+
+ return item;
+ }
+
+ public MetaItem getMetaItemOrThrow(String name, JsonValue value) throws NoSuchElementException {
+ return getMetaItemOrThrow(name, value, 0);
+ }
+
+ public MetaItem getMetaItemOrThrow(String name, JsonValue value, int startIndex) throws NoSuchElementException {
+ MetaItem item = getMetaItem(name, value, startIndex).orElse(null);
+
+ if (item == null) {
+ throw new NoSuchElementException("Missing item: " + name);
+ }
+
+ return item;
+ }
+
+ public <T extends JsonValue> MetaItem getMetaItemOrThrow(String name, Class<T> clazz) throws NoSuchElementException {
+ return getMetaItemOrThrow(name, clazz, 0);
+ }
+
+ public <T extends JsonValue> MetaItem getMetaItemOrThrow(String name, Class<T> clazz, int startIndex) throws NoSuchElementException {
+ MetaItem item = getMetaItem(name, clazz, startIndex).orElse(null);
+
+ if (item == null) {
+ throw new NoSuchElementException("Missing item: " + name);
+ }
+
+ return item;
+ }
+
+ public boolean hasMetaItem(MetaItem item) {
+ return hasMeta() && getMeta().contains(item);
+ }
+
+ public boolean hasMetaItem(String name) {
+ return hasMeta() && getMeta().contains(name);
+ }
+
+ public boolean hasMetaItem(String name, JsonValue value) {
+ return hasMeta() && getMeta().contains(name, value);
+ }
+
+ public <T extends JsonValue> boolean hasMetaItem(String name, Class<T> clazz) {
+ return hasMeta() && getMeta().contains(name, clazz);
+ }
+
+ public int indexOfMetaItem(MetaItem item) {
+ return indexOfMetaItem(item, 0);
+ }
+
+ public int indexOfMetaItem(MetaItem item, int startIndex) {
+ return hasMeta() ? getMeta().indexOf(item) : -1;
}
- public static UnaryOperator<Attribute> removeAttributeLink(String metaName) {
- return attribute -> attribute.setMeta(attribute.getMeta().removeAll(metaName));
+ public int indexOfMetaItem(String name) {
+ return indexOfMetaItem(name, 0);
+ }
+
+ public int indexOfMetaItem(String name, int startIndex) {
+ return hasMeta() ? getMeta().indexOf(name) : -1;
+ }
+
+ public int indexOfMetaItem(String name, JsonValue value) {
+ return indexOfMetaItem(name, value, 0);
+ }
+
+ public int indexOfMetaItem(String name, JsonValue value, int startIndex) {
+ return hasMeta() ? getMeta().indexOf(name, value, startIndex) : -1;
+ }
+
+ public <T extends JsonValue> int indexOfMetaItem(String name, Class<T> clazz) {
+ return indexOfMetaItem(name, clazz, 0);
+ }
+
+ public <T extends JsonValue> int indexOfMetaItem(String name, Class<T> clazz, int startIndex) {
+ return hasMeta() ? getMeta().indexOf(name, clazz, startIndex) : -1;
+ }
+
+ @Override
+ public boolean isValid() {
+ return super.isValid() && ATTRIBUTE_NAME_VALIDATOR.test(name) && getValue() != null && (getValue().getType() == JsonType.NULL || getValue().getType() == getType().getJsonType());
}
}
diff --git a/model/src/main/java/org/openremote/model/AttributeRef.java b/model/src/main/java/org/openremote/model/AttributeRef.java
index 0932b5a83..7a48e6917 100644
--- a/model/src/main/java/org/openremote/model/AttributeRef.java
+++ b/model/src/main/java/org/openremote/model/AttributeRef.java
@@ -21,6 +21,10 @@ package org.openremote.model;
import elemental.json.Json;
import elemental.json.JsonArray;
+import elemental.json.JsonType;
+
+import java.util.function.Function;
+import java.util.function.Predicate;
/**
* A reference to an entity and an {@link Attribute}.
@@ -85,4 +89,21 @@ public class AttributeRef {
", attributeName='" + attributeName + '\'' +
'}';
}
+
+ public static final <T extends AbstractValueHolder> Predicate<T> isAttributeRef() {
+ return abstractValueHolder -> {
+ return abstractValueHolder != null
+ && abstractValueHolder.getValue() != null
+ && abstractValueHolder.getValue().getType() == JsonType.ARRAY
+ && abstractValueHolder.getValueAsArray().length() == 2;
+ };
+ }
+
+ public static final Function<AbstractValueHolder, AttributeRef> getAttributeRef() {
+ return abstractValueHolder ->
+ isAttributeRef()
+ .test(abstractValueHolder)
+ ? new AttributeRef(abstractValueHolder.getValueAsArray())
+ : null;
+ }
}
diff --git a/model/src/main/java/org/openremote/model/AttributeType.java b/model/src/main/java/org/openremote/model/AttributeType.java
index d497b0018..4fb3ca34b 100644
--- a/model/src/main/java/org/openremote/model/AttributeType.java
+++ b/model/src/main/java/org/openremote/model/AttributeType.java
@@ -32,6 +32,7 @@ import elemental.json.JsonValue;
*/
public enum AttributeType {
+ NULL("Null", JsonType.NULL),
STRING("String", JsonType.STRING),
OBJECT("Object", JsonType.OBJECT),
INTEGER("Integer", JsonType.NUMBER),
diff --git a/model/src/main/java/org/openremote/model/Meta.java b/model/src/main/java/org/openremote/model/Meta.java
index 83c586964..d55668994 100644
--- a/model/src/main/java/org/openremote/model/Meta.java
+++ b/model/src/main/java/org/openremote/model/Meta.java
@@ -57,25 +57,36 @@ public class Meta {
return getJsonArray().length();
}
- public List<MetaItem> all() {
- return get((Predicate<MetaItem>) null);
+ public Stream<MetaItem> stream() {
+ return getAll().stream();
}
- public Stream<MetaItem> stream() {
- return all().stream();
+ public boolean any() {
+ return size() == 0;
+ }
+
+ public List<MetaItem> getAll() {
+ return getAll((Predicate<MetaItem>) null);
}
- public List<MetaItem> get(String name) {
- return get(
+ public List<MetaItem> getAll(String name) {
+ return getAll(
item -> item.getName().equals(name)
);
}
- public List<MetaItem> get(String name, JsonValue value) {
- return get(metaItem -> metaItem.getName().equals(name) && JsonUtil.equals(metaItem.getValue(), value));
+ public List<MetaItem> getAll(String name, JsonValue value) {
+ return getAll(metaItem -> metaItem.getName().equals(name) && JsonUtil.equals(metaItem.getValue(), value));
}
- public List<MetaItem> get(Predicate<MetaItem> filter) {
+ public <T extends JsonValue> List<MetaItem> getAll(String name, Class<T> clazz) {
+ return getAll(
+ item -> item.getName().equals(name)
+ && item.getValue() != null
+ && item.getValue().getClass().getSuperclass() == clazz);
+ }
+
+ public List<MetaItem> getAll(Predicate<MetaItem> filter) {
List<MetaItem> list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JsonObject jsonObject = jsonArray.getObject(i);
@@ -91,36 +102,148 @@ public class Meta {
public Optional<MetaItem> get(int index) {
return Optional.ofNullable(
- index > 0 && index < jsonArray.length()
+ index >= 0 && index < jsonArray.length()
? new MetaItem(jsonArray.getObject(index))
: null
);
}
- public Optional<MetaItem> first(AssetMeta assetMeta) {
- return first(assetMeta.getUrn());
+ public Optional<MetaItem> get(String name) {
+ return get(name, 0);
+ }
+
+ public Optional<MetaItem> get(String name, int startIndex) {
+ int index = indexOf(name, startIndex);
+ if (index >= 0) {
+ return get(index);
+ }
+
+ return Optional.empty();
+ }
+
+ public Optional<MetaItem> get(String name, JsonValue value) {
+ return get(name, value, 0);
+ }
+
+ public Optional<MetaItem> get(String name, JsonValue value, int startIndex) {
+ int index = indexOf(name, value, startIndex);
+ if (index >= 0) {
+ return get(index);
+ }
+
+ return Optional.empty();
+ }
+
+ public <T extends JsonValue> Optional<MetaItem> get(String name, Class<T> clazz) {
+ return get(name, clazz, 0);
+ }
+
+ public <T extends JsonValue> Optional<MetaItem> get(String name, Class<T> clazz, int startIndex) {
+ int index = indexOf(name, clazz, startIndex);
+ if (index >= 0) {
+ return get(index);
+ }
+
+ return Optional.empty();
+ }
+
+ public Optional<MetaItem> get(AssetMeta meta) {
+ return get(meta.getUrn(), 0);
+ }
+
+ public Optional<MetaItem> get(AssetMeta meta, int startIndex) {
+ return get(meta.getUrn(), startIndex);
+ }
+
+ public Optional<MetaItem> get(AssetMeta meta, JsonValue value) {
+ return get(meta.getUrn(), value, 0);
+ }
+
+ public Optional<MetaItem> get(AssetMeta meta, JsonValue value, int startIndex) {
+ return get(meta.getUrn(), value, startIndex);
}
- public Optional<MetaItem> first(String name) {
- return all().stream().filter(item -> item.getName().equals(name)).findFirst();
+ public <T extends JsonValue> Optional<MetaItem> get(AssetMeta meta, Class<T> clazz) {
+ return get(meta.getUrn(), clazz, 0);
}
- public boolean contains(AssetMeta assetMeta) {
- return contains(assetMeta.getUrn());
+ public <T extends JsonValue> Optional<MetaItem> get(AssetMeta meta, Class<T> clazz, int startIndex) {
+ return get(meta.getUrn(), clazz, startIndex);
+ }
+
+ public boolean contains(MetaItem item) {
+ return contains(item.getName(), item.getValue());
}
public boolean contains(String name) {
- return first(name) != null;
+ return get(name) != null;
+ }
+
+ public <T extends JsonValue> boolean contains(String name, Class<T> clazz) {
+ return indexOf(name, clazz) >= 0;
+ }
+
+ public boolean contains(String name, JsonValue value) {
+ return indexOf(name, value) >= 0;
+ }
+
+ public boolean contains(AssetMeta meta) {
+ return get(meta.getUrn()) != null;
+ }
+
+ public <T extends JsonValue> boolean contains(AssetMeta meta, Class<T> clazz) {
+ return indexOf(meta.getUrn(), clazz) >= 0;
+ }
+
+ public boolean contains(AssetMeta meta, JsonValue value) {
+ return indexOf(meta.getUrn(), value) >= 0;
+ }
+
+ public int indexOf(MetaItem item) {
+ return indexOf(item.getName(), item.getValue(), 0);
+ }
+
+ public int indexOf(MetaItem item, int startIndex) {
+ return indexOf(item.getName(), item.getValue(), startIndex);
+ }
+
+ public int indexOf(String name) {
+ return indexOf(name, 0);
+ }
+
+ public int indexOf(String name, int startIndex) {
+ List<MetaItem> list = getAll();
+ for (int i = startIndex; i < list.size(); i++) {
+ MetaItem item = list.get(i);
+ if (MetaItem.matches(name).test(item))
+ return i;
+ }
+ return -1;
+ }
+
+ public <T extends JsonValue> int indexOf(String name, Class<T> clazz) {
+ return indexOf(name, clazz, 0);
+ }
+
+ public <T extends JsonValue> int indexOf(String name, Class<T> clazz, int startIndex) {
+ List<MetaItem> list = getAll();
+ for (int i = startIndex; i < list.size(); i++) {
+ MetaItem item = list.get(i);
+ if (MetaItem.matches(name, clazz).test(item))
+ return i;
+ }
+ return -1;
}
- public int firstIndexOf(MetaItem item) {
- return firstIndexOf(item, 0);
+ public <T extends JsonValue> int indexOf(String name, JsonValue value) {
+ return indexOf(name, value, 0);
}
- public int firstIndexOf(MetaItem item, int startIndex) {
- List<MetaItem> list = all();
+ public <T extends JsonValue> int indexOf(String name, JsonValue value, int startIndex) {
+ List<MetaItem> list = getAll();
for (int i = startIndex; i < list.size(); i++) {
- if (list.get(i).getName().equals(item.getName()))
+ MetaItem item = list.get(i);
+ if (MetaItem.matches(name, value).test(item))
return i;
}
return -1;
@@ -131,8 +254,8 @@ public class Meta {
return this;
}
- public Meta removeAll(AssetMeta assetMeta) {
- return removeAll(assetMeta.getUrn());
+ public Meta removeAll(AssetMeta meta) {
+ return removeAll(meta.getUrn());
}
public Meta removeAll(String name) {
diff --git a/model/src/main/java/org/openremote/model/MetaItem.java b/model/src/main/java/org/openremote/model/MetaItem.java
index 3ded7786b..c5315bdde 100644
--- a/model/src/main/java/org/openremote/model/MetaItem.java
+++ b/model/src/main/java/org/openremote/model/MetaItem.java
@@ -23,6 +23,9 @@ import elemental.json.Json;
import elemental.json.JsonObject;
import elemental.json.JsonValue;
import org.openremote.model.asset.AssetMeta;
+import org.openremote.model.util.JsonUtil;
+
+import java.util.function.Predicate;
/**
* A named arbitrary {@link JsonValue}.
@@ -77,4 +80,20 @@ public class MetaItem extends AbstractValueHolder {
public boolean isValid() {
return getName() != null && getName().length() > 0 && hasValue();
}
+
+ public static Predicate<MetaItem> matches(MetaItem item) {
+ return matches(item.getName(), item.getValue());
+ }
+
+ public static Predicate<MetaItem> matches(String name) {
+ return item -> item.getName().equals(name);
+ }
+
+ public static Predicate<MetaItem> matches(String name, JsonValue value) {
+ return item -> item.getName().equals(name) && item.getValue() != null && JsonUtil.equals(item.getValue(), value);
+ }
+
+ public static <T extends JsonValue> Predicate<MetaItem> matches(String name, Class<T> clazz) {
+ return item -> item.getName().equals(name) && item.getValue() != null && item.getValue().getClass().getSuperclass() == clazz;
+ }
}
diff --git a/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java b/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java
index b064d9eb2..23d4f4236 100644
--- a/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java
+++ b/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java
@@ -227,7 +227,7 @@ public abstract class AbstractAssetUpdate {
}
public AttributeType getAttributeType() {
- return attribute.getType().orElse(null);
+ return attribute.getType();
}
public AttributeEvent getStateEvent() {
diff --git a/model/src/main/java/org/openremote/model/asset/Asset.java b/model/src/main/java/org/openremote/model/asset/Asset.java
index 43dc60f28..00f4d7ebf 100644
--- a/model/src/main/java/org/openremote/model/asset/Asset.java
+++ b/model/src/main/java/org/openremote/model/asset/Asset.java
@@ -20,7 +20,9 @@
package org.openremote.model.asset;
import elemental.json.JsonObject;
+import elemental.json.JsonValue;
import org.hibernate.annotations.Formula;
+import org.openremote.model.AttributeType;
import org.openremote.model.IdentifiableEntity;
import org.openremote.model.geo.GeoJSON;
import org.openremote.model.geo.GeoJSONFeature;
@@ -32,16 +34,15 @@ import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.math.BigDecimal;
import java.math.RoundingMode;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.List;
+import java.util.*;
+import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
+import static org.openremote.model.Attribute.Functions.isValueEqualTo;
import static org.openremote.model.Constants.PERSISTENCE_JSON_OBJECT_TYPE;
import static org.openremote.model.Constants.PERSISTENCE_UNIQUE_ID_GENERATOR;
-import static org.openremote.model.asset.AssetAttribute.*;
+import static org.openremote.model.asset.AssetAttribute.Functions.*;
// @formatter:off
/**
@@ -546,6 +547,31 @@ public class Asset implements IdentifiableEntity {
}
}
+ public Optional<AssetAttribute> getAttribute(String name) {
+ return getFromJson(id, name).apply(getAttributes());
+ }
+
+ public boolean hasAttribute(String name) {
+ return getAttribute(name).isPresent();
+ }
+
+ public boolean hasAttribute(String name, AttributeType type) {
+ Optional<AssetAttribute> attribute = getAttribute(name);
+ return attribute.isPresent() && attribute.get().getType() == type;
+ }
+
+ public boolean hasAttribute(String name, JsonValue value) {
+ return getAttribute(name)
+ .map(isValueEqualTo(value)::test)
+ .orElse(false);
+ }
+
+ public boolean hasAttribute(String name, Predicate<AssetAttribute> predicate) {
+ return getAttribute(name)
+ .map(predicate::test)
+ .orElse(false);
+ }
+
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
@@ -573,4 +599,4 @@ public class Asset implements IdentifiableEntity {
", attributes=" + attributes +
'}';
}
-}
+}
\ No newline at end of file
diff --git a/model/src/main/java/org/openremote/model/asset/AssetAttribute.java b/model/src/main/java/org/openremote/model/asset/AssetAttribute.java
index 3b05c2a27..5b7324247 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetAttribute.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetAttribute.java
@@ -32,14 +32,159 @@ import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.openremote.model.Constants.NAMESPACE;
+import static org.openremote.model.asset.AssetAttribute.Functions.removeAllMetaItem;
+import static org.openremote.model.asset.AssetAttribute.Functions.replaceMetaItem;
import static org.openremote.model.asset.AssetMeta.*;
public class AssetAttribute extends Attribute {
+ public static final class Functions {
+
+ private Functions() {}
+
+ public static <A extends Attribute> Predicate<A> hasMetaItem(AssetMeta assetMeta) {
+ return Attribute.Functions.hasMetaItem(assetMeta.getUrn());
+ }
+
+ public static Predicate<AssetAttribute> hasMetaItem(AssetMeta assetMeta, JsonValue value) {
+ return Attribute.Functions.hasMetaItem(assetMeta.getUrn(), value);
+ }
+
+ public static <T extends JsonValue> Predicate<AssetAttribute> hasMetaItem(AssetMeta assetMeta, Class<T> clazz) {
+ return Attribute.Functions.hasMetaItem(assetMeta.getUrn(), clazz);
+ }
+
+ public static Function<AssetAttribute, Optional<MetaItem>> getMetaItem(AssetMeta meta) {
+ return Attribute.Functions.getMetaItem(meta.getUrn());
+ }
+
+ public static <T extends JsonValue> Function<AssetAttribute, Optional<MetaItem>> getMetaItem(AssetMeta assetMeta, Class<T> clazz) {
+ return Attribute.Functions.getMetaItem(assetMeta.getUrn(), clazz);
+ }
+
+ public static Function<AssetAttribute, Optional<MetaItem>> getMetaItem(AssetMeta assetMeta, JsonValue value) {
+ return Attribute.Functions.getMetaItem(assetMeta.getUrn(), value);
+ }
+
+ public static Function<AssetAttribute, Optional<AttributeRef>> getAttributeLink(AssetMeta meta) {
+ return Attribute.Functions.getAttributeLink(meta.getUrn());
+ }
+
+ public static <T extends Attribute> Predicate<T> isAttributeLink(AssetMeta meta) {
+ return Attribute.Functions.isAttributeLink(meta.getUrn());
+ }
+
+ public static Function<AssetAttribute, AssetAttribute> setAttributeLink(AssetMeta meta, AttributeRef attributeRef) {
+ return Attribute.Functions.setAttributeLink(meta.getUrn(), attributeRef);
+ }
+
+ public static Function<AssetAttribute, AssetAttribute> removeAttributeLink(AssetMeta meta) {
+ return Attribute.Functions.removeAttributeLink(meta.getUrn());
+ }
+
+ public static Function<AssetAttribute, AssetAttribute> replaceMetaItem(AssetMeta meta, MetaItem item) {
+ return attribute -> attribute.setMeta(
+ attribute.getMeta().replace(meta.getUrn(), item)
+ );
+ }
+
+ public static Function<AssetAttribute, AssetAttribute> removeAllMetaItem(AssetMeta meta) {
+ return attribute -> attribute.setMeta(
+ attribute.getMeta().removeAll(meta.getUrn())
+ );
+ }
+
+ public static Predicate<AssetAttribute> matches(AttributeEvent event) {
+ return attribute -> attribute.getAssetId().map(assetId -> assetId.equals(event.getEntityId())).orElse(false)
+ && attribute.getName().equals(event.getAttributeName());
+ }
+
+ /**
+ * Returns either an attribute with protected-only meta items, or <code>null</code> if
+ * the attribute is private.
+ */
+ public static Function<Stream<AssetAttribute>, Stream<AssetAttribute>> filterProtectedAssetAttribute() {
+ return attributeStream ->
+ attributeStream
+ .filter(AssetAttribute::isProtected)
+ .filter(Attribute::hasMeta)
+ .map(attribute -> {
+ // 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().getAll()) {
+ if (!metaItem.getName().startsWith(NAMESPACE))
+ continue;
+ boolean protectedRead =
+ AssetMeta.byUrn(metaItem.getName()).map(meta -> meta.getAccess().protectedRead).orElse(false);
+ if (protectedRead) {
+ protectedMeta.add(
+ new MetaItem(metaItem.getName(), metaItem.getValue())
+ );
+ }
+ }
+ if (protectedMeta.size() > 0)
+ attribute.setMeta(protectedMeta);
+
+ return attribute;
+ });
+ }
+
+ public static Function<JsonObject, Optional<AssetAttribute>> getFromJson(String assetId, String attributeName) {
+ return jsonObject -> {
+ if (jsonObject == null || jsonObject.keys().length == 0 || !jsonObject.hasKey(attributeName)) {
+ return Optional.empty();
+ }
+ return Optional.of(new AssetAttribute(assetId, attributeName, jsonObject.getObject(attributeName)));
+ };
+ }
+
+ public static Function<JsonObject, Optional<AssetAttribute>> getFromJson(String assetId, String attributeName, AttributeType type) {
+ return jsonObject -> {
+ if (jsonObject == null || jsonObject.keys().length == 0 || !jsonObject.hasKey(attributeName)) {
+ return Optional.empty();
+ }
+ AssetAttribute attribute = new AssetAttribute(assetId, attributeName, jsonObject.getObject(attributeName));
+ return attribute.getType() == type ? Optional.of((attribute)) : Optional.empty();
+ };
+ }
+
+ public static Function<JsonObject, Stream<AssetAttribute>> getAssetAttributesFromJson(String assetId) {
+ return jsonObject -> {
+ if (jsonObject == null || jsonObject.keys().length == 0) {
+ return Stream.empty();
+ }
+ Stream.Builder<AssetAttribute> sb = Stream.builder();
+ String[] keys = jsonObject.keys();
+ for (String key : keys) {
+ sb.add(new AssetAttribute(assetId, key, jsonObject.getObject(key)));
+ }
+ return sb.build();
+ };
+ }
+
+ /**
+ * Maps the attribute stream to a {@link JsonObject}, duplicate attribute names are not
+ * allowed (internally this is a hash map in Elemental, thus not allowing duplicate
+ * JSON object property names).
+ */
+ public static Function<Stream<AssetAttribute>, Optional<JsonObject>> getAssetAttributesAsJson() {
+ return attributeStream -> {
+ List<AssetAttribute> list = attributeStream.collect(Collectors.toList());
+ if (list.size() == 0)
+ return Optional.empty();
+ JsonObject jsonObject = Json.createObject();
+ for (AssetAttribute attribute : list) {
+ jsonObject.put(attribute.getName(), attribute.getJsonObject());
+ }
+ return Optional.of(jsonObject);
+ };
+ }
+ }
+
final protected Optional<String> assetId;
public static AssetAttribute createEmpty() {
- return new AssetAttribute(null, Json.createObject());
+ return new AssetAttribute(null, AttributeType.NULL, Json.createNull());
}
public AssetAttribute(String name) {
@@ -115,7 +260,7 @@ public class AssetAttribute extends Attribute {
}
public Optional<MetaItem> firstMetaItem(AssetMeta assetMeta) {
- return firstMetaItem(assetMeta.getUrn());
+ return getMetaItem(assetMeta.getUrn());
}
public String getLabel() {
@@ -123,9 +268,7 @@ public class AssetAttribute extends Attribute {
}
public AssetAttribute setLabel(String label) {
- return setMeta(
- getMeta().replace(AssetMeta.LABEL, new MetaItem(AssetMeta.LABEL, Json.create(label)))
- );
+ return replaceMetaItem(AssetMeta.LABEL, new MetaItem(AssetMeta.LABEL, Json.create(label))).apply(this);
}
public boolean isExecutable() {
@@ -134,14 +277,13 @@ public class AssetAttribute extends Attribute {
public AssetAttribute setExecutable(boolean executable) {
if (executable) {
- return setMeta(
- getMeta()
- .replace(EXECUTABLE, new MetaItem(EXECUTABLE, Json.create(true)))
- );
+ return replaceMetaItem(
+ AssetMeta.EXECUTABLE,
+ new MetaItem(AssetMeta.EXECUTABLE, Json.create(true))
+ ).apply(this);
} else {
- return setMeta(
- getMeta().removeAll(EXECUTABLE)
- );
+ return removeAllMetaItem(EXECUTABLE)
+ .apply(this);
}
}
@@ -194,103 +336,7 @@ public class AssetAttribute extends Attribute {
return firstMetaItem(RULE_EVENT_EXPIRES).map(AbstractValueHolder::getValueAsString);
}
- public static Predicate<Attribute> hasMetaItem(AssetMeta assetMeta) {
- return hasMetaItem(assetMeta.getUrn());
- }
-
- public static Predicate<MetaItem> isAssetMetaItem(AssetMeta assetMeta) {
- return isMetaItem(assetMeta.getUrn());
- }
-
- public static Function<Asset, Optional<AssetAttribute>> findAssetAttribute(String name) {
- return asset -> getAssetAttributeFromJson(asset.getId(), name).apply(asset.getAttributes());
- }
-
- public static Predicate<Asset> containsAssetAttributeNamed(String name) {
- return asset -> findAssetAttribute(name).apply(asset).isPresent();
- }
-
- public static Predicate<Asset> isAssetAttribute(String name, Predicate<AssetAttribute> predicate) {
- return asset -> {
- Optional<AssetAttribute> attribute = findAssetAttribute(name).apply(asset);
- return attribute.isPresent() && predicate.test(attribute.get());
- };
- }
-
- public static Predicate<AssetAttribute> isMatchingAttributeEvent(AttributeEvent event) {
- return attribute -> attribute.getAssetId().map(assetId -> assetId.equals(event.getEntityId())).orElse(false)
- && attribute.getName().equals(event.getAttributeName());
- }
-
- /**
- * Returns either an attribute with protected-only meta items, or <code>null</code> if
- * the attribute is private.
- */
- public static Function<Stream<AssetAttribute>, Stream<AssetAttribute>> filterProtectedAssetAttribute() {
- return attributeStream ->
- attributeStream
- .filter(AssetAttribute::isProtected)
- .filter(Attribute::hasMeta)
- .map(attribute -> {
- // 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;
- boolean protectedRead =
- AssetMeta.byUrn(metaItem.getName()).map(meta -> meta.getAccess().protectedRead).orElse(false);
- if (protectedRead) {
- protectedMeta.add(
- new MetaItem(metaItem.getName(), metaItem.getValue())
- );
- }
- }
- if (protectedMeta.size() > 0)
- attribute.setMeta(protectedMeta);
-
- return attribute;
- });
- }
-
- public static Function<JsonObject, Stream<AssetAttribute>> getAssetAttributesFromJson(String assetId) {
- return jsonObject -> {
- if (jsonObject == null || jsonObject.keys().length == 0) {
- return Stream.empty();
- }
- Stream.Builder<AssetAttribute> sb = Stream.builder();
- String[] keys = jsonObject.keys();
- for (String key : keys) {
- sb.add(new AssetAttribute(assetId, key, jsonObject.getObject(key)));
- }
- return sb.build();
- };
+ public boolean isAgentLinked() {
+ return Functions.hasMetaItem(AGENT_LINK).test(this);
}
-
- public static Function<JsonObject, Optional<AssetAttribute>> getAssetAttributeFromJson(String assetId, String attributeName) {
- return jsonObject -> {
- if (jsonObject == null || jsonObject.keys().length == 0 || !jsonObject.hasKey(attributeName)) {
- return Optional.empty();
- }
- return Optional.of(new AssetAttribute(assetId, attributeName, jsonObject.getObject(attributeName)));
- };
- }
-
- /**
- * Maps the attribute stream to a {@link JsonObject}, duplicate attribute names are not
- * allowed (internally this is a hash map in Elemental, thus not allowing duplicate
- * JSON object property names).
- */
- public static Function<Stream<AssetAttribute>, Optional<JsonObject>> getAssetAttributesAsJson() {
- return attributeStream -> {
- List<AssetAttribute> list = attributeStream.collect(Collectors.toList());
- if (list.size() == 0)
- return Optional.empty();
- JsonObject jsonObject = Json.createObject();
- for (AssetAttribute attribute : list) {
- jsonObject.put(attribute.getName(), attribute.getJsonObject());
- }
- return Optional.of(jsonObject);
- };
- }
-
}
diff --git a/model/src/main/java/org/openremote/model/asset/agent/AgentLink.java b/model/src/main/java/org/openremote/model/asset/agent/AgentLink.java
index 2d9ede455..6436f07ea 100644
--- a/model/src/main/java/org/openremote/model/asset/agent/AgentLink.java
+++ b/model/src/main/java/org/openremote/model/asset/agent/AgentLink.java
@@ -21,13 +21,15 @@ package org.openremote.model.asset.agent;
import org.openremote.model.Attribute;
import org.openremote.model.AttributeRef;
+import org.openremote.model.asset.AssetAttribute;
import org.openremote.model.asset.AssetMeta;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
-import static org.openremote.model.Attribute.*;
+import static org.openremote.model.Attribute.Functions.isValid;
+import static org.openremote.model.asset.AssetAttribute.Functions.*;
import static org.openremote.model.asset.AssetMeta.AGENT_LINK;
/**
@@ -44,23 +46,25 @@ final public class AgentLink {
private AgentLink() {
}
- public static Predicate<Attribute> isAgentLink() {
- return attribute -> getAgentLink().apply(attribute) != null;
+ public static <A extends Attribute> Predicate<A> isAgentLink() {
+ return attribute -> getAgentLink().apply(attribute).isPresent();
}
- public static Predicate<Attribute> isValidAgentLink() {
- return isAttributeValid().and(isAgentLink());
+ @SuppressWarnings("unchecked")
+ public static <A extends Attribute> Predicate<A> isValidAgentLink() {
+ return (Predicate<A>) isValid().and(isAgentLink());
}
- public static Function<Attribute, Optional<AttributeRef>> getAgentLink() {
- return getAttributeLink(AGENT_LINK.getUrn());
+ @SuppressWarnings("unchecked")
+ public static <A extends Attribute> Function<A, Optional<AttributeRef>> getAgentLink() {
+ return (Function<A, Optional<AttributeRef>>) getAttributeLink(AGENT_LINK);
}
- public static Function<Attribute, Attribute> setAgentLink(AttributeRef protocolConfigurationRef) {
- return setAttributeLink(AGENT_LINK.getUrn(), protocolConfigurationRef);
+ public static Function<AssetAttribute, AssetAttribute> setAgentLink(AttributeRef protocolConfigurationRef) {
+ return setAttributeLink(AGENT_LINK, protocolConfigurationRef);
}
- public static Function<Attribute, Attribute> removeAgentLink() {
- return removeAttributeLink(AGENT_LINK.getUrn());
+ public static Function<AssetAttribute, AssetAttribute> removeAgentLink() {
+ return removeAttributeLink(AGENT_LINK);
}
}
diff --git a/model/src/main/java/org/openremote/model/asset/agent/ProtocolConfiguration.java b/model/src/main/java/org/openremote/model/asset/agent/ProtocolConfiguration.java
index b09a41917..e4f9da742 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
@@ -31,9 +31,9 @@ import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
-import static org.openremote.model.Attribute.isAttributeType;
+import static org.openremote.model.Attribute.Functions.isOfType;
+import static org.openremote.model.Attribute.Functions.isValid;
import static org.openremote.model.AttributeType.STRING;
-import static org.openremote.model.asset.AssetAttribute.isAttributeValid;
/**
* Agent attributes can be named protocol configurations.
@@ -59,13 +59,14 @@ final public class ProtocolConfiguration {
};
}
- public static Predicate<Attribute> isProtocolConfiguration() {
+ public static <A extends Attribute> Predicate<A> isProtocolConfiguration() {
return attribute -> isProtocolUrn().test(attribute.getValueAsString());
}
- public static Predicate<Attribute> isValidProtocolConfiguration() {
- return isAttributeValid()
- .and(isAttributeType(STRING))
+ @SuppressWarnings("unchecked")
+ public static <A extends Attribute> Predicate<A> isValidProtocolConfiguration() {
+ return (Predicate<A>) isValid()
+ .and(isOfType(STRING))
.and(isProtocolConfiguration());
}