Skip to content

armgit / core

Public Imported from GitHub
0

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

Implemented AttributeLink UI support (using MetaEditor)

Rich Turnerf9d85fb5dac6
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AbstractAssetActivity.java b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AbstractAssetActivity.java
index 81609baad..ac82b6cd3 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AbstractAssetActivity.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AbstractAssetActivity.java
@@ -49,15 +49,10 @@ import org.openremote.model.asset.Asset;
import org.openremote.model.asset.AssetAttribute;
import org.openremote.model.asset.AssetMeta;
import org.openremote.model.asset.agent.ProtocolConfiguration;
-import org.openremote.model.attribute.AttributeEvent;
-import org.openremote.model.attribute.AttributeState;
-import org.openremote.model.attribute.AttributeValidationResult;
-import org.openremote.model.attribute.MetaItem;
+import org.openremote.model.attribute.*;
import org.openremote.model.event.bus.EventBus;
import org.openremote.model.event.bus.EventRegistration;
-import org.openremote.model.value.ArrayValue;
-import org.openremote.model.value.ObjectValue;
-import org.openremote.model.value.ValueType;
+import org.openremote.model.value.*;
import java.util.*;
import java.util.function.Consumer;
@@ -313,14 +308,7 @@ public abstract class AbstractAssetActivity<V extends AssetBaseView.Presenter, U
for (int i=0; i<attribute.getMeta().size(); i++) {
MetaItem item = attribute.getMeta().get(i);
- List<ValidationFailure> metaItemFailures = attribute.getMetaItemValidationFailures(item);
-
- if (metaItemFailures.isEmpty()) {
- // Look for meta descriptor and do additional validation
- AssetMeta.getAssetMeta(item.getName().orElse(""))
- .flatMap(assetMeta -> assetMeta.validateValue(item.getValue().orElse(null)))
- .ifPresent(metaItemFailures::add);
- }
+ List<ValidationFailure> metaItemFailures = attribute.getMetaItemValidationFailures(item, getMetaItemDescriptor(item));
if (!metaItemFailures.isEmpty()) {
metaFailures.put(i, metaItemFailures);
@@ -330,22 +318,24 @@ public abstract class AbstractAssetActivity<V extends AssetBaseView.Presenter, U
resultConsumer.accept(new AttributeValidationResult(attributeName, attributeFailures, metaFailures));
}
+ protected Optional<MetaItemDescriptor> getMetaItemDescriptor(MetaItem item) {
+ return AssetMeta
+ .getAssetMeta(item.getName().orElse(""))
+ .map(assetMeta -> (MetaItemDescriptor)assetMeta);
+ }
+
protected void processValidationResults(List<AttributeValidationResult> results) {
// Update each of the attribute views (the views are responsible for displaying any failure messages)
view.setFormBusy(false);
- results.forEach(result -> {
- view.getAttributeViews()
- .stream()
- .filter(attrView -> attrView
- .getAttribute()
- .getName()
- .map(name -> name.equals(result.getAttributeName())).orElse(false))
- .findFirst()
- .ifPresent(attrView -> {
- attrView.onValidationStateChange(result);
- });
- });
+ results.forEach(result -> view.getAttributeViews()
+ .stream()
+ .filter(attrView -> attrView
+ .getAttribute()
+ .getName()
+ .map(name -> name.equals(result.getAttributeName())).orElse(false))
+ .findFirst()
+ .ifPresent(attrView -> attrView.onValidationStateChange(result)));
}
protected Optional<AttributeView> getAttributeView(AssetAttribute attribute) {
@@ -382,8 +372,10 @@ public abstract class AbstractAssetActivity<V extends AssetBaseView.Presenter, U
return false;
}
- protected boolean isShowTimestamp(ValueHolder valueHolder) {
- return !editMode && (valueHolder instanceof AssetAttribute);
+ protected Optional<Long> getTimestamp(ValueHolder valueHolder) {
+ return !editMode || !(valueHolder instanceof AssetAttribute) ?
+ Optional.empty() :
+ ((AssetAttribute)valueHolder).getValueTimestamp();
}
abstract protected void onAttributeModified(AssetAttribute attribute);
@@ -393,10 +385,8 @@ public abstract class AbstractAssetActivity<V extends AssetBaseView.Presenter, U
* <p>
* Custom {@link MetaItem}s don't contain any value type information so we need this provided based on user's
* type selection.
- * <p>
- * NOTE: The value holder can also be the attribute (e.g. when creating an editor for the attribute value).
*/
- protected IsWidget createValueEditor(ValueHolder valueHolder, ValueType valueType, AttributeView.Style style, Runnable onValueModified) {
+ protected IsWidget createValueEditor(ValueHolder valueHolder, ValueType valueType, AttributeView.Style style, AttributeView parentView, Consumer<Value> onValueModified) {
// TODO: Implement support for setting access permissions on individual meta item instances
// // Super users can edit any meta items but other users can only edit non-restricted meta items
@@ -406,7 +396,7 @@ public abstract class AbstractAssetActivity<V extends AssetBaseView.Presenter, U
// assetMeta.map(AssetMeta::isRestricted).orElse(true);
boolean isReadOnly = isValueReadOnly(valueHolder);
- boolean showTimestamp = isShowTimestamp(valueHolder);
+ Optional<Long> timestamp = getTimestamp(valueHolder);
switch(valueType) {
case OBJECT:
@@ -414,29 +404,53 @@ public abstract class AbstractAssetActivity<V extends AssetBaseView.Presenter, U
String label = environment.getMessages().jsonObject();
String title = environment.getMessages().edit() + " " + environment.getMessages().jsonObject();
return createObjectEditor(
- valueHolder, onValueModified, isReadOnly, showTimestamp, currentValueObj, label, title, jsonEditorProvider.get()
+ currentValueObj,
+ onValueModified::accept,
+ timestamp,
+ isReadOnly,
+ label,
+ title,
+ jsonEditorProvider.get()
);
case ARRAY:
ArrayValue currentValueArray = valueHolder.getValueAsArray().orElse(null);
label = environment.getMessages().jsonArray();
title = environment.getMessages().edit() + " " + environment.getMessages().jsonArray();
return createArrayEditor(
- valueHolder, onValueModified, isReadOnly, showTimestamp, currentValueArray, label, title, jsonEditorProvider.get()
+ currentValueArray,
+ onValueModified::accept,
+ timestamp,
+ isReadOnly,
+ label,
+ title,
+ jsonEditorProvider.get()
);
case STRING:
- String currentValueStr = valueHolder.getValueAsString().orElse(null);
+ StringValue currentValueStr = (StringValue)valueHolder.getValue().orElse(null);
return createStringEditor(
- valueHolder, onValueModified, isReadOnly, showTimestamp, currentValueStr, style.stringEditor()
+ currentValueStr,
+ onValueModified::accept,
+ timestamp,
+ isReadOnly,
+ style.stringEditor()
);
case NUMBER:
- Optional<Double> currentValueNumber = valueHolder.getValueAsNumber();
+ NumberValue currentValueNumber = (NumberValue)valueHolder.getValue().orElse(null);
return createNumberEditor(
- valueHolder, onValueModified, isReadOnly, showTimestamp, currentValueNumber.map(Object::toString).orElse(null), style.numberEditor()
+ currentValueNumber,
+ onValueModified::accept,
+ timestamp,
+ isReadOnly,
+ style.numberEditor()
);
case BOOLEAN:
- Boolean currentValueBool = valueHolder.getValueAsBoolean().orElse(null);
+ BooleanValue currentValueBool = (BooleanValue)valueHolder.getValue().orElse(null);
return createBooleanEditor(
- valueHolder, onValueModified, isReadOnly, showTimestamp, currentValueBool, style.booleanEditor()
+ currentValueBool,
+ onValueModified::accept,
+ timestamp,
+ isReadOnly,
+ style.booleanEditor()
);
default:
return new FormOutputText(valueHolder instanceof MetaItem ?
@@ -469,7 +483,7 @@ public abstract class AbstractAssetActivity<V extends AssetBaseView.Presenter, U
String str = environment.getMessages().validationFailureParameter(parameter);
return isNullOrEmpty(str) ? parameter : str;
})
- .orElse(null);
+ .orElse("Value");
error.append(
environment.getMessages().validationFailure(parameterStr, validationFailure.getReason().name())
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEdit.java b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEdit.java
index 174d49076..6be1d3d32 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEdit.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEdit.java
@@ -20,14 +20,15 @@
package org.openremote.manager.client.assets.asset;
import org.openremote.manager.client.assets.browser.BrowserTreeNode;
+import org.openremote.manager.client.widget.AttributeRefEditor;
import org.openremote.manager.client.widget.FormView;
import org.openremote.model.ValueHolder;
-import org.openremote.model.asset.Asset;
import org.openremote.model.asset.AssetAttribute;
import org.openremote.model.asset.AssetType;
import org.openremote.model.util.Pair;
import java.util.List;
+import java.util.Map;
import java.util.function.Consumer;
public interface AssetEdit extends FormView, AssetBaseView<AssetEdit.Presenter> {
@@ -50,9 +51,7 @@ public interface AssetEdit extends FormView, AssetBaseView<AssetEdit.Presenter>
void delete();
- void getLinkableAssets(ValueHolder value, Consumer<Asset[]> assetConsumer);
-
- void getLinkableAttributes(Pair<ValueHolder, Asset> valueAssetPair, Consumer<AssetAttribute[]> attributeConusmer);
+ void getLinkableAssetsAndAttributes(ValueHolder valueHolder, Consumer<Map<AttributeRefEditor.AssetInfo, List<AttributeRefEditor.AttributeInfo>>> assetAttributeConsumer);
}
void setPresenter(Presenter presenter);
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 04d6439c0..2ff36e450 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
@@ -33,6 +33,8 @@ import org.openremote.manager.client.event.ShowFailureEvent;
import org.openremote.manager.client.event.ShowSuccessEvent;
import org.openremote.manager.client.interop.jackson.FileInfoMapper;
import org.openremote.manager.client.interop.value.ObjectValueMapper;
+import org.openremote.manager.client.widget.AttributeLinkEditor;
+import org.openremote.manager.client.widget.AttributeRefEditor;
import org.openremote.manager.client.widget.FormButton;
import org.openremote.manager.client.widget.ValueEditors;
import org.openremote.manager.shared.agent.AgentResource;
@@ -45,23 +47,22 @@ import org.openremote.model.asset.*;
import org.openremote.model.asset.agent.AgentLink;
import org.openremote.model.asset.agent.ProtocolConfiguration;
import org.openremote.model.asset.agent.ProtocolDescriptor;
-import org.openremote.model.attribute.AttributeType;
-import org.openremote.model.attribute.AttributeValidationResult;
-import org.openremote.model.attribute.MetaItem;
-import org.openremote.model.attribute.MetaItemDescriptor;
+import org.openremote.model.attribute.*;
import org.openremote.model.util.EnumUtil;
import org.openremote.model.util.Pair;
+import org.openremote.model.value.Value;
import org.openremote.model.value.ValueType;
import javax.inject.Inject;
import java.util.*;
import java.util.function.Consumer;
+import java.util.function.Predicate;
import java.util.stream.Collectors;
import static org.openremote.manager.client.http.RequestExceptionHandler.handleRequestException;
-import static org.openremote.manager.client.widget.ValueEditors.createAttributeRefEditor;
import static org.openremote.model.attribute.Attribute.ATTRIBUTE_NAME_VALIDATOR;
import static org.openremote.model.attribute.Attribute.isAttributeNameEqualTo;
+import static org.openremote.model.attribute.MetaItem.isMetaNameEqualTo;
import static org.openremote.model.util.TextUtil.isNullOrEmpty;
public class AssetEditActivity
@@ -80,10 +81,6 @@ public class AssetEditActivity
protected final AttributeValidationResultMapper attributeValidationResultMapper;
protected final AssetAttributeMapper assetAttributeMapper;
protected final Consumer<ConstraintViolation[]> validationErrorHandler;
- protected final List<Consumer<Asset[]>> agentAssetConsumers = new ArrayList<>();
- protected final List<Consumer<Asset[]>> allAssetConsumers = new ArrayList<>();
- protected Asset[] agentAssets;
- protected Asset[] allAssets;
protected List<ProtocolDescriptor> protocolDescriptors = new ArrayList<>();
protected List<MetaItemDescriptor> metaItemDescriptors = new ArrayList<>(Arrays.asList(AssetMeta.values()));
double[] selectedCoordinates;
@@ -341,19 +338,12 @@ public class AssetEditActivity
}
@Override
- public void getLinkableAssets(ValueHolder value, Consumer<Asset[]> assetConsumer) {
- List<Consumer<Asset[]>> consumers;
- Asset[] retrievedAssets;
- Consumer<Asset[]> assetStore;
+ public void getLinkableAssetsAndAttributes(ValueHolder valueHolder, Consumer<Map<AttributeRefEditor.AssetInfo, List<AttributeRefEditor.AttributeInfo>>> assetAttributeConsumer) {
AssetQuery query;
+ Predicate<AssetAttribute> attributeFilter = null;
- if ((value instanceof MetaItem) && AgentLink.isAgentLink((MetaItem) value)) {
- consumers = agentAssetConsumers;
- retrievedAssets = agentAssets;
- assetStore = assets -> agentAssets = assets;
+ if ((valueHolder instanceof MetaItem) && AgentLink.isAgentLink((MetaItem) valueHolder)) {
query = new AssetQuery()
- // There shouldn't be many agents so retrieve their attributes to speed up getting
- // Protocol Configuration attribute names
.select(new AssetQuery.Select(AssetQuery.Include.ONLY_ID_AND_NAME_AND_ATTRIBUTES))
// Limit to agents
.type(AssetType.AGENT);
@@ -363,83 +353,96 @@ public class AssetEditActivity
if (!isNullOrEmpty(asset.getRealmId())) {
query.tenant(new AbstractAssetQuery.TenantPredicate(asset.getRealmId()));
}
+
+ attributeFilter = ProtocolConfiguration::isProtocolConfiguration;
} else {
- consumers = allAssetConsumers;
- retrievedAssets = allAssets;
- assetStore = assets -> allAssets = assets;
- // Limit to assets that have the same realm as the asset being edited
query = new AssetQuery()
.select(new AssetQuery.Select(AssetQuery.Include.ONLY_ID_AND_NAME_AND_ATTRIBUTE_NAMES, true));
- }
- if (retrievedAssets != null) {
- // Already retrieved so return results
- assetConsumer.accept(retrievedAssets);
- return;
+ // Limit to assets that have the same realm as the asset being edited (if it has been assigned a realm
+ // otherwise the query will be automatically restricted to the logged in users realm)
+ if (!isNullOrEmpty(asset.getRealmId())) {
+ query.tenant(new AbstractAssetQuery.TenantPredicate(asset.getRealmId()));
+ }
}
- consumers.add(assetConsumer);
+ // Do request
+ final Predicate<AssetAttribute> finalAttributeFilter = attributeFilter;
+ environment.getRequestService().execute(
+ assetArrayMapper,
+ assetQueryMapper,
+ requestParams -> assetResource.queryAssets(requestParams, query),
+ 200,
+ assets -> {
+ Map<AttributeRefEditor.AssetInfo, List<AttributeRefEditor.AttributeInfo>> assetAttributeMap = Arrays
+ .stream(assets)
+ .filter(asset -> !asset.getAttributesList().isEmpty())
+ .collect(Collectors.toMap(
+ asset -> new AttributeRefEditor.AssetInfo(asset.getName(), asset.getId()),
+ asset ->
+ asset.getAttributesStream()
+ .filter(attribute -> finalAttributeFilter == null || finalAttributeFilter.test(attribute))
+ .map(attribute ->
+ new AttributeRefEditor.AttributeInfo(
+ attribute.getName().orElse(null),
+ attribute.getLabelOrName().orElse(null)
+ )
+ )
+ .collect(Collectors.toList())
- if (consumers.size() == 1) {
- // Do request
- environment.getRequestService().execute(
- assetArrayMapper,
- assetQueryMapper,
- requestParams -> assetResource.queryAssets(requestParams, query),
- 200,
- assets -> {
- assetStore.accept(assets);
- consumers.forEach(consumer -> consumer.accept(assets));
- consumers.clear();
- },
- exception -> {
- Asset[] assets = new Asset[0];
- assetStore.accept(assets);
- consumers.forEach(consumer -> consumer.accept(assets));
- consumers.clear();
- }
- );
- }
- }
+ ));
- @Override
- public void getLinkableAttributes(Pair<ValueHolder, Asset> valueAssetPair, Consumer<AssetAttribute[]> attributeConsumer) {
- ValueHolder value = valueAssetPair.key;
- Asset asset = valueAssetPair.value;
-
- if ((value instanceof MetaItem) && AgentLink.isAgentLink((MetaItem) value)) {
- // Asset should have fully populated attributes so filter them
- attributeConsumer.accept(
- asset.getAttributesStream()
- .filter(ProtocolConfiguration::isProtocolConfiguration)
- .toArray(AssetAttribute[]::new)
- );
- } else {
- // Asset should just have attribute names and labels loaded so return them
- attributeConsumer.accept(
- asset
- .getAttributesStream()
- .toArray(AssetAttribute[]::new)
- );
- }
+ assetAttributeConsumer.accept(assetAttributeMap);
+ },
+ exception -> assetAttributeConsumer.accept(new HashMap<>())
+ );
}
@Override
- protected IsWidget createValueEditor(ValueHolder valueHolder, ValueType valueType, AttributeView.Style style, Runnable onValueModified) {
+ protected IsWidget createValueEditor(ValueHolder valueHolder, ValueType valueType, AttributeView.Style style, AttributeView parentView, Consumer<Value> onValueModified) {
switch (valueType) {
case ARRAY:
if (valueHolder instanceof MetaItem) {
- Optional<AssetMeta> assetMeta = AssetMeta.getAssetMeta(((MetaItem) valueHolder).getName().orElse(null));
-
- if (assetMeta.map(am -> am == AssetMeta.AGENT_LINK).orElse(false)) {
+ if (isMetaNameEqualTo((MetaItem)valueHolder, AssetMeta.AGENT_LINK)) {
boolean isReadOnly = isValueReadOnly(valueHolder);
String assetWatermark = environment.getMessages().selectAgent();
String attributeWatermark = environment.getMessages().selectProtocolConfiguration();
- return createAttributeRefEditor(valueHolder, onValueModified, isReadOnly, this::getLinkableAssets, this::getLinkableAttributes, assetWatermark, attributeWatermark, style.agentLinkEditor());
+ return new AttributeRefEditor(
+ valueHolder.getValue().flatMap(AttributeRef::fromValue).orElse(null),
+ attrRef -> onValueModified.accept(attrRef != null ? attrRef.toArrayValue() : null),
+ isReadOnly,
+ assetAttributeConsumer -> getLinkableAssetsAndAttributes(valueHolder, assetAttributeConsumer),
+ assetWatermark,
+ attributeWatermark,
+ style.agentLinkEditor()
+ );
+ }
+ }
+ break;
+ case OBJECT:
+ if (valueHolder instanceof MetaItem) {
+ if (isMetaNameEqualTo((MetaItem)valueHolder, AssetMeta.ATTRIBUTE_LINK)) {
+ boolean isReadOnly = isValueReadOnly(valueHolder);
+ String assetWatermark = environment.getMessages().selectAsset();
+ String attributeWatermark = environment.getMessages().selectAttribute();
+ return new AttributeLinkEditor(
+ environment,
+ style,
+ parentView,
+ this::createValueEditor,
+ this::showValidationError,
+ valueHolder.getValue().flatMap(AttributeLink::fromValue).orElse(null),
+ attrLink -> onValueModified.accept(attrLink != null ? attrLink.toObjectValue() : null),
+ isReadOnly,
+ assetAttributeConsumer -> getLinkableAssetsAndAttributes(valueHolder, assetAttributeConsumer),
+ assetWatermark,
+ attributeWatermark,
+ style.agentLinkEditor()
+ );
}
}
}
- return super.createValueEditor(valueHolder, valueType, style, onValueModified);
+ return super.createValueEditor(valueHolder, valueType, style, parentView, onValueModified);
}
@Override
@@ -493,7 +496,7 @@ public class AssetEditActivity
);
}
- extensions.add(new MetaEditor(environment, this.view.getStyle(), view, attribute, () -> protocolDescriptors));
+ extensions.add(new MetaEditor(environment, this.view.getStyle(), environment.getMessages().metaItems(), environment.getMessages().newMetaItems(), view, attribute, () -> protocolDescriptors));
return extensions;
}
@@ -525,21 +528,6 @@ public class AssetEditActivity
@Override
protected void validateAttribute(boolean clientSideOnly, AssetAttribute attribute, Consumer<AttributeValidationResult> resultConsumer) {
super.validateAttribute(clientSideOnly, attribute, validationResult -> {
- if (validationResult.isValid() && attribute.hasMetaItems()) {
- // Do additional validation on the meta items
-
- for (int i = 0; i < attribute.getMeta().size(); i++) {
- MetaItem metaItem = attribute.getMeta().get(i);
- int finalI = i;
- metaItemDescriptors.stream()
- .filter(metaItemDescriptor -> metaItemDescriptor.getUrn().equals(metaItem.getName().orElse("")))
- .findFirst()
- .flatMap(metaItemDescriptor ->
- MetaItemDescriptor.validateValue(metaItem.getValue().orElse(null), metaItemDescriptor)
- )
- .ifPresent(failure -> validationResult.addMetaFailure(finalI, failure));
- }
- }
if (!clientSideOnly && validationResult.isValid() && ProtocolConfiguration.isProtocolConfiguration(attribute)) {
// Ask the server to validate the protocol configuration
@@ -558,6 +546,13 @@ public class AssetEditActivity
}
+ @Override
+ protected Optional<MetaItemDescriptor> getMetaItemDescriptor(MetaItem item) {
+ return metaItemDescriptors.stream()
+ .filter(metaItemDescriptor -> metaItemDescriptor.getUrn().equals(item.getName().orElse("")))
+ .findFirst();
+ }
+
protected void writeAttributeTypesToView(Runnable onComplete) {
view.selectWellKnownType(asset.getWellKnownType());
view.setAvailableWellKnownTypes(AssetType.valuesSorted());
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributeView.java b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributeView.java
index 4fffcd777..5bf70e0e4 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributeView.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributeView.java
@@ -24,6 +24,7 @@ import org.openremote.model.ValidationFailure;
import org.openremote.model.ValueHolder;
import org.openremote.model.asset.AssetAttribute;
import org.openremote.model.attribute.AttributeValidationResult;
+import org.openremote.model.value.Value;
import org.openremote.model.value.ValueType;
import java.util.function.Consumer;
@@ -41,7 +42,7 @@ public interface AttributeView extends IsWidget {
@FunctionalInterface
interface ValueEditorSupplier {
- IsWidget createValueEditor(ValueHolder valueHolder, ValueType valueType, AttributeView.Style style, Runnable onValueModified);
+ IsWidget createValueEditor(ValueHolder valueHolder, ValueType valueType, AttributeView.Style style, AttributeView parentView, Consumer<Value> onValueModified);
}
interface Style {
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributeViewImpl.java b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributeViewImpl.java
index 1fe1ddd2e..9f1a32f65 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributeViewImpl.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributeViewImpl.java
@@ -25,10 +25,10 @@ import com.google.gwt.user.client.ui.Widget;
import elemental.client.Browser;
import org.openremote.manager.client.Environment;
import org.openremote.manager.client.widget.*;
-import org.openremote.model.ValidationFailure;
import org.openremote.model.asset.AssetAttribute;
import org.openremote.model.attribute.AttributeType;
import org.openremote.model.attribute.AttributeValidationResult;
+import org.openremote.model.value.Value;
import java.util.List;
import java.util.Optional;
@@ -168,7 +168,10 @@ public class AttributeViewImpl extends FormGroup implements AttributeView {
return this;
}
- protected void notifyAttributeModified() {
+ protected void notifyAttributeModified(Value newValue) {
+ // Push new value into the attribute
+ attribute.setValue(newValue, 0);
+
if (attributeModifiedCallback != null) {
attributeModifiedCallback.accept(attribute);
}
@@ -178,6 +181,7 @@ public class AttributeViewImpl extends FormGroup implements AttributeView {
return valueEditorSupplier.createValueEditor(attribute,
attribute.getType().map(AttributeType::getValueType).orElse(null),
style,
+ null,
this::notifyAttributeModified);
}
@@ -241,10 +245,4 @@ public class AttributeViewImpl extends FormGroup implements AttributeView {
getFormField().add(createAttributeValueEditor());
}
-
- public void showValidationError(String attributeName, String metaItemName, ValidationFailure validationFailure) {
- if (validationErrorConsumer != null) {
- validationErrorConsumer.accept(attributeName, metaItemName, validationFailure);
- }
- }
}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/MetaEditor.java b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/MetaEditor.java
index a7218885a..7c14777fa 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/MetaEditor.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/MetaEditor.java
@@ -24,7 +24,6 @@ import com.google.gwt.user.client.ui.IsWidget;
import org.openremote.manager.client.Environment;
import org.openremote.manager.client.widget.*;
import org.openremote.model.ValidationFailure;
-import org.openremote.model.ValueHolder;
import org.openremote.model.asset.AssetAttribute;
import org.openremote.model.asset.AssetMeta;
import org.openremote.model.asset.agent.AgentLink;
@@ -40,8 +39,9 @@ import org.openremote.model.value.Values;
import java.util.*;
import java.util.function.Supplier;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
-import static org.openremote.model.attribute.MetaItem.MetaItemFailureReason.META_ITEM_VALUE_IS_REQUIRED;
import static org.openremote.model.util.TextUtil.isNullOrEmpty;
public class MetaEditor extends AbstractAttributeViewExtension {
@@ -53,20 +53,19 @@ public class MetaEditor extends AbstractAttributeViewExtension {
protected FormListBox nameList;
protected FormListBox typeList;
protected FormInputText nameInput;
- protected FormGroupActions formGroupActions;
protected IsWidget valueEditor;
- protected boolean isNewItem;
+ protected boolean newItem;
protected MetaItemDescriptor currentDescriptor;
- public MetaItemEditor(MetaEditor parentEditor, MetaItem item, boolean isNewItem) {
+ public MetaItemEditor(MetaEditor parentEditor, MetaItem item, boolean newItem) {
this.parentEditor = parentEditor;
this.item = item;
- this.isNewItem = isNewItem;
+ this.newItem = newItem;
field = new FormField();
this.setFormField(field);
// Don't show protocol configuration item in main section
- if (!isNewItem && item.getName()
+ if (!newItem && item.getName()
.map(name -> AssetMeta.PROTOCOL_CONFIGURATION.getUrn().equals(name))
.orElse(false)) {
setVisible(false);
@@ -99,15 +98,14 @@ public class MetaEditor extends AbstractAttributeViewExtension {
nameInput = new FormInputText();
field.add(nameInput);
nameInput.addStyleName(style.metaItemNameEditor());
- nameInput.setPlaceholder(environment.getMessages().enterCustomAssetAttributeMetaName());
+ nameInput.setPlaceholder(getCustomNameWatermark());
nameInput.addKeyUpHandler(event -> {
if (isNullOrEmpty(nameInput.getValue())) {
item.clearName();
} else {
item.setName(nameInput.getValue());
}
- notifyAttributeModified();
- notifyAttributeModified();
+ validateItem(this);
});
nameInput.addValueChangeHandler(event -> {
if (isNullOrEmpty(event.getValue())) {
@@ -115,27 +113,24 @@ public class MetaEditor extends AbstractAttributeViewExtension {
} else {
item.setName(event.getValue());
}
- notifyAttributeModified();
+ validateItem(this);
});
typeList = new FormListBox();
field.add(typeList);
- typeList.addItem(environment.getMessages().selectType(), "");
- valueTypes.stream()
- .map(Enum::name)
- .map(valueType -> new Pair<>(environment.getMessages().valueTypeDisplayName(valueType), valueType))
- .sorted(Comparator.comparing(typeEntry -> typeEntry.key))
- .forEach(typeEntry -> typeList.addItem(typeEntry.key, typeEntry.value));
+ populateTypeList(this);
- typeList.addChangeHandler(event -> onTypeChanged(true));
+ typeList.addChangeHandler(event -> onMetaItemTypeChanged(this, true));
- formGroupActions = new FormGroupActions();
+ FormGroupActions formGroupActions = new FormGroupActions();
FormButton button = new FormButton();
- button.setText(isNewItem ? environment.getMessages().addItem() : environment.getMessages().deleteItem());
- button.setIcon(isNewItem ? "plus" : "remove");
+ button.setText(newItem ? getAddButtonLabel() : getDeleteButtonLabel());
+ // This has to be after setText otherwise get strange behaviour due to faces of push button
+ button.setEnabled(!newItem);
+ button.setIcon(newItem ? "plus" : "remove");
button.addClickHandler(clickEvent -> {
- if (isNewItem) {
+ if (newItem) {
if (parentEditor.addItem(item.copy(), false)) {
reset();
}
@@ -150,11 +145,28 @@ public class MetaEditor extends AbstractAttributeViewExtension {
onNameChanged(false);
}
- protected IsWidget createItemValueEditor() {
- return valueEditorSupplier.createValueEditor(item,
- EnumUtil.enumFromString(ValueType.class, typeList.getSelectedValue()).orElse(ValueType.STRING),
- style,
- this::onModified);
+ public FormListBox getNameList() {
+ return nameList;
+ }
+
+ public FormListBox getTypeList() {
+ return typeList;
+ }
+
+ public FormField getField() {
+ return field;
+ }
+
+ public MetaItem getItem() {
+ return item;
+ }
+
+ public boolean isNewItem() {
+ return newItem;
+ }
+
+ public Optional<MetaItemDescriptor> getCurrentDescriptor() {
+ return Optional.ofNullable(currentDescriptor);
}
protected void onNameChanged(boolean updateItem) {
@@ -191,63 +203,27 @@ public class MetaEditor extends AbstractAttributeViewExtension {
nameInput.setVisible(!currentMetaItemDescriptor.isPresent());
typeList.setVisible(!currentMetaItemDescriptor.isPresent());
typeList.selectItem(typeListValue);
- onTypeChanged(updateItem);
+ onMetaItemTypeChanged(this, updateItem);
}
- protected void onTypeChanged(boolean updateItem) {
- Optional<AssetMeta> assetMeta = AssetMeta.getAssetMeta(nameList.getSelectedValue());
-
- if (updateItem) {
- item.clearValue();
- Value initialValue = assetMeta.map(AssetMeta::getInitialValue).orElse(null);
- ValueType valueType = EnumUtil.enumFromString(ValueType.class, typeList.getSelectedValue()).orElse(null);
- if (valueType == ValueType.BOOLEAN && initialValue == null) {
- initialValue = Values.create(false);
- }
-
- item.setValue(initialValue);
- onModified();
- }
- updateValueEditor();
- }
-
- protected void updateValueEditor() {
+ public void updateValueEditor() {
if (valueEditor != null) {
field.remove(valueEditor);
+ valueEditor = null;
}
if (typeList.getSelectedIndex() > 0) {
- valueEditor = createItemValueEditor();
- field.add(valueEditor);
+ valueEditor = createItemValueEditor(this);
+ if (valueEditor != null) {
+ field.add(valueEditor);
+ }
}
}
- protected void onModified() {
- if (isNewItem) {
- // Do basic validation on new meta item in situ
- List<ValidationFailure> failures = item.getValidationFailures();
- boolean hasFailures = failures != null && !failures.isEmpty();
-
- if (!hasFailures && currentDescriptor != null) {
- ValidationFailure failure = item.getValue()
- .flatMap(currentDescriptor::validateValue)
- .orElse(null);
- if (failure != null) {
- failures = Collections.singletonList(failure);
- }
- }
-
- formGroupActions.forEach(widget -> {
- if (widget instanceof FormButton) {
- ((FormButton) widget).setEnabled(!hasFailures);
- }
- });
- updateEditorFailures(this, failures);
- } else {
- // Presenter will notify us of failures in the context of the whole attribute as well as any asset meta
- // type mismatching etc.
- notifyAttributeModified();
- }
+ public void onModified(Value newValue) {
+ // Push new value into the meta item
+ item.setValue(newValue);
+ validateItem(this);
}
protected void reset() {
@@ -256,8 +232,27 @@ public class MetaEditor extends AbstractAttributeViewExtension {
nameList.setSelectedIndex(0);
nameInput.setValue(null);
typeList.setSelectedIndex(0);
+ if (newItem) {
+ formGroupActions.forEach(widget -> {
+ if (widget instanceof FormButton) {
+ ((FormButton) widget).setEnabled(!errorInField);
+ }
+ });
+ }
onNameChanged(false);
}
+
+ @Override
+ public void setError(boolean errorInField) {
+ super.setError(errorInField);
+ if (newItem) {
+ formGroupActions.forEach(widget -> {
+ if (widget instanceof FormButton) {
+ ((FormButton) widget).setEnabled(!errorInField);
+ }
+ });
+ }
+ }
}
protected static final List<ValueType> valueTypes = Arrays.asList(ValueType.values());
@@ -269,8 +264,8 @@ public class MetaEditor extends AbstractAttributeViewExtension {
protected boolean isProtocolConfiguration;
protected AttributeValidationResult lastValidationResult;
- public MetaEditor(Environment environment, AttributeView.Style style, AttributeView parentView, AssetAttribute attribute, Supplier<List<ProtocolDescriptor>> protocolDescriptorSupplier) {
- super(environment, style, parentView, attribute, environment.getMessages().metaItems());
+ public MetaEditor(Environment environment, AttributeView.Style style, String existingItemsHeader, String newItemsHeader, AttributeView parentView, AssetAttribute attribute, Supplier<List<ProtocolDescriptor>> protocolDescriptorSupplier) {
+ super(environment, style, parentView, attribute, existingItemsHeader);
this.attribute = attribute;
this.style = style;
isProtocolConfiguration = attribute.hasMetaItem(AssetMeta.PROTOCOL_CONFIGURATION);
@@ -317,7 +312,7 @@ public class MetaEditor extends AbstractAttributeViewExtension {
.sorted(Comparator.comparing(MetaItemDescriptor::name))
.toArray(MetaItemDescriptor[]::new);
- itemEditorSectionLabel = new FormSectionLabel(environment.getMessages().newItem());
+ itemEditorSectionLabel = new FormSectionLabel(newItemsHeader);
add(itemListPanel);
add(itemEditorSectionLabel);
add(itemEditorPanel);
@@ -339,10 +334,78 @@ public class MetaEditor extends AbstractAttributeViewExtension {
}
}
+ protected String getCustomNameWatermark() {
+ return environment.getMessages().enterCustomAssetAttributeMetaName();
+ }
+
+ protected String getTypeWatermark() {
+ return environment.getMessages().selectType();
+ }
+
+ protected String getAddButtonLabel() {
+ return environment.getMessages().addItem();
+ }
+
+ protected List<MetaItemEditor> getExistingItemEditors() {
+ return IntStream.range(0, itemListPanel.getWidgetCount())
+ .mapToObj(i -> (MetaItemEditor)itemListPanel.getWidget(i))
+ .collect(Collectors.toList());
+ }
+
+ protected String getDeleteButtonLabel() {
+ return environment.getMessages().deleteItem();
+ }
+
+ protected void populateTypeList(MetaItemEditor itemEditor) {
+ itemEditor.typeList.addItem(getTypeWatermark(), "");
+
+ valueTypes.stream()
+ .map(Enum::name)
+ .map(valueType -> new Pair<>(environment.getMessages().valueTypeDisplayName(valueType), valueType))
+ .sorted(Comparator.comparing(typeEntry -> typeEntry.key))
+ .forEach(typeEntry -> itemEditor.typeList.addItem(typeEntry.key, typeEntry.value));
+ }
+
+ protected IsWidget createItemValueEditor(MetaItemEditor itemEditor) {
+ return valueEditorSupplier.createValueEditor(itemEditor.item,
+ EnumUtil.enumFromString(ValueType.class, itemEditor.typeList.getSelectedValue()).orElse(ValueType.STRING),
+ style,
+ parentView,
+ itemEditor::onModified);
+ }
+
+ protected void onMetaItemTypeChanged(MetaItemEditor itemEditor, boolean updateItem) {
+ Optional<AssetMeta> assetMeta = AssetMeta.getAssetMeta(itemEditor.nameList.getSelectedValue());
+
+ if (updateItem) {
+ itemEditor.item.clearValue();
+ Value initialValue = assetMeta.map(AssetMeta::getInitialValue).orElse(null);
+ ValueType valueType = EnumUtil.enumFromString(ValueType.class, itemEditor.typeList.getSelectedValue()).orElse(null);
+ if (valueType == ValueType.BOOLEAN && initialValue == null) {
+ initialValue = Values.create(false);
+ }
+
+ itemEditor.onModified(initialValue);
+ }
+ itemEditor.updateValueEditor();
+ }
+
+ protected void validateItem(MetaItemEditor itemEditor) {
+ if (itemEditor.newItem) {
+ // Do basic validation on new meta item in situ
+ List<ValidationFailure> failures = itemEditor.getItem().getValidationFailures(itemEditor.getCurrentDescriptor());
+ updateEditorFailures(itemEditor, failures);
+ } else {
+ // Presenter will notify us of failures in the context of the whole attribute as well as any asset meta
+ // type mismatching etc.
+ notifyAttributeModified();
+ }
+ }
+
protected void buildNewItemEditor() {
itemEditorPanel.clear();
MetaItem item = new MetaItem();
- MetaItemEditor metaItemEditor = new MetaItemEditor(this, item, true);
+ MetaItemEditor metaItemEditor = createMetaItemEditor(item, true);
itemEditorPanel.add(metaItemEditor);
}
@@ -381,7 +444,7 @@ public class MetaEditor extends AbstractAttributeViewExtension {
}
int index = itemListPanel.getWidgetCount();
- MetaItemEditor metaItemEditor = new MetaItemEditor(this, item, false);
+ MetaItemEditor metaItemEditor = createMetaItemEditor(item, false);
itemListPanel.add(metaItemEditor);
// Check if we have a validation failure for this editor
@@ -394,6 +457,10 @@ public class MetaEditor extends AbstractAttributeViewExtension {
return true;
}
+ protected MetaItemEditor createMetaItemEditor(MetaItem item, boolean isNewItem) {
+ return new MetaItemEditor(this, item, isNewItem);
+ }
+
protected void removeItem(MetaItemEditor itemEditor) {
int index = itemListPanel.getWidgetIndex(itemEditor);
itemListPanel.remove(itemEditor);
@@ -408,75 +475,72 @@ public class MetaEditor extends AbstractAttributeViewExtension {
lastValidationResult = validationResult;
boolean hasMetaFailures = validationResult.getMetaFailures() != null;
- for (int i = 0; i < itemListPanel.getWidgetCount(); i++) {
- MetaItemEditor editor = (MetaItemEditor) itemListPanel.getWidget(i);
- List<ValidationFailure> failures = !hasMetaFailures ? null : validationResult.getMetaFailures().get(i);
- updateEditorFailures(editor, failures);
- }
+ List<MetaItemEditor> editors = getExistingItemEditors();
+ IntStream.range(0, editors.size())
+ .forEach(i -> {
+ MetaItemEditor editor = editors.get(i);
+ List<ValidationFailure> failures = !hasMetaFailures ? null : validationResult.getMetaFailures().get(i);
+ updateEditorFailures(editor, failures);
+ }
+ );
- if (hasMetaFailures) {
- if (itemListPanel.getWidgetCount() == 0) {
- // Editor hasn't been attached to the view yet but still show toast messages
- validationResult.getMetaFailures().forEach((index, failures) ->
- showMetaItemFailure(attribute.getMeta().get(index), Optional.empty(), failures)
- );
- } else if (validationResult.getMetaFailures().containsKey(-1)) {
- // Check for missing meta item messages
- List<ValidationFailure> failures = validationResult.getMetaFailures().get(-1);
- if (failures != null) {
- failures.forEach(failure ->
- showValidationError(
- attribute.getName().orElse(""),
- null,
- new ValidationFailure(
- failure.getReason(),
- failure.getParameter()
- .map(parameter ->
- // Parameter should be meta item name URN
- getMetaItemDescriptor(parameter)
- .map(metaItemDescriptor -> getMetaItemDisplayName(environment, metaItemDescriptor.name()))
- .orElse(parameter)
- )
- .orElse("")
- )
+ // Check for missing meta item messages
+ if (validationResult.getMetaFailures() != null && validationResult.getMetaFailures().containsKey(-1)) {
+ List<ValidationFailure> failures = validationResult.getMetaFailures().get(-1);
+ if (failures != null) {
+ failures.forEach(failure ->
+ showValidationError(
+ attribute.getName().orElse(""),
+ null,
+ new ValidationFailure(
+ failure.getReason(),
+ failure.getParameter()
+ .map(parameter ->
+ // Parameter should be meta item name URN
+ getMetaItemDescriptor(parameter)
+ .map(metaItemDescriptor -> getMetaItemDisplayName(environment, metaItemDescriptor.name()))
+ .orElse(parameter)
+ )
+ .orElse("")
)
- );
- }
+ )
+ );
}
}
}
- protected void updateEditorFailures(MetaItemEditor editor, List<ValidationFailure> failures) {
+ protected void updateEditorFailures(MetaItemEditor metaItemEditor, List<ValidationFailure> failures) {
boolean hasFailures = failures != null && !failures.isEmpty();
- editor.setError(hasFailures);
+ metaItemEditor.setError(hasFailures);
if (hasFailures) {
- Optional<ValueType> valueType = EnumUtil.enumFromString(ValueType.class, editor.typeList.getSelectedValue());
- showMetaItemFailure(editor.item, valueType, failures);
+ showMetaItemFailure(metaItemEditor, failures);
}
}
- protected void showMetaItemFailure(MetaItem metaItem, Optional<ValueType> valueType, List<ValidationFailure> failures) {
- Optional<MetaItemDescriptor> optionalMetaItemDescriptor = metaItem.getName()
- .flatMap(this::getMetaItemDescriptor);
+ protected void showMetaItemFailure(MetaItemEditor metaItemEditor, List<ValidationFailure> failures) {
+ if (failures != null) {
+ Optional<MetaItemDescriptor> optionalMetaItemDescriptor = metaItemEditor.getCurrentDescriptor();
+ String displayName = optionalMetaItemDescriptor
+ .map(metaItemDescriptor -> getMetaItemDisplayName(environment, metaItemDescriptor.name()))
+ .orElse(metaItemEditor.getItem().getName().orElse(""));
+
+ failures.forEach(failure -> {
+ if (failure.getReason() == MetaItem.MetaItemFailureReason.META_ITEM_VALUE_IS_REQUIRED) {
+ // Substitute in value type info
+ String parameter = EnumUtil.enumFromString(ValueType.class, metaItemEditor.getTypeList().getSelectedValue())
+ .map(Enum::name)
+ .orElse("Value");
- String displayName = optionalMetaItemDescriptor
- .map(metaItemDescriptor -> getMetaItemDisplayName(environment, metaItemDescriptor.name()))
- .orElse(metaItem.getName().orElse(""));
+ failure = new ValidationFailure(failure.getReason(), parameter);
+ }
- if (failures != null) {
- failures.forEach(failure ->
showValidationError(
attribute.getName().orElse(""),
displayName,
- mapValidationFailure(
- failure,
- valueType.orElse(optionalMetaItemDescriptor
- .map(MetaItemDescriptor::getValueType)
- .orElse(null))
- )
- )
- );
+ failure
+ );
+ });
}
}
@@ -486,40 +550,6 @@ public class MetaEditor extends AbstractAttributeViewExtension {
.findFirst();
}
- /**
- * This allows descriptor value type to be used to provide more specific meta item value messages
- */
- protected ValidationFailure mapValidationFailure(ValidationFailure failure, ValueType valueType) {
- ValidationFailure validationFailure = failure;
- ValidationFailure.Reason reason = failure.getReason();
- String parameter = failure.getParameter().orElse(null);
-
- // Convert certain errors to something more meaningful
- if (reason == META_ITEM_VALUE_IS_REQUIRED && valueType != null) {
-
- switch (valueType) {
- case OBJECT:
- reason = ValueHolder.ValueFailureReason.VALUE_EXPECTED_OBJECT;
- break;
- case ARRAY:
- reason = ValueHolder.ValueFailureReason.VALUE_EXPECTED_ARRAY;
- break;
- case STRING:
- reason = ValueHolder.ValueFailureReason.VALUE_EXPECTED_STRING;
- break;
- case NUMBER:
- reason = ValueHolder.ValueFailureReason.VALUE_EXPECTED_NUMBER;
- break;
- case BOOLEAN:
- reason = ValueHolder.ValueFailureReason.VALUE_EXPECTED_BOOLEAN;
- break;
- }
- validationFailure = new ValidationFailure(reason, parameter);
- }
-
- return validationFailure;
- }
-
@Override
public void onAttributeChanged() {
onAttach();
diff --git a/manager/client/src/main/java/org/openremote/manager/client/i18n/ManagerMessages.java b/manager/client/src/main/java/org/openremote/manager/client/i18n/ManagerMessages.java
index 0f12b29b4..b1fc01eed 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/i18n/ManagerMessages.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/i18n/ManagerMessages.java
@@ -211,7 +211,7 @@ public interface ManagerMessages extends Messages {
String deleteItem();
- String newItem();
+ String newMetaItems();
String addItem();
@@ -428,4 +428,20 @@ public interface ManagerMessages extends Messages {
String protocolLinkDiscoverySuccess(@PluralCount int assetCount);
String protocolLinkDiscoveryFailure(int failureCode);
+
+ String attributeLinkConverterValues();
+
+ String attributeLinkNewConverterValue();
+
+ String enterConverterValue();
+
+ String selectConverter();
+
+ String customConverter();
+
+ String converterType(@Select String type);
+
+ String addConverterValue();
+
+ String deleteConverterValue();
}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/simulator/Simulator.java b/manager/client/src/main/java/org/openremote/manager/client/simulator/Simulator.java
index c7c66c127..5ee1423df 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/simulator/Simulator.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/simulator/Simulator.java
@@ -38,9 +38,11 @@ import org.openremote.model.event.bus.EventRegistration;
import org.openremote.model.simulator.RequestSimulatorState;
import org.openremote.model.simulator.SimulatorElement;
import org.openremote.model.simulator.SimulatorState;
+import org.openremote.model.value.Value;
import org.openremote.model.value.ValueType;
import java.util.*;
+import java.util.function.Consumer;
public class Simulator extends AbstractAttributeViewExtension {
@@ -116,13 +118,14 @@ public class Simulator extends AbstractAttributeViewExtension {
// Don't push simulator value validation up to the presenter as it is a special case that should
// just be evaluated in-situ and shouldn't invalidate the parent attribute
- Runnable onModified = () -> {
+ Consumer<Value> onModified = value -> {
+ element.setValue(value);
List<ValidationFailure> failures = element.getValidationFailures();
formGroup.setError(failures != null && !failures.isEmpty());
};
ValueType valueType = element.getExpectedType().getValueType();
- IsWidget editor = valueEditorSupplier.createValueEditor(element, valueType, style, onModified);
+ IsWidget editor = valueEditorSupplier.createValueEditor(element, valueType, style, parentView, onModified);
formField.add(editor);
formGroups.put(element.getAttributeRef(), formGroup);
add(formGroup);
diff --git a/manager/client/src/main/java/org/openremote/manager/client/widget/AttributeLinkEditor.java b/manager/client/src/main/java/org/openremote/manager/client/widget/AttributeLinkEditor.java
new file mode 100644
index 000000000..cc27cb4e7
--- /dev/null
+++ b/manager/client/src/main/java/org/openremote/manager/client/widget/AttributeLinkEditor.java
@@ -0,0 +1,341 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.manager.client.widget;
+
+import com.google.gwt.dom.client.Style;
+import com.google.gwt.user.client.ui.FlowPanel;
+import com.google.gwt.user.client.ui.IsWidget;
+import org.openremote.manager.client.Environment;
+import org.openremote.manager.client.assets.attributes.AttributeView;
+import org.openremote.manager.client.assets.attributes.MetaEditor;
+import org.openremote.model.ValidationFailure;
+import org.openremote.model.asset.AssetAttribute;
+import org.openremote.model.asset.AssetMeta;
+import org.openremote.model.attribute.*;
+import org.openremote.model.util.EnumUtil;
+import org.openremote.model.util.Pair;
+import org.openremote.model.value.ObjectValue;
+import org.openremote.model.value.Value;
+import org.openremote.model.value.ValueType;
+import org.openremote.model.value.Values;
+
+import java.util.*;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+public class AttributeLinkEditor extends FlowPanel {
+
+ public enum FailureReason implements ValidationFailure.Reason {
+ CONVERTER_KEY_DUPLICATION,
+ CONVERTER_KEY_REQUIRED,
+ CONVERTER_VALUE_REQUIRED,
+ CONVERTER_VALUE_MISMATCH
+ }
+
+ protected final Environment environment;
+ protected final AttributeRefEditor attributeRefEditor;
+ protected final MetaEditor converterEditor;
+ protected final Consumer<AttributeLink> onValueModified;
+ protected final AttributeView parentView;
+ protected final AttributeView.ValidationErrorConsumer validationErrorConsumer;
+
+ // This is used to map converter values to attribute meta so we can use the meta editor
+ protected final AssetAttribute converterAttribute;
+ protected AttributeRef attributeRef;
+
+ public AttributeLinkEditor(Environment environment,
+ AttributeView.Style viewStyle,
+ AttributeView parentView,
+ AttributeView.ValueEditorSupplier valueEditorSupplier,
+ AttributeView.ValidationErrorConsumer validationErrorConsumer,
+ AttributeLink currentValue,
+ Consumer<AttributeLink> onValueModified,
+ boolean readOnly,
+ Consumer<Consumer<Map<AttributeRefEditor.AssetInfo, List<AttributeRefEditor.AttributeInfo>>>> assetAttributeSupplier,
+ String assetWatermark,
+ String attributeWatermark,
+ String styleName) {
+
+ this.getElement().getStyle().setWidth(100, Style.Unit.PCT);
+ this.environment = environment;
+ this.parentView = parentView;
+ this.validationErrorConsumer = validationErrorConsumer;
+ this.onValueModified = onValueModified;
+
+ // Create the attribute ref editor
+ this.attributeRef = currentValue != null ? currentValue.getAttributeRef() : null;
+ attributeRefEditor = new AttributeRefEditor(
+ this.attributeRef,
+ this::onAttributeRefModified,
+ readOnly,
+ assetAttributeSupplier,
+ assetWatermark,
+ attributeWatermark,
+ styleName);
+
+ add(attributeRefEditor);
+
+ // Create the meta editor (although converter is not meta the editor fits here so convert the converter
+ // into compatible data - ideally the meta editor would be more generic but this will do for now)
+ converterAttribute = new AssetAttribute(parentView.getAttribute().getName().orElse(""));
+ if (currentValue != null) {
+ currentValue.getConverter()
+ .map(AttributeLinkEditor::convertConverterToMeta)
+ .ifPresent(converterAttribute::setMeta);
+ }
+
+ converterEditor = new MetaEditor(
+ environment,
+ viewStyle,
+ environment.getMessages().attributeLinkConverterValues(),
+ environment.getMessages().attributeLinkNewConverterValue(),
+ parentView,
+ converterAttribute,
+ null
+ ) {
+ @Override
+ protected String getCustomNameWatermark() {
+ return environment.getMessages().enterConverterValue();
+ }
+
+ @Override
+ protected String getTypeWatermark() {
+ return environment.getMessages().selectConverter();
+ }
+
+ @Override
+ protected String getAddButtonLabel() {
+ return environment.getMessages().addConverterValue();
+ }
+
+ @Override
+ protected String getDeleteButtonLabel() {
+ return environment.getMessages().deleteConverterValue();
+ }
+
+ @Override
+ protected void populateTypeList(MetaItemEditor itemEditor) {
+ itemEditor.getTypeList().addItem(getTypeWatermark(), "");
+
+ // Include converter enum
+ AttributeLink.ConverterType[] converters = AttributeLink.ConverterType.values();
+ List<Pair<String,String>> typeValues = new ArrayList<>(valueTypes.size() + converters.length);
+
+ typeValues.addAll(
+ Arrays.stream(converters)
+ .map(converter ->
+ new Pair<>(environment.getMessages().converterType(converter.name()), converter.getValue())
+ )
+ .collect(Collectors.toList())
+ );
+
+ typeValues.addAll(
+ valueTypes.stream()
+ .map(Enum::name)
+ .map(valueType -> new Pair<>(environment.getMessages().valueTypeDisplayName(valueType), valueType))
+ .collect(Collectors.toList())
+ );
+
+ typeValues.stream()
+ .sorted(Comparator.comparing(typeEntry -> typeEntry.key))
+ .forEach(typeEntry -> itemEditor.getTypeList().addItem(typeEntry.key, typeEntry.value));
+ }
+
+ @Override
+ protected MetaItemEditor createMetaItemEditor(MetaItem item, boolean isNewItem) {
+ MetaItemEditor itemEditor = super.createMetaItemEditor(item, isNewItem);
+ itemEditor.getNameList().setVisible(false);
+ return itemEditor;
+ }
+
+ @Override
+ protected IsWidget createItemValueEditor(MetaItemEditor itemEditor) {
+ // If type is a converter then don't use a value editor
+ if (isStandardConverter(itemEditor.getTypeList().getSelectedValue())) {
+ // This is a standard converter and no editor required
+ return null;
+ }
+ return super.createItemValueEditor(itemEditor);
+ }
+
+ @Override
+ protected void onMetaItemTypeChanged(MetaItemEditor itemEditor, boolean updateItem) {
+ if (updateItem) {
+ Value initialValue = AttributeLink.ConverterType
+ .fromValue(itemEditor.getTypeList().getSelectedValue())
+ .map(converter -> (Value)Values.create(converter.getValue()))
+ .orElseGet(() ->
+ EnumUtil.enumFromString(ValueType.class, itemEditor.getTypeList().getSelectedValue())
+ .map(valueType ->
+ valueType == ValueType.BOOLEAN ? Values.create(false) : null
+ )
+ .orElse(null)
+ );
+
+ itemEditor.onModified(initialValue);
+ } else {
+ // This is the editor initialising select the correct type for known converter values
+ itemEditor.getItem()
+ .getValueAsString()
+ .flatMap(AttributeLink.ConverterType::fromValue)
+ .ifPresent(converterType -> itemEditor.getTypeList().selectItem(converterType.getValue()));
+ }
+
+ itemEditor.updateValueEditor();
+ }
+
+ @Override
+ protected boolean addItem(MetaItem item, boolean viewOnly) {
+ if (viewOnly) {
+ return super.addItem(item, true);
+ }
+
+ // Check item with this name doesn't already exist
+ boolean canAdd = !converterAttribute.hasMetaItem(item.getName().orElse(null));
+ if (!canAdd) {
+ String metaItemName = getMetaItemDisplayName(environment, AssetMeta.ATTRIBUTE_LINK.name());
+ showValidationError(attribute.getName().orElse(""), metaItemName, new ValidationFailure(FailureReason.CONVERTER_KEY_DUPLICATION, item.getName().orElse("")));
+ return false;
+ }
+
+ attribute.getMeta().add(item);
+ // Notify the presenter that the attribute has changed
+ notifyAttributeModified();
+ return super.addItem(item, true);
+ }
+
+ @Override
+ protected void validateItem(MetaItemEditor itemEditor) {
+ if (!itemEditor.isNewItem()) {
+ super.validateItem(itemEditor);
+ return;
+ }
+
+ // Converter items need a key and a value and key must be unique
+ List<ValidationFailure> failures = itemEditor.getItem().getValidationFailures();
+ boolean hasFailures = failures != null && !failures.isEmpty();
+ if (!hasFailures && converterAttribute.hasMetaItem(itemEditor.getItem().getName().orElse(null))) {
+ failures = Collections.singletonList(new ValidationFailure(FailureReason.CONVERTER_KEY_DUPLICATION, itemEditor.getItem().getName().orElse("")));
+ }
+ updateEditorFailures(itemEditor, failures);
+ }
+
+ protected boolean isStandardConverter(String typeValue) {
+ return typeValue != null && typeValue.indexOf('@') == 0;
+ }
+ };
+
+ converterEditor.setValueEditorSupplier(valueEditorSupplier);
+ converterEditor.setEditMode(true);
+ converterEditor.setAttributeModifiedCallback(this::onConverterModified);
+ converterEditor.setValidationErrorConsumer(this::showConverterEditorValidationError);
+
+ add(converterEditor);
+ }
+
+ protected void onAttributeRefModified(AttributeRef attributeRef) {
+ this.attributeRef = attributeRef;
+ updateAttributeLink();
+ }
+
+ @SuppressWarnings("unused")
+ protected void onConverterModified(AssetAttribute converterAttribute) {
+ updateAttributeLink();
+ }
+
+ @SuppressWarnings("ParameterCanBeLocal")
+ protected void showConverterEditorValidationError(String attributeName, String metaItemName, ValidationFailure validationFailure) {
+ // Replace metaItemName with AttributeLink
+ metaItemName = environment.getMessages().metaItemDisplayName(AssetMeta.ATTRIBUTE_LINK.name());
+
+ // Replace meta item validation failures
+ if (validationFailure != null) {
+ if (validationFailure.getReason() == MetaItem.MetaItemFailureReason.META_ITEM_NAME_IS_REQUIRED) {
+ validationFailure = new ValidationFailure(FailureReason.CONVERTER_KEY_REQUIRED, validationFailure.getParameter().orElse(null));
+ } else if (validationFailure.getReason() == MetaItem.MetaItemFailureReason.META_ITEM_VALUE_IS_REQUIRED) {
+ validationFailure = new ValidationFailure(FailureReason.CONVERTER_VALUE_REQUIRED, validationFailure.getParameter().orElse(null));
+ } else if (validationFailure.getReason() == MetaItem.MetaItemFailureReason.META_ITEM_VALUE_MISMATCH) {
+ validationFailure = new ValidationFailure(FailureReason.CONVERTER_VALUE_MISMATCH, validationFailure.getParameter().orElse(null));
+ }
+ }
+
+ validationErrorConsumer.accept(attributeName, metaItemName, validationFailure);
+ }
+
+ protected void updateAttributeLink() {
+ // Push attribute link back up the chain
+
+ // Validate attributeRef
+ if (attributeRef == null) {
+ onValueModified.accept(null);
+ return;
+ }
+
+ // Validate converter
+ // Check all meta items have unique non empty names if not flag as meta item failure
+ List<String> converterKeys = new ArrayList<>(converterAttribute.getMeta().size());
+ AttributeValidationResult validationResult = new AttributeValidationResult(parentView.getAttribute().getName().orElse(""));
+
+ IntStream.range(0, converterAttribute.getMeta().size())
+ .forEach(i -> {
+ MetaItem metaItem = converterAttribute.getMeta().get(i);
+ List<ValidationFailure> failures = metaItem.getValidationFailures();
+ if (failures != null) {
+ failures.forEach(failure -> validationResult.addMetaFailure(i, failure));
+ }
+ if (converterKeys.contains(metaItem.getName().orElse(""))) {
+ // We have a duplicate converter key name
+ validationResult.addMetaFailure(i, new ValidationFailure(FailureReason.CONVERTER_KEY_DUPLICATION, metaItem.getName().orElse("")));
+ } else {
+ converterKeys.add(metaItem.getName().orElse(""));
+ }
+ });
+
+ // Notify the embedded meta editor
+ converterEditor.onValidationStateChange(validationResult);
+
+ // Push AttributeLink update
+ if (!validationResult.isValid()) {
+ onValueModified.accept(null);
+ } else {
+ onValueModified.accept(new AttributeLink(attributeRef, convertMetaToConverter(converterAttribute.getMeta())));
+ }
+ }
+
+ protected static Meta convertConverterToMeta(ObjectValue converter) {
+ Meta meta = new Meta();
+
+ converter.stream()
+ .forEach(stringValuePair -> meta.add(new MetaItem(stringValuePair.key, stringValuePair.value)));
+
+ return meta;
+ }
+
+ protected static ObjectValue convertMetaToConverter(Meta meta) {
+ if (meta == null || meta.isEmpty()) {
+ return null;
+ }
+
+ ObjectValue converter = Values.createObject();
+ meta.forEach(metaItem -> converter.put(metaItem.getName().orElse(null), metaItem.getValue().orElse(null)));
+ return converter;
+ }
+}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/widget/AttributeRefEditor.java b/manager/client/src/main/java/org/openremote/manager/client/widget/AttributeRefEditor.java
new file mode 100644
index 000000000..df7e1ad20
--- /dev/null
+++ b/manager/client/src/main/java/org/openremote/manager/client/widget/AttributeRefEditor.java
@@ -0,0 +1,187 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.manager.client.widget;
+
+import com.google.gwt.user.client.ui.FlowPanel;
+import org.openremote.model.attribute.AttributeRef;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.IntStream;
+
+import static org.openremote.model.util.TextUtil.isNullOrEmpty;
+
+public class AttributeRefEditor extends FlowPanel {
+
+ public static class AssetInfo {
+ String name;
+ String id;
+
+ public AssetInfo(String name, String id) {
+ this.name = name;
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getId() {
+ return id;
+ }
+ }
+
+ public static class AttributeInfo {
+ String name;
+ String label;
+
+ public AttributeInfo(String name, String label) {
+ this.name = name;
+ this.label = label;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getLabel() {
+ return label;
+ }
+ }
+
+ protected final String[] currentAssetAttribute;
+ protected final FormListBox assetList;
+ protected final FormListBox attributeList;
+ protected final String attributeWatermark;
+ protected Map<AssetInfo, List<AttributeInfo>> assetAttributeMap;
+ protected final Consumer<AttributeRef> onValueModified;
+
+ public AttributeRefEditor(AttributeRef currentValue,
+ Consumer<AttributeRef> onValueModified,
+ boolean readOnly,
+ Consumer<Consumer<Map<AssetInfo, List<AttributeInfo>>>> assetAttributeSupplier,
+ String assetWatermark,
+ String attributeWatermark,
+ String styleName) {
+
+ setStyleName("flex layout horizontal center or-ValueEditor");
+ setStyleName(styleName, true);
+
+ FlowPanel widgetWrapper = new FlowPanel();
+ widgetWrapper.setStyleName("flex layout horizontal center");
+ add(widgetWrapper);
+
+ this.onValueModified = onValueModified;
+ this.attributeWatermark = attributeWatermark;
+ assetList = new FormListBox();
+ assetList.setEnabled(!readOnly);
+ attributeList = new FormListBox();
+ attributeList.setEnabled(!readOnly);
+
+ currentAssetAttribute = currentValue != null ?
+ new String[]{currentValue.getEntityId(), currentValue.getAttributeName()} :
+ new String[2];
+
+ assetList.addItem(assetWatermark);
+ attributeList.addItem(attributeWatermark);
+ attributeList.setVisible(false);
+
+ assetList.addChangeHandler(event -> onAssetListChanged());
+ attributeList.addChangeHandler(event -> onAttributeListChanged());
+
+ // Populate asset list
+ // TODO: indicate loading state
+
+ assetAttributeSupplier.accept(retrievedAssetsAndAttributes -> {
+ assetAttributeMap = retrievedAssetsAndAttributes;
+ // Update asset list box
+
+ // Current index and selected index
+ final int[] indexes = {0,0};
+
+ retrievedAssetsAndAttributes.forEach((assetInfo, attributeNameLabel) -> {
+ assetList.addItem(assetInfo.getName(), assetInfo.getId());
+ if (assetInfo.getId().equals(currentAssetAttribute[0])) {
+ indexes[1] = indexes[0] + 1;
+ }
+ indexes[0]++;
+ });
+
+ assetList.setSelectedIndex(indexes[1]);
+ onAssetListChanged();
+ });
+
+ widgetWrapper.add(assetList);
+ widgetWrapper.add(attributeList);
+ }
+
+ protected void onAssetListChanged() {
+ int selectedIndex = assetList.getSelectedIndex();
+ attributeList.clear();
+ attributeList.addItem(attributeWatermark);
+ final int[] attributeSelectedIndex = {0};
+
+ if (selectedIndex == 0) {
+ attributeList.setVisible(false);
+ currentAssetAttribute[0] = null;
+ currentAssetAttribute[1] = null;
+ } else {
+ if (!assetList.getSelectedValue().equals(currentAssetAttribute[0])) {
+ currentAssetAttribute[0] = assetList.getSelectedValue();
+ currentAssetAttribute[1] = null;
+ }
+
+ // Populate attribute list
+ List<AttributeInfo> attributeInfos = assetAttributeMap.entrySet().stream()
+ .filter(assetAndAttributes -> assetAndAttributes.getKey().getId().equals(assetList.getSelectedValue()))
+ .findFirst()
+ .map(Map.Entry::getValue)
+ .orElse(Collections.emptyList());
+
+ IntStream.range(0, attributeInfos.size())
+ .forEach(i -> {
+ AttributeInfo attributeInfo = attributeInfos.get(i);
+ attributeList.addItem(attributeInfo.getLabel(), attributeInfo.getName());
+ if (attributeInfo.getName().equals(currentAssetAttribute[1])) {
+ attributeSelectedIndex[0] = i + 1;
+ }
+ });
+
+ attributeList.setVisible(true);
+ }
+ attributeList.setSelectedIndex(attributeSelectedIndex[0]);
+ onAttributeListChanged();
+ }
+
+ protected void onAttributeListChanged() {
+ int selectedIndex = attributeList.getSelectedIndex();
+ if (selectedIndex == 0) {
+ currentAssetAttribute[1] = null;
+ } else {
+ currentAssetAttribute[1] = attributeList.getSelectedValue();
+ }
+
+ if (onValueModified != null) {
+ onValueModified.accept(!isNullOrEmpty(currentAssetAttribute[0]) && !isNullOrEmpty(currentAssetAttribute[1]) ? new AttributeRef(currentAssetAttribute[0], currentAssetAttribute[1]) : null);
+ }
+ }
+}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/widget/ValueEditors.java b/manager/client/src/main/java/org/openremote/manager/client/widget/ValueEditors.java
index ff8346901..73ff3cf88 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/widget/ValueEditors.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/widget/ValueEditors.java
@@ -22,27 +22,12 @@ package org.openremote.manager.client.widget;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.IsWidget;
-import org.openremote.manager.client.Environment;
import org.openremote.manager.client.app.dialog.JsonEditor;
-import org.openremote.manager.client.event.ShowFailureEvent;
-import org.openremote.model.AbstractValueTimestampHolder;
import org.openremote.model.Constants;
-import org.openremote.model.ValidationFailure;
-import org.openremote.model.ValueHolder;
-import org.openremote.model.asset.Asset;
-import org.openremote.model.asset.AssetAttribute;
-import org.openremote.model.attribute.AttributeRef;
-import org.openremote.model.util.Pair;
-import org.openremote.model.value.ArrayValue;
-import org.openremote.model.value.ObjectValue;
-import org.openremote.model.value.Value;
-import org.openremote.model.value.Values;
-
-import java.util.ArrayList;
-import java.util.Arrays;
+import org.openremote.model.value.*;
+
import java.util.Date;
-import java.util.List;
-import java.util.function.BiConsumer;
+import java.util.Optional;
import java.util.function.Consumer;
import static org.openremote.model.util.TextUtil.isNullOrEmpty;
@@ -52,95 +37,8 @@ import static org.openremote.model.util.TextUtil.isNullOrEmpty;
*/
public final class ValueEditors {
- public enum ConversionFailureReason implements ValidationFailure.Reason {
- CONVERSION_NOT_A_VALID_NUMBER
- }
-
- /**
- * Maps a {@link FormGroup} which is typically one editor line to a {@link ValueHolder} and
- * encapsulates the raw value that should be set on the value holder and the consumer of
- * validation failure results. If there are no validation failures, the update was successful.
- */
- private static class ValueUpdate<T> {
- final ValueHolder valueHolder;
- final Runnable onValueModified;
- final T rawValue;
-
- public ValueUpdate(ValueHolder valueHolder, Runnable onValueModified, T rawValue) {
- this.valueHolder = valueHolder;
- this.onValueModified = onValueModified;
- this.rawValue = rawValue;
- }
- }
-
- /**
- * Performs the update and notifies the result consumer of any validation failures.
- */
- private static abstract class ValueUpdater<T> implements Consumer<ValueUpdate<T>> {
-
- @Override
- public void accept(ValueUpdate<T> valueUpdate) {
- try {
- valueUpdate.valueHolder.setValue(
- valueUpdate.rawValue != null ? createValue(valueUpdate.rawValue) : null
- );
-
- // Let the server set the timestamp by setting it to 0
- if (valueUpdate.valueHolder instanceof AbstractValueTimestampHolder) {
- AbstractValueTimestampHolder timestampHolder = (AbstractValueTimestampHolder) valueUpdate.valueHolder;
- timestampHolder.setValueTimestamp(0);
- }
- } catch (Exception e) {
- // Remove the current value
- valueUpdate.valueHolder.clearValue();
- }
- valueUpdate.onValueModified.run();
- }
-
- abstract Value createValue(T rawValue) throws IllegalArgumentException;
- }
-
public static final String EMPTY_LINE = "----------------------";
- private static ValueUpdater<String> STRING_UPDATER = new ValueUpdater<String>() {
- @Override
- Value createValue(String rawValue) throws IllegalArgumentException {
- return Values.create(rawValue);
- }
- };
-
- private static ValueUpdater<String> DOUBLE_UPDATER = new ValueUpdater<String>() {
- @Override
- Value createValue(String rawValue) throws IllegalArgumentException {
- try {
- return Values.create(Double.valueOf(rawValue));
- } catch (NumberFormatException ex) {
- throw new IllegalArgumentException(ConversionFailureReason.CONVERSION_NOT_A_VALID_NUMBER.name());
- }
- }
- };
-
- private static ValueUpdater<Boolean> BOOLEAN_UPDATER = new ValueUpdater<Boolean>() {
- @Override
- Value createValue(Boolean rawValue) throws IllegalArgumentException {
- return Values.create(rawValue);
- }
- };
-
- private static ValueUpdater<Value> VALUE_UPDATER = new ValueUpdater<Value>() {
- @Override
- Value createValue(Value rawValue) throws IllegalArgumentException {
- return rawValue;
- }
- };
-
- private static ValueUpdater<AttributeRef> ATTRIBUTE_REF_UPDATER = new ValueUpdater<AttributeRef>() {
- @Override
- Value createValue(AttributeRef rawValue) throws IllegalArgumentException {
- return rawValue != null ? rawValue.toArrayValue() : null;
- }
- };
-
private static class TimestampLabel extends FlowPanel {
static protected DateTimeFormat dateFormat = DateTimeFormat.getFormat(Constants.DEFAULT_DATE_FORMAT);
@@ -155,84 +53,88 @@ public final class ValueEditors {
}
}
- public static IsWidget createStringEditor(ValueHolder valueHolder,
- Runnable onValueModified,
+ public static IsWidget createStringEditor(StringValue currentValue,
+ Consumer<StringValue> onValueModified,
+ Optional<Long> timestamp,
boolean readOnly,
- boolean showTimestamp,
- String currentValue,
String styleName) {
- Consumer<String> updateConsumer = !readOnly
- ? rawValue -> STRING_UPDATER.accept(new ValueUpdate<>(valueHolder, onValueModified, rawValue))
- : null;
+
+ Consumer<String> updateConsumer = readOnly ? null : str ->
+ onValueModified.accept(isNullOrEmpty(str) ? null : Values.create(str));
+
FlowPanel panel = new FlowPanel();
panel.setStyleName("flex layout horizontal center or-ValueEditor or-StringValueEditor");
- IsWidget widget = ValueEditors.createStringEditorWidget(styleName, readOnly, currentValue, updateConsumer);
+ IsWidget widget = ValueEditors.createStringEditorWidget(styleName, readOnly, currentValue != null ? currentValue.getString() : null, updateConsumer);
FlowPanel widgetWrapper = new FlowPanel();
widgetWrapper.setStyleName("flex layout horizontal center");
widgetWrapper.add(widget);
panel.add(widgetWrapper);
- if (showTimestamp)
- addTimestampLabel(valueHolder, panel);
- return () -> panel;
+ timestamp.ifPresent(time -> addTimestampLabel(time, panel));
+ return panel;
}
- public static IsWidget createNumberEditor(ValueHolder valueHolder,
- Runnable onValueModified,
+ public static IsWidget createNumberEditor(NumberValue currentValue,
+ Consumer<NumberValue> onValueModified,
+ Optional<Long> timestamp,
boolean readOnly,
- boolean showTimestamp,
- String currentValue,
String styleName) {
- Consumer<String> updateConsumer = !readOnly
- ? rawValue -> DOUBLE_UPDATER.accept(new ValueUpdate<>(valueHolder, onValueModified, rawValue))
- : null;
+ Consumer<String> updateConsumer = readOnly ? null : str -> {
+ NumberValue newValue = null;
+
+ if (!isNullOrEmpty(str)) {
+ try {
+ newValue = Values.create(Double.valueOf(str));
+ } catch (NumberFormatException ignored) {
+ }
+ }
+
+ onValueModified.accept(newValue);
+ };
FlowPanel panel = new FlowPanel();
panel.setStyleName("flex layout horizontal center or-ValueEditor or-NumberValueEditor");
- IsWidget widget = createStringEditorWidget(styleName, readOnly, currentValue, updateConsumer);
+ IsWidget widget = createStringEditorWidget(styleName, readOnly, currentValue != null ? currentValue.asString() : null, updateConsumer);
FlowPanel widgetWrapper = new FlowPanel();
widgetWrapper.setStyleName("flex layout horizontal center");
widgetWrapper.add(widget);
panel.add(widgetWrapper);
- if (showTimestamp)
- addTimestampLabel(valueHolder, panel);
- return () -> panel;
+ timestamp.ifPresent(time -> addTimestampLabel(time, panel));
+ return panel;
}
- public static IsWidget createBooleanEditor(ValueHolder valueHolder,
- Runnable onValueModified,
+ public static IsWidget createBooleanEditor(BooleanValue currentValue,
+ Consumer<BooleanValue> onValueModified,
+ Optional<Long> timestamp,
boolean readOnly,
- boolean showTimestamp,
- Boolean currentValue,
String styleName) {
- Consumer<Boolean> updateConsumer = !readOnly
- ? rawValue -> BOOLEAN_UPDATER.accept(new ValueUpdate<>(valueHolder, onValueModified, rawValue))
- : null;
+
+ Consumer<Boolean> updateConsumer = readOnly ? null : bool ->
+ onValueModified.accept(Values.create(bool));
FlowPanel panel = new FlowPanel();
panel.setStyleName("flex layout horizontal center or-ValueEditor or-BooleanValueEditor");
- IsWidget widget = ValueEditors.createBooleanEditorWidget(styleName, readOnly, currentValue, updateConsumer);
+ IsWidget widget = ValueEditors.createBooleanEditorWidget(styleName, readOnly, currentValue != null && currentValue.getBoolean(), updateConsumer);
FlowPanel widgetWrapper = new FlowPanel();
widgetWrapper.setStyleName("flex layout horizontal center");
widgetWrapper.add(widget);
panel.add(widgetWrapper);
- if (showTimestamp)
- addTimestampLabel(valueHolder, panel);
- return () -> panel;
+ timestamp.ifPresent(time -> addTimestampLabel(time, panel));
+ return panel;
}
- public static IsWidget createObjectEditor(ValueHolder valueHolder,
- Runnable onValueModified,
+ public static IsWidget createObjectEditor(ObjectValue currentValue,
+ Consumer<ObjectValue> onValueModified,
+ Optional<Long> timestamp,
boolean readOnly,
- boolean showTimestamp,
- ObjectValue currentValue,
String label,
String title,
JsonEditor jsonEditor) {
- Consumer<Value> updateConsumer = !readOnly
- ? rawValue -> VALUE_UPDATER.accept(new ValueUpdate<>(valueHolder, onValueModified, rawValue))
- : null;
+
+ Consumer<Value> updateConsumer = readOnly ? null : value ->
+ onValueModified.accept(Values.getObject(value).orElse(null));
+
FlowPanel panel = new FlowPanel();
panel.setStyleName("flex layout horizontal center or-ValueEditor or-ObjectValueEditor");
IsWidget widget = createJsonEditorWidget(
@@ -242,127 +144,20 @@ public final class ValueEditors {
widgetWrapper.setStyleName("flex layout horizontal center");
widgetWrapper.add(widget);
panel.add(widgetWrapper);
- if (showTimestamp)
- addTimestampLabel(valueHolder, panel);
- return () -> panel;
+ timestamp.ifPresent(time -> addTimestampLabel(time, panel));
+ return panel;
}
- public static IsWidget createAttributeRefEditor(ValueHolder valueHolder,
- Runnable onValueModified,
- boolean readOnly,
- BiConsumer<ValueHolder, Consumer<Asset[]>> assetSupplier,
- BiConsumer<Pair<ValueHolder, Asset>, Consumer<AssetAttribute[]>> attributeSupplier,
- String assetWatermark,
- String attributeWatermark,
- String styleName) {
-
- Consumer<AttributeRef> updateConsumer = !readOnly
- ? rawValue -> ATTRIBUTE_REF_UPDATER.accept(new ValueUpdate<>(valueHolder, onValueModified, rawValue))
- : null;
-
- FlowPanel panel = new FlowPanel();
- panel.setStyleName("flex layout horizontal center or-ValueEditor or-AttributeRefEditor");
- FlowPanel widgetWrapper = new FlowPanel();
- widgetWrapper.setStyleName("flex layout horizontal center");
- panel.add(widgetWrapper);
-
- List<Asset> assets = new ArrayList<>();
- FormListBox assetList = new FormListBox();
- assetList.setEnabled(!readOnly);
- FormListBox attributeList = new FormListBox();
- attributeList.setEnabled(!readOnly);
- String[] existingValue = valueHolder
- .getValueAsArray()
- .filter(arr -> arr.length() == 2)
- .map(arr -> new String[] {arr.getString(0).orElse(null), arr.getString(1).orElse(null)})
- .orElse(new String[2]);
- Runnable onAssetListChanged = () -> {
- int selectedIndex = assetList.getSelectedIndex();
- attributeList.clear();
- attributeList.addItem(attributeWatermark);
- if (selectedIndex == 0) {
- attributeList.setVisible(false);
- existingValue[0] = null;
- existingValue[1] = null;
- } else {
- if (!assetList.getSelectedValue().equals(existingValue[0])) {
- existingValue[0] = assetList.getSelectedValue();
- existingValue[1] = null;
- }
-
- attributeSupplier.accept(new Pair<>(valueHolder, assets.get(selectedIndex-1)), attributes -> {
- int attributeSelectedIndex = 0;
-
- for (int i=0; i<attributes.length; i++) {
- AssetAttribute attribute = attributes[i];
- attributeList.addItem(attribute.getLabelOrName().orElse(""), attribute.getName().orElse(""));
- if (attribute.getName().orElse("").equals(existingValue[1])) {
- attributeSelectedIndex = i+1;
- }
- }
-
- attributeList.setSelectedIndex(attributeSelectedIndex);
- attributeList.setVisible(true);
- });
- }
- if (updateConsumer != null) {
- updateConsumer.accept(!isNullOrEmpty(existingValue[0]) && !isNullOrEmpty(existingValue[1]) ? new AttributeRef(existingValue[0], existingValue[1]) : null);
- }
- };
- Runnable onAttributeListChanged = () -> {
- int selectedIndex = attributeList.getSelectedIndex();
- if (selectedIndex == 0) {
- existingValue[1] = null;
- } else {
- existingValue[1] = attributeList.getSelectedValue();
- }
- if (updateConsumer != null) {
- updateConsumer.accept(!isNullOrEmpty(existingValue[0]) && !isNullOrEmpty(existingValue[1]) ? new AttributeRef(existingValue[0], existingValue[1]) : null);
- }
- };
-
-
- assetList.addItem(assetWatermark);
- attributeList.addItem(attributeWatermark);
- attributeList.setVisible(false);
-
- assetList.addChangeHandler(event -> onAssetListChanged.run());
- attributeList.addChangeHandler(event -> onAttributeListChanged.run());
-
- // Populate asset list
- assetSupplier.accept(valueHolder, retrievedAssets -> {
- assets.addAll(Arrays.asList(retrievedAssets));
- int assetSelectedIndex = 0;
-
- for (int i=0; i<assets.size(); i++) {
- Asset asset = assets.get(i);
- assetList.addItem(asset.getName(), asset.getId());
- if (asset.getId().equals(existingValue[0])) {
- assetSelectedIndex = i+1;
- }
- }
-
- assetList.setSelectedIndex(assetSelectedIndex);
- onAssetListChanged.run();
- });
-
- widgetWrapper.add(assetList);
- widgetWrapper.add(attributeList);
-
- return () -> panel;
- }
-
- public static IsWidget createArrayEditor(ValueHolder valueHolder,
- Runnable onValueModified,
+ public static IsWidget createArrayEditor(ArrayValue currentValue,
+ Consumer<ArrayValue> onValueModified,
+ Optional<Long> timestamp,
boolean readOnly,
- boolean showTimestamp,
- ArrayValue currentValue,
String label,
String title,
JsonEditor jsonEditor) {
- Consumer<Value> updateConsumer = !readOnly
- ? rawValue -> VALUE_UPDATER.accept(new ValueUpdate<>(valueHolder, onValueModified, rawValue))
- : null;
+
+ Consumer<Value> updateConsumer = readOnly ? null : value ->
+ onValueModified.accept(Values.getArray(value).orElse(null));
FlowPanel panel = new FlowPanel();
panel.setStyleName("flex layout horizontal center or-ValueEditor or-ArrayValueEditor");
@@ -373,17 +168,13 @@ public final class ValueEditors {
widgetWrapper.setStyleName("flex layout horizontal center");
widgetWrapper.add(widget);
panel.add(widgetWrapper);
- if (showTimestamp)
- addTimestampLabel(valueHolder, panel);
- return () -> panel;
+ timestamp.ifPresent(time -> addTimestampLabel(time, panel));
+ return panel;
}
- private static void addTimestampLabel(ValueHolder valueHolder, FlowPanel editorPanel) {
- if (valueHolder instanceof AbstractValueTimestampHolder) {
- AbstractValueTimestampHolder timestampHolder = (AbstractValueTimestampHolder) valueHolder;
- TimestampLabel timestampLabel = new TimestampLabel(timestampHolder.getValueTimestamp().orElse(null));
- editorPanel.add(timestampLabel);
- }
+ private static void addTimestampLabel(long timestamp, FlowPanel editorPanel) {
+ TimestampLabel timestampLabel = new TimestampLabel(timestamp);
+ editorPanel.add(timestampLabel);
}
private static IsWidget createStringEditorWidget(String styleName,
diff --git a/manager/client/src/main/resources/org/openremote/manager/client/i18n/ManagerMessages.properties b/manager/client/src/main/resources/org/openremote/manager/client/i18n/ManagerMessages.properties
index d5b2f9b25..1f736310d 100644
--- a/manager/client/src/main/resources/org/openremote/manager/client/i18n/ManagerMessages.properties
+++ b/manager/client/src/main/resources/org/openremote/manager/client/i18n/ManagerMessages.properties
@@ -113,7 +113,7 @@ deleteAttribute=Delete attribute
addAttribute=Add attribute
itemName=Item name/URN
deleteItem=Delete item
-newItem=New configuration item
+newMetaItems=New configuration item
addItem=Add item
type=Type
value=Value
@@ -233,6 +233,7 @@ attributeType[BRIGHTNESS_LUX]=Lux brightness
validationFailureOnAttribute=Attribute error on ''{0}''
validationFailureOnMetaItem=Meta item error on ''{0}'' meta item ''{1}''
validationFailure=Unknown validation failure.
+validationFailure[VALUE_REQUIRED]=Value must be a valid ''{0}''.
validationFailure[VALUE_INVALID]=Value is not valid.
validationFailure[VALUE_MISMATCH]=Value must be of type ''{0}''.
validationFailure[VALUE_PERCENTAGE_OUT_OF_RANGE]=Percentage value must be a number between 0 and 100.
@@ -240,30 +241,32 @@ validationFailure[VALUE_TEMPERATURE_OUT_OF_RANGE]=Temperature out of scale''s ra
validationFailure[VALUE_INVALID_COLOR_FORMAT]=Invalid color format.
validationFailure[VALUE_NUMBER_OUT_OF_RANGE]=Number out of scale''s range.
validationFailure[META_ITEM_NAME_IS_REQUIRED]=Meta item name is required.
-validationFailure[META_ITEM_VALUE_IS_REQUIRED]=Meta item value is required.
+validationFailure[META_ITEM_VALUE_IS_REQUIRED]=Meta item value must be a valid ''{0}''.
validationFailure[META_ITEM_MISSING]=A required meta item is missing ''{0}''.
validationFailure[META_ITEM_DUPLICATION]=Multiple ''{0}'' meta items not allowed.
-validationFailure[META_ITEM_VALUE_MISMATCH]=Meta item value must be ''{0}''.
+validationFailure[META_ITEM_VALUE_MISMATCH]=Meta item value must be a valid ''{0}''.
validationFailure[ATTRIBUTE_NAME_INVALID]=Invalid attribute name.
validationFailure[ATTRIBUTE_TYPE_MISSING]=Missing attribute type.
validationFailure[ATTRIBUTE_VALUE_TIMESTAMP_MISSING]=Missing attribute value timestamp.
validationFailure[ATTRIBUTE_TYPE_VALUE_DOES_NOT_MATCH]=Value does not match attribute type.
validationFailure[ATTRIBUTE_TYPE_INVALID_TEMPLATE_FILTER]=Invalid template filter.
-validationFailure[VALUE_EXPECTED_NUMBER]=Must be a number.
-validationFailure[VALUE_EXPECTED_INTEGER]=Must be an integer.
-validationFailure[VALUE_EXPECTED_DOUBLE]=Must be a double.
-validationFailure[VALUE_EXPECTED_OBJECT]=Must be an object.
-validationFailure[VALUE_EXPECTED_ARRAY]=Must be an array.
-validationFailure[VALUE_EXPECTED_BOOLEAN]=Must be a boolean.
-validationFailure[VALUE_EXPECTED_STRING]=Must be a string.
+validationFailure[CONVERTER_KEY_DUPLICATION]=Duplicate converter key ''{0}''.
+validationFailure[CONVERTER_KEY_REQUIRED]=Converter key is required.
+validationFailure[CONVERTER_VALUE_REQUIRED]=Converter value must be a valid ''{0}''.
+validationFailure[CONVERTER_VALUE_MISMATCH]=Converter value must be a valid ''{0}''.
validationFailureParameter=
+validationFailureParameter[OBJECT]=JSON object
+validationFailureParameter[ARRAY]=JSON array
+validationFailureParameter[BOOLEAN]=Boolean
+validationFailureParameter[STRING]=String
+validationFailureParameter[NUMBER]=Number
validationFailureParameter[INTEGER]=Integer
validationFailureParameter[INTEGER_POSITIVE]=Positive integer
validationFailureParameter[INTEGER_NEGATIVE]=Negative integer
validationFailureParameter[INTEGER_NON_ZERO]=Non zero integer
validationFailureParameter[INTEGER_POSITIVE_NON_ZERO]=Positive non zero integer
validationFailureParameter[INTEGER_NEGATIVE_NON_ZERO]=Negative non zero integer
-validationFailureParameter[DOUBLE]=Integer
+validationFailureParameter[DOUBLE]=Decimal
validationFailureParameter[DOUBLE_POSITIVE]=Positive decimal
validationFailureParameter[DOUBLE_NEGATIVE]=Negative decimal
validationFailureParameter[DOUBLE_NON_ZERO]=Non zero decimal
@@ -355,4 +358,17 @@ metaItemDisplayName[PROTOCOL_TIMER_CRON]=Timer CRON Expression
metaItemDisplayName[PROTOCOL_TIMER_LINK]=Timer Value Link
metaItemDisplayName[PROTOCOL_SIMULATOR_MODE]=Simulator Mode
metaItemDisplayName[PROTOCOL_SIMULATOR_WRITE_DELAY]=Simulator Write Delay (ms)
-metaItemDisplayName[PROTOCOL_SIMULATOR_ELEMENT]=Simulator Element Type
\ No newline at end of file
+metaItemDisplayName[PROTOCOL_SIMULATOR_ELEMENT]=Simulator Element Type
+attributeLinkConverterValues=Converter values
+attributeLinkNewConverterValue=New Converter value
+enterConverterValue=Enter converter value
+selectConverter=Select converter
+customConverter=Custom
+converterType=Unkown Type
+converterType[IGNORE]=Ignore
+converterType[NULL]=Null
+converterType[TOGGLE]=Toggle
+converterType[DECREMENT]=Decrement
+converterType[INCREMENT]=Increment
+addConverterValue=Add value
+deleteConverterValue=Delete value
\ No newline at end of file
diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetAttributeLinkingService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetAttributeLinkingService.java
index 4d2fcc4fc..0cddf0c1e 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetAttributeLinkingService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetAttributeLinkingService.java
@@ -23,6 +23,7 @@ import org.openremote.container.Container;
import org.openremote.container.ContainerService;
import org.openremote.model.asset.*;
import org.openremote.model.attribute.AttributeEvent;
+import org.openremote.model.attribute.AttributeLink;
import org.openremote.model.attribute.AttributeRef;
import org.openremote.model.attribute.MetaItem;
import org.openremote.model.util.Pair;
@@ -46,13 +47,13 @@ import static org.openremote.model.attribute.MetaItem.isMetaNameEqualTo;
* By default the exact value of the attribute is forwarded unless a key exists in the converter JSON Object that
* matches the value as a string (note matches are case sensitive so booleans should be lower case i.e. true or false);
* in that case the value of the key is forwarded instead. There are several special conversions available by using
- * the value of a {@link Converter} as the value. This allows for example a button press to toggle a boolean
+ * the value of a {@link AttributeLink.ConverterType} as the value. This allows for example a button press to toggle a boolean
* attribute or for a particular value to be ignored.
* <p>
* To convert null values the converter key of "NULL" can be used.
* <p>
* <b>
- * NOTE: State converters (e.g. {@link Converter#TOGGLE}, {@link Converter#INCREMENT}, {@link Converter#DECREMENT}) are
+ * NOTE: State converters (e.g. {@link AttributeLink.ConverterType#TOGGLE}, {@link AttributeLink.ConverterType#INCREMENT}, {@link AttributeLink.ConverterType#DECREMENT}) are
* not synchronised so if the initiating attribute (the one with the {@link AssetMeta#ATTRIBUTE_LINK} meta items)
* generates multiple attribute events in a short period of time then the value pushed to the linked attribute may not
* be correct.
@@ -87,57 +88,6 @@ import static org.openremote.model.attribute.MetaItem.isMetaNameEqualTo;
// TODO: Improve AssetAttributeLinkingService so that outbound events are synchronsied with inbound
public class AssetAttributeLinkingService implements ContainerService, Consumer<AssetState> {
- public enum Converter {
-
- /**
- * Ignore this value (do not send to the linked attribute)
- */
- IGNORE("@IGNORE"),
-
- /**
- * Send a null vale to the linked attribute
- */
- NULL("@NULL"),
-
- /**
- * Toggle the value of the linked attribute; the linked attribute's type must be
- * {@link org.openremote.model.attribute.AttributeType#BOOLEAN}
- */
- TOGGLE("@TOGGLE"),
-
- /**
- * Increment the value of the linked attribute; the linked attribute's type must be
- * {@link org.openremote.model.attribute.AttributeType#NUMBER}
- */
- INCREMENT("@INCREMENT"),
-
- /**
- * Decrement the value of the linked attribute; the linked attribute's type must be
- * {@link org.openremote.model.attribute.AttributeType#NUMBER}
- */
- DECREMENT("@DECREMENT");
-
- private String value;
- // Prevents cloning of values each time fromString is called
- private static final Converter[] copyOfValues = values();
-
- Converter(String value) {
- this.value = value;
- }
-
- public String getValue() {
- return value;
- }
-
- public static Optional<Converter> fromString(String value) {
- for (Converter converter : copyOfValues) {
- if (converter.getValue().equalsIgnoreCase(value))
- return Optional.of(converter);
- }
- return Optional.empty();
- }
- }
-
private static final Logger LOG = Logger.getLogger(AssetAttributeLinkingService.class.getName());
protected AssetProcessingService assetProcessingService;
protected AssetStorageService assetStorageService;
@@ -170,11 +120,11 @@ public class AssetAttributeLinkingService implements ContainerService, Consumer<
assetProcessingService.sendAttributeEvent(attributeEvent);
}
- protected void processLinkedAttributeUpdate(MetaItem attributeLink, AssetState assetState) {
+ protected void processLinkedAttributeUpdate(MetaItem metaItem, AssetState assetState) {
LOG.fine("Processing attribute event for linked attribute");
- Optional<Pair<AttributeRef, Optional<ObjectValue>>> linkAndConverter = getAttributeLinkAndConverter(attributeLink);
+ Optional<AttributeLink> attributeLink = metaItem.getValue().flatMap(AttributeLink::fromValue);
- if (!linkAndConverter.isPresent()) {
+ if (!attributeLink.isPresent()) {
LOG.info("Invalid attribute link on: " + assetState.getAttributeRef());
return;
}
@@ -182,8 +132,7 @@ public class AssetAttributeLinkingService implements ContainerService, Consumer<
// Convert the value as required
Pair<Boolean, Value> sendConvertedValue = convertValueForLinkedAttribute(
assetState.getValue(),
- linkAndConverter.get().key,
- linkAndConverter.get().value,
+ attributeLink.get(),
assetStorageService
);
@@ -192,47 +141,34 @@ public class AssetAttributeLinkingService implements ContainerService, Consumer<
return;
}
- sendAttributeEvent(new AttributeEvent(linkAndConverter.get().key, sendConvertedValue.value));
- }
-
- protected static Optional<Pair<AttributeRef, Optional<ObjectValue>>> getAttributeLinkAndConverter(MetaItem metaItem) {
- return metaItem
- .getValueAsObject()
- .map(obj -> {
- Optional<AttributeRef> ref = AttributeRef.fromValue(obj.get("attributeRef").orElse(null));
- Optional<ObjectValue> converter = obj.getObject("converter");
-
- return ref
- .map(attributeRef -> new Pair<>(attributeRef, converter))
- .orElse(null);
- });
+ sendAttributeEvent(new AttributeEvent(attributeLink.get().getAttributeRef(), sendConvertedValue.value));
}
- protected static Pair<Boolean, Value> convertValueForLinkedAttribute(Value originalValue, AttributeRef linkedAttributeRef, Optional<ObjectValue> converter, AssetStorageService assetStorageService) {
- return converter
+ protected static Pair<Boolean, Value> convertValueForLinkedAttribute(Value originalValue, AttributeLink attributeLink, AssetStorageService assetStorageService) {
+ return attributeLink.getConverter()
.map(
- conv -> {
+ converter -> {
String converterKey = originalValue == null ? "NULL": originalValue.toString();
- Optional<Value> converterValue = conv.get(converterKey);
+ Optional<Value> converterValue = converter.get(converterKey);
// Convert the value
return converterValue
.map(value ->
getSpecialConverter(value)
- .map(c -> doSpecialConversion(c, linkedAttributeRef, assetStorageService))
+ .map(c -> doSpecialConversion(c, attributeLink.getAttributeRef(), assetStorageService))
.orElse(new Pair<>(true, value))) // use the converter value as the new value
.orElseGet(() -> new Pair<>(true, originalValue)); // use the original value
})
.orElse(new Pair<>(true, originalValue)); // use the original value
}
- protected static Optional<Converter> getSpecialConverter(Value value) {
+ protected static Optional<AttributeLink.ConverterType> getSpecialConverter(Value value) {
if (value.getType() == ValueType.STRING) {
- return Converter.fromString(value.toString());
+ return AttributeLink.ConverterType.fromValue(value.toString());
}
return Optional.empty();
}
- protected static Pair<Boolean, Value> doSpecialConversion(Converter converter, AttributeRef linkedAttributeRef, AssetStorageService assetStorageService) {
+ protected static Pair<Boolean, Value> doSpecialConversion(AttributeLink.ConverterType converter, AttributeRef linkedAttributeRef, AssetStorageService assetStorageService) {
switch (converter) {
case IGNORE:
LOG.fine("Converter set to ignore value so not forwarding to linked attribute");
@@ -261,7 +197,7 @@ public class AssetAttributeLinkingService implements ContainerService, Consumer<
LOG.fine("Cannot increment/decrement attribute value as attribute is not of type NUMBER: " + linkedAttributeRef);
return new Pair<>(false, null);
}
- int change = converter == Converter.INCREMENT ? +1 : -1;
+ int change = converter == AttributeLink.ConverterType.INCREMENT ? +1 : -1;
return new Pair<>(true, Values.create(((NumberValue)currentValue).getNumber() + change));
} catch (NoSuchElementException e) {
LOG.fine("The attribute doesn't exist so ignoring increment/decrement value request: " + linkedAttributeRef);
@@ -279,7 +215,7 @@ public class AssetAttributeLinkingService implements ContainerService, Consumer<
.select(new AbstractAssetQuery.Select(AbstractAssetQuery.Include.ALL, false, false, attributeRef.getAttributeName()))
);
- Optional<AssetAttribute> attribute = Optional.empty();
+ Optional<AssetAttribute> attribute;
if (asset == null || !(attribute = asset.getAttribute(attributeRef.getAttributeName())).isPresent()) {
throw new NoSuchElementException("Attribute or asset could not be found: " + attributeRef);
}
diff --git a/model/src/main/java/org/openremote/model/ValueHolder.java b/model/src/main/java/org/openremote/model/ValueHolder.java
index 76322595e..f7240abac 100644
--- a/model/src/main/java/org/openremote/model/ValueHolder.java
+++ b/model/src/main/java/org/openremote/model/ValueHolder.java
@@ -19,7 +19,6 @@
*/
package org.openremote.model;
-import org.openremote.model.util.Pair;
import org.openremote.model.value.ArrayValue;
import org.openremote.model.value.ObjectValue;
import org.openremote.model.value.Value;
@@ -39,13 +38,7 @@ public interface ValueHolder {
VALUE_NUMBER_OUT_OF_RANGE,
VALUE_INVALID,
VALUE_MISMATCH,
- VALUE_EXPECTED_NUMBER,
- VALUE_EXPECTED_INTEGER,
- VALUE_EXPECTED_DOUBLE,
- VALUE_EXPECTED_OBJECT,
- VALUE_EXPECTED_ARRAY,
- VALUE_EXPECTED_BOOLEAN,
- VALUE_EXPECTED_STRING
+ VALUE_REQUIRED
}
void clearValue();
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 5f2217d71..c93e025a8 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetAttribute.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetAttribute.java
@@ -20,7 +20,6 @@
package org.openremote.model.asset;
import com.fasterxml.jackson.annotation.JsonIgnore;
-import com.fasterxml.jackson.annotation.JsonProperty;
import org.openremote.model.AbstractValueHolder;
import org.openremote.model.ValidationFailure;
import org.openremote.model.attribute.*;
@@ -120,8 +119,8 @@ public class AssetAttribute extends Attribute {
}
@Override
- public List<ValidationFailure> getMetaItemValidationFailures(MetaItem item) {
- return super.getMetaItemValidationFailures(item);
+ public List<ValidationFailure> getMetaItemValidationFailures(MetaItem item, Optional<MetaItemDescriptor> metaItemDescriptor) {
+ return super.getMetaItemValidationFailures(item, metaItemDescriptor);
}
@Override
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 ed89602c4..f7ded9632 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetMeta.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetMeta.java
@@ -20,10 +20,7 @@
package org.openremote.model.asset;
import org.openremote.model.ValidationFailure;
-import org.openremote.model.attribute.AttributeExecuteStatus;
-import org.openremote.model.attribute.AttributeRef;
-import org.openremote.model.attribute.MetaItem;
-import org.openremote.model.attribute.MetaItemDescriptor;
+import org.openremote.model.attribute.*;
import org.openremote.model.value.Value;
import org.openremote.model.value.ValueType;
import org.openremote.model.value.Values;
@@ -88,7 +85,12 @@ public enum AssetMeta implements MetaItemDescriptor {
null,
null,
null,
- false),
+ false,
+ value ->
+ Optional.ofNullable(AttributeLink.isAttributeLink(value)
+ ? null
+ : new ValidationFailure(META_ITEM_VALUE_MISMATCH, AttributeLink.class.getSimpleName()))
+ ),
/**
* A human-friendly string that can be displayed in UI instead of the raw attribute name.
@@ -375,10 +377,8 @@ public enum AssetMeta implements MetaItemDescriptor {
}
@Override
- public Optional<ValidationFailure> validateValue(Value value) {
- return Optional.ofNullable(MetaItemDescriptor
- .validateValue(value, this)
- .orElse(validator != null ? validator.apply(value).orElse(null) : null));
+ public Optional<Function<Value, Optional<ValidationFailure>>> getValidator() {
+ return Optional.ofNullable(validator);
}
public Value getInitialValue() {
diff --git a/model/src/main/java/org/openremote/model/attribute/Attribute.java b/model/src/main/java/org/openremote/model/attribute/Attribute.java
index 549ebf7ae..da5c62545 100644
--- a/model/src/main/java/org/openremote/model/attribute/Attribute.java
+++ b/model/src/main/java/org/openremote/model/attribute/Attribute.java
@@ -233,16 +233,14 @@ public abstract class Attribute extends AbstractValueTimestampHolder {
List<ValidationFailure> failures = new ArrayList<>();
if (hasMetaItems()) {
for (MetaItem metaItem : getMeta()) {
- failures.addAll(getMetaItemValidationFailures(metaItem));
+ failures.addAll(getMetaItemValidationFailures(metaItem, Optional.empty()));
}
}
return failures;
}
- public List<ValidationFailure> getMetaItemValidationFailures(MetaItem item) {
- List<ValidationFailure> failures = new ArrayList<>();
- failures.addAll(item.getValidationFailures());
- return failures;
+ public List<ValidationFailure> getMetaItemValidationFailures(MetaItem item, Optional<MetaItemDescriptor> metaItemDescriptor) {
+ return item.getValidationFailures(metaItemDescriptor);
}
// ---------------------------------------------------
diff --git a/model/src/main/java/org/openremote/model/attribute/AttributeLink.java b/model/src/main/java/org/openremote/model/attribute/AttributeLink.java
new file mode 100644
index 000000000..534100945
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/attribute/AttributeLink.java
@@ -0,0 +1,157 @@
+/*
+ * Copyright 2016, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.attribute;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.openremote.model.value.ObjectValue;
+import org.openremote.model.value.Value;
+import org.openremote.model.value.ValueType;
+import org.openremote.model.value.Values;
+
+import java.util.Optional;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * A link from one attribute to another with a definition of how to map the value from the source attribute
+ * to the linked attribute.
+ */
+public class AttributeLink {
+
+ public enum ConverterType {
+
+ /**
+ * Ignore this value (do not send to the linked attribute)
+ */
+ IGNORE("@IGNORE"),
+
+ /**
+ * Send a null vale to the linked attribute
+ */
+ NULL("@NULL"),
+
+ /**
+ * Toggle the value of the linked attribute; the linked attribute's type must be
+ * {@link AttributeType#BOOLEAN}
+ */
+ TOGGLE("@TOGGLE"),
+
+ /**
+ * Increment the value of the linked attribute; the linked attribute's type must be
+ * {@link AttributeType#NUMBER}
+ */
+ INCREMENT("@INCREMENT"),
+
+ /**
+ * Decrement the value of the linked attribute; the linked attribute's type must be
+ * {@link AttributeType#NUMBER}
+ */
+ DECREMENT("@DECREMENT");
+
+ private String value;
+ // Prevents cloning of values each time fromString is called
+ private static final ConverterType[] copyOfValues = values();
+
+ ConverterType(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ public static Optional<ConverterType> fromValue(String value) {
+ for (ConverterType converter : copyOfValues) {
+ if (converter.getValue().equalsIgnoreCase(value))
+ return Optional.of(converter);
+ }
+ return Optional.empty();
+ }
+ }
+
+ protected AttributeRef attributeRef;
+ protected ObjectValue converter;
+
+ public AttributeLink(String entityId, String attributeName, ObjectValue converter) {
+ this(new AttributeRef(entityId, attributeName), converter);
+ }
+
+ /**
+ * @param converter can be <code>null</code> if no conversions are defined (i.e. value is direct write through).
+ */
+ public AttributeLink(AttributeRef attributeRef, ObjectValue converter) {
+ this.attributeRef = requireNonNull(attributeRef);
+ this.converter = converter;
+ }
+
+ public AttributeRef getAttributeRef() {
+ return attributeRef;
+ }
+
+ @JsonIgnore
+ public Optional<ObjectValue> getConverter() {
+ return Optional.ofNullable(converter);
+ }
+
+ public void setConverter(ObjectValue converter) {
+ this.converter = converter;
+ }
+
+ // For GWT jackson only
+ @JsonProperty("converter")
+ private ObjectValue getConverterPrivate() {
+ return converter;
+ }
+
+ public ObjectValue toObjectValue() {
+ ObjectValue objectValue = Values.createObject();
+ objectValue.put("attributeRef", getAttributeRef().toArrayValue());
+ objectValue.put("converter", converter);
+ return objectValue;
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "attributeRef=" + attributeRef +
+ ", converter=" + converter +
+ '}';
+ }
+
+ public static boolean isAttributeLink(Value value) {
+ return Values.getObject(value)
+ .map(objectValue -> {
+ return AttributeRef.isAttributeRef(objectValue.get("attributeRef").orElse(null)) &&
+ objectValue.get("converter").map(v -> v.getType() == ValueType.OBJECT).orElse(true);
+ })
+ .orElse(false);
+ }
+
+ @SuppressWarnings("ConstantConditions")
+ public static Optional<AttributeLink> fromValue(Value value) {
+ return Values.getObject(value)
+ .filter(AttributeLink::isAttributeLink)
+ .flatMap(objectValue ->
+ AttributeRef.fromValue(objectValue.get("attributeRef").get())
+ .map(attrRef -> new AttributeLink(attrRef, objectValue.getObject("converter").orElse(null)))
+ );
+ }
+}
\ No newline at end of file
diff --git a/model/src/main/java/org/openremote/model/attribute/AttributeRef.java b/model/src/main/java/org/openremote/model/attribute/AttributeRef.java
index 83ca9bcfb..d2ab78e0b 100644
--- a/model/src/main/java/org/openremote/model/attribute/AttributeRef.java
+++ b/model/src/main/java/org/openremote/model/attribute/AttributeRef.java
@@ -104,6 +104,7 @@ public class AttributeRef {
).isPresent();
}
+ @SuppressWarnings("ConstantConditions")
public static Optional<AttributeRef> fromValue(Value value) {
return Values.getArray(value)
.filter(AttributeRef::isAttributeRef)
diff --git a/model/src/main/java/org/openremote/model/attribute/MetaItem.java b/model/src/main/java/org/openremote/model/attribute/MetaItem.java
index 4970862d8..b94397359 100644
--- a/model/src/main/java/org/openremote/model/attribute/MetaItem.java
+++ b/model/src/main/java/org/openremote/model/attribute/MetaItem.java
@@ -19,6 +19,7 @@
*/
package org.openremote.model.attribute;
+import com.google.gwt.regexp.shared.RegExp;
import org.openremote.model.AbstractValueHolder;
import org.openremote.model.HasUniqueResourceName;
import org.openremote.model.ValidationFailure;
@@ -36,6 +37,8 @@ import java.util.function.Predicate;
import static org.openremote.model.attribute.MetaItem.MetaItemFailureReason.META_ITEM_NAME_IS_REQUIRED;
import static org.openremote.model.attribute.MetaItem.MetaItemFailureReason.META_ITEM_VALUE_IS_REQUIRED;
+import static org.openremote.model.attribute.MetaItem.MetaItemFailureReason.META_ITEM_VALUE_MISMATCH;
+import static org.openremote.model.util.TextUtil.isNullOrEmpty;
/**
* A named arbitrary {@link Value}. A meta item must have a value to be stored.
@@ -102,13 +105,59 @@ public class MetaItem extends AbstractValueHolder {
@Override
public List<ValidationFailure> getValidationFailures() {
+ return getValidationFailures(Optional.empty());
+ }
+
+ public List<ValidationFailure> getValidationFailures(Optional<MetaItemDescriptor> metaItemDescriptor) {
+
List<ValidationFailure> failures = super.getValidationFailures();
+ // Check name
if (!getName().isPresent())
failures.add(new ValidationFailure(META_ITEM_NAME_IS_REQUIRED));
- // Meta items must have a value, unlike attributes
- if (!getValue().isPresent()) {
+ // MetaItemDescriptor validation takes priority
+ metaItemDescriptor
+ .ifPresent(descriptor ->
+ descriptor.getValidator()
+ .map(validator ->
+ validator.apply(getValue().orElse(null))
+ .map(failures::add)
+ .orElse(true)
+ )
+ .orElseGet(
+ () -> {
+ if (!getValue().isPresent()) {
+ failures.add(new ValidationFailure(META_ITEM_VALUE_IS_REQUIRED, descriptor.getValueType().name())
+ );
+ }
+
+ if (getValue().map(Value::getType).map(type -> descriptor.getValueType() != type).orElse(true)) {
+ failures.add(new ValidationFailure(META_ITEM_VALUE_MISMATCH, descriptor.getValueType().name()));
+ return true;
+ }
+
+ if (getValue().isPresent() && !isNullOrEmpty(descriptor.getPattern())) {
+ String valueStr = getValue().get().toString();
+
+ if (isNullOrEmpty(valueStr)) {
+ failures.add(new ValidationFailure(MetaItemFailureReason.META_ITEM_VALUE_IS_REQUIRED, descriptor.getValueType().name()));
+ return true;
+ }
+
+ // Do case insensitive regex (can't include this flag in the pattern like in normal java)
+ if (!RegExp.compile(descriptor.getPattern(), "i").test(valueStr)) {
+ failures.add(new ValidationFailure(MetaItemFailureReason.META_ITEM_VALUE_MISMATCH, descriptor.getPatternFailureMessage()));
+ return true;
+ }
+ }
+
+ // Here because Optional doesn't support ifAbsent
+ return true;
+ }
+ ));
+
+ if (!metaItemDescriptor.isPresent() && !getValue().isPresent()) {
failures.add(new ValidationFailure(META_ITEM_VALUE_IS_REQUIRED));
}
diff --git a/model/src/main/java/org/openremote/model/attribute/MetaItemDescriptor.java b/model/src/main/java/org/openremote/model/attribute/MetaItemDescriptor.java
index d707e8e62..135012688 100644
--- a/model/src/main/java/org/openremote/model/attribute/MetaItemDescriptor.java
+++ b/model/src/main/java/org/openremote/model/attribute/MetaItemDescriptor.java
@@ -19,20 +19,15 @@
*/
package org.openremote.model.attribute;
-
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
-import com.google.gwt.regexp.shared.RegExp;
import org.openremote.model.HasUniqueResourceName;
import org.openremote.model.ValidationFailure;
import org.openremote.model.value.Value;
import org.openremote.model.value.ValueType;
import java.util.Optional;
-
-import static org.openremote.model.attribute.MetaItem.MetaItemFailureReason.META_ITEM_VALUE_IS_REQUIRED;
-import static org.openremote.model.attribute.MetaItem.MetaItemFailureReason.META_ITEM_VALUE_MISMATCH;
-import static org.openremote.model.util.TextUtil.isNullOrEmpty;
+import java.util.function.Function;
@JsonSerialize(as = MetaItemDescriptorImpl.class)
@JsonDeserialize(as = MetaItemDescriptorImpl.class)
@@ -54,38 +49,6 @@ public interface MetaItemDescriptor extends HasUniqueResourceName {
DAYS_HOURS_MINS_SECONDS
}
- /**
- * Validate meta item value using meta item descriptor
- */
- static Optional<ValidationFailure> validateValue(Value value, MetaItemDescriptor metaItemDescriptor) {
- if (metaItemDescriptor == null) {
- return Optional.empty();
- }
-
- if (value == null) {
- return Optional.of(new ValidationFailure(META_ITEM_VALUE_IS_REQUIRED));
- }
-
- if (metaItemDescriptor.getValueType() != value.getType()) {
- return Optional.of(new ValidationFailure(META_ITEM_VALUE_MISMATCH, metaItemDescriptor.getValueType().name()));
- }
-
- if (!isNullOrEmpty(metaItemDescriptor.getPattern())) {
- String valueStr = value.toString();
-
- if (isNullOrEmpty(valueStr)) {
- return Optional.of(new ValidationFailure(MetaItem.MetaItemFailureReason.META_ITEM_VALUE_IS_REQUIRED));
- }
-
- // Do case insensitive regex (can't include this flag in the pattern like in normal java)
- if (!RegExp.compile(metaItemDescriptor.getPattern(), "i").test(valueStr)) {
- return Optional.of(new ValidationFailure(MetaItem.MetaItemFailureReason.META_ITEM_VALUE_MISMATCH, metaItemDescriptor.getPatternFailureMessage()));
- }
- }
-
- return Optional.empty();
- }
-
String name();
String getUrn();
@@ -126,7 +89,8 @@ public interface MetaItemDescriptor extends HasUniqueResourceName {
boolean isValueFixed();
/**
- * Validate the supplied {@link MetaItem} against this {@link MetaItemDescriptor}
+ * Get optional validation function; this allows {@link MetaItemDescriptor} implementations to do more advanced
+ * validation. If defined this takes priority over all other value checks
*/
- Optional<ValidationFailure> validateValue(Value value);
+ Optional<Function<Value, Optional<ValidationFailure>>> getValidator();
}
diff --git a/model/src/main/java/org/openremote/model/attribute/MetaItemDescriptorImpl.java b/model/src/main/java/org/openremote/model/attribute/MetaItemDescriptorImpl.java
index 6b69b07d7..a30e6874a 100644
--- a/model/src/main/java/org/openremote/model/attribute/MetaItemDescriptorImpl.java
+++ b/model/src/main/java/org/openremote/model/attribute/MetaItemDescriptorImpl.java
@@ -20,12 +20,14 @@
package org.openremote.model.attribute;
import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.openremote.model.ValidationFailure;
import org.openremote.model.value.Value;
import org.openremote.model.value.ValueType;
import java.util.Optional;
+import java.util.function.Function;
public class MetaItemDescriptorImpl implements MetaItemDescriptor {
@@ -105,8 +107,9 @@ public class MetaItemDescriptorImpl implements MetaItemDescriptor {
return valueFixed;
}
+ @JsonIgnore
@Override
- public Optional<ValidationFailure> validateValue(Value value) {
- return MetaItemDescriptor.validateValue(value, this);
+ public Optional<Function<Value, Optional<ValidationFailure>>> getValidator() {
+ return Optional.empty();
}
}