Skip to content

armgit / core

Public Imported from GitHub
0

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

Introduced Optional to reduce NPEs

Christian Bauer9214f497f73d
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroAction.java b/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroAction.java
index e95186205..b8a619a72 100644
--- a/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroAction.java
+++ b/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroAction.java
@@ -36,6 +36,7 @@ import static org.openremote.model.Constants.ASSET_META_NAMESPACE;
public class MacroAction {
public static final String MACRO_ACTION = ASSET_META_NAMESPACE + ":macroAction";
+
protected AttributeState attributeState;
protected int delayMilliseconds;
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 bb72c690d..9443babf6 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
@@ -29,13 +29,14 @@ import org.openremote.model.util.JsonUtil;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
+import java.util.function.UnaryOperator;
import java.util.stream.IntStream;
import java.util.stream.Stream;
-import static org.openremote.model.Attribute.isAttributeType;
-import static org.openremote.model.Attribute.isAttributeValid;
+import static org.openremote.agent3.protocol.macro.MacroAction.MACRO_ACTION;
+import static org.openremote.model.Attribute.*;
import static org.openremote.model.AttributeType.STRING;
-import static org.openremote.model.asset.AssetAttribute.hasAssetMetaItem;
+import static org.openremote.model.asset.AssetAttribute.hasMetaItem;
import static org.openremote.model.asset.AssetAttribute.isAssetMetaItem;
/**
@@ -49,7 +50,7 @@ final public class MacroConfiguration {
private MacroConfiguration() {
}
- public static Function<AssetAttribute, AssetAttribute> initMacroConfiguration() {
+ public static UnaryOperator<AssetAttribute> initMacroConfiguration() {
return attribute -> {
attribute.setType(AttributeType.STRING);
attribute.setValue(Json.create(MacroProtocol.MACRO_PROTOCOL_NAME));
@@ -68,29 +69,29 @@ final public class MacroConfiguration {
return isAttributeValid()
.and(isAttributeType(STRING))
.and(isMacroConfiguration())
- .and(hasAssetMetaItem(MacroAction.MACRO_ACTION)); // Must have at least one macro action
+ .and(hasMetaItem(MACRO_ACTION)); // Must have at least one macro action
}
public static Function<AssetAttribute, Stream<MacroAction>> getMacroActions() {
return attribute -> attribute.getMetaItemStream()
- .filter(isAssetMetaItem(MacroAction.MACRO_ACTION))
+ .filter(isMetaItem(MACRO_ACTION))
.map(MacroAction.getMacroActionFromMetaItem());
}
- public static Function<AssetAttribute, AssetAttribute> addMacroAction(MacroAction action) {
+ public static UnaryOperator<AssetAttribute> addMacroAction(MacroAction action) {
return attribute -> attribute.setMeta(
attribute.getMeta().add(MacroAction.getMetaItemFromMacroAction().apply(action))
);
}
- public static Function<AssetAttribute, AssetAttribute> removeMacroAction(MacroAction action) {
+ public static UnaryOperator<AssetAttribute> removeMacroAction(MacroAction action) {
return attribute -> {
if (!attribute.hasMeta()) {
return attribute;
}
List<MetaItem> metaItems = attribute.getMeta().all();
IntStream.range(0, metaItems.size())
- .filter(i -> isAssetMetaItem(MacroAction.MACRO_ACTION).test(metaItems.get(i)))
+ .filter(i -> isMetaItem(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/simulator/SimulatorProtocol.java b/agent/src/main/java/org/openremote/agent3/protocol/simulator/SimulatorProtocol.java
index 03eba1d53..d56f083e6 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,10 +22,10 @@ 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.AbstractValueHolder;
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 java.util.HashMap;
@@ -113,29 +113,32 @@ public class SimulatorProtocol extends AbstractProtocol {
}
@Override
- protected void onAttributeAdded(AssetAttribute attribute, AssetAttribute protocolConfiguration) {
- String elementType = attribute.firstMetaItemOrThrow(SIMULATOR_ELEMENT).getValueAsString();
+ protected void onAttributeAdded(AssetAttribute attribute, AssetAttribute protocolConfiguration) {
+ String elementType = attribute.firstMetaItem(SIMULATOR_ELEMENT)
+ .map(AbstractValueHolder::getValueAsString).orElseThrow(
+ () -> new IllegalArgumentException(
+ "Can't configure simulator, missing " + SIMULATOR_ELEMENT + " meta item on: " + attribute
+ )
+ );
String protocolConfigurationName = protocolConfiguration.getName();
Instance instance = instances.get(protocolConfigurationName);
if (instance == null) {
- MetaItem configModeMeta = protocolConfiguration.firstMetaItem(CONFIG_MODE);
- MetaItem configDelayMeta = protocolConfiguration.firstMetaItem(CONFIG_WRITE_DELAY_MILLISECONDS);
-
- Mode mode = Mode.WRITE_THROUGH_IMMEDIATE;
- if (configModeMeta != null) {
- try {
- mode = Mode.valueOf(configModeMeta.getValueAsString());
- } catch (Exception e) {
- LOG.fine("Invalid Mode value '" + configModeMeta.getValueAsString() + "' provided");
- }
- }
-
- int writeDelay = DEFAULT_WRITE_DELAY;
- if (configDelayMeta != null) {
- writeDelay = configDelayMeta.getValueAsInteger();
- }
+ Mode mode = protocolConfiguration.firstMetaItem(CONFIG_MODE)
+ .map(item -> {
+ try {
+ return Mode.valueOf(item.getValueAsString());
+ } catch (Exception e) {
+ LOG.fine("Invalid Mode value '" + item + "' provided");
+ return null;
+ }
+ })
+ .orElse(Mode.WRITE_THROUGH_IMMEDIATE);
+
+ int writeDelay = protocolConfiguration.firstMetaItem(CONFIG_WRITE_DELAY_MILLISECONDS)
+ .map(AbstractValueHolder::getValueAsInteger)
+ .orElse(DEFAULT_WRITE_DELAY);
instance = new Instance(mode, writeDelay);
instances.put(protocolConfigurationName, instance);
@@ -154,12 +157,12 @@ public class SimulatorProtocol extends AbstractProtocol {
}
@Override
- protected void onAttributeUpdated(AssetAttribute attribute, AssetAttribute protocolConfiguration) {
+ protected void onAttributeUpdated(AssetAttribute attribute, AssetAttribute protocolConfiguration) {
onAttributeAdded(attribute, protocolConfiguration);
}
@Override
- protected void onAttributeRemoved(AssetAttribute attribute, AssetAttribute protocolConfiguration) {
+ protected void onAttributeRemoved(AssetAttribute attribute, AssetAttribute protocolConfiguration) {
elements.remove(attribute.getReference());
attributeInstanceMap.remove(attribute.getReference());
}
@@ -285,10 +288,8 @@ public class SimulatorProtocol extends AbstractProtocol {
case DecimalSimulatorElement.ELEMENT_NAME:
return new DecimalSimulatorElement();
case IntegerSimulatorElement.ELEMENT_NAME_RANGE:
- MetaItem minItem = attribute.firstMetaItem(RANGE_MIN);
- MetaItem maxItem = attribute.firstMetaItem(RANGE_MAX);
- double min = minItem != null ? minItem.getValueAsInteger() : 0;
- double max = maxItem != null ? maxItem.getValueAsInteger() : 100;
+ double min = attribute.firstMetaItem(RANGE_MIN).map(AbstractValueHolder::getValueAsInteger).orElse(0);
+ double max = attribute.firstMetaItem(RANGE_MAX).map(AbstractValueHolder::getValueAsInteger).orElse(100);
return new IntegerSimulatorElement(min, max);
case ColorSimulatorElement.ELEMENT_NAME:
return new ColorSimulatorElement();
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditActivity.java b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditActivity.java
index 068a5f727..a2505f375 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
@@ -39,10 +39,11 @@ import org.openremote.model.event.bus.EventBus;
import org.openremote.model.event.bus.EventRegistration;
import javax.inject.Inject;
-import java.util.Arrays;
+import java.util.ArrayList;
import java.util.Collection;
import java.util.function.Consumer;
+import static java.util.stream.Collectors.toCollection;
import static org.openremote.manager.client.http.RequestExceptionHandler.handleRequestException;
public class AssetEditActivity
@@ -331,7 +332,7 @@ public class AssetEditActivity
environment,
view.getAttributesEditorContainer(),
assetId == null
- ? Arrays.asList(asset.getWellKnownType().getDefaultAttributes())
+ ? asset.getWellKnownType().getDefaultAttributes().collect(toCollection(ArrayList::new))
: asset.getAttributeList(),
assetId == 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.java
index 034f5db9d..064885e0f 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
@@ -201,8 +201,10 @@ public abstract class AttributesBrowser
}
protected void readAttributeValue(AssetAttribute attribute) {
- environment.getEventService().dispatch(
- new ReadAttributesEvent(attribute.getAssetId(), attribute.getName())
+ attribute.getAssetId().ifPresent(assetId ->
+ environment.getEventService().dispatch(
+ new ReadAttributesEvent(assetId, attribute.getName())
+ )
);
}
@@ -252,7 +254,8 @@ public abstract class AttributesBrowser
protected DatapointBrowser createDatapointBrowser(AssetAttribute attribute) {
if (!attribute.isStoreDatapoints())
return null;
- if (!(attribute.getType() == AttributeType.DECIMAL || attribute.getType() == AttributeType.INTEGER))
+ if (!attribute.getType().isPresent()
+ || !(attribute.getType().get() == AttributeType.DECIMAL || attribute.getType().get() == 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 9c4244b04..289e371b1 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
@@ -37,6 +37,7 @@ import org.openremote.model.asset.AssetAttribute;
import org.openremote.model.asset.AssetMeta;
import java.util.List;
+import java.util.Optional;
import java.util.function.Consumer;
import static org.openremote.model.Attribute.ATTRIBUTE_NAME_VALIDATOR;
@@ -73,8 +74,8 @@ public class AttributesEditor
}
@Override
- protected String getAttributeDescription(AssetAttribute attribute) {
- return null;
+ protected Optional<String> getAttributeDescription(AssetAttribute attribute) {
+ return Optional.empty();
}
@Override
@@ -322,7 +323,7 @@ public class AttributesEditor
formGroup.setError(false);
item.setValueAsString(value);
} : null;
- editor = createStringEditorWidget(style, currentValue, null, updateConsumer);
+ editor = createStringEditorWidget(style, currentValue, Optional.empty(), updateConsumer);
} else if (valueType.equals(JsonType.NUMBER)) {
String currentValue = item.getValueAsString();
Consumer<String> updateConsumer = isEditable == null || isEditable || forceEditable ? value -> {
@@ -330,14 +331,14 @@ public class AttributesEditor
formGroup.setError(false);
item.setValueAsDecimal(decimalValue);
} : null;
- editor = createDecimalEditorWidget(style, currentValue, null, updateConsumer, errorConsumer);
+ editor = createDecimalEditorWidget(style, currentValue, Optional.empty(), updateConsumer, errorConsumer);
} else if (valueType.equals(JsonType.BOOLEAN)) {
Boolean currentValue = item.getValueAsBoolean();
Consumer<Boolean> updateConsumer = isEditable == null || isEditable || forceEditable ? value -> {
formGroup.setError(false);
- item.setValueAsBoolean(value);
+ item.setValueUnchecked(Json.create(value));
} : null;
- editor = createBooleanEditorWidget(style, currentValue, null, updateConsumer);
+ editor = createBooleanEditorWidget(style, currentValue, Optional.empty(), updateConsumer);
} else {
FormField unsupportedField = new FormField();
unsupportedField.add(new FormOutputText(
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 8e3f08916..522ac7ec4 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,10 +32,7 @@ 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.Attribute;
-import org.openremote.model.AttributeType;
-import org.openremote.model.Constants;
-import org.openremote.model.MetaItem;
+import org.openremote.model.*;
import org.openremote.model.asset.AssetAttribute;
import org.openremote.model.asset.AssetMeta;
import org.openremote.model.util.TextUtil;
@@ -165,10 +162,8 @@ public abstract class AttributesView<
FormLabel formLabel = createAttributeLabel(attribute);
formGroup.addFormLabel(formLabel);
- String description = getAttributeDescription(attribute);
- if (description != null) {
- formGroup.addInfolabel(new Label(description));
- }
+ Optional<String> description = getAttributeDescription(attribute);
+ description.ifPresent(s -> formGroup.addInfolabel(new Label(s)));
FormGroupActions formGroupActions = new FormGroupActions();
@@ -203,22 +198,23 @@ public abstract class AttributesView<
return attribute.getLabel();
}
- protected String getAttributeDescription(AssetAttribute attribute) {
+ protected Optional<String> getAttributeDescription(AssetAttribute attribute) {
return attribute.getDescription();
}
protected AttributeEditor createEditor(AssetAttribute attribute, FormGroup formGroup) {
- MetaItem defaultValueItem = attribute.firstMetaItem(AssetMeta.DEFAULT);
+ Optional<MetaItem> defaultValueItem = attribute.firstMetaItem(AssetMeta.DEFAULT);
S style = container.getStyle();
AttributeEditor attributeEditor;
- if (attribute.getType().equals(AttributeType.STRING)) {
+ AttributeType attributeType = attribute.getType().orElse(AttributeType.STRING);
+ if (attributeType == AttributeType.STRING) {
attributeEditor = createStringEditor(attribute, defaultValueItem, style, formGroup);
- } else if (attribute.getType().equals(AttributeType.INTEGER)) {
+ } else if (attributeType == AttributeType.INTEGER) {
attributeEditor = createIntegerEditor(attribute, defaultValueItem, style, formGroup);
- } else if (attribute.getType().equals(AttributeType.DECIMAL)) {
+ } else if (attributeType == AttributeType.DECIMAL) {
attributeEditor = createDecimalEditor(attribute, defaultValueItem, style, formGroup);
- } else if (attribute.getType().equals(AttributeType.BOOLEAN)) {
+ } else if (attributeType == AttributeType.BOOLEAN) {
attributeEditor = createBooleanEditor(attribute, defaultValueItem, style, formGroup);
} else {
return null;
@@ -229,14 +225,16 @@ public abstract class AttributesView<
protected AttributeEditor createUnsupportedEditor(AssetAttribute attribute) {
FormField unsupportedField = new FormField();
unsupportedField.add(new FormOutputText(
- environment.getMessages().unsupportedAttributeType(attribute.getType().getValue())
+ environment.getMessages().unsupportedAttributeType(
+ attribute.getType().map(AttributeType::getValue).orElse(null)
+ )
));
return () -> unsupportedField;
}
- protected AttributeEditor createStringEditor(AssetAttribute attribute, MetaItem defaultValueItem, S style, FormGroup formGroup) {
+ protected AttributeEditor createStringEditor(AssetAttribute attribute, Optional<MetaItem> defaultValueItem, S style, FormGroup formGroup) {
String currentValue = attribute.getValueAsString();
- String defaultValue = defaultValueItem != null ? defaultValueItem.getValueAsString() : null;
+ Optional<String> defaultValue = defaultValueItem.map(AbstractValueHolder::getValueAsString);
Consumer<String> updateConsumer = isReadOnly(attribute) ? null : value -> {
formGroup.setError(false);
@@ -257,15 +255,13 @@ public abstract class AttributesView<
protected FormInputText createStringEditorWidget(S style,
String currentValue,
- String defaultValue,
+ Optional<String> defaultValue,
Consumer<String> updateConsumer) {
FormInputText input = createFormInputText(style.stringEditor());
if (currentValue != null) {
input.setValue(currentValue);
- } else if ((defaultValue) != null) {
- input.setValue(defaultValue);
- }
+ } else defaultValue.ifPresent(input::setValue);
if (updateConsumer != null) {
input.addValueChangeHandler(
@@ -281,9 +277,9 @@ public abstract class AttributesView<
return input;
}
- protected AttributeEditor createIntegerEditor(AssetAttribute attribute, MetaItem defaultValueItem, S style, FormGroup formGroup) {
+ protected AttributeEditor createIntegerEditor(AssetAttribute attribute, Optional<MetaItem> defaultValueItem, S style, FormGroup formGroup) {
String currentValue = attribute.getValueAsString();
- String defaultValue = defaultValueItem != null ? defaultValueItem.getValueAsString() : null;
+ Optional<String> defaultValue = defaultValueItem.map(AbstractValueHolder::getValueAsString);
Consumer<String> updateConsumer = isReadOnly(attribute) ? null : value -> {
Integer intValue = Integer.valueOf(value);
formGroup.setError(false);
@@ -309,16 +305,14 @@ public abstract class AttributesView<
protected FormInputNumber createIntegerEditorWidget(S style,
String currentValue,
- String defaultValue,
+ Optional<String> defaultValue,
Consumer<String> updateConsumer,
Consumer<String> errorConsumer) {
FormInputNumber input = createFormInputNumber(style.integerEditor());
if (currentValue != null) {
input.setValue(currentValue);
- } else if (defaultValue != null) {
- input.setValue(defaultValue);
- }
+ } else defaultValue.ifPresent(input::setValue);
if (updateConsumer != null) {
input.addValueChangeHandler(event -> {
@@ -338,9 +332,9 @@ public abstract class AttributesView<
return input;
}
- protected AttributeEditor createDecimalEditor(AssetAttribute attribute, MetaItem defaultValueItem, S style, FormGroup formGroup) {
+ protected AttributeEditor createDecimalEditor(AssetAttribute attribute, Optional<MetaItem> defaultValueItem, S style, FormGroup formGroup) {
String currentValue = attribute.getValueAsString();
- String defaultValue = defaultValueItem != null ? defaultValueItem.getValueAsString() : null;
+ Optional<String> defaultValue = defaultValueItem.map(AbstractValueHolder::getValueAsString);
Consumer<String> updateConsumer = isReadOnly(attribute) ? null : value -> {
Double decimalValue = Double.valueOf(value);
formGroup.setError(false);
@@ -366,16 +360,14 @@ public abstract class AttributesView<
protected FormInputText createDecimalEditorWidget(S style,
String currentValue,
- String defaultValue,
+ Optional<String> defaultValue,
Consumer<String> updateConsumer,
Consumer<String> errorConsumer) {
FormInputText input = createFormInputText(style.decimalEditor());
if (currentValue != null) {
input.setValue(currentValue);
- } else if (defaultValue != null) {
- input.setValue(defaultValue);
- }
+ } else defaultValue.ifPresent(input::setValue);
if (updateConsumer != null) {
input.addValueChangeHandler(event -> {
@@ -395,9 +387,9 @@ public abstract class AttributesView<
return input;
}
- protected AttributeEditor createBooleanEditor(AssetAttribute attribute, MetaItem defaultValueItem, S style, FormGroup formGroup) {
+ protected AttributeEditor createBooleanEditor(AssetAttribute attribute, Optional<MetaItem> defaultValueItem, S style, FormGroup formGroup) {
Boolean currentValue = attribute.getValueAsBoolean();
- Boolean defaultValue = defaultValueItem != null ? defaultValueItem.getValueAsBoolean() : null;
+ Optional<Boolean> defaultValue = defaultValueItem.map(AbstractValueHolder::getValueAsBoolean);
Consumer<Boolean> updateConsumer = isReadOnly(attribute) ? null : value -> {
formGroup.setError(false);
attribute.setValueUnchecked(Json.create(value));
@@ -417,15 +409,15 @@ public abstract class AttributesView<
protected FormCheckBox createBooleanEditorWidget(S style,
Boolean currentValue,
- Boolean defaultValue,
+ Optional<Boolean> defaultValue,
Consumer<Boolean> updateConsumer) {
FormCheckBox input = createFormInputCheckBox(style.booleanEditor());
Boolean value = null;
if (currentValue != null) {
value = currentValue;
- } else if (defaultValue != null) {
- value = defaultValue;
+ } else if (defaultValue.isPresent()) {
+ value = defaultValue.get();
}
input.setValue(value);
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.java
index 20c383873..5de6a04e8 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
@@ -33,7 +33,6 @@ import org.openremote.manager.client.mvp.AppActivity;
import org.openremote.manager.shared.asset.AssetResource;
import org.openremote.manager.shared.map.MapResource;
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.asset.Asset;
@@ -191,7 +190,7 @@ public class MapActivity extends AssetBrowsingActivity<MapPlace> implements MapV
protected void showAssetInfoItems() {
List<Pair<String, String>> infoItems = dashboardAttributes.stream()
- .map(attribute -> new Pair<>(attribute.getLabel(), format(attribute.getFormat(), attribute.getValueAsString())))
+ .map(attribute -> new Pair<>(attribute.getLabel(), format(attribute.getFormat().orElse(null), attribute.getValueAsString())))
.sorted(Comparator.comparing(pair -> pair.key))
.collect(Collectors.toList());
if (asset.hasGeoFeature()) {
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 0f5c5fe91..f43d16109 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
@@ -32,8 +32,8 @@ import org.openremote.manager.server.asset.ServerAsset;
import org.openremote.manager.server.datapoint.AssetDatapointService;
import org.openremote.model.AbstractValueTimestampHolder;
import org.openremote.model.AttributeRef;
+import org.openremote.model.Pair;
import org.openremote.model.asset.*;
-import org.openremote.model.asset.agent.AgentLink;
import org.openremote.model.util.JsonUtil;
import java.util.*;
@@ -66,11 +66,14 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons
protected AssetDatapointService assetDatapointService;
protected MessageBrokerService messageBrokerService;
protected final Map<AttributeRef, AssetAttribute> protocolConfigurations = new HashMap<>();
- protected Function<AttributeRef, AssetAttribute> protocolConfigurationResolver = (AttributeRef protocolRef) -> {
- synchronized (protocolConfigurations) {
- return protocolConfigurations.get(protocolRef);
- }
- };
+ protected Function<Optional<AttributeRef>, Optional<AssetAttribute>> protocolConfigurationResolver =
+ (Optional<AttributeRef> protocolRef) -> {
+ synchronized (protocolConfigurations) {
+ return Optional.ofNullable(
+ protocolRef.isPresent() ? protocolConfigurations.get(protocolRef.get()) : null
+ );
+ }
+ };
@Override
public void init(Container container) throws Exception {
@@ -150,12 +153,12 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons
getAssetAttributesFromJson(agent.getId()).apply(
(JsonObject) persistenceEvent.getPreviousState()[attributesIndex]
).filter(isProtocolConfiguration())
- .collect(Collectors.toList());
+ .collect(Collectors.toList());
List<AssetAttribute> newProtocolConfigurations =
getAssetAttributesFromJson(agent.getId()).apply(
(JsonObject) persistenceEvent.getCurrentState()[attributesIndex]
).filter(isProtocolConfiguration())
- .collect(Collectors.toList());
+ .collect(Collectors.toList());
// Compare protocol configurations by JSON value
// Unlink protocols that are in oldConfigs but not in newConfigs
@@ -210,7 +213,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons
// Link any AGENT_LINK attributes to the referenced protocol
Map<AssetAttribute, List<AssetAttribute>> groupedAgentLinksAttributes =
- getGroupedAgentLinkAttributes(asset.getAttributeStream(), null);
+ getGroupedAgentLinkAttributes(asset.getAttributeStream(), attribute -> true);
groupedAgentLinksAttributes.forEach(this::linkAttributes);
break;
@@ -228,12 +231,12 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons
getAssetAttributesFromJson(asset.getId()).apply(
(JsonObject) persistenceEvent.getPreviousState()[attributesIndex]
).filter(isAgentLink())
- .collect(Collectors.toList());
+ .collect(Collectors.toList());
List<AssetAttribute> newAgentLinkedAttributes =
getAssetAttributesFromJson(asset.getId()).apply(
(JsonObject) persistenceEvent.getCurrentState()[attributesIndex]
).filter(isAgentLink())
- .collect(Collectors.toList());
+ .collect(Collectors.toList());
// Unlink thing attributes that are in old but not in new
Stream<AssetAttribute> attributesToUnlink = oldAgentLinkedAttributes
@@ -247,7 +250,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons
)
);
- getGroupedAgentLinkAttributes(attributesToUnlink, null)
+ getGroupedAgentLinkAttributes(attributesToUnlink, attribute -> true)
.forEach(this::unlinkAttributes);
// Link thing attributes that are in new but not in old
@@ -262,7 +265,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons
)
);
- getGroupedAgentLinkAttributes(attributesToLink, null)
+ getGroupedAgentLinkAttributes(attributesToLink, attribute -> true)
.forEach(this::linkAttributes);
break;
@@ -270,7 +273,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons
// Unlink any AGENT_LINK attributes from the referenced protocol
Map<AssetAttribute, List<AssetAttribute>> groupedAgentLinkAndProtocolAttributes =
- getGroupedAgentLinkAttributes(asset.getAttributeStream(), null);
+ getGroupedAgentLinkAttributes(asset.getAttributeStream(), attribute -> true);
groupedAgentLinkAndProtocolAttributes
.forEach(
this::unlinkAttributes
@@ -307,9 +310,10 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons
asset ->
getGroupedAgentLinkAttributes(
asset.getAttributeStream(),
- assetAttribute -> AgentLink.getAgentLink().apply(assetAttribute).equals(protocolAttributeRef)
- )
- .forEach(this::linkAttributes)
+ assetAttribute -> getAgentLink().apply(assetAttribute)
+ .map(attributeRef -> attributeRef.equals(protocolAttributeRef))
+ .orElse(false)
+ ).forEach(this::linkAttributes)
);
}
@@ -333,9 +337,10 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons
asset ->
getGroupedAgentLinkAttributes(
asset.getAttributeStream(),
- assetAttribute -> AgentLink.getAgentLink().apply(assetAttribute).equals(protocolAttributeRef)
- )
- .forEach(this::unlinkAttributes)
+ assetAttribute -> getAgentLink().apply(assetAttribute)
+ .map(attributeRef -> attributeRef.equals(protocolAttributeRef))
+ .orElse(false)
+ ).forEach(this::unlinkAttributes)
);
synchronized (protocolConfigurations) {
@@ -406,11 +411,11 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons
return;
}
- AttributeRef protocolRef = getAgentLink().apply(assetState.getAttribute());
+ Optional<AttributeRef> agentLink = getAgentLink().apply(assetState.getAttribute());
- if (protocolRef != null) {
+ if (agentLink.isPresent()) {
// Check attribute is linked to an actual agent
- AssetAttribute protocolConfiguration = protocolConfigurationResolver.apply(protocolRef);
+ AssetAttribute protocolConfiguration = protocolConfigurationResolver.apply(agentLink).orElse(null);
if (protocolConfiguration == null) {
LOG.warning("Cannot process as agent link is invalid:" + assetState);
@@ -433,33 +438,27 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons
assetState.setProcessingStatus(AssetState.ProcessingStatus.HANDLED);
}
- public Function<AttributeRef, AssetAttribute> getProtocolConfigurationResolver() {
+ public Function<Optional<AttributeRef>, Optional<AssetAttribute>> getProtocolConfigurationResolver() {
return protocolConfigurationResolver;
}
/**
* Gets all agent link attributes and their linked protocol configuration and groups them by Protocol Configuration
*/
- protected Map<AssetAttribute, List<AssetAttribute>> getGroupedAgentLinkAttributes(Stream<AssetAttribute> attributes, Predicate<AssetAttribute> filter) {
-
- Map<AssetAttribute, List<AssetAttribute>> map = new HashMap<>();
-
+ protected Map<AssetAttribute, List<AssetAttribute>> getGroupedAgentLinkAttributes(Stream<AssetAttribute> attributes,
+ Predicate<AssetAttribute> filter) {
+ Map<AssetAttribute, List<AssetAttribute>> result = new HashMap<>();
attributes
.filter(isValidAgentLink())
- .forEach(agentLinkAttribute -> {
- if (filter == null || filter.test(agentLinkAttribute)) {
- AttributeRef protocolRef = getAgentLink().apply(agentLinkAttribute);
- AssetAttribute protocolConfiguration = protocolConfigurationResolver.apply(protocolRef);
-
- if (protocolConfiguration == null) {
- LOG.warning("Invalid agent link '" + protocolRef + "' on attribute '" + agentLinkAttribute.getReference() + "'");
- } else {
- map.computeIfAbsent(protocolConfiguration, newProtocolConfiguration -> new ArrayList<>())
- .add(agentLinkAttribute);
- }
- }
- });
- return map;
+ .filter(filter)
+ .map(attribute -> new Pair<>(attribute, getAgentLink().apply(attribute)))
+ .filter(pair -> pair.value.isPresent())
+ .map(pair -> new Pair<>(pair.key, protocolConfigurationResolver.apply(pair.value)))
+ .filter(pair -> pair.value.isPresent())
+ .forEach(pair -> result.computeIfAbsent(pair.value.get(), newProtocolConfiguration -> new ArrayList<>())
+ .add(pair.key)
+ );
+ return result;
}
public String toString() {
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 89ff87712..4aae54054 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
@@ -39,6 +39,7 @@ import org.openremote.model.asset.*;
import java.util.ArrayList;
import java.util.List;
+import java.util.Optional;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -316,22 +317,22 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
// Pass attribute event through the processing chain
LOG.fine("Processing " + attributeEvent + " for: " + asset);
- AssetAttribute attribute = findAssetAttribute(attributeEvent.getAttributeName()).apply(asset);
+ Optional<AssetAttribute> attribute = findAssetAttribute(attributeEvent.getAttributeName()).apply(asset);
- if (attribute == null) {
+ if (!attribute.isPresent()) {
LOG.warning("Ignoring " + attributeEvent + ", attribute doesn't exist on asset: " + asset);
return;
}
// Prevent editing of read only attributes
// TODO This also means a rule RHS can't write a read-only attribute with Assets#dispatch!
- if (attribute.isReadOnly()) {
+ if (attribute.get().isReadOnly()) {
LOG.warning("Ignoring " + attributeEvent + ", attribute is read-only in: " + asset);
return;
}
// If attribute is marked as executable and not from northbound only allow write AttributeExecuteStatus to be sent
- if (!fromProtocol && attribute.isExecutable()) {
+ if (!fromProtocol && attribute.get().isExecutable()) {
JsonValue value = attributeEvent.getValue();
AttributeExecuteStatus status;
@@ -346,7 +347,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
}
}
- processUpdate(asset, attribute, attributeEvent, false);
+ processUpdate(asset, attribute.get(), attributeEvent, false);
}
/**
@@ -372,10 +373,10 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
return;
}
- AssetAttribute protocolConfiguration =
+ Optional<AssetAttribute> protocolConfiguration =
getAgentLink().andThen(agentService.getProtocolConfigurationResolver()).apply(attribute);
- if (protocolConfiguration == null) {
+ if (!protocolConfiguration.isPresent()) {
LOG.warning("Processing sensor update failed, linked agent protocol configuration not found: " + attributeEvent);
return;
}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/event/EventService.java b/manager/server/src/main/java/org/openremote/manager/server/event/EventService.java
index 07072ff3c..3806ba03c 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
@@ -139,14 +139,8 @@ public class EventService implements ContainerService {
String sessionKey = getSessionKey(exchange);
EventSubscription subscription = exchange.getIn().getBody(EventSubscription.class);
WebsocketAuth auth = getWebsocketAuth(exchange);
- boolean isAuthorized = false;
- for (EventSubscriptionAuthorizer authorizer : eventSubscriptionAuthorizers) {
- if (authorizer.isAuthorized(auth, subscription)) {
- isAuthorized = true;
- break;
- }
- }
- if (isAuthorized) {
+ if (eventSubscriptionAuthorizers.stream()
+ .anyMatch(authorizer -> authorizer.apply(auth, subscription))) {
eventSubscriptions.update(sessionKey, subscription);
} else {
LOG.warning("Unauthorized subscription from '"
diff --git a/manager/server/src/main/java/org/openremote/manager/server/event/EventSubscriptionAuthorizer.java b/manager/server/src/main/java/org/openremote/manager/server/event/EventSubscriptionAuthorizer.java
index da1b1f049..5fe28a5f0 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/event/EventSubscriptionAuthorizer.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/event/EventSubscriptionAuthorizer.java
@@ -22,6 +22,8 @@ package org.openremote.manager.server.event;
import org.openremote.container.web.socket.WebsocketAuth;
import org.openremote.model.event.shared.EventSubscription;
+import java.util.function.BiFunction;
+
/**
* Authorizes event subscriptions.
* <p>
@@ -29,8 +31,6 @@ import org.openremote.model.event.shared.EventSubscription;
* permissions. It might also fail if the subscription is invalid, for example, if
* a required filter is not supplied or if the filter is not valid.
*/
-public interface EventSubscriptionAuthorizer {
-
- boolean isAuthorized(WebsocketAuth auth, EventSubscription subscription);
+public interface EventSubscriptionAuthorizer extends BiFunction<WebsocketAuth, EventSubscription, Boolean> {
}
\ No newline at end of file
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 8e72270cc..f97e295c5 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
@@ -286,13 +286,13 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
getAssetAttributesFromJson(asset.getId()).apply(
(JsonObject) persistenceEvent.getPreviousState()[attributesIndex]
).filter(AssetAttribute::isRuleState)
- .collect(Collectors.toList());
+ .collect(Collectors.toList());
List<AssetAttribute> newFactAttributes =
getAssetAttributesFromJson(asset.getId()).apply(
(JsonObject) persistenceEvent.getCurrentState()[attributesIndex]
).filter(AssetAttribute::isRuleState)
- .collect(Collectors.toList());
+ .collect(Collectors.toList());
// Compare attributes by JSON value
// Retract facts for attributes that are in oldFactAttributes but not in newFactAttributes
@@ -530,7 +530,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
// Any exceptions in rule RHS will bubble up and the engine would be marked as in ERROR so future
// updates will be blocked
- String eventExpires = assetEvent.getExpires() != null ? assetEvent.getExpires() : configEventExpires;
+ String eventExpires = assetEvent.getExpires().orElse(configEventExpires);
long expirationOffset = TimeIntervalParser.parseSingle(eventExpires);
deployment.insertAssetEvent(assetEvent, expirationOffset);
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 d2fd60cd6..9ac5ae4b1 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
@@ -51,6 +51,7 @@ 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;
public class ManagerDemoSetup extends AbstractManagerSetup {
@@ -133,7 +134,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
agent.setLocation(geometryFactory.createPoint(new Coordinate(5.460315214821094, 51.44541688237109)));
agent.setType(AssetType.AGENT);
List<AssetAttribute> agentAttributes = Collections.singletonList(
- ProtocolConfiguration.initProtocolConfiguration(SimulatorProtocol.PROTOCOL_NAME)
+ initProtocolConfiguration(SimulatorProtocol.PROTOCOL_NAME)
.apply(new AssetAttribute(agentProtocolConfigName))
.setMeta(new Meta()
.add(new MetaItem(
@@ -254,7 +255,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
thing = assetStorageService.find(thingId, true);
ZonedDateTime now = LocalDateTime.now().atZone(ZoneId.systemDefault());
- AssetAttribute light1PowerConsumptionAttribute = findAssetAttribute("light1PowerConsumption").apply(thing);
+ AssetAttribute light1PowerConsumptionAttribute = findAssetAttribute("light1PowerConsumption").apply(thing).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 963517daf..f62d28393 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
@@ -54,8 +54,8 @@ class AgentDeploymentTest extends Specification implements ManagerContainerTrait
def thing = assetStorageService.find(managerDemoSetup.thingId, true)
def attributes = thing.getAttributeStream()
def attribute = findAttribute("light1Dimmer").apply(attributes)
- assert attribute.getValue().getType() == JsonType.NUMBER
- assert attribute.getValueAsInteger() == 66
+ assert attribute.get().getValue().getType() == JsonType.NUMBER
+ assert attribute.get().getValueAsInteger() == 66
}
when: "a simulated sensor changes its value"
@@ -67,8 +67,8 @@ class AgentDeploymentTest extends Specification implements ManagerContainerTrait
def thing = assetStorageService.find(managerDemoSetup.thingId, true)
def attributes = thing.getAttributeStream()
def attribute = findAttribute("light1Dimmer").apply(attributes)
- assert attribute.getValue().getType() == JsonType.NUMBER
- assert attribute.getValueAsInteger() == 77
+ assert attribute.get().getValue().getType() == JsonType.NUMBER
+ assert attribute.get().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.groovy
index 9ddcca4c6..43f45bafc 100644
--- a/manager/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy
@@ -45,7 +45,7 @@ class AssetDatapointTest extends Specification implements ManagerContainerTrait
then: "the thing attribute value should be updated and the datapoints stored"
conditions.eventually {
def thing = assetStorageService.find(managerDemoSetup.thingId, true)
- assert findAssetAttribute("light1PowerConsumption").apply(thing).getValueAsDecimal() == 15.5d
+ assert findAssetAttribute("light1PowerConsumption").apply(thing).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 7b5010b7f..cc3746fcb 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
@@ -76,7 +76,7 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTrait
then: "the attribute should exist"
findAssetAttribute("foo").apply(testAsset) != null
- findAssetAttribute("foo").apply(testAsset).getValueAsString() == "bar"
+ findAssetAttribute("foo").apply(testAsset).get().getValueAsString() == "bar"
when: "an asset attribute value is written directly"
assetResource.writeAttributeValue(null, testAsset.getId(), "foo", "\"bar2\"")
@@ -84,7 +84,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).getValueAsString() == "bar2"
+ assert findAssetAttribute("foo").apply(asset).get().getValueAsString() == "bar2"
}
when: "an asset attribute value null is written directly"
@@ -93,7 +93,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).hasValue() == false
+ assert findAssetAttribute("foo").apply(asset).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 ae6f06b61..4b2553ade 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
@@ -168,7 +168,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
def asset
conditions.eventually {
asset = assetResource.get(null, managerDemoSetup.smartOfficeId)
- assert findAssetAttribute("geoStreet").apply(asset).getValue().toJson() == Json.create("Teststreet 123").toJson()
+ assert findAssetAttribute("geoStreet").apply(asset).get().getValue().toJson() == Json.create("Teststreet 123").toJson()
}
when: "an non-existent attribute is written in the authenticated realm"
@@ -191,7 +191,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
then: "result should match"
conditions.eventually {
asset = assetResource.get(null, managerDemoSetup.smartHomeId)
- assert findAssetAttribute("geoStreet").apply(asset).getValue().toJson() == Json.create("Teststreet 456").toJson()
+ assert findAssetAttribute("geoStreet").apply(asset).get().getValue().toJson() == Json.create("Teststreet 456").toJson()
}
cleanup: "the server should be stopped"
@@ -340,7 +340,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
def asset
conditions.eventually {
asset = assetResource.get(null, managerDemoSetup.smartOfficeId)
- assert findAssetAttribute("geoStreet").apply(asset).getValue().toJson() == Json.create("Teststreet 123").toJson()
+ assert findAssetAttribute("geoStreet").apply(asset).get().getValue().toJson() == Json.create("Teststreet 123").toJson()
}
when: "an asset attribute is written in a foreign realm"
@@ -588,13 +588,13 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
def protectedAttributes = apartment1LivingroomThermostat.getAttributeList()
protectedAttributes.size() == 2
def currentTemperature = findAssetAttribute("currentTemperature").apply(apartment1LivingroomThermostat)
- currentTemperature.getType() == AttributeType.DECIMAL
- currentTemperature.getValueAsDecimal() == null
- Meta protectedMeta = currentTemperature.getMeta()
+ currentTemperature.get().getType().get() == AttributeType.DECIMAL
+ currentTemperature.get().getValueAsDecimal() == null
+ Meta protectedMeta = currentTemperature.get().getMeta()
protectedMeta.all().size() == 3
- protectedMeta.first(AssetMeta.LABEL).getValueAsString() == "Current Temperature"
- protectedMeta.first(AssetMeta.READ_ONLY).getValueAsBoolean()
- protectedMeta.first(AssetMeta.RULE_STATE).getValueAsBoolean()
+ protectedMeta.first(AssetMeta.LABEL).get().getValueAsString() == "Current Temperature"
+ protectedMeta.first(AssetMeta.READ_ONLY).get().getValueAsBoolean()
+ protectedMeta.first(AssetMeta.RULE_STATE).get().getValueAsBoolean()
when: "an asset is retrieved by ID in a foreign realm"
assetResource.get(null, managerDemoSetup.thingId)
@@ -666,7 +666,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).getValue().toJson() == Json.create(22.123).toJson()
+ assert findAssetAttribute("comfortTemperature").apply(asset).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 dc73bc8eb..46e5a4ac3 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
@@ -103,7 +103,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
asset.coordinates.length == 2
asset.path.length == 1
asset.path[0] == managerDemoSetup.smartOfficeId
- findAssetAttribute("geoStreet").apply(asset).valueAsString == "Torenallee 20"
+ findAssetAttribute("geoStreet").apply(asset).get().valueAsString == "Torenallee 20"
when: "a query is executed"
def assets = assetStorageService.findAll(
@@ -153,7 +153,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)).valueAsString == "Torenallee 20"
+ findAssetAttribute("geoStreet").apply(assets.get(0)).get().valueAsString == "Torenallee 20"
when: "a query is executed"
assets = assetStorageService.findAll(
@@ -251,10 +251,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)).valueAsDecimal == null
- findAssetAttribute("currentTemperature").apply(assets.get(2)).meta.size() == 3
- findAssetAttribute("comfortTemperature").apply(assets.get(2)).valueAsDecimal == null
- findAssetAttribute("comfortTemperature").apply(assets.get(2)).meta.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(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 c72367744..7f04539d6 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
@@ -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).valueAsBoolean
+ assert findAssetAttribute("lightSwitch").apply(livingRoomAsset).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).valueAsBoolean
+ assert !findAssetAttribute("lightSwitch").apply(livingRoomAsset).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).valueAsBoolean
+ assert !findAssetAttribute("presenceDetected").apply(livingRoomAsset).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).valueAsBoolean
+ assert !findAssetAttribute("presenceDetected").apply(otherLivingRoomAsset).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).valueAsBoolean
+ assert findAssetAttribute("presenceDetected").apply(asset).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).valueAsBoolean
+ assert !findAssetAttribute("presenceDetected").apply(asset).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).valueAsInteger == 5
+ assert findAssetAttribute("vacationDays").apply(asset).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).valueAsInteger == 4
+ assert findAssetAttribute("vacationDays").apply(asset).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).valueAsInteger == 4
+ assert findAssetAttribute("vacationDays").apply(asset).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).valueAsInteger == remainingDays
+ assert findAssetAttribute("vacationDays").apply(asset).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 bd656b66d..ea6abe385 100644
--- a/model/src/main/java/org/openremote/model/Attribute.java
+++ b/model/src/main/java/org/openremote/model/Attribute.java
@@ -20,13 +20,17 @@
package org.openremote.model;
import com.google.gwt.regexp.shared.RegExp;
-import elemental.json.*;
+import elemental.json.Json;
+import elemental.json.JsonObject;
+import elemental.json.JsonType;
+import elemental.json.JsonValue;
+import org.openremote.model.asset.AssetMeta;
-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;
+import java.util.function.UnaryOperator;
import java.util.stream.Stream;
/**
@@ -69,13 +73,13 @@ public abstract class Attribute extends AbstractValueTimestampHolder {
}
protected Attribute(Attribute attribute) {
- this(attribute.getName(), attribute.getType(), attribute.getJsonObject());
+ this(attribute.getName(), attribute.getType().orElse(null), attribute.getJsonObject());
}
@Override
protected boolean isValidValue(JsonValue value) {
- return getType() != null
- ? getType().isValid(value)
+ return getType().isPresent()
+ ? getType().get().isValid(value)
: super.isValidValue(value);
}
@@ -91,18 +95,16 @@ public abstract class Attribute extends AbstractValueTimestampHolder {
return jsonObject;
}
- public AttributeType getType() {
+ public Optional<AttributeType> getType() {
String typeName = jsonObject.hasKey(TYPE_FIELD_NAME) ? jsonObject.get(TYPE_FIELD_NAME).asString() : null;
- return typeName != null ? AttributeType.fromValue(typeName) : null;
+ return Optional.ofNullable(typeName != null ? AttributeType.fromValue(typeName) : null);
}
@SuppressWarnings("unchecked")
public void setType(AttributeType type) {
if (type != null) {
jsonObject.put(TYPE_FIELD_NAME, Json.create(type.getValue()));
- }/* else if (jsonObject.hasKey(TYPE_FIELD_NAME)) {
- jsonObject.remove(TYPE_FIELD_NAME);
- }*/
+ }
}
public boolean hasMeta() {
@@ -127,65 +129,13 @@ public abstract class Attribute extends AbstractValueTimestampHolder {
return this;
}
- public boolean hasMetaItem(String name) {
- return 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 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);
+ public Optional<MetaItem> firstMetaItem(String name) {
+ return getMeta().first(name);
}
@Override
public boolean isValid() {
- return super.isValid() && ATTRIBUTE_NAME_VALIDATOR.test(name) && getType() != null;
+ return super.isValid() && ATTRIBUTE_NAME_VALIDATOR.test(name) && getType().isPresent();
}
public static Predicate<Attribute> isAttributeValid() {
@@ -193,47 +143,47 @@ public abstract class Attribute extends AbstractValueTimestampHolder {
}
public static Predicate<Attribute> isAttributeType(AttributeType attributeType) {
- return attribute -> attribute.getType().equals(attributeType);
+ return attribute -> attribute.getType().map(at -> at.equals(attributeType)).orElse(false);
+ }
+
+ public static Predicate<Attribute> hasMetaItem(String name) {
+ return attribute -> attribute.firstMetaItem(name).isPresent();
}
public static Predicate<MetaItem> isMetaItem(String name) {
return metaItem -> metaItem.getName().equals(name);
}
- public static Function<Stream<? extends Attribute>, Attribute> findAttribute(String name) {
+ public static Function<Stream<? extends Attribute>, Optional<? extends Attribute>> findAttribute(String name) {
return attributeStream -> attributeStream
.filter(attribute -> attribute.getName().equals(name))
- .findFirst()
- .orElse(null);
+ .findFirst();
}
public static Predicate<Stream<? extends Attribute>> containsAttributeNamed(String name) {
- return attributeStream -> findAttribute(name).apply(attributeStream) != null;
+ return attributeStream -> findAttribute(name).apply(attributeStream).isPresent();
}
- public static java.util.function.Function<Attribute, AttributeRef> getAttributeLink(String metaName) {
- return attribute -> {
- MetaItem metaItem = attribute.firstMetaItem(metaName);
- JsonArray array = metaItem != null && metaItem.getValue().getType() == JsonType.ARRAY
- ? metaItem.getValueAsArray()
- : null;
- return array != null && array.length() == 2 ? new AttributeRef(array) : null;
- };
+ 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 static void removeAttribute(List<? extends Attribute> attributes, String name) {
attributes.removeIf(attribute -> attribute.getName().equals(name));
}
- public static <A extends Attribute> A findAttribute(List<A> attributes, String name) {
+ public static <A extends Attribute> Optional<A> findAttribute(List<A> attributes, String name) {
for (A attribute : attributes) {
if (attribute.getName().equals(name))
- return attribute;
+ return Optional.of(attribute);
}
- return null;
+ return Optional.empty();
}
- public static Function<Attribute, Attribute> setAttributeLink(String metaName, AttributeRef attributeRef) {
+ public static UnaryOperator<Attribute> setAttributeLink(String metaName, AttributeRef attributeRef) {
return attribute -> {
if (attributeRef == null) {
throw new IllegalArgumentException(
@@ -246,7 +196,7 @@ public abstract class Attribute extends AbstractValueTimestampHolder {
};
}
- public static Function<Attribute, Attribute> removeAttributeLink(String metaName) {
+ public static UnaryOperator<Attribute> removeAttributeLink(String metaName) {
return attribute -> attribute.setMeta(attribute.getMeta().removeAll(metaName));
}
}
diff --git a/model/src/main/java/org/openremote/model/Meta.java b/model/src/main/java/org/openremote/model/Meta.java
index 58ccacdb2..83c586964 100644
--- a/model/src/main/java/org/openremote/model/Meta.java
+++ b/model/src/main/java/org/openremote/model/Meta.java
@@ -28,6 +28,7 @@ import org.openremote.model.util.JsonUtil;
import java.util.ArrayList;
import java.util.List;
+import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Stream;
@@ -88,32 +89,20 @@ public class Meta {
return list;
}
- public MetaItem get(int index) {
- return index > 0 && index < jsonArray.length()
+ public Optional<MetaItem> get(int index) {
+ return Optional.ofNullable(
+ index > 0 && index < jsonArray.length()
? new MetaItem(jsonArray.getObject(index))
- : null;
+ : null
+ );
}
- public MetaItem first(AssetMeta assetMeta) {
+ public Optional<MetaItem> first(AssetMeta assetMeta) {
return first(assetMeta.getUrn());
}
- public MetaItem first(String name) {
- 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;
- }
- return null;
+ public Optional<MetaItem> first(String name) {
+ return all().stream().filter(item -> item.getName().equals(name)).findFirst();
}
public boolean contains(AssetMeta assetMeta) {
@@ -124,9 +113,8 @@ public class Meta {
return first(name) != null;
}
- public boolean contains(String name, JsonValue value) {
- MetaItem metaItem = first(name);
- return metaItem != null && JsonUtil.equals(metaItem.getValue(), value);
+ public int firstIndexOf(MetaItem item) {
+ return firstIndexOf(item, 0);
}
public int firstIndexOf(MetaItem item, int startIndex) {
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 595691c86..b064d9eb2 100644
--- a/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java
+++ b/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java
@@ -27,6 +27,7 @@ import org.openremote.model.AttributeType;
import org.openremote.model.util.JsonUtil;
import java.util.Date;
+import java.util.Optional;
/**
* An asset attribute value update, capturing that asset state at a point in time.
@@ -226,7 +227,7 @@ public abstract class AbstractAssetUpdate {
}
public AttributeType getAttributeType() {
- return attribute.getType();
+ return attribute.getType().orElse(null);
}
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 26299b154..6825ed8c5 100644
--- a/model/src/main/java/org/openremote/model/asset/Asset.java
+++ b/model/src/main/java/org/openremote/model/asset/Asset.java
@@ -32,6 +32,7 @@ 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;
@@ -40,9 +41,7 @@ import java.util.stream.Stream;
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.filterProtectedAssetAttribute;
-import static org.openremote.model.asset.AssetAttribute.getAssetAttributesAsJson;
-import static org.openremote.model.asset.AssetAttribute.getAssetAttributesFromJson;
+import static org.openremote.model.asset.AssetAttribute.*;
// @formatter:off
/**
@@ -75,9 +74,9 @@ import static org.openremote.model.asset.AssetAttribute.getAssetAttributesFromJs
* <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 #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
+ * An asset may have dynamically-typed {@link #attributes} with an underlying
+ * {@link elemental.json.JsonObject} model. Use the {@link org.openremote.model.Attribute}
+ * etc. class to work with this API. This property can be empty when certain optimized loading
* operations are used.
* <p>
* Constructors can filter attributes of an asset as to only contain protected attributes,
@@ -312,7 +311,7 @@ public class Asset implements IdentifiableEntity {
this.attributes = getAssetAttributesFromJson(id)
.andThen(filterProtectedAssetAttribute())
.andThen(getAssetAttributesAsJson())
- .apply(attributes);
+ .apply(attributes).orElse(null);
} else {
this.attributes = attributes;
}
@@ -493,11 +492,11 @@ public class Asset implements IdentifiableEntity {
}
public void setAttributeStream(Stream<AssetAttribute> attributeStream) {
- setAttributes(getAssetAttributesAsJson().apply(attributeStream));
+ setAttributes(getAssetAttributesAsJson().apply(attributeStream).orElse(null));
}
public List<AssetAttribute> getAttributeList() {
- return getAttributeStream().collect(Collectors.toList());
+ return getAttributeStream().collect(Collectors.toCollection(ArrayList::new));
}
public void setAttributeList(List<AssetAttribute> attributes) {
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 559f26131..3b05c2a27 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetAttribute.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetAttribute.java
@@ -25,6 +25,7 @@ import elemental.json.JsonValue;
import org.openremote.model.*;
import java.util.List;
+import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
@@ -35,7 +36,7 @@ import static org.openremote.model.asset.AssetMeta.*;
public class AssetAttribute extends Attribute {
- final protected String assetId;
+ final protected Optional<String> assetId;
public static AssetAttribute createEmpty() {
return new AssetAttribute(null, Json.createObject());
@@ -43,7 +44,7 @@ public class AssetAttribute extends Attribute {
public AssetAttribute(String name) {
super(name);
- this.assetId = null;
+ this.assetId = Optional.empty();
}
public AssetAttribute(String name, AttributeType type) {
@@ -60,17 +61,17 @@ public class AssetAttribute extends Attribute {
public AssetAttribute(String assetId, String name, AttributeType type) {
super(name, type);
- this.assetId = assetId;
+ this.assetId = Optional.ofNullable(assetId);
}
public AssetAttribute(String assetId, String name, AttributeType type, JsonValue value) {
super(name, type, value);
- this.assetId = assetId;
+ this.assetId = Optional.ofNullable(assetId);
}
public AssetAttribute(String assetId, String name, JsonObject jsonObject) {
super(name, jsonObject);
- this.assetId = assetId;
+ this.assetId = Optional.ofNullable(assetId);
}
public AssetAttribute(AssetAttribute assetAttribute) {
@@ -83,15 +84,14 @@ public class AssetAttribute extends Attribute {
return (AssetAttribute) super.setMeta(meta);
}
- public String getAssetId() {
+ public Optional<String> getAssetId() {
return assetId;
}
public AttributeRef getReference() {
- if (getAssetId() == null) {
- throw new IllegalStateException("Asset identifier not set on: " + this);
- }
- return new AttributeRef(getAssetId(), getName());
+ return getAssetId()
+ .map(assetId -> new AttributeRef(assetId, getName()))
+ .orElseThrow(() -> new IllegalStateException("Asset identifier not set on: " + this));
}
/**
@@ -114,20 +114,12 @@ public class AssetAttribute extends Attribute {
);
}
- public boolean hasMetaItem(AssetMeta assetMeta) {
- return hasMetaItem(assetMeta.getUrn());
- }
-
- public MetaItem firstMetaItem(AssetMeta assetMeta) {
+ public Optional<MetaItem> firstMetaItem(AssetMeta assetMeta) {
return firstMetaItem(assetMeta.getUrn());
}
- public List<MetaItem> getMetaItems(AssetMeta assetMeta) {
- return getMetaItems(assetMeta.getUrn());
- }
-
public String getLabel() {
- return hasMetaItem(LABEL) ? firstMetaItem(LABEL).getValueAsString() : getName();
+ return firstMetaItem(LABEL).map(AbstractValueHolder::getValueAsString).orElse(getName());
}
public AssetAttribute setLabel(String label) {
@@ -137,7 +129,7 @@ public class AssetAttribute extends Attribute {
}
public boolean isExecutable() {
- return hasMetaItem(EXECUTABLE) ? firstMetaItem(EXECUTABLE).getValueAsBoolean() : false;
+ return firstMetaItem(EXECUTABLE).map(AbstractValueHolder::isValueTrue).orElse(false);
}
public AssetAttribute setExecutable(boolean executable) {
@@ -154,20 +146,22 @@ public class AssetAttribute extends Attribute {
}
public boolean isShowOnDashboard() {
- return hasMetaItem(SHOWN_ON_DASHBOARD) && firstMetaItem(SHOWN_ON_DASHBOARD).isValueTrue();
+ return firstMetaItem(SHOWN_ON_DASHBOARD).map(AbstractValueHolder::isValueTrue).orElse(false);
}
- public String getFormat() {
- return hasMetaItem(FORMAT) ? firstMetaItem(FORMAT).getValueAsString() : null;
+ public Optional<String> getFormat() {
+ return firstMetaItem(FORMAT).map(AbstractValueHolder::getValueAsString);
}
- public String getDescription() {
- return hasMetaItem(DESCRIPTION) ? firstMetaItem(DESCRIPTION).getValueAsString() : null;
+ public Optional<String> getDescription() {
+ return firstMetaItem(DESCRIPTION).map(AbstractValueHolder::getValueAsString);
}
+ /**
+ * Defaults to <code>true</code> if there is no {@link AssetMeta#ENABLED} item.
+ */
public boolean isEnabled() {
- // Default to true
- return hasMetaItem(ENABLED) ? firstMetaItem(AssetMeta.ENABLED).isValueTrue() : true;
+ return firstMetaItem(ENABLED).map(AbstractValueHolder::isValueTrue).orElse(true);
}
public AssetAttribute setEnabled(boolean enabled) {
@@ -177,66 +171,54 @@ public class AssetAttribute extends Attribute {
}
public boolean isProtected() {
- return hasMetaItem(PROTECTED) && firstMetaItem(PROTECTED).isValueTrue();
+ return firstMetaItem(PROTECTED).map(AbstractValueHolder::isValueTrue).orElse(false);
}
public boolean isReadOnly() {
- return hasMetaItem(READ_ONLY) && firstMetaItem(READ_ONLY).isValueTrue();
+ return firstMetaItem(READ_ONLY).map(AbstractValueHolder::isValueTrue).orElse(false);
}
public boolean isStoreDatapoints() {
- return hasMetaItem(STORE_DATA_POINTS) && firstMetaItem(STORE_DATA_POINTS).isValueTrue();
+ return firstMetaItem(STORE_DATA_POINTS).map(AbstractValueHolder::isValueTrue).orElse(false);
}
public boolean isRuleState() {
- return hasMetaItem(RULE_STATE) && firstMetaItem(RULE_STATE).isValueTrue();
+ return firstMetaItem(RULE_STATE).map(AbstractValueHolder::isValueTrue).orElse(false);
}
public boolean isRuleEvent() {
- return hasMetaItem(RULE_EVENT) && firstMetaItem(RULE_EVENT).isValueTrue();
+ return firstMetaItem(RULE_EVENT).map(AbstractValueHolder::isValueTrue).orElse(false);
}
- public String getRuleEventExpires() {
- return hasMetaItem(RULE_EVENT_EXPIRES) ? firstMetaItem(RULE_EVENT_EXPIRES).getValueAsString() : null;
+ public Optional<String> getRuleEventExpires() {
+ return firstMetaItem(RULE_EVENT_EXPIRES).map(AbstractValueHolder::getValueAsString);
}
- public boolean isAgentLinked() {
- return hasMetaItem(AGENT_LINK);
- }
-
- public static Predicate<Attribute> hasAssetMetaItem(String name) {
- return attribute -> attribute.hasMetaItem(name);
- }
-
- public static Predicate<Attribute> hasAssetMetaItem(AssetMeta assetMeta) {
- return attribute -> attribute.hasMetaItem(assetMeta.getUrn());
+ public static Predicate<Attribute> hasMetaItem(AssetMeta assetMeta) {
+ return hasMetaItem(assetMeta.getUrn());
}
public static Predicate<MetaItem> isAssetMetaItem(AssetMeta assetMeta) {
return isMetaItem(assetMeta.getUrn());
}
- public static Predicate<MetaItem> isAssetMetaItem(String name) {
- return isMetaItem(name);
- }
-
- public static Function<Asset, AssetAttribute> findAssetAttribute(String name) {
+ 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) != null;
+ return asset -> findAssetAttribute(name).apply(asset).isPresent();
}
public static Predicate<Asset> isAssetAttribute(String name, Predicate<AssetAttribute> predicate) {
return asset -> {
- AssetAttribute attribute = findAssetAttribute(name).apply(asset);
- return attribute != null && predicate.test(attribute);
+ 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().equals(event.getEntityId())
+ return attribute -> attribute.getAssetId().map(assetId -> assetId.equals(event.getEntityId())).orElse(false)
&& attribute.getName().equals(event.getAttributeName());
}
@@ -255,9 +237,9 @@ public class AssetAttribute extends Attribute {
for (MetaItem metaItem : attribute.getMeta().all()) {
if (!metaItem.getName().startsWith(NAMESPACE))
continue;
-
- AssetMeta wellKnownMeta = AssetMeta.byUrn(metaItem.getName());
- if (wellKnownMeta != null && wellKnownMeta.getAccess().protectedRead) {
+ boolean protectedRead =
+ AssetMeta.byUrn(metaItem.getName()).map(meta -> meta.getAccess().protectedRead).orElse(false);
+ if (protectedRead) {
protectedMeta.add(
new MetaItem(metaItem.getName(), metaItem.getValue())
);
@@ -284,12 +266,12 @@ public class AssetAttribute extends Attribute {
};
}
- public static Function<JsonObject, AssetAttribute> getAssetAttributeFromJson(String assetId, String attributeName) {
+ public static Function<JsonObject, Optional<AssetAttribute>> getAssetAttributeFromJson(String assetId, String attributeName) {
return jsonObject -> {
if (jsonObject == null || jsonObject.keys().length == 0 || !jsonObject.hasKey(attributeName)) {
- return null;
+ return Optional.empty();
}
- return new AssetAttribute(assetId, attributeName, jsonObject.getObject(attributeName));
+ return Optional.of(new AssetAttribute(assetId, attributeName, jsonObject.getObject(attributeName)));
};
}
@@ -298,16 +280,16 @@ public class AssetAttribute extends Attribute {
* allowed (internally this is a hash map in Elemental, thus not allowing duplicate
* JSON object property names).
*/
- public static Function<Stream<AssetAttribute>, JsonObject> getAssetAttributesAsJson() {
+ public static Function<Stream<AssetAttribute>, Optional<JsonObject>> getAssetAttributesAsJson() {
return attributeStream -> {
List<AssetAttribute> list = attributeStream.collect(Collectors.toList());
if (list.size() == 0)
- return null;
+ return Optional.empty();
JsonObject jsonObject = Json.createObject();
for (AssetAttribute attribute : list) {
jsonObject.put(attribute.getName(), attribute.getJsonObject());
}
- return jsonObject;
+ return Optional.of(jsonObject);
};
}
diff --git a/model/src/main/java/org/openremote/model/asset/AssetEvent.java b/model/src/main/java/org/openremote/model/asset/AssetEvent.java
index 71bb06f02..d958b3dbb 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetEvent.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetEvent.java
@@ -21,6 +21,8 @@ package org.openremote.model.asset;
import org.kie.api.definition.type.Role;
+import java.util.Optional;
+
/**
* An asset attribute value change as a punctual event in rules processing.
*/
@@ -32,7 +34,7 @@ public class AssetEvent extends AbstractAssetUpdate {
super(that);
}
- public String getExpires() {
+ public Optional<String> getExpires() {
return attribute.getRuleEventExpires();
}
}
diff --git a/model/src/main/java/org/openremote/model/asset/AssetMeta.java b/model/src/main/java/org/openremote/model/asset/AssetMeta.java
index 26d3c1be0..9852dabe0 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetMeta.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetMeta.java
@@ -27,6 +27,7 @@ import org.openremote.model.units.AttributeUnits;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
+import java.util.Optional;
import static org.openremote.model.Constants.ASSET_META_NAMESPACE;
@@ -189,12 +190,12 @@ public enum AssetMeta {
return null;
}
- public static AssetMeta byUrn(String urn) {
+ public static Optional<AssetMeta> byUrn(String urn) {
for (AssetMeta assetMeta : values()) {
if (assetMeta.getUrn().equals(urn))
- return assetMeta;
+ return Optional.of(assetMeta);
}
- return null;
+ return Optional.empty();
}
public static MetaItem createMetaItem(AssetMeta assetMeta, JsonValue value) {
diff --git a/model/src/main/java/org/openremote/model/asset/AssetType.java b/model/src/main/java/org/openremote/model/asset/AssetType.java
index a20ebf212..1936c078e 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetType.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetType.java
@@ -27,6 +27,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
+import java.util.stream.Stream;
import static org.openremote.model.AttributeType.INTEGER;
import static org.openremote.model.AttributeType.STRING;
@@ -97,8 +98,8 @@ public enum AssetType {
return value;
}
- public AssetAttribute[] getDefaultAttributes() {
- return defaultAttributes != null ? defaultAttributes.toArray(new AssetAttribute[0]) : new AssetAttribute[0];
+ public Stream<AssetAttribute> getDefaultAttributes() {
+ return defaultAttributes != null ? defaultAttributes.stream() : Stream.empty();
}
public static AssetType[] valuesSorted() {
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 76dd55edc..2d9ede455 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
@@ -23,7 +23,7 @@ import org.openremote.model.Attribute;
import org.openremote.model.AttributeRef;
import org.openremote.model.asset.AssetMeta;
-import java.util.function.Consumer;
+import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
@@ -52,7 +52,7 @@ final public class AgentLink {
return isAttributeValid().and(isAgentLink());
}
- public static Function<Attribute, AttributeRef> getAgentLink() {
+ public static Function<Attribute, Optional<AttributeRef>> getAgentLink() {
return getAttributeLink(AGENT_LINK.getUrn());
}
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 d7e45d3cd..b09a41917 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
@@ -27,9 +27,9 @@ import org.openremote.model.Meta;
import org.openremote.model.asset.AssetAttribute;
import java.util.Locale;
-import java.util.function.Consumer;
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.AttributeType.STRING;
@@ -50,7 +50,7 @@ final public class ProtocolConfiguration {
private ProtocolConfiguration() {
}
- public static Function<AssetAttribute, AssetAttribute> initProtocolConfiguration(String protocolName) {
+ public static UnaryOperator<AssetAttribute> initProtocolConfiguration(String protocolName) {
return attribute -> {
attribute.setEnabled(true);
attribute.setType(AttributeType.STRING);
@@ -73,12 +73,13 @@ final public class ProtocolConfiguration {
return value -> value != null && value.toLowerCase(Locale.ROOT).startsWith(Constants.PROTOCOL_NAMESPACE);
}
- public static Consumer<AssetAttribute> setProtocolName(String protocolName) throws IllegalArgumentException {
+ public static UnaryOperator<AssetAttribute> setProtocolName(String protocolName) throws IllegalArgumentException {
return attribute -> {
if (!isProtocolUrn().test(protocolName)) {
throw new IllegalArgumentException("Protocol configuration value should contain a protocol URN");
}
attribute.setValue(Json.create(protocolName));
+ return attribute;
};
}