Skip to content

armgit / core

Public Imported from GitHub
0

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

Overhaul of Meta Item Validation, Attributes Editor/Viewer and started protocol discovery

Rich Turner9ae5f2e9ec2d
diff --git a/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java
index 1b05ae502..6417b23d0 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java
@@ -26,17 +26,16 @@ import org.openremote.container.message.MessageBrokerContext;
import org.openremote.container.message.MessageBrokerService;
import org.openremote.container.message.MessageBrokerSetupService;
import org.openremote.container.timer.TimerService;
+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;
-import org.openremote.model.attribute.AttributeEvent;
-import org.openremote.model.attribute.AttributeRef;
-import org.openremote.model.attribute.AttributeState;
-import org.openremote.model.attribute.MetaItem;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Map;
+import org.openremote.model.asset.agent.ProtocolConfiguration;
+import org.openremote.model.attribute.*;
+import org.openremote.model.asset.agent.ProtocolDescriptor;
+
+import java.util.*;
import java.util.function.Consumer;
import java.util.logging.Logger;
@@ -289,12 +288,54 @@ public abstract class AbstractProtocol implements Protocol {
}
}
+ @Override
+ public ProtocolDescriptor getProtocolDescriptor() {
+ return new ProtocolDescriptor(
+ getProtocolName(),
+ getProtocolDisplayName(),
+ getVersion(),
+ this instanceof ProtocolConfigurationDiscovery,
+ this instanceof ProtocolConfigurationImport,
+ this instanceof ProtocolDeviceDiscovery,
+ this instanceof ProtocolDeviceImport,
+ getProtocolConfigurationTemplate(),
+ getProtocolConfigurationMetaItemDescriptors(),
+ getLinkedAttributeMetaItemDescriptors()
+ );
+ }
+
+ @Override
+ public AssetAttribute getProtocolConfigurationTemplate() {
+ return ProtocolConfiguration.initProtocolConfiguration(new AssetAttribute(), getProtocolName());
+ }
+
+ @Override
+ public AttributeValidationResult validateProtocolConfiguration(AssetAttribute protocolConfiguration) {
+ AttributeValidationResult result = new AttributeValidationResult(protocolConfiguration.getName().orElse(""));
+
+ if (!ProtocolConfiguration.isProtocolConfiguration(protocolConfiguration)) {
+ result.addMetaFailure(new ValidationFailure(MetaItem.MetaItemFailureReason.META_ITEM_MISSING, AssetMeta.PROTOCOL_CONFIGURATION.name()));
+ }
+ if (!ProtocolConfiguration.isValidProtocolName(protocolConfiguration.getValueAsString().orElse(null))) {
+ result.addAttributeFailure(new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_INVALID));
+ }
+ return result;
+ }
+
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
'}';
}
+ protected List<MetaItemDescriptor> getProtocolConfigurationMetaItemDescriptors() {
+ return Collections.emptyList();
+ }
+
+ protected List<MetaItemDescriptor> getLinkedAttributeMetaItemDescriptors() {
+ return Collections.emptyList();
+ }
+
/**
* Link the protocol configuration.
*/
diff --git a/agent/src/main/java/org/openremote/agent/protocol/ConnectionStatus.java b/agent/src/main/java/org/openremote/agent/protocol/ConnectionStatus.java
index 703994093..d1294fe85 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/ConnectionStatus.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/ConnectionStatus.java
@@ -50,8 +50,8 @@ public enum ConnectionStatus {
/**
* Disabled.
* <p>
- * For protocol configurations this generally means that it is not enabled (i.e. it has a
- * {@link org.openremote.model.asset.AssetMeta#ENABLED} {@link MetaItem} with a value of <code>false</code>).
+ * For protocol configurations this generally means that it is disabled (i.e. it has a
+ * {@link org.openremote.model.asset.AssetMeta#DISABLED} {@link MetaItem} with a value of <code>true</code>).
*/
DISABLED,
diff --git a/agent/src/main/java/org/openremote/agent/protocol/Protocol.java b/agent/src/main/java/org/openremote/agent/protocol/Protocol.java
index ae1517458..4457b4d81 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/Protocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/Protocol.java
@@ -25,12 +25,15 @@ import org.openremote.model.asset.AssetAttribute;
import org.openremote.model.asset.AssetMeta;
import org.openremote.model.asset.AssetType;
import org.openremote.model.asset.agent.ProtocolConfiguration;
+import org.openremote.model.attribute.AttributeValidationResult;
+import org.openremote.model.asset.agent.ProtocolDescriptor;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeType;
import org.openremote.model.attribute.MetaItem;
import org.openremote.model.value.ValueType;
import java.util.Collection;
+import java.util.List;
import java.util.function.Consumer;
/**
@@ -132,8 +135,21 @@ public interface Protocol extends ContainerService {
// Message queue for communicating from protocol to asset/thing layer (sensor changed, trigger asset attribute update)
String SENSOR_QUEUE = "seda://SensorQueue?waitForTaskToComplete=NEVER&purgeWhenStopping=true&discardIfNoConsumers=false&size=1000";
+ /**
+ * Get the name for this protocol
+ */
String getProtocolName();
+ /**
+ * Get the display friendly name for this protocol
+ */
+ String getProtocolDisplayName();
+
+ /**
+ * Get the version number for this protocol
+ */
+ String getVersion();
+
/**
* Links attributes to their protocolConfiguration; the protocolConfiguration would have
* been linked before this call. If an attribute is not valid for this protocol or the protocol
@@ -162,4 +178,22 @@ public interface Protocol extends ContainerService {
* or removed.
*/
void unlinkProtocolConfiguration(AssetAttribute protocolConfiguration);
+
+ /**
+ * Get a {@link ProtocolDescriptor} for this protocol.
+ */
+ ProtocolDescriptor getProtocolDescriptor();
+
+ /**
+ * Create an empty {@link ProtocolConfiguration} attribute that contains the required meta items needed
+ * by the protocol. The purpose of this is to populate the UI when adding a new protocol configuration
+ * for this protocol.
+ */
+ AssetAttribute getProtocolConfigurationTemplate();
+
+ /**
+ * Validate the supplied {@link ProtocolConfiguration} attribute against this protocol (should indicate that the
+ * protocol configuration is well formed but not necessarily that it connects to a working system).
+ */
+ AttributeValidationResult validateProtocolConfiguration(AssetAttribute protocolConfiguration);
}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/ProtocolConfigurationDiscovery.java b/agent/src/main/java/org/openremote/agent/protocol/ProtocolConfigurationDiscovery.java
new file mode 100644
index 000000000..170a88621
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/ProtocolConfigurationDiscovery.java
@@ -0,0 +1,33 @@
+/*
+ * 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.agent.protocol;
+
+import org.openremote.model.asset.AssetAttribute;
+
+/**
+ * To be used by protocols that support {@link org.openremote.model.asset.agent.ProtocolConfiguration} discovery.
+ */
+public interface ProtocolConfigurationDiscovery {
+
+ /**
+ * Get discovered {@link org.openremote.model.asset.agent.ProtocolConfiguration}s.
+ */
+ AssetAttribute[] getProtocolConfigurationsByDiscovery();
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/ProtocolConfigurationImport.java b/agent/src/main/java/org/openremote/agent/protocol/ProtocolConfigurationImport.java
new file mode 100644
index 000000000..8fdcca9b3
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/ProtocolConfigurationImport.java
@@ -0,0 +1,35 @@
+/*
+ * 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.agent.protocol;
+
+import org.openremote.model.asset.AssetAttribute;
+import org.openremote.model.file.FileInfo;
+
+/**
+ * To be used by protocols that support {@link org.openremote.model.asset.agent.ProtocolConfiguration}
+ * import from one or more protocol specific files.
+ */
+public interface ProtocolConfigurationImport {
+
+ /**
+ * Import available {@link org.openremote.model.asset.agent.ProtocolConfiguration}s from the supplied file(s).
+ */
+ AssetAttribute getProtocolConfigurationsByImport(FileInfo[] files);
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/ProtocolDeviceDiscovery.java b/agent/src/main/java/org/openremote/agent/protocol/ProtocolDeviceDiscovery.java
new file mode 100644
index 000000000..3eaef5a52
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/ProtocolDeviceDiscovery.java
@@ -0,0 +1,46 @@
+/*
+ * 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.agent.protocol;
+
+import org.openremote.model.asset.Asset;
+import org.openremote.model.asset.AssetAttribute;
+
+/**
+ * To be used by protocols that support device discovery.
+ * <p>
+ * The discovery process should return an array of {@link Asset}s that represent the physical devices
+ * connected to a particular {@link org.openremote.model.asset.agent.ProtocolConfiguration}. The device
+ * assets should contain all the appropriate {@link AssetAttribute}s needed for interacting with the
+ * device. Each {@link AssetAttribute} should be of the correct type and have any required
+ * {@link org.openremote.model.attribute.MetaItem}s already set.
+ * <p>
+ * <b>
+ * NOTE: It is not necessary to set an {@link org.openremote.model.asset.agent.AgentLink}
+ * {@link org.openremote.model.attribute.MetaItem} for each attribute as the system will insert these
+ * automatically if omitted.
+ * </b>
+ */
+public interface ProtocolDeviceDiscovery {
+
+ /**
+ * Get discovered devices for the specified {@link org.openremote.model.asset.agent.ProtocolConfiguration}.
+ */
+ Asset[] getDevicesByDiscovery(AssetAttribute protocolConfiguration);
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/ProtocolDeviceImport.java b/agent/src/main/java/org/openremote/agent/protocol/ProtocolDeviceImport.java
new file mode 100644
index 000000000..f63a04f2c
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/ProtocolDeviceImport.java
@@ -0,0 +1,47 @@
+/*
+ * 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.agent.protocol;
+
+import org.openremote.model.asset.Asset;
+import org.openremote.model.asset.AssetAttribute;
+
+/**
+ * To be used by protocols that support device import from one or more protocol specific files.
+ * <p>
+ * The import process should return an array of {@link Asset}s that represent the physical devices
+ * connected to a particular {@link org.openremote.model.asset.agent.ProtocolConfiguration}. The device
+ * assets should contain all the appropriate {@link AssetAttribute}s needed for interacting with the
+ * device. Each {@link AssetAttribute} should be of the correct type and have any required
+ * {@link org.openremote.model.attribute.MetaItem}s already set.
+ * <p>
+ * <b>
+ * NOTE: It is not necessary to set an {@link org.openremote.model.asset.agent.AgentLink}
+ * {@link org.openremote.model.attribute.MetaItem} for each attribute as the system will insert these
+ * automatically if omitted.
+ * </b>
+ */
+public interface ProtocolDeviceImport {
+
+ /**
+ * Import devices for the specified {@link org.openremote.model.asset.agent.ProtocolConfiguration}
+ * using the supplied file(s).
+ */
+ Asset[] getDevicesByDiscovery(AssetAttribute protocolConfiguration);
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/knx/KNXConnection.java b/agent/src/main/java/org/openremote/agent/protocol/knx/KNXConnection.java
index 4372d1af3..b93135a4e 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/knx/KNXConnection.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/knx/KNXConnection.java
@@ -254,7 +254,7 @@ public class KNXConnection implements NetworkLinkListener, ProcessListener {
LOG.fine("Sending read request to KNX status datapoint '" + datapoint);
this.knxLink.sendRequest(datapoint.getMainAddress(), datapoint.getPriority(), DataUnitBuilder.createLengthOptimizedAPDU(0x00, null));
} catch (Exception e) {
- LOG.log(Level.INFO, "Error sending KNX read request for DPT: " + datapoint, e);
+ LOG.log(Level.INFO, "Error sending KNX read request for META_KNX_DPT: " + datapoint, e);
}
}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/knx/KNXProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/knx/KNXProtocol.java
index 0ee3a66e8..107bb5bc2 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/knx/KNXProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/knx/KNXProtocol.java
@@ -1,23 +1,26 @@
package org.openremote.agent.protocol.knx;
import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;
+import static org.openremote.model.attribute.MetaItem.isMetaNameEqualTo;
+import static org.openremote.model.util.TextUtil.REGEXP_PATTERN_INTEGER_POSITIVE_NON_ZERO;
+import static org.openremote.model.util.TextUtil.isNullOrEmpty;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Optional;
+import java.util.*;
import java.util.function.Consumer;
import java.util.logging.Logger;
import org.openremote.agent.protocol.AbstractProtocol;
import org.openremote.agent.protocol.ConnectionStatus;
import org.openremote.model.AbstractValueHolder;
+import org.openremote.model.ValidationFailure;
+import org.openremote.model.ValueHolder;
import org.openremote.model.asset.AssetAttribute;
-import org.openremote.model.attribute.AttributeEvent;
-import org.openremote.model.attribute.AttributeRef;
-import org.openremote.model.attribute.AttributeState;
+import org.openremote.model.attribute.*;
import org.openremote.model.util.Pair;
import org.openremote.model.value.Value;
+import org.openremote.model.value.ValueType;
+import org.openremote.model.value.Values;
import tuwien.auto.calimero.GroupAddress;
import tuwien.auto.calimero.KNXFormatException;
import tuwien.auto.calimero.datapoint.CommandDP;
@@ -32,50 +35,74 @@ public class KNXProtocol extends AbstractProtocol {
private static final Logger LOG = Logger.getLogger(KNXProtocol.class.getName());
public static final String PROTOCOL_NAME = PROTOCOL_NAMESPACE + ":knx";
-
+ public static final String PROTOCOL_DISPLAY_NAME = "KNX";
+
//Protocol specific configuration meta items
/**
- * IP address of the KNX gateway to connect to in TUNNEL mode. Optional if {@link #KNX_IP_CONNECTION_TYPE} is ROUTING.<br>
+ * IP address of the KNX gateway to connect to in TUNNEL mode. Optional if {@link #META_KNX_IP_CONNECTION_TYPE} is ROUTING.<br>
* In ROUTING mode, the IP address specifies the multicast group to join.
*/
- public static final String KNX_GATEWAY_IP = PROTOCOL_NAME + ":gatewayIp";
+ public static final String META_KNX_GATEWAY_IP = PROTOCOL_NAME + ":gatewayIp";
/**
* The KNX gateway port to connect to in TUNNEL mode. Not used in ROUTING mode.<br>
* Default: 3671
*/
- public static final String KNX_GATEWAY_PORT = PROTOCOL_NAME + ":gatewayPort";
+ public static final String META_KNX_GATEWAY_PORT = PROTOCOL_NAME + ":gatewayPort";
/**
* <code>TRUE</code> to use network address translation in TUNNELLING mode, <code>FALSE</code>
* to use the default (non aware) mode; parameter is ignored for ROUTING<br>
* Default: <code>FALSE</code>
*/
- public static final String KNX_GATEWAY_USENAT = PROTOCOL_NAME + ":useNAT";
+ public static final String META_KNX_GATEWAY_USENAT = PROTOCOL_NAME + ":useNAT";
/**
* ServiceMode mode of communication to open, <code>connectionType</code> is one of TUNNELLING or ROUTING<br>
* Default: TUNNELLING
*/
- public static final String KNX_IP_CONNECTION_TYPE = PROTOCOL_NAME + ":connectionType";
+ public static final String META_KNX_IP_CONNECTION_TYPE = PROTOCOL_NAME + ":connectionType";
/**
* Device individual address to use as source address in KNX messages.<br>
* Default: 0.0.0
*/
- public static final String KNX_LOCAL_BUS_ADDRESS = PROTOCOL_NAME + ":localBusAddress";
+ public static final String META_KNX_LOCAL_BUS_ADDRESS = PROTOCOL_NAME + ":localBusAddress";
/**
* Local IP address or hostname to establish connection from.<br>
* Default: hostname
*/
- public static final String KNX_LOCAL_IP = PROTOCOL_NAME + ":localIP";
+ public static final String META_KNX_LOCAL_IP = PROTOCOL_NAME + ":localIP";
//Attribute specific configuration meta items
- public static final String DPT = PROTOCOL_NAME + ":dpt";
- public static final String STATUS_GA = PROTOCOL_NAME + ":statusGA";
- public static final String ACTION_GA = PROTOCOL_NAME + ":actionGA";
+ public static final String META_KNX_DPT = PROTOCOL_NAME + ":dpt";
+ public static final String META_KNX_STATUS_GA = PROTOCOL_NAME + ":statusGA";
+ public static final String META_KNX_ACTION_GA = PROTOCOL_NAME + ":actionGA";
+
+ protected static final String VERSION = "1.0";
+
+ public static final String REGEXP_GROUP_ADDRESS = "^\\d\\.\\d\\.\\d$";
+ public static final String REGEXP_DPT = "^\\d{1,2}\\.\\d{1,3}$";
+ public static final String PATTERN_FAILURE_CONNECTION_TYPE = "TUNNELLING|ROUTING";
+ public static final String PATTERN_FAILURE_DPT = "KNX DPT (e.g. 1.001)";
+ public static final String PATTERN_FAILURE_GROUP_ADDRESS = "KNX Group Address (e.g. 1.1.1)";
+
+ protected static final List<MetaItemDescriptor> PROTOCOL_CONFIG_META_ITEM_DESCRIPTORS = Arrays.asList(
+ new MetaItemDescriptorImpl("PROTOCOL_KNX_IP", META_KNX_GATEWAY_IP, ValueType.STRING, false, null, null, 1, null, false),
+ new MetaItemDescriptorImpl("PROTOCOL_KNX_PORT", META_KNX_GATEWAY_PORT, ValueType.NUMBER, false, REGEXP_PATTERN_INTEGER_POSITIVE_NON_ZERO, MetaItemDescriptor.PatternFailure.INTEGER_POSITIVE_NON_ZERO.name(), 1, null, false),
+ new MetaItemDescriptorImpl("PROTOCOL_KNX_USENAT", META_KNX_GATEWAY_USENAT, ValueType.BOOLEAN, false, null, null, 1, Values.create(false), false),
+ new MetaItemDescriptorImpl("PROTOCOL_KNX_CONNECTION_TYPE", META_KNX_IP_CONNECTION_TYPE, ValueType.STRING, false, "^(TUNNELLING|ROUTING)$", PATTERN_FAILURE_CONNECTION_TYPE, 1, Values.create("TUNNELLING"), false),
+ new MetaItemDescriptorImpl("PROTOCOL_KNX_LOCAL_BUS_ADDRESS", META_KNX_LOCAL_BUS_ADDRESS, ValueType.STRING, false, REGEXP_GROUP_ADDRESS, "0.0.0", 1, null, false),
+ new MetaItemDescriptorImpl("PROTOCOL_KNX_LOCAL_IP", META_KNX_LOCAL_IP, ValueType.STRING, false, null, null, 1, null, false)
+ );
+
+ protected static final List<MetaItemDescriptor> ATTRIBUTE_META_ITEM_DESCRIPTORS = Arrays.asList(
+ new MetaItemDescriptorImpl("PROTOCOL_KNX_DPT", META_KNX_DPT, ValueType.STRING, true, REGEXP_DPT, PATTERN_FAILURE_DPT, 1, null, false),
+ new MetaItemDescriptorImpl("PROTOCOL_KNX_STATUS_GA", META_KNX_STATUS_GA, ValueType.NUMBER, false, REGEXP_GROUP_ADDRESS, PATTERN_FAILURE_GROUP_ADDRESS, 1, null, false),
+ new MetaItemDescriptorImpl("PROTOCOL_KNX_ACTION_GA", META_KNX_ACTION_GA, ValueType.NUMBER, false, REGEXP_GROUP_ADDRESS, PATTERN_FAILURE_GROUP_ADDRESS, 1, Values.create(false), false)
+ );
final protected Map<String, KNXConnection> knxConnections = new HashMap<>();
final protected Map<AttributeRef, Consumer<ConnectionStatus>> statusConsumerMap = new HashMap<>();
@@ -87,16 +114,84 @@ public class KNXProtocol extends AbstractProtocol {
return PROTOCOL_NAME;
}
+ @Override
+ public String getProtocolDisplayName() {
+ return PROTOCOL_DISPLAY_NAME;
+ }
+
+ @Override
+ public String getVersion() {
+ return VERSION;
+ }
+
+ @Override
+ public AssetAttribute getProtocolConfigurationTemplate() {
+ return super.getProtocolConfigurationTemplate()
+ .addMeta(
+ new MetaItem(META_KNX_IP_CONNECTION_TYPE, null),
+ new MetaItem(META_KNX_GATEWAY_IP, null)
+ );
+ }
+
+ @Override
+ public AttributeValidationResult validateProtocolConfiguration(AssetAttribute protocolConfiguration) {
+ AttributeValidationResult result = super.validateProtocolConfiguration(protocolConfiguration);
+ if (result.isValid()) {
+ boolean ipFound = false;
+
+ if (protocolConfiguration.getMeta() != null && !protocolConfiguration.getMeta().isEmpty()) {
+ for (int i = 0; i < protocolConfiguration.getMeta().size(); i++) {
+ MetaItem actionMetaItem = protocolConfiguration.getMeta().get(i);
+ if (isMetaNameEqualTo(actionMetaItem, META_KNX_IP_CONNECTION_TYPE)) {
+ String connectionType = actionMetaItem.getValueAsString().orElse("TUNNELLING");
+ if (!connectionType.equals("TUNNELLING") && !connectionType.equals("ROUTING")) {
+ result.addMetaFailure(
+ new ValidationFailure(MetaItem.MetaItemFailureReason.META_ITEM_VALUE_MISMATCH, PATTERN_FAILURE_CONNECTION_TYPE)
+ );
+ }
+
+ ipFound = "ROUTING".equals(connectionType);
+ } else if (isMetaNameEqualTo(actionMetaItem, META_KNX_GATEWAY_IP)) {
+ ipFound = true;
+ if (isNullOrEmpty(actionMetaItem.getValueAsString().orElse(null))) {
+ result.addMetaFailure(
+ new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_EXPECTED_STRING)
+ );
+ }
+ }
+ }
+ }
+
+ if (!ipFound) {
+ result.addMetaFailure(
+ new ValidationFailure(MetaItem.MetaItemFailureReason.META_ITEM_MISSING, META_KNX_GATEWAY_IP)
+ );
+ }
+ }
+
+ return result;
+ }
+
+ @Override
+ protected List<MetaItemDescriptor> getProtocolConfigurationMetaItemDescriptors() {
+ return PROTOCOL_CONFIG_META_ITEM_DESCRIPTORS;
+ }
+
+ @Override
+ protected List<MetaItemDescriptor> getLinkedAttributeMetaItemDescriptors() {
+ return ATTRIBUTE_META_ITEM_DESCRIPTORS;
+ }
+
@Override
protected void doLinkProtocolConfiguration(AssetAttribute protocolConfiguration) {
- String connectionType = protocolConfiguration.getMetaItem(KNX_IP_CONNECTION_TYPE).flatMap(AbstractValueHolder::getValueAsString).orElse("TUNNELLING");
+ String connectionType = protocolConfiguration.getMetaItem(META_KNX_IP_CONNECTION_TYPE).flatMap(AbstractValueHolder::getValueAsString).orElse("TUNNELLING");
if (!connectionType.equals("TUNNELLING") && !connectionType.equals("ROUTING")) {
LOG.severe("KNX connectionType can either be 'TUNNELLING' or 'ROUTING' for protocol configuration: " + protocolConfiguration);
updateStatus(protocolConfiguration.getReferenceOrThrow(), ConnectionStatus.ERROR);
return;
}
- Optional<String> gatewayIpParam = protocolConfiguration.getMetaItem(KNX_GATEWAY_IP).flatMap(AbstractValueHolder::getValueAsString);
+ Optional<String> gatewayIpParam = protocolConfiguration.getMetaItem(META_KNX_GATEWAY_IP).flatMap(AbstractValueHolder::getValueAsString);
if (!gatewayIpParam.isPresent() && connectionType.equals("TUNNELLING")) {
LOG.severe("No KNX gateway IP address provided for TUNNELLING mode for protocol configuration: " + protocolConfiguration);
updateStatus(protocolConfiguration.getReferenceOrThrow(), ConnectionStatus.ERROR);
@@ -108,10 +203,10 @@ public class KNXProtocol extends AbstractProtocol {
return;
}
- String localIp = protocolConfiguration.getMetaItem(KNX_LOCAL_IP).flatMap(AbstractValueHolder::getValueAsString).orElse(null);
- Integer remotePort = protocolConfiguration.getMetaItem(KNX_GATEWAY_PORT).flatMap(AbstractValueHolder::getValueAsInteger).orElse(Integer.valueOf(3671));
- String localKNXAddress = protocolConfiguration.getMetaItem(KNX_LOCAL_BUS_ADDRESS).flatMap(AbstractValueHolder::getValueAsString).orElse("0.0.0");
- Boolean useNat = protocolConfiguration.getMetaItem(KNX_GATEWAY_USENAT).flatMap(AbstractValueHolder::getValueAsBoolean).orElse(Boolean.FALSE);
+ String localIp = protocolConfiguration.getMetaItem(META_KNX_LOCAL_IP).flatMap(AbstractValueHolder::getValueAsString).orElse(null);
+ Integer remotePort = protocolConfiguration.getMetaItem(META_KNX_GATEWAY_PORT).flatMap(AbstractValueHolder::getValueAsInteger).orElse(3671);
+ String localKNXAddress = protocolConfiguration.getMetaItem(META_KNX_LOCAL_BUS_ADDRESS).flatMap(AbstractValueHolder::getValueAsString).orElse("0.0.0");
+ Boolean useNat = protocolConfiguration.getMetaItem(META_KNX_GATEWAY_USENAT).flatMap(AbstractValueHolder::getValueAsBoolean).orElse(Boolean.FALSE);
AttributeRef protocolRef = protocolConfiguration.getReferenceOrThrow();
@@ -141,7 +236,7 @@ public class KNXProtocol extends AbstractProtocol {
statusConsumer = statusConsumerMap.get(protocolConfiguration.getReferenceOrThrow());
}
- String gatewayIp = protocolConfiguration.getMetaItem(KNX_GATEWAY_IP).flatMap(AbstractValueHolder::getValueAsString).orElse("");
+ String gatewayIp = protocolConfiguration.getMetaItem(META_KNX_GATEWAY_IP).flatMap(AbstractValueHolder::getValueAsString).orElse("");
synchronized (knxConnections) {
KNXConnection knxConnection = knxConnections.get(gatewayIp);
if (knxConnection != null) {
@@ -156,18 +251,18 @@ public class KNXProtocol extends AbstractProtocol {
@Override
protected void doLinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration) {
- String gatewayIp = protocolConfiguration.getMetaItem(KNX_GATEWAY_IP).flatMap(AbstractValueHolder::getValueAsString).orElse("");
+ String gatewayIp = protocolConfiguration.getMetaItem(META_KNX_GATEWAY_IP).flatMap(AbstractValueHolder::getValueAsString).orElse("");
final AttributeRef attributeRef = attribute.getReferenceOrThrow();
- // Check there is a DPT
- Optional<String> dpt = attribute.getMetaItem(DPT).flatMap(AbstractValueHolder::getValueAsString);
+ // Check there is a META_KNX_DPT
+ Optional<String> dpt = attribute.getMetaItem(META_KNX_DPT).flatMap(AbstractValueHolder::getValueAsString);
if (!dpt.isPresent()) {
- LOG.severe("No DPT for protocol attribute: " + attributeRef);
+ LOG.severe("No META_KNX_DPT for protocol attribute: " + attributeRef);
return;
}
- Optional<String> statusGA = attribute.getMetaItem(STATUS_GA).flatMap(AbstractValueHolder::getValueAsString);
- Optional<String> actionGA = attribute.getMetaItem(ACTION_GA).flatMap(AbstractValueHolder::getValueAsString);
+ Optional<String> statusGA = attribute.getMetaItem(META_KNX_STATUS_GA).flatMap(AbstractValueHolder::getValueAsString);
+ Optional<String> actionGA = attribute.getMetaItem(META_KNX_ACTION_GA).flatMap(AbstractValueHolder::getValueAsString);
if (!statusGA.isPresent() && !actionGA.isPresent()) {
LOG.warning("No status group address or action group address provided so nothing to do for protocol attribute: " + attributeRef);
@@ -318,5 +413,4 @@ public class KNXProtocol extends AbstractProtocol {
return clientStillUsed;
}
-
}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/macro/MacroConfiguration.java b/agent/src/main/java/org/openremote/agent/protocol/macro/MacroConfiguration.java
index cca26dd65..d07b1ed69 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/macro/MacroConfiguration.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/macro/MacroConfiguration.java
@@ -20,7 +20,11 @@
package org.openremote.agent.protocol.macro;
import org.openremote.model.AbstractValueHolder;
+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.attribute.MetaItem;
import java.util.Arrays;
import java.util.Collection;
@@ -31,6 +35,7 @@ import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.openremote.agent.protocol.macro.MacroProtocol.META_MACRO_ACTION;
+import static org.openremote.agent.protocol.macro.MacroProtocol.PROTOCOL_NAME;
import static org.openremote.model.asset.agent.ProtocolConfiguration.getProtocolName;
import static org.openremote.model.asset.agent.ProtocolConfiguration.initProtocolConfiguration;
import static org.openremote.model.attribute.MetaItem.isMetaNameEqualTo;
@@ -56,12 +61,51 @@ final public class MacroConfiguration {
.orElse(false);
}
- public static boolean isValidMacroConfiguration(AssetAttribute attribute) {
- return attribute != null
- && isMacroConfiguration(attribute)
- && attribute.getMetaItem(META_MACRO_ACTION).isPresent(); // Must have at least one macro action
+ public static boolean validateMacroConfiguration(AssetAttribute attribute, AttributeValidationResult result) {
+ boolean failure = false;
+
+ if (!isMacroConfiguration(attribute)) {
+ failure = true;
+ if (result != null) {
+ result.addAttributeFailure(new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_MISMATCH, PROTOCOL_NAME));
+ }
+ }
+
+ int actionCount = 0;
+ if (attribute.getMeta() != null && !attribute.getMeta().isEmpty()) {
+ for (int i = 0; i < attribute.getMeta().size(); i++) {
+ MetaItem metaItem = attribute.getMeta().get(i);
+ if (isMetaNameEqualTo(metaItem, META_MACRO_ACTION)) {
+ actionCount++;
+ if (!MacroAction.fromValue(metaItem.getValue().orElse(null)).isPresent()) {
+ failure = true;
+ if (result == null) {
+ break;
+ }
+ result.addMetaFailure(
+ i, new ValidationFailure(MetaItem.MetaItemFailureReason.META_ITEM_VALUE_MISMATCH, "Macro Action")
+ );
+ }
+ }
+ }
+ }
+
+ if (actionCount == 0) {
+ failure = true;
+ if (result != null) {
+ result.addMetaFailure(
+ new ValidationFailure(MetaItem.MetaItemFailureReason.META_ITEM_MISSING, META_MACRO_ACTION)
+ );
+ }
+ }
+
+ return !failure;
}
+ public static boolean isValidMacroConfiguration(AssetAttribute attribute) {
+
+ return validateMacroConfiguration(attribute, null);
+ }
public static Stream<MacroAction> getMacroActionsStream(AssetAttribute attribute) {
return attribute == null ? Stream.empty() :
diff --git a/agent/src/main/java/org/openremote/agent/protocol/macro/MacroProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/macro/MacroProtocol.java
index f734ceebd..91604be26 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/macro/MacroProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/macro/MacroProtocol.java
@@ -25,6 +25,7 @@ import org.openremote.model.asset.AssetAttribute;
import org.openremote.model.attribute.*;
import org.openremote.model.util.Pair;
import org.openremote.model.value.Value;
+import org.openremote.model.value.ValueType;
import org.openremote.model.value.Values;
import java.util.*;
@@ -34,6 +35,7 @@ import java.util.logging.Logger;
import static org.openremote.agent.protocol.macro.MacroConfiguration.getMacroActionIndex;
import static org.openremote.agent.protocol.macro.MacroConfiguration.isValidMacroConfiguration;
import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;
+import static org.openremote.model.util.TextUtil.REGEXP_PATTERN_INTEGER_POSITIVE;
/**
* This protocol is responsible for executing macros.
@@ -49,8 +51,19 @@ public class MacroProtocol extends AbstractProtocol {
private static final Logger LOG = Logger.getLogger(MacroProtocol.class.getName());
public static final String PROTOCOL_NAME = PROTOCOL_NAMESPACE + ":macro";
+ public static final String PROTOCOL_DISPLAY_NAME = "Macro";
public static final String META_MACRO_ACTION = PROTOCOL_NAME + ":action";
public static final String META_MACRO_ACTION_INDEX = PROTOCOL_NAME + ":actionIndex";
+ protected static final String VERSION = "1.0";
+ protected static final MacroAction EMPTY_ACTION = new MacroAction(new AttributeState(new AttributeRef("ENTITY_ID", "ATTRIBUTE_NAME"), null));
+
+ protected static final List<MetaItemDescriptor> PROTOCOL_META_ITEM_DESCRIPTORS = Collections.singletonList(
+ new MetaItemDescriptorImpl("PROTOCOL_MACRO_ACTION", META_MACRO_ACTION, ValueType.OBJECT, true, null, null, null, EMPTY_ACTION.toObjectValue(), false)
+ );
+
+ protected static final List<MetaItemDescriptor> ATTRIBUTE_META_ITEM_DESCRIPTORS = Collections.singletonList(
+ new MetaItemDescriptorImpl("PROTOCOL_MACRO_ACTION_INDEX", META_MACRO_ACTION_INDEX, ValueType.NUMBER, false, REGEXP_PATTERN_INTEGER_POSITIVE, MetaItemDescriptor.PatternFailure.INTEGER_POSITIVE.name(), null, null, false)
+ );
class MacroExecutionTask {
@@ -145,6 +158,41 @@ public class MacroProtocol extends AbstractProtocol {
return PROTOCOL_NAME;
}
+ @Override
+ public String getProtocolDisplayName() {
+ return PROTOCOL_DISPLAY_NAME;
+ }
+
+ @Override
+ public String getVersion() {
+ return VERSION;
+ }
+
+ @Override
+ public AssetAttribute getProtocolConfigurationTemplate() {
+ return super.getProtocolConfigurationTemplate()
+ .addMeta(new MetaItem(META_MACRO_ACTION, EMPTY_ACTION.toObjectValue()));
+ }
+
+ @Override
+ public AttributeValidationResult validateProtocolConfiguration(AssetAttribute protocolConfiguration) {
+ AttributeValidationResult result = super.validateProtocolConfiguration(protocolConfiguration);
+ if (result.isValid()) {
+ MacroConfiguration.validateMacroConfiguration(protocolConfiguration, result);
+ }
+ return result;
+ }
+
+ @Override
+ protected List<MetaItemDescriptor> getProtocolConfigurationMetaItemDescriptors() {
+ return PROTOCOL_META_ITEM_DESCRIPTORS;
+ }
+
+ @Override
+ protected List<MetaItemDescriptor> getLinkedAttributeMetaItemDescriptors() {
+ return ATTRIBUTE_META_ITEM_DESCRIPTORS;
+ }
+
@Override
protected void doLinkProtocolConfiguration(AssetAttribute protocolConfiguration) {
// Protocol configuration is actually a Macro Configuration
@@ -333,4 +381,6 @@ public class MacroProtocol extends AbstractProtocol {
MacroExecutionTask task = new MacroExecutionTask(attributeRef, actions, repeat);
task.start();
}
+
+
}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorProtocol.java
index 3ae30d49b..72a283078 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorProtocol.java
@@ -21,18 +21,17 @@ package org.openremote.agent.protocol.simulator;
import org.openremote.agent.protocol.AbstractProtocol;
import org.openremote.agent.protocol.ConnectionStatus;
-import org.openremote.model.simulator.element.ColorSimulatorElement;
-import org.openremote.model.simulator.element.NumberSimulatorElement;
-import org.openremote.model.simulator.SimulatorElement;
-import org.openremote.model.simulator.element.SwitchSimulatorElement;
import org.openremote.model.AbstractValueHolder;
import org.openremote.model.ValidationFailure;
import org.openremote.model.asset.AssetAttribute;
-import org.openremote.model.attribute.AttributeEvent;
-import org.openremote.model.attribute.AttributeRef;
-import org.openremote.model.attribute.AttributeState;
+import org.openremote.model.attribute.*;
+import org.openremote.model.simulator.SimulatorElement;
import org.openremote.model.simulator.SimulatorState;
+import org.openremote.model.simulator.element.ColorSimulatorElement;
+import org.openremote.model.simulator.element.NumberSimulatorElement;
+import org.openremote.model.simulator.element.SwitchSimulatorElement;
import org.openremote.model.value.Value;
+import org.openremote.model.value.ValueType;
import java.util.*;
import java.util.function.Consumer;
@@ -42,6 +41,7 @@ import java.util.stream.Collectors;
import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;
import static org.openremote.model.asset.AssetMeta.RANGE_MAX;
import static org.openremote.model.asset.AssetMeta.RANGE_MIN;
+import static org.openremote.model.util.TextUtil.REGEXP_PATTERN_INTEGER_POSITIVE;
public class SimulatorProtocol extends AbstractProtocol {
@@ -98,6 +98,7 @@ public class SimulatorProtocol extends AbstractProtocol {
public static final int DEFAULT_WRITE_DELAY = 1000;
public static final String PROTOCOL_NAME = PROTOCOL_NAMESPACE + ":simulator";
+ public static final String PROTOCOL_DISPLAY_NAME = "Simulator";
/**
* Required meta item, the simulator element that should be used, see subclasses of {@link SimulatorElement}.
@@ -115,10 +116,55 @@ public class SimulatorProtocol extends AbstractProtocol {
*/
public static final String CONFIG_WRITE_DELAY_MILLISECONDS = PROTOCOL_NAME + ":delayMilliseconds";
+ protected static final String VERSION = "1.0";
+
static final protected Map<AttributeRef, Instance> instances = new HashMap<>();
static final protected Map<AttributeRef, AttributeRef> attributeInstanceMap = new HashMap<>();
static final protected Map<AttributeRef, SimulatorElement> elements = new HashMap<>();
+ protected static final List<MetaItemDescriptor> PROTOCOL_META_ITEM_DESCRIPTORS = Arrays.asList(
+ new MetaItemDescriptorImpl("PROTOCOL_SIMULATOR_MODE",
+ CONFIG_MODE,
+ ValueType.STRING,
+ false,
+ "^(WRITE_THROUGH_IMMEDIATE|WRITE_THROUGH_DELAYED|MANUAL)$",
+ "WRITE_THROUGH_IMMEDIATE|WRITE_THROUGH_DELAYED|MANUAL",
+ null,
+ null,
+ false),
+ new MetaItemDescriptorImpl(
+ "PROTOCOL_SIMULATOR_WRITE_DELAY",
+ CONFIG_WRITE_DELAY_MILLISECONDS,
+ ValueType.NUMBER,
+ false,
+ REGEXP_PATTERN_INTEGER_POSITIVE,
+ MetaItemDescriptor.PatternFailure.INTEGER_POSITIVE.name(),
+ null,
+ null,
+ false)
+ );
+
+ protected static final List<MetaItemDescriptor> ATTRIBUTE_META_ITEM_DESCRIPTORS = Collections.singletonList(
+ new MetaItemDescriptorImpl(
+ "PROTOCOL_SIMULATOR_ELEMENT",
+ SIMULATOR_ELEMENT,
+ ValueType.STRING,
+ true,
+ "^(" +
+ SwitchSimulatorElement.ELEMENT_NAME.toUpperCase(Locale.ROOT) + "|" +
+ NumberSimulatorElement.ELEMENT_NAME.toUpperCase(Locale.ROOT) + "|" +
+ NumberSimulatorElement.ELEMENT_NAME_RANGE.toUpperCase(Locale.ROOT) + "|" +
+ ColorSimulatorElement.ELEMENT_NAME.toUpperCase(Locale.ROOT) +
+ ")$",
+ SwitchSimulatorElement.ELEMENT_NAME.toUpperCase(Locale.ROOT) + "|" +
+ NumberSimulatorElement.ELEMENT_NAME.toUpperCase(Locale.ROOT) + "|" +
+ NumberSimulatorElement.ELEMENT_NAME_RANGE.toUpperCase(Locale.ROOT) + "|" +
+ ColorSimulatorElement.ELEMENT_NAME.toUpperCase(Locale.ROOT),
+ null,
+ null,
+ false)
+ );
+
// TODO This is not nice, find a better way how the protocol can talk to the service (through message bus?)
protected Consumer<AttributeRef> protocolConfigurationValuesChangedHandler;
@@ -127,6 +173,26 @@ public class SimulatorProtocol extends AbstractProtocol {
return PROTOCOL_NAME;
}
+ @Override
+ public String getProtocolDisplayName() {
+ return PROTOCOL_DISPLAY_NAME;
+ }
+
+ @Override
+ public String getVersion() {
+ return VERSION;
+ }
+
+ @Override
+ protected List<MetaItemDescriptor> getProtocolConfigurationMetaItemDescriptors() {
+ return PROTOCOL_META_ITEM_DESCRIPTORS;
+ }
+
+ @Override
+ protected List<MetaItemDescriptor> getLinkedAttributeMetaItemDescriptors() {
+ return ATTRIBUTE_META_ITEM_DESCRIPTORS;
+ }
+
@Override
protected void doLinkProtocolConfiguration(AssetAttribute protocolConfiguration) {
AttributeRef protocolRef = protocolConfiguration.getReferenceOrThrow();
@@ -351,7 +417,8 @@ public class SimulatorProtocol extends AbstractProtocol {
Optional<Value> oldValue = element.getValue();
element.setValue(attributeState.getCurrentValue().orElse(null));
- List<ValidationFailure> failures =element.getValidationFailures();
+ List<ValidationFailure> failures = element.getValidationFailures();
+
if (!failures.isEmpty()) {
// Reset to old value
oldValue.ifPresent(element::setValue);
diff --git a/agent/src/main/java/org/openremote/agent/protocol/timer/TimerConfiguration.java b/agent/src/main/java/org/openremote/agent/protocol/timer/TimerConfiguration.java
index 5f490747b..d423fc084 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/timer/TimerConfiguration.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/timer/TimerConfiguration.java
@@ -20,8 +20,13 @@
package org.openremote.agent.protocol.timer;
import org.openremote.model.AbstractValueHolder;
+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.AttributeState;
+import org.openremote.model.attribute.AttributeValidationResult;
+import org.openremote.model.attribute.MetaItem;
import org.openremote.model.value.Values;
import java.util.Optional;
@@ -54,6 +59,69 @@ final public class TimerConfiguration {
.orElse(false);
}
+ public static boolean validateTimerConfiguration(AssetAttribute attribute, AttributeValidationResult result) {
+ boolean failure = false;
+
+ if (!isTimerConfiguration(attribute)) {
+ failure = true;
+ if (result != null) {
+ result.addAttributeFailure(new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_MISMATCH, PROTOCOL_NAME));
+ }
+ }
+
+ boolean actionFound = false;
+ boolean cronFound = false;
+
+ if (attribute.getMeta() != null && !attribute.getMeta().isEmpty()) {
+ for (int i = 0; i < attribute.getMeta().size(); i++) {
+ MetaItem metaItem = attribute.getMeta().get(i);
+ if (isMetaNameEqualTo(metaItem, META_TIMER_ACTION)) {
+ actionFound = true;
+ if (!getAction(metaItem).isPresent()) {
+ failure = true;
+ if (result == null) {
+ break;
+ }
+ result.addMetaFailure(
+ i, new ValidationFailure(MetaItem.MetaItemFailureReason.META_ITEM_VALUE_MISMATCH, "Timer Action")
+ );
+ }
+ } else if (isMetaNameEqualTo(metaItem, META_TIMER_CRON_EXPRESSION)) {
+ cronFound = true;
+ if (!metaItem.getValueAsString().map(TimerProtocol::createCronExpression).isPresent()) {
+ failure = true;
+ if (result == null) {
+ break;
+ }
+ result.addMetaFailure(
+ i, new ValidationFailure(MetaItem.MetaItemFailureReason.META_ITEM_VALUE_MISMATCH, "Timer Cron Expression")
+ );
+ }
+ }
+ }
+ }
+
+ if (!cronFound) {
+ failure = true;
+ if (result != null) {
+ result.addMetaFailure(
+ new ValidationFailure(MetaItem.MetaItemFailureReason.META_ITEM_MISSING, META_TIMER_CRON_EXPRESSION)
+ );
+ }
+ }
+
+ if (!actionFound) {
+ failure = true;
+ if (result != null) {
+ result.addMetaFailure(
+ new ValidationFailure(MetaItem.MetaItemFailureReason.META_ITEM_MISSING, META_TIMER_ACTION)
+ );
+ }
+ }
+
+ return !failure;
+ }
+
public static boolean isValidTimerConfiguration(AssetAttribute attribute) {
return isTimerConfiguration(attribute)
&& isActionValid(attribute)
@@ -103,7 +171,11 @@ final public class TimerConfiguration {
public static Optional<AttributeState> getAction(AssetAttribute attribute) {
return attribute == null ? Optional.empty() : attribute
.getMetaItem(META_TIMER_ACTION)
- .flatMap(AbstractValueHolder::getValueAsObject)
+ .flatMap(TimerConfiguration::getAction);
+ }
+
+ public static Optional<AttributeState> getAction(MetaItem metaItem) {
+ return metaItem.getValueAsObject()
.flatMap(AttributeState::fromValue);
}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/timer/TimerProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/timer/TimerProtocol.java
index 225ecf11f..afd369a0f 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/timer/TimerProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/timer/TimerProtocol.java
@@ -23,25 +23,22 @@ import org.openremote.agent.protocol.AbstractProtocol;
import org.openremote.agent.protocol.ConnectionStatus;
import org.openremote.model.asset.AssetAttribute;
import org.openremote.model.asset.AssetMeta;
-import org.openremote.model.attribute.AttributeEvent;
-import org.openremote.model.attribute.AttributeRef;
-import org.openremote.model.attribute.AttributeState;
-import org.openremote.model.attribute.MetaItem;
+import org.openremote.model.attribute.*;
import org.openremote.model.util.TextUtil;
import org.openremote.model.value.Value;
+import org.openremote.model.value.ValueType;
import org.openremote.model.value.Values;
import org.quartz.CronExpression;
import javax.ws.rs.NotSupportedException;
import java.text.ParseException;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Optional;
+import java.util.*;
import java.util.logging.Logger;
import static java.util.logging.Level.FINER;
import static org.openremote.agent.protocol.timer.TimerConfiguration.*;
import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;
+import static org.openremote.model.util.TextUtil.REGEXP_PATTERN_CRON_EXPRESSION;
/**
* This protocol can be used to trigger an {@link AttributeEvent} using a cron based timer.
@@ -62,9 +59,53 @@ public class TimerProtocol extends AbstractProtocol {
private static final Logger LOG = Logger.getLogger(TimerProtocol.class.getName());
public static final String PROTOCOL_NAME = PROTOCOL_NAMESPACE + ":timer";
+ public static final String PROTOCOL_DISPLAY_NAME = "Timer";
public static final String META_TIMER_CRON_EXPRESSION = PROTOCOL_NAME + ":cronExpression";
public static final String META_TIMER_ACTION = PROTOCOL_NAME + ":action";
public static final String META_TIMER_VALUE_LINK = PROTOCOL_NAME + ":link";
+ protected static final String VERSION = "1.0";
+
+ protected static final List<MetaItemDescriptor> PROTOCOL_META_ITEM_DESCRIPTORS = Arrays.asList(
+ new MetaItemDescriptorImpl("PROTOCOL_TIMER_CRON",
+ META_TIMER_CRON_EXPRESSION,
+ ValueType.STRING,
+ true,
+ REGEXP_PATTERN_CRON_EXPRESSION,
+ MetaItemDescriptor.PatternFailure.CRON_EXPRESSION.name(),
+ null,
+ null,
+ false),
+ new MetaItemDescriptorImpl(
+ "PROTOCOL_TIMER_ACTION",
+ META_TIMER_ACTION,
+ ValueType.OBJECT,
+ true,
+ null,
+ null,
+ null,
+ null,
+ false)
+ );
+
+ protected static final List<MetaItemDescriptor> ATTRIBUTE_META_ITEM_DESCRIPTORS = Collections.singletonList(
+ new MetaItemDescriptorImpl(
+ "PROTOCOL_TIMER_LINK",
+ META_TIMER_VALUE_LINK,
+ ValueType.STRING,
+ true,
+ "^(?i)(" +
+ TimerValue.ENABLED + "|" +
+ TimerValue.CRON_EXPRESSION + "|" +
+ TimerValue.TIME +
+ ")$",
+ TimerValue.ENABLED + "|" +
+ TimerValue.CRON_EXPRESSION + "|" +
+ TimerValue.TIME,
+ null,
+ null,
+ false)
+ );
+
protected final Map<AttributeRef, CronExpressionParser> cronExpressionMap = new HashMap<>();
protected CronScheduler cronScheduler;
@@ -73,6 +114,39 @@ public class TimerProtocol extends AbstractProtocol {
return PROTOCOL_NAME;
}
+ @Override
+ public String getProtocolDisplayName() {
+ return PROTOCOL_DISPLAY_NAME;
+ }
+
+ @Override
+ public AssetAttribute getProtocolConfigurationTemplate() {
+ return super.getProtocolConfigurationTemplate()
+ .addMeta(
+ new MetaItem(META_TIMER_CRON_EXPRESSION, null),
+ new MetaItem(META_TIMER_ACTION, null)
+ );
+ }
+
+ @Override
+ public AttributeValidationResult validateProtocolConfiguration(AssetAttribute protocolConfiguration) {
+ AttributeValidationResult result = super.validateProtocolConfiguration(protocolConfiguration);
+ if (result.isValid()) {
+ TimerConfiguration.validateTimerConfiguration(protocolConfiguration, result);
+ }
+ return result;
+ }
+
+ @Override
+ protected List<MetaItemDescriptor> getProtocolConfigurationMetaItemDescriptors() {
+ return PROTOCOL_META_ITEM_DESCRIPTORS;
+ }
+
+ @Override
+ protected List<MetaItemDescriptor> getLinkedAttributeMetaItemDescriptors() {
+ return ATTRIBUTE_META_ITEM_DESCRIPTORS;
+ }
+
@Override
protected void doLinkProtocolConfiguration(AssetAttribute protocolConfiguration) {
AttributeRef protocolRef = protocolConfiguration.getReferenceOrThrow();
@@ -283,6 +357,11 @@ public class TimerProtocol extends AbstractProtocol {
}
}
+ @Override
+ public String getVersion() {
+ return VERSION;
+ }
+
protected static String getTimerId(AttributeRef timerRef) {
return timerRef.getEntityId() + ":" + timerRef.getAttributeName();
}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/upnp/UpnpProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/upnp/UpnpProtocol.java
index 03f20e984..bcda9a470 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/upnp/UpnpProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/upnp/UpnpProtocol.java
@@ -32,8 +32,12 @@ public class UpnpProtocol extends AbstractProtocol {
private static final Logger LOG = Logger.getLogger(UpnpProtocol.class.getName());
public static final String PROTOCOL_NAME = PROTOCOL_NAMESPACE + ":upnp";
+ public static final String PROTOCOL_DISPLAY_NAME = "UPnP";
+
+ protected static final String VERSION = "1.0";
static protected UpnpService INSTANCE = null;
+
final protected RegistryListener registryListener = new DefaultRegistryListener() {
@Override
public void deviceAdded(Registry registry, Device device) {
@@ -58,6 +62,16 @@ public class UpnpProtocol extends AbstractProtocol {
return PROTOCOL_NAME;
}
+ @Override
+ public String getProtocolDisplayName() {
+ return PROTOCOL_DISPLAY_NAME;
+ }
+
+ @Override
+ public String getVersion() {
+ return VERSION;
+ }
+
@Override
protected void doLinkProtocolConfiguration(AssetAttribute protocolConfiguration) {
protocolConfiguration.getAssetId().ifPresent(agentId -> {
@@ -180,5 +194,4 @@ public class UpnpProtocol extends AbstractProtocol {
device.getIdentity().getUdn().getIdentifierString()
).toString();
}
-
}
diff --git a/container/src/main/java/org/openremote/container/Container.java b/container/src/main/java/org/openremote/container/Container.java
index fdd4f964d..a9fa83adc 100644
--- a/container/src/main/java/org/openremote/container/Container.java
+++ b/container/src/main/java/org/openremote/container/Container.java
@@ -64,11 +64,9 @@ public class Container {
.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)
.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false)
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
+ .setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE)
.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)
- .setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE)
- .setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE)
- .setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE)
- .setVisibility(PropertyAccessor.CREATOR, JsonAutoDetect.Visibility.NONE)
+ .setVisibility(PropertyAccessor.CREATOR, JsonAutoDetect.Visibility.ANY)
.registerModule(new ModelValueModule());
protected final Map<String, String> config = new HashMap<>();
diff --git a/manager/client/src/main/java/org/openremote/manager/client/admin/syslog/SyslogFilter.java b/manager/client/src/main/java/org/openremote/manager/client/admin/syslog/SyslogFilter.java
index f639dc2c0..73e948ea1 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/admin/syslog/SyslogFilter.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/admin/syslog/SyslogFilter.java
@@ -45,10 +45,10 @@ public abstract class SyslogFilter extends FlowPanel {
FormLabel showLastLabel = new FormLabel(messages.showLast());
showLastLabel.addStyleName("inline");
- formGroup.addFormLabel(showLastLabel);
+ formGroup.setFormLabel(showLastLabel);
FormField field = new FormField();
- formGroup.addFormField(field);
+ formGroup.setFormField(field);
FlowPanel fieldPanel = new FlowPanel();
field.add(fieldPanel);
@@ -70,7 +70,7 @@ public abstract class SyslogFilter extends FlowPanel {
fieldPanel.add(eventsLabel);
FormGroupActions actions = new FormGroupActions();
- formGroup.addFormGroupActions(actions);
+ formGroup.setFromGroupActions(actions);
pauseButton = new FormButton(messages.pauseLog());
pauseButton.setIcon("pause");
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/AssetAttributeMapper.java b/manager/client/src/main/java/org/openremote/manager/client/assets/AssetAttributeMapper.java
new file mode 100644
index 000000000..dfe7d8922
--- /dev/null
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/AssetAttributeMapper.java
@@ -0,0 +1,34 @@
+/*
+ * 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.manager.client.assets;
+
+import com.github.nmorel.gwtjackson.client.ObjectMapper;
+import com.github.nmorel.gwtjackson.client.annotation.JsonMixIns;
+import org.openremote.manager.client.interop.jackson.DefaultJsonMixin;
+import org.openremote.manager.shared.http.EntityReader;
+import org.openremote.manager.shared.http.EntityWriter;
+import org.openremote.model.asset.AssetAttribute;
+
+@JsonMixIns({@JsonMixIns.JsonMixIn(target = AssetAttribute.class, mixIn = DefaultJsonMixin.class)})
+public interface AssetAttributeMapper
+ extends ObjectMapper<AssetAttribute>,
+ EntityReader<AssetAttribute>,
+ EntityWriter<AssetAttribute> {
+}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/AssetsModule.java b/manager/client/src/main/java/org/openremote/manager/client/assets/AssetsModule.java
index de9e42671..da9372712 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/AssetsModule.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/AssetsModule.java
@@ -29,6 +29,7 @@ import org.openremote.manager.client.assets.browser.AssetBrowserPresenter;
import org.openremote.manager.client.assets.tenant.AssetsTenant;
import org.openremote.manager.client.assets.tenant.AssetsTenantActivity;
import org.openremote.manager.client.assets.tenant.AssetsTenantImpl;
+import org.openremote.manager.shared.agent.AgentResource;
import org.openremote.manager.shared.asset.AssetResource;
import org.openremote.manager.shared.datapoint.AssetDatapointResource;
@@ -63,4 +64,10 @@ public class AssetsModule extends AbstractGinModule {
public native AssetDatapointResource getAssetDatapointResource() /*-{
return $wnd.AssetDatapointResource;
}-*/;
+
+ @Provides
+ @Singleton
+ public native AgentResource getAgentResource() /*-{
+ return $wnd.AgentResource;
+ }-*/;
}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/MetaItemDescriptorMapper.java b/manager/client/src/main/java/org/openremote/manager/client/assets/MetaItemDescriptorMapper.java
new file mode 100644
index 000000000..b96fff98a
--- /dev/null
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/MetaItemDescriptorMapper.java
@@ -0,0 +1,35 @@
+/*
+ * 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.manager.client.assets;
+
+import com.github.nmorel.gwtjackson.client.ObjectMapper;
+import com.github.nmorel.gwtjackson.client.annotation.JsonMixIns;
+import org.openremote.manager.client.interop.jackson.DefaultJsonMixin;
+import org.openremote.manager.shared.http.EntityReader;
+import org.openremote.manager.shared.http.EntityWriter;
+import org.openremote.model.asset.Asset;
+import org.openremote.model.attribute.MetaItemDescriptor;
+import org.openremote.model.attribute.MetaItemDescriptorImpl;
+
+@JsonMixIns({@JsonMixIns.JsonMixIn(target = MetaItemDescriptorImpl.class, mixIn = DefaultJsonMixin.class)})
+public interface MetaItemDescriptorMapper
+ extends ObjectMapper<MetaItemDescriptorImpl>,
+ EntityReader<MetaItemDescriptorImpl> {
+}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/ProtocolDescriptorArrayMapper.java b/manager/client/src/main/java/org/openremote/manager/client/assets/ProtocolDescriptorArrayMapper.java
new file mode 100644
index 000000000..60b0ee998
--- /dev/null
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/ProtocolDescriptorArrayMapper.java
@@ -0,0 +1,33 @@
+/*
+ * 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.assets;
+
+import com.github.nmorel.gwtjackson.client.ObjectMapper;
+import com.github.nmorel.gwtjackson.client.annotation.JsonMixIns;
+import org.openremote.manager.client.interop.jackson.DefaultJsonMixin;
+import org.openremote.manager.shared.http.EntityReader;
+import org.openremote.manager.shared.http.EntityWriter;
+import org.openremote.model.asset.agent.ProtocolDescriptor;
+
+@JsonMixIns({@JsonMixIns.JsonMixIn(target = ProtocolDescriptor.class, mixIn = DefaultJsonMixin.class)})
+public interface ProtocolDescriptorArrayMapper
+ extends ObjectMapper<ProtocolDescriptor[]>,
+ EntityReader<ProtocolDescriptor[]> {
+}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/ProtocolDescriptorMapMapper.java b/manager/client/src/main/java/org/openremote/manager/client/assets/ProtocolDescriptorMapMapper.java
new file mode 100644
index 000000000..3d697f632
--- /dev/null
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/ProtocolDescriptorMapMapper.java
@@ -0,0 +1,33 @@
+/*
+ * 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.assets;
+
+import com.github.nmorel.gwtjackson.client.ObjectMapper;
+import com.github.nmorel.gwtjackson.client.annotation.JsonMixIns;
+import org.openremote.manager.client.interop.jackson.DefaultJsonMixin;
+import org.openremote.manager.shared.http.EntityReader;
+import org.openremote.model.asset.agent.ProtocolDescriptor;
+
+import java.util.Map;
+
+public interface ProtocolDescriptorMapMapper
+ extends ObjectMapper<Map<String, ProtocolDescriptor[]>>,
+ EntityReader<Map<String, ProtocolDescriptor[]>> {
+}
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 491e5ee05..9804596d2 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
@@ -19,21 +19,80 @@
*/
package org.openremote.manager.client.assets.asset;
+import com.google.gwt.place.shared.Place;
+import com.google.gwt.user.client.ui.AcceptsOneWidget;
+import com.google.gwt.user.client.ui.IsWidget;
+import com.google.inject.Provider;
import org.openremote.manager.client.Environment;
+import org.openremote.manager.client.app.dialog.JsonEditor;
import org.openremote.manager.client.assets.AssetBrowsingActivity;
+import org.openremote.manager.client.assets.attributes.AbstractAttributeViewExtension;
+import org.openremote.manager.client.assets.attributes.AttributeView;
+import org.openremote.manager.client.assets.attributes.AttributeViewImpl;
+import org.openremote.manager.client.assets.attributes.MetaEditor;
import org.openremote.manager.client.assets.browser.AssetBrowser;
+import org.openremote.manager.client.assets.browser.AssetBrowserSelection;
+import org.openremote.manager.client.assets.browser.AssetTreeNode;
+import org.openremote.manager.client.assets.browser.TenantTreeNode;
+import org.openremote.manager.client.assets.tenant.AssetsTenantPlace;
+import org.openremote.manager.client.event.ShowFailureEvent;
+import org.openremote.manager.client.event.ShowInfoEvent;
+import org.openremote.manager.client.event.ShowSuccessEvent;
+import org.openremote.manager.client.interop.value.ObjectValueMapper;
import org.openremote.manager.client.mvp.AppActivity;
+import org.openremote.manager.client.widget.FormButton;
+import org.openremote.manager.client.widget.FormOutputText;
+import org.openremote.manager.shared.map.MapResource;
import org.openremote.manager.shared.security.Tenant;
+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.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.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;
-public abstract class AbstractAssetActivity<PLACE extends AssetPlace> extends AssetBrowsingActivity<PLACE> {
+import java.util.*;
+import java.util.function.Consumer;
+import static org.openremote.manager.client.http.RequestExceptionHandler.handleRequestException;
+import static org.openremote.manager.client.widget.ValueEditors.*;
+import static org.openremote.model.util.TextUtil.isNullOrEmpty;
+
+public abstract class AbstractAssetActivity<V extends AssetBaseView.Presenter, U extends AssetBaseView<V>, PLACE extends AssetPlace> extends AssetBrowsingActivity<PLACE> implements AssetBaseView.Presenter {
+
+ protected final List<AttributeView> attributeViews = new ArrayList<>();
+ protected final Provider<JsonEditor> jsonEditorProvider;
+ protected final boolean editMode;
+ protected final ObjectValueMapper objectValueMapper;
+ protected final MapResource mapResource;
protected String assetId;
protected Asset asset;
protected Asset parentAsset;
+ protected Collection<EventRegistration> registrations;
+ protected U view;
+ protected V presenter;
- public AbstractAssetActivity(Environment environment, Tenant currentTenant, AssetBrowser.Presenter assetBrowserPresenter) {
+ public AbstractAssetActivity(Environment environment,
+ Tenant currentTenant,
+ AssetBrowser.Presenter assetBrowserPresenter,
+ Provider<JsonEditor> jsonEditorProvider,
+ ObjectValueMapper objectValueMapper,
+ MapResource mapResource,
+ boolean editMode) {
super(environment, currentTenant, assetBrowserPresenter);
+ this.objectValueMapper = objectValueMapper;
+ this.mapResource = mapResource;
+ this.editMode = editMode;
+ this.jsonEditorProvider = jsonEditorProvider;
}
@Override
@@ -41,4 +100,382 @@ public abstract class AbstractAssetActivity<PLACE extends AssetPlace> extends As
this.assetId = place.getAssetId();
return this;
}
+
+ @Override
+ public void start(AcceptsOneWidget container, EventBus eventBus, Collection<EventRegistration> registrations) {
+ this.registrations = registrations;
+ view.setPresenter(presenter);
+ container.setWidget(view.asWidget());
+
+ registrations.add(eventBus.register(
+ AssetBrowserSelection.class, event -> {
+ if (event.getSelectedNode() instanceof TenantTreeNode) {
+ environment.getPlaceController().goTo(
+ new AssetsTenantPlace(event.getSelectedNode().getId())
+ );
+ } else if (event.getSelectedNode() instanceof AssetTreeNode) {
+ if (this.assetId == null || !this.assetId.equals(event.getSelectedNode().getId())) {
+ this.assetId = event.getSelectedNode().getId();
+ environment.getPlaceController().goTo(
+ getPlace(editMode)
+ );
+ }
+ }
+ }
+ ));
+
+ if (!view.isMapInitialised()) {
+ environment.getRequestService().execute(
+ objectValueMapper,
+ mapResource::getSettings,
+ 200,
+ view::initialiseMap,
+ ex -> handleRequestException(ex, environment)
+ );
+ } else {
+ onMapReady();
+ }
+ }
+
+ @Override
+ public void onMapReady() {
+ asset = null;
+ if (!isNullOrEmpty(assetId)) {
+ assetBrowserPresenter.loadAsset(assetId, loadedAsset -> {
+ this.asset = loadedAsset;
+ assetBrowserPresenter.selectAsset(asset);
+ view.setHistoryToken(environment.getPlaceHistoryMapper().getToken(getPlace(!editMode)));
+ start();
+ });
+ } else {
+ start();
+ }
+ }
+
+ @Override
+ public Place getPlace(boolean editPlace) {
+ return editPlace ? new AssetEditPlace(assetId) : new AssetViewPlace(assetId);
+ }
+
+ @Override
+ public void loadParent() {
+ // TODO This fails if the user is restricted, can't just load parent and assume we have access
+ if (asset.getParentId() != null) {
+ assetBrowserPresenter.loadAsset(asset.getParentId(), loadedParentAsset -> {
+ this.parentAsset = loadedParentAsset;
+ writeParentToView();
+ view.setFormBusy(false);
+ });
+ } else {
+ writeParentToView();
+ view.setFormBusy(false);
+ }
+ }
+
+ @Override
+ public void writeParentToView() {
+ if (parentAsset != null) {
+ view.setParentNode(new AssetTreeNode(parentAsset));
+ } else {
+ view.setParentNode(
+ new TenantTreeNode(
+ new Tenant(asset.getRealmId(), asset.getTenantRealm(), asset.getTenantDisplayName(), true)
+ )
+ );
+ }
+ }
+
+ @Override
+ public void writeAssetToView() {
+ view.setName(asset.getName());
+ view.setCreatedOn(asset.getCreatedOn());
+ view.setLocation(asset.getCoordinates());
+ view.showDroppedPin(asset.getGeoFeature(20));
+ view.flyTo(asset.getCoordinates());
+ }
+
+ @Override
+ public void writeAttributesToView() {
+ if (asset != null && asset.getAttributesList().size() > 0) {
+ for (AssetAttribute attribute : asset.getAttributesList()) {
+ writeAttributeToView(attribute, false);
+ }
+ }
+
+ view.setAttributeViews(attributeViews);
+ validateAttributes(true, this::processValidationResults);
+ }
+
+ protected void writeAttributeToView(AssetAttribute attribute, boolean addToView) {
+ AttributeView attributeView = createAttributeView(attribute);
+ attributeViews.add(attributeView);
+
+ if (addToView) {
+ view.addAttributeViews(Collections.singletonList(attributeView));
+ validateAttribute(true, attribute, result -> processValidationResults(Collections.singletonList(result)));
+ }
+ }
+
+ protected AttributeView createAttributeView(AssetAttribute attribute) {
+
+ AttributeViewImpl attributeView = new AttributeViewImpl(environment,
+ view.getStyle(),
+ attribute);
+
+ attributeView.setAttributeActions(createAttributeActions(attribute, attributeView));
+
+ List<AbstractAttributeViewExtension> extensions = createAttributeExtensions(attribute, attributeView);
+ if (extensions != null && !extensions.isEmpty()) {
+ extensions.forEach(this::linkAttributeView);
+ }
+
+ attributeView.setAttributeExtensions(extensions);
+ linkAttributeView(attributeView);
+ return attributeView;
+ }
+
+ abstract protected List<AbstractAttributeViewExtension> createAttributeExtensions(AssetAttribute attribute, AttributeViewImpl view);
+
+ abstract protected List<FormButton> createAttributeActions(AssetAttribute attribute, AttributeViewImpl view);
+
+ protected void linkAttributeView(AttributeView attributeView) {
+ attributeView.setValueEditorSupplier(this::createValueEditor);
+ attributeView.setEditMode(editMode);
+ attributeView.setAttributeModifiedCallback(this::onAttributeModified);
+ attributeView.setValidationErrorConsumer(this::showValidationError);
+ }
+
+ /**
+ * Attribute view action button is requesting the value be written to the server
+ */
+ protected void writeAttributeValue(AssetAttribute attribute) {
+
+ getAttributeView(attribute)
+ .ifPresent(
+ attributeView -> {
+
+ attributeView.setBusy(true);
+ validateAttribute(false, attribute, result -> {
+
+ // Notify the view of the result
+ attributeView.onValidationStateChange(result);
+ attributeView.setBusy(false);
+
+ if (result.isValid()) {
+ attribute
+ .getReference()
+ .map(attributeRef -> new AttributeState(attributeRef, attribute.getValue().orElse(null)))
+ .map(attributeState -> new AttributeEvent(attributeState, attribute.getValueTimestamp().orElse(0L)))
+ .ifPresent(attributeEvent -> {
+ environment.getEventService().dispatch(attributeEvent);
+ if (attribute.isExecutable()) {
+ showSuccess(environment
+ .getMessages()
+ .commandRequestSent(attribute.getLabelOrName().orElse("")));
+ } else {
+ showSuccess(
+ environment
+ .getMessages()
+ .attributeWriteSent(attribute.getLabelOrName().orElse("")));
+ }
+ });
+ }
+ });
+ }
+ );
+
+ }
+
+ protected void validateAttributes(boolean clientSideOnly, Consumer<List<AttributeValidationResult>> resultsConsumer) {
+ if (asset.getAttributesList().isEmpty()) {
+ resultsConsumer.accept(Collections.emptyList());
+ return;
+ }
+
+ List<AttributeValidationResult> results = new ArrayList<>(asset.getAttributesList().size());
+ Consumer<AttributeValidationResult> resultConsumer = attributeValidationResult -> {
+ results.add(attributeValidationResult);
+ if (results.size() == asset.getAttributesList().size()) {
+ resultsConsumer.accept(results);
+ }
+ };
+
+ asset.getAttributesList().forEach(attribute -> validateAttribute(clientSideOnly, attribute, resultConsumer));
+ }
+
+ protected void validateAttribute(boolean clientSideOny, AssetAttribute attribute, Consumer<AttributeValidationResult> resultConsumer) {
+ List<ValidationFailure> attributeFailures = attribute.getValidationFailures(false);
+ Map<Integer, List<ValidationFailure>> metaFailures = new HashMap<>(attribute.getMeta().size());
+ String attributeName = attribute.getName().orElseThrow(() -> new IllegalStateException("Attribute name cannot be null"));
+
+ 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);
+ }
+
+ if (!metaItemFailures.isEmpty()) {
+ metaFailures.put(i, metaItemFailures);
+ }
+ }
+
+ resultConsumer.accept(new AttributeValidationResult(attributeName, attributeFailures, metaFailures));
+ }
+
+ 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);
+ });
+ });
+ }
+
+ protected Optional<AttributeView> getAttributeView(AssetAttribute attribute) {
+ return attributeViews
+ .stream()
+ .filter(attributeView -> attributeView.getAttribute() == attribute)
+ .findFirst();
+ }
+
+ protected void showInfo(String text) {
+ environment.getEventBus().dispatch(new ShowInfoEvent(text));
+ }
+
+ protected void showSuccess(String text) {
+ environment.getEventBus().dispatch(new ShowSuccessEvent(text));
+ }
+
+ protected boolean isValueReadOnly(ValueHolder valueHolder) {
+
+ // Meta item value is read only if value is fixed
+ if (valueHolder instanceof MetaItem) {
+ return ((MetaItem) valueHolder).getName()
+ .flatMap(AssetMeta::getAssetMeta)
+ .map(AssetMeta::isValueFixed)
+ .orElse(false);
+ }
+
+ if (valueHolder instanceof AssetAttribute) {
+ // Attribute Value is read only if it is readonly or a protocol configuration
+ AssetAttribute attribute = (AssetAttribute) valueHolder;
+ return attribute.isReadOnly() || ProtocolConfiguration.isProtocolConfiguration(attribute);
+ }
+
+ return false;
+ }
+
+ protected boolean isShowTimestamp(ValueHolder valueHolder) {
+ return !editMode && (valueHolder instanceof AssetAttribute);
+ }
+
+ abstract protected void onAttributeModified(AssetAttribute attribute);
+
+ /**
+ * Creates editors for {@link ValueHolder}s.
+ * <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) {
+
+ // 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
+// // Individual instances of meta items can be set to restricted by a super user.
+// boolean isEditable = environment.getSecurityService().isSuperUser() ||
+// (item.hasRestrictedFlag() && !item.isRestricted()) ||
+// assetMeta.map(AssetMeta::isRestricted).orElse(true);
+
+ boolean isReadOnly = isValueReadOnly(valueHolder);
+ boolean showTimestamp = isShowTimestamp(valueHolder);
+
+ switch(valueType) {
+ case OBJECT:
+ ObjectValue currentValueObj = valueHolder.getValueAsObject().orElse(null);
+ String label = environment.getMessages().jsonObject();
+ String title = environment.getMessages().edit() + " " + environment.getMessages().jsonObject();
+ return createObjectEditor(
+ valueHolder, onValueModified, isReadOnly, showTimestamp, currentValueObj, 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()
+ );
+ case STRING:
+ String currentValueStr = valueHolder.getValueAsString().orElse(null);
+ return createStringEditor(
+ valueHolder, onValueModified, isReadOnly, showTimestamp, currentValueStr, style.stringEditor()
+ );
+ case NUMBER:
+ Optional<Double> currentValueNumber = valueHolder.getValueAsNumber();
+ return createNumberEditor(
+ valueHolder, onValueModified, isReadOnly, showTimestamp, currentValueNumber.map(Object::toString).orElse(null), style.numberEditor()
+ );
+ case BOOLEAN:
+ Boolean currentValueBool = valueHolder.getValueAsBoolean().orElse(null);
+ return createBooleanEditor(
+ valueHolder, onValueModified, isReadOnly, showTimestamp, currentValueBool, style.booleanEditor()
+ );
+ default:
+ return new FormOutputText(valueHolder instanceof MetaItem ?
+ environment.getMessages().unsupportedMetaItemType(valueType.name()) :
+ environment.getMessages().unsupportedValueType(valueType.name())
+ );
+ }
+ }
+
+ public void showValidationError(String attributeName, String metaItemName, ValidationFailure validationFailure) {
+ StringBuilder error = new StringBuilder();
+
+ if (!isNullOrEmpty(metaItemName)) {
+ error.append(
+ environment.getMessages().validationFailureOnMetaItem(
+ attributeName,
+ metaItemName
+ )
+ );
+ } else {
+ error.append(environment.getMessages().validationFailureOnAttribute(
+ attributeName
+ ));
+ }
+
+ error.append(": ");
+
+ String parameterStr = validationFailure.getParameter()
+ .map(parameter -> {
+ String str = environment.getMessages().validationFailureParameter(parameter);
+ return isNullOrEmpty(str) ? parameter : str;
+ })
+ .orElse(null);
+
+ error.append(
+ environment.getMessages().validationFailure(parameterStr, validationFailure.getReason().name())
+ );
+
+ showFailureMessage(error.toString());
+ }
+
+ public void showFailureMessage(String failureMessage) {
+ environment.getEventBus().dispatch(new ShowFailureEvent(failureMessage, 5000));
+ }
}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetBaseView.java b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetBaseView.java
new file mode 100644
index 000000000..3d91e03c4
--- /dev/null
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetBaseView.java
@@ -0,0 +1,87 @@
+/*
+ * 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.assets.asset;
+
+import com.google.gwt.place.shared.Place;
+import com.google.gwt.user.client.ui.IsWidget;
+import org.openremote.manager.client.assets.attributes.AttributeView;
+import org.openremote.manager.client.assets.browser.AssetBrowserSelection;
+import org.openremote.manager.client.assets.browser.BrowserTreeNode;
+import org.openremote.model.asset.Asset;
+import org.openremote.model.geo.GeoJSON;
+import org.openremote.model.value.ObjectValue;
+
+import java.util.Date;
+import java.util.List;
+
+public interface AssetBaseView<P extends AssetBaseView.Presenter> extends IsWidget {
+
+ interface Presenter {
+ Place getPlace(boolean editPlace);
+
+ void onMapReady();
+
+ void start();
+
+ void centerMap();
+
+ void loadParent();
+
+ void writeParentToView();
+
+ void writeAssetToView();
+
+ void writeAttributesToView();
+ }
+
+ void setPresenter(P presenter);
+
+ AttributeView.Style getStyle();
+
+ void setFormBusy(boolean busy);
+
+ void setAsset(Asset asset);
+
+ void setName(String name);
+
+ void setCreatedOn(Date createdOn);
+
+ void setParentNode(BrowserTreeNode treeNode);
+
+ void setHistoryToken(String token);
+
+ void initialiseMap(ObjectValue mapOptions);
+
+ boolean isMapInitialised();
+
+ void setLocation(double[] coordinates);
+
+ void showDroppedPin(GeoJSON geoFeature);
+
+ void flyTo(double[] coordinates);
+
+ void setAttributeViews(List<AttributeView> attributeViews);
+
+ void addAttributeViews(List<AttributeView> attributeViews);
+
+ void removeAttributeViews(List<AttributeView> attributeViews);
+
+ List<AttributeView> getAttributeViews();
+}
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 86a3e7f67..174d49076 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
@@ -19,37 +19,30 @@
*/
package org.openremote.manager.client.assets.asset;
-import com.google.gwt.user.client.ui.IsWidget;
-import org.openremote.manager.client.assets.attributes.AttributesEditor;
import org.openremote.manager.client.assets.browser.BrowserTreeNode;
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.attribute.AttributeType;
-import org.openremote.model.geo.GeoJSON;
import org.openremote.model.util.Pair;
-import org.openremote.model.value.ObjectValue;
-import java.util.Date;
+import java.util.List;
import java.util.function.Consumer;
-public interface AssetEdit extends FormView, IsWidget {
+public interface AssetEdit extends FormView, AssetBaseView<AssetEdit.Presenter> {
- interface Presenter {
-
- void onMapReady();
+ interface Presenter extends AssetBaseView.Presenter {
void onParentSelection(BrowserTreeNode treeNode);
- void centerMap();
-
void onMapClicked(double lng, double lat);
void onAssetTypeSelected(AssetType value);
- void addAttribute(String name, int attributeTypeIndex);
+ boolean addAttribute(String name, String type);
+
+ void removeAttribute(AssetAttribute attribute);
void update();
@@ -62,34 +55,16 @@ public interface AssetEdit extends FormView, IsWidget {
void getLinkableAttributes(Pair<ValueHolder, Asset> valueAssetPair, Consumer<AssetAttribute[]> attributeConusmer);
}
- void setAssetViewHistoryToken(String token);
-
void setPresenter(Presenter presenter);
- void setName(String name);
-
String getName();
void setNameError(boolean error);
- void setCreatedOn(Date createdOn);
-
- void setParentNode(BrowserTreeNode treeNode);
-
- void initialiseMap(ObjectValue mapOptions);
-
- boolean isMapInitialised();
-
- void setLocation(double[] coordinates);
-
void showMapPopup(double lng, double lat, String text);
void hideMapPopup();
- void showDroppedPin(GeoJSON geoFeature);
-
- void flyTo(double[] coordinates);
-
void selectWellKnownType(AssetType assetType);
void setAvailableWellKnownTypes(AssetType[] assetTypes);
@@ -102,13 +77,7 @@ public interface AssetEdit extends FormView, IsWidget {
void setTypeError(boolean error);
- AttributesEditor.Container getAttributesEditorContainer();
-
- void setAttributesEditor(AttributesEditor attributesEditor);
-
- void setAvailableAttributeTypes(AttributeType[] types);
-
- void setNewAttributeError(boolean error);
+ void setAvailableAttributeTypes(List<Pair<String, String>> displayNamesAndTypes);
void enableCreate(boolean enable);
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 0c63683c7..cbf8a4433 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
@@ -19,18 +19,23 @@
*/
package org.openremote.manager.client.assets.asset;
-import com.google.gwt.user.client.ui.AcceptsOneWidget;
+import com.google.gwt.user.client.ui.IsWidget;
+import com.google.inject.Provider;
import org.openremote.manager.client.Environment;
-import org.openremote.manager.client.assets.AssetArrayMapper;
-import org.openremote.manager.client.assets.AssetMapper;
-import org.openremote.manager.client.assets.AssetQueryMapper;
-import org.openremote.manager.client.assets.AssetsDashboardPlace;
-import org.openremote.manager.client.assets.attributes.AttributesEditor;
-import org.openremote.manager.client.assets.browser.*;
-import org.openremote.manager.client.assets.tenant.AssetsTenantPlace;
+import org.openremote.manager.client.app.dialog.JsonEditor;
+import org.openremote.manager.client.assets.*;
+import org.openremote.manager.client.assets.attributes.*;
+import org.openremote.manager.client.assets.browser.AssetBrowser;
+import org.openremote.manager.client.assets.browser.AssetTreeNode;
+import org.openremote.manager.client.assets.browser.BrowserTreeNode;
+import org.openremote.manager.client.assets.browser.TenantTreeNode;
import org.openremote.manager.client.event.ShowFailureEvent;
import org.openremote.manager.client.event.ShowSuccessEvent;
import org.openremote.manager.client.interop.value.ObjectValueMapper;
+import org.openremote.manager.client.widget.FormButton;
+import org.openremote.manager.client.widget.FormSectionLabel;
+import org.openremote.manager.client.widget.ValueEditors;
+import org.openremote.manager.shared.agent.AgentResource;
import org.openremote.manager.shared.asset.AssetResource;
import org.openremote.manager.shared.map.MapResource;
import org.openremote.manager.shared.security.Tenant;
@@ -39,62 +44,77 @@ import org.openremote.model.ValueHolder;
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.event.bus.EventBus;
-import org.openremote.model.event.bus.EventRegistration;
+import org.openremote.model.attribute.MetaItemDescriptor;
+import org.openremote.model.util.EnumUtil;
import org.openremote.model.util.Pair;
+import org.openremote.model.value.ValueType;
import javax.inject.Inject;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
+import java.util.*;
import java.util.function.Consumer;
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.util.TextUtil.isNullOrEmpty;
public class AssetEditActivity
- extends AbstractAssetActivity<AssetEditPlace>
+ extends AbstractAssetActivity<AssetEdit.Presenter, AssetEdit, AssetEditPlace>
implements AssetEdit.Presenter {
- final AssetEdit view;
- final AssetResource assetResource;
- final AssetMapper assetMapper;
- final AssetArrayMapper assetArrayMapper;
- final AssetQueryMapper assetQueryMapper;
- final MapResource mapResource;
- final ObjectValueMapper objectValueMapper;
- final protected Consumer<ConstraintViolation[]> validationErrorHandler;
+ protected final AssetResource assetResource;
+ protected final AgentResource agentResource;
+ protected final AssetMapper assetMapper;
+ protected final AssetArrayMapper assetArrayMapper;
+ protected final AssetQueryMapper assetQueryMapper;
+ protected final ProtocolDescriptorArrayMapper protocolDescriptorArrayMapper;
+ protected final ProtocolDescriptorMapMapper protocolDescriptorMapMapper;
+ 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;
- AttributesEditor attributesEditor;
@Inject
public AssetEditActivity(Environment environment,
Tenant currentTenant,
AssetBrowser.Presenter assetBrowserPresenter,
+ Provider<JsonEditor> jsonEditorProvider,
AssetEdit view,
AssetResource assetResource,
+ AgentResource agentResource,
AssetMapper assetMapper,
AssetArrayMapper assetArrayMapper,
AssetQueryMapper assetQueryMapper,
+ ProtocolDescriptorArrayMapper protocolDescriptorArrayMapper,
+ ProtocolDescriptorMapMapper protocolDescriptorMapMapper,
+ AttributeValidationResultMapper attributeValidationResultMapper,
+ AssetAttributeMapper assetAttributeMapper,
MapResource mapResource,
ObjectValueMapper objectValueMapper) {
- super(environment, currentTenant, assetBrowserPresenter);
+ super(environment, currentTenant, assetBrowserPresenter, jsonEditorProvider, objectValueMapper, mapResource, true);
+ this.presenter = this;
this.view = view;
this.assetResource = assetResource;
+ this.agentResource = agentResource;
this.assetMapper = assetMapper;
this.assetArrayMapper = assetArrayMapper;
this.assetQueryMapper = assetQueryMapper;
- this.mapResource = mapResource;
- this.objectValueMapper = objectValueMapper;
+ this.protocolDescriptorArrayMapper = protocolDescriptorArrayMapper;
+ this.protocolDescriptorMapMapper = protocolDescriptorMapMapper;
+ this.attributeValidationResultMapper = attributeValidationResultMapper;
+ this.assetAttributeMapper = assetAttributeMapper;
validationErrorHandler = violations -> {
for (ConstraintViolation violation : violations) {
@@ -109,68 +129,32 @@ public class AssetEditActivity
}
view.setFormBusy(false);
};
-
- }
-
- @Override
- public void start(AcceptsOneWidget container, EventBus eventBus, Collection<EventRegistration> registrations) {
- view.setPresenter(this);
- container.setWidget(view.asWidget());
-
- registrations.add(eventBus.register(
- AssetBrowserSelection.class, event -> {
- if (event.getSelectedNode() instanceof TenantTreeNode) {
- environment.getPlaceController().goTo(
- new AssetsTenantPlace(event.getSelectedNode().getId())
- );
- } else if (event.getSelectedNode() instanceof AssetTreeNode) {
- if (this.assetId == null || !this.assetId.equals(event.getSelectedNode().getId())) {
- environment.getPlaceController().goTo(
- new AssetEditPlace(event.getSelectedNode().getId())
- );
- }
- }
- }
- ));
-
- if (!view.isMapInitialised()) {
- environment.getRequestService().execute(
- objectValueMapper,
- mapResource::getSettings,
- 200,
- view::initialiseMap,
- ex -> handleRequestException(ex, environment)
- );
- } else {
- onMapReady();
- }
-
- view.setAvailableAttributeTypes(AttributeType.values());
}
@Override
public void onStop() {
super.onStop();
- if (attributesEditor != null) {
- attributesEditor.close();
- }
clearViewMessages();
view.setPresenter(null);
}
-
@Override
- public void onMapReady() {
- asset = null;
- if (assetId != null) {
- assetBrowserPresenter.loadAsset(assetId, loadedAsset -> {
- this.asset = loadedAsset;
- assetBrowserPresenter.selectAsset(asset);
- startEditAsset();
- });
- } else {
- startCreateAsset();
+ public void start() {
+ if (isNullOrEmpty(assetId)) {
+ assetBrowserPresenter.clearSelection();
+ asset = new Asset();
+ asset.setName("My New Asset");
+ asset.setRealmId(currentTenant.getId());
+ asset.setTenantDisplayName(currentTenant.getDisplayName());
+ asset.setType("urn:mydomain:customtype");
}
+
+ clearViewMessages();
+ writeAssetToView();
+ writeAttributeTypesToView(() -> {
+ writeAttributesToView();
+ loadParent();
+ });
}
@Override
@@ -206,65 +190,124 @@ public class AssetEditActivity
@Override
public void onAssetTypeSelected(AssetType type) {
asset.setType(type);
- writeTypeToView(true);
- writeAttributesEditorToView();
+ writeAttributeTypesToView(this::writeAttributesToView);
}
@Override
- public void addAttribute(String name, int attributeTypeIndex) {
- if (attributesEditor != null) {
- view.setNewAttributeError(
- !attributesEditor.addAttribute(name, attributeTypeIndex >= 0 ? AttributeType.values()[attributeTypeIndex] : null)
- );
+ public boolean addAttribute(String name, String type) {
+ if (isNullOrEmpty(name) || isNullOrEmpty(type)) {
+ return false;
+ }
+
+ if (asset.getAttributesStream().anyMatch(isAttributeNameEqualTo(name))) {
+ showFailureMessage(environment.getMessages().duplicateAttributeName());
+ return false;
+ }
+
+ if (!ATTRIBUTE_NAME_VALIDATOR.test(name)) {
+ showFailureMessage(environment.getMessages().invalidAttributeName());
+ return false;
+ }
+ AssetAttribute attribute;
+
+ Optional<ProtocolDescriptor> protocolDescriptor = protocolDescriptors == null ?
+ Optional.empty() :
+ protocolDescriptors.stream()
+ .filter(pd -> pd.getName().equals(type))
+ .findFirst();
+
+ if (protocolDescriptor.isPresent()) {
+ // This is a protocol configuration add request
+ attribute = protocolDescriptor.get().getConfigurationTemplate().deepCopy();
+ } else {
+ AttributeType attributeType = EnumUtil.enumFromString(AttributeType.class, type).orElse(null);
+
+ if (attributeType == null) {
+ showFailureMessage(environment.getMessages().invalidAttributeType());
+ return false;
+ }
+
+ attribute = new AssetAttribute();
+ attribute.setType(attributeType);
+ attribute.addMeta(attributeType.getDefaultMetaItems());
}
+
+ attribute.setName(name);
+
+ // Tell the server to set the timestamp when saving because we don't want to use browser time
+ attribute.setValueTimestamp(0);
+
+ asset.getAttributesList().add(attribute);
+ writeAttributeToView(attribute, true);
+ return true;
+ }
+
+ @Override
+ public void removeAttribute(AssetAttribute attribute) {
+ // Allow deleting any attributes for now
+ asset.getAttributesList().remove(attribute);
+ view.getAttributeViews()
+ .stream()
+ .filter(attributeView -> attributeView.getAttribute() == attribute)
+ .findFirst()
+ .ifPresent(attributeView -> view.removeAttributeViews(Collections.singletonList(attributeView)));
}
@Override
public void update() {
view.setFormBusy(true);
clearViewMessages();
- if (attributesEditor != null && !attributesEditor.validateAttributes()) {
- view.setFormBusy(false);
- return;
- }
- readFromView();
- environment.getRequestService().execute(
- assetMapper,
- requestParams -> assetResource.update(requestParams, assetId, asset),
- 204,
- () -> {
+ validateAttributes(false, results -> {
+ if (results.stream().anyMatch(result -> !result.isValid())) {
view.setFormBusy(false);
- environment.getEventBus().dispatch(new ShowSuccessEvent(
- environment.getMessages().assetUpdated(asset.getName())
- ));
- environment.getPlaceController().goTo(new AssetViewPlace(assetId));
- },
- ex -> handleRequestException(ex, environment.getEventBus(), environment.getMessages(), validationErrorHandler)
- );
+ processValidationResults(results);
+ } else {
+ readFromView();
+ environment.getRequestService().execute(
+ assetMapper,
+ requestParams -> assetResource.update(requestParams, assetId, asset),
+ 204,
+ () -> {
+ view.setFormBusy(false);
+ environment.getEventBus().dispatch(new ShowSuccessEvent(
+ environment.getMessages().assetUpdated(asset.getName())
+ ));
+ environment.getPlaceController().goTo(new AssetViewPlace(assetId));
+ },
+ ex -> {
+ view.setFormBusy(false);
+ handleRequestException(ex, environment.getEventBus(), environment.getMessages(), validationErrorHandler);
+ }
+ );
+ }
+ });
}
@Override
public void create() {
view.setFormBusy(true);
clearViewMessages();
- if (attributesEditor != null && !attributesEditor.validateAttributes()) {
- view.setFormBusy(false);
- return;
- }
- readFromView();
- environment.getRequestService().execute(
- assetMapper,
- requestParams -> assetResource.create(requestParams, asset),
- 204,
- () -> {
+ validateAttributes(false, results -> {
+ if (results.stream().anyMatch(result -> !result.isValid())) {
view.setFormBusy(false);
- environment.getEventBus().dispatch(new ShowSuccessEvent(
- environment.getMessages().assetCreated(asset.getName())
- ));
- environment.getPlaceController().goTo(new AssetsDashboardPlace());
- },
- ex -> handleRequestException(ex, environment.getEventBus(), environment.getMessages(), validationErrorHandler)
- );
+ processValidationResults(results);
+ } else {
+ readFromView();
+ environment.getRequestService().execute(
+ assetMapper,
+ requestParams -> assetResource.create(requestParams, asset),
+ 204,
+ () -> {
+ view.setFormBusy(false);
+ environment.getEventBus().dispatch(new ShowSuccessEvent(
+ environment.getMessages().assetCreated(asset.getName())
+ ));
+ environment.getPlaceController().goTo(new AssetsDashboardPlace());
+ },
+ ex -> handleRequestException(ex, environment.getEventBus(), environment.getMessages(), validationErrorHandler)
+ );
+ }
+ });
}
@Override
@@ -375,6 +418,24 @@ public class AssetEditActivity
}
}
+ @Override
+ protected IsWidget createValueEditor(ValueHolder valueHolder, ValueType valueType, AttributeView.Style style, Runnable 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)) {
+ 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 super.createValueEditor(valueHolder, valueType, style, onValueModified);
+ }
+
@Override
public void centerMap() {
if (selectedCoordinates != null) {
@@ -384,82 +445,183 @@ public class AssetEditActivity
}
}
- protected void startCreateAsset() {
- assetBrowserPresenter.clearSelection();
- asset = new Asset();
- asset.setName("My New Asset");
- asset.setRealmId(currentTenant.getId());
- asset.setTenantDisplayName(currentTenant.getDisplayName());
- asset.setType("urn:mydomain:customtype");
- clearViewMessages();
- writeAssetToView();
- writeParentToView();
- writeTypeToView(true);
- writeAttributesEditorToView();
- view.setFormBusy(false);
+ @Override
+ public void writeAssetToView() {
+ super.writeAssetToView();
+ view.enableCreate(assetId == null);
+ view.enableUpdate(assetId != null);
+ view.enableDelete(assetId != null);
}
- protected void startEditAsset() {
- clearViewMessages();
- view.setAssetViewHistoryToken(environment.getPlaceHistoryMapper().getToken(new AssetViewPlace(assetId)));
- writeAssetToView();
- writeTypeToView(false);
- writeAttributesEditorToView();
- if (asset.getParentId() != null) {
- assetBrowserPresenter.loadAsset(asset.getParentId(), loadedAsset -> {
- this.parentAsset = loadedAsset;
- writeParentToView();
- view.setFormBusy(false);
- });
- } else {
- writeParentToView();
- view.setFormBusy(false);
+ @Override
+ protected List<AbstractAttributeViewExtension> createAttributeExtensions(AssetAttribute attribute, AttributeViewImpl view) {
+ List<AbstractAttributeViewExtension> extensions = new ArrayList<>();
+
+ // if this is a protocol configuration then add a protocol link editor first
+ if (ProtocolConfiguration.isProtocolConfiguration(attribute)) {
+ protocolDescriptors
+ .stream()
+ .filter(protocolDescriptor -> protocolDescriptor.getName().equals(attribute.getValueAsString().orElse("")))
+ .findFirst()
+ .ifPresent(
+ protocolDescriptor -> {
+ extensions.add(
+ new ProtocolLinksEditor(environment, this.view.getStyle(), view, attribute, protocolDescriptor, false)
+ );
+
+ if (protocolDescriptor.isDeviceDiscovery() || protocolDescriptor.isDeviceImport()) {
+ extensions.add(
+ new ProtocolLinksEditor(environment, this.view.getStyle(), view, attribute, protocolDescriptor, true)
+ );
+ }
+ }
+ );
}
+
+ extensions.add(new MetaEditor(environment, this.view.getStyle(), view, attribute, () -> protocolDescriptors));
+ return extensions;
}
- protected void writeAssetToView() {
- view.setName(asset.getName());
- view.setCreatedOn(asset.getCreatedOn());
- view.setLocation(asset.getCoordinates());
- view.showDroppedPin(asset.getGeoFeature(20));
- view.flyTo(asset.getCoordinates());
- view.enableCreate(assetId == null);
- view.enableUpdate(assetId != null);
- view.enableDelete(assetId != null);
+ @Override
+ protected List<FormButton> createAttributeActions(AssetAttribute attribute, AttributeViewImpl view) {
+ FormButton deleteButton = new FormButton();
+ deleteButton.setText(environment.getMessages().deleteAttribute());
+ deleteButton.setIcon("remove");
+ deleteButton.addClickHandler(clickEvent -> {
+ removeAttribute(attribute);
+ attribute.getName()
+ .ifPresent(name ->
+ showInfo(environment.getMessages().attributeDeleted(name))
+ );
+ });
+
+ return Collections.singletonList(deleteButton);
}
- protected void writeParentToView() {
- if (parentAsset != null) {
- view.setParentNode(new AssetTreeNode(parentAsset));
- } else {
- view.setParentNode(
- new TenantTreeNode(
- new Tenant(asset.getRealmId(), asset.getTenantRealm(), asset.getTenantDisplayName(), true)
- )
- );
- }
+ // TODO: Create a richer client side validation mechanism
+ @Override
+ protected void onAttributeModified(AssetAttribute attribute) {
+ // Called when a view has modified the attribute so we need to do validation this is called a lot by value
+ // editors (every key stroke) so use basic client side validation - use full validation before submitting
+ // the asset to the server
+ validateAttribute(true, attribute, result -> processValidationResults(Collections.singletonList(result)));
+ }
+
+ @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
+ environment.getRequestService().execute(
+ attributeValidationResultMapper,
+ assetAttributeMapper,
+ requestParams -> agentResource.validateProtocolConfiguration(requestParams, assetId, attribute),
+ Collections.singletonList(200),
+ resultConsumer,
+ ex -> handleRequestException(ex, environment.getEventBus(), environment.getMessages(), validationErrorHandler)
+ );
+ } else {
+ resultConsumer.accept(validationResult);
+ }
+ });
+
}
- protected void writeTypeToView(boolean typeEditable) {
+ protected void writeAttributeTypesToView(Runnable onComplete) {
view.selectWellKnownType(asset.getWellKnownType());
view.setAvailableWellKnownTypes(AssetType.valuesSorted());
view.setType(asset.getType());
- view.setTypeEditable(typeEditable);
+ view.setTypeEditable(isNullOrEmpty(assetId));
+
+ // Populate add attributes drop down based on asset type
+ if (asset.getWellKnownType() == AssetType.AGENT && !isNullOrEmpty(asset.getId())) {
+ List<Pair<String, String>> displayNamesAndTypes = new ArrayList<>();
+ displayNamesAndTypes.add(new Pair<>(ValueEditors.EMPTY_LINE, null));
+
+ environment.getRequestService().execute(
+ protocolDescriptorArrayMapper,
+ requestParams -> agentResource.getSupportedProtocols(requestParams, assetId),
+ 200,
+ protocolDescriptors -> {
+ this.protocolDescriptors.addAll(Arrays.asList(protocolDescriptors));
+ updateMetaItemDescriptors();
+ view.setFormBusy(false);
+ Arrays.stream(protocolDescriptors)
+ .sorted(Comparator.comparing(ProtocolDescriptor::getDisplayName))
+ .forEach(protocolDescriptor -> displayNamesAndTypes
+ .add(new Pair<>(protocolDescriptor.getDisplayName(), protocolDescriptor.getName()))
+ );
+
+ displayNamesAndTypes.add(new Pair<>(ValueEditors.EMPTY_LINE, null));
+ displayNamesAndTypes.addAll(attributeTypesToList());
+ view.setAvailableAttributeTypes(displayNamesAndTypes);
+ onComplete.run();
+ },
+ ex -> handleRequestException(ex, environment.getEventBus(), environment.getMessages(), validationErrorHandler)
+ );
+ } else {
+ // Get all protocol descriptors for all agents
+ environment.getRequestService().execute(
+ protocolDescriptorMapMapper,
+ agentResource::getAllSupportedProtocols,
+ 200,
+ protocolDescriptorMap -> {
+ protocolDescriptorMap.forEach((id, descriptors) -> {
+ for (ProtocolDescriptor newDescriptor : descriptors) {
+ if (this.protocolDescriptors.stream().noneMatch(pd -> pd.getName().equals(newDescriptor.getName()))) {
+ this.protocolDescriptors.add(newDescriptor);
+ }
+ }
+ });
+ updateMetaItemDescriptors();
+ view.setFormBusy(false);
+ view.setAvailableAttributeTypes(attributeTypesToList());
+ onComplete.run();
+ },
+ ex -> handleRequestException(ex, environment.getEventBus(), environment.getMessages(), validationErrorHandler)
+ );
+ }
}
- protected void writeAttributesEditorToView() {
- attributesEditor = new AttributesEditor(
- environment,
- view.getAttributesEditorContainer(),
- assetId == null
- ? asset.getWellKnownType().getDefaultAttributes().collect(Collectors.toList())
- : asset.getAttributesList(),
- assetId == null,
- this::getLinkableAssets,
- this::getLinkableAttributes
- );
- view.setAttributesEditor(attributesEditor);
- attributesEditor.build();
+ protected void updateMetaItemDescriptors() {
+ if (protocolDescriptors != null) {
+ for (ProtocolDescriptor descriptor : protocolDescriptors) {
+ if (descriptor.getProtocolConfigurationMetaItems() != null) {
+ metaItemDescriptors.addAll(descriptor.getProtocolConfigurationMetaItems());
+ }
+ if (descriptor.getLinkedAttributeMetaItems() != null) {
+ descriptor.getLinkedAttributeMetaItems().forEach(newDescriptor -> {
+ if (metaItemDescriptors.stream().noneMatch(md -> md.getUrn().equals(newDescriptor.getUrn()))) {
+ metaItemDescriptors.add(newDescriptor);
+ }
+ });
+ }
+ }
+ }
+ }
+
+ protected List<Pair<String, String>> attributeTypesToList() {
+ return Arrays.stream(AttributeType.values())
+ .map(Enum::name)
+ .map(attrType -> new Pair<>(environment.getMessages().attributeType(attrType), attrType))
+ .sorted(Comparator.comparing(a -> a.key))
+ .collect(Collectors.toList());
}
protected void readFromView() {
@@ -477,9 +639,6 @@ public class AssetEditActivity
if (selectedCoordinates != null) {
asset.setCoordinates(selectedCoordinates);
}
- asset.setAttributes(
- attributesEditor != null ? attributesEditor.getAttributes() : null
- );
}
protected void clearViewMessages() {
@@ -491,5 +650,4 @@ public class AssetEditActivity
view.setNameError(false);
view.setTypeError(false);
}
-
}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditImpl.java b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditImpl.java
index 36c6ce2c7..a4fad8e75 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditImpl.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditImpl.java
@@ -27,35 +27,35 @@ import com.google.gwt.text.shared.AbstractRenderer;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
-import com.google.gwt.user.client.ui.*;
+import com.google.gwt.user.client.ui.FlowPanel;
+import com.google.gwt.user.client.ui.HTMLPanel;
+import com.google.gwt.user.client.ui.Label;
+import com.google.gwt.user.client.ui.TextBox;
import com.google.inject.Provider;
+import org.openremote.manager.client.Environment;
import org.openremote.manager.client.app.dialog.Confirmation;
import org.openremote.manager.client.app.dialog.JsonEditor;
-import org.openremote.manager.client.assets.attributes.AttributesEditor;
+import org.openremote.manager.client.assets.attributes.AttributeView;
import org.openremote.manager.client.assets.browser.AssetBrowser;
import org.openremote.manager.client.assets.browser.AssetSelector;
import org.openremote.manager.client.assets.browser.BrowserTreeNode;
-import org.openremote.manager.client.i18n.ManagerMessages;
import org.openremote.manager.client.widget.*;
-import org.openremote.manager.client.widget.Hyperlink;
-import org.openremote.manager.client.widget.PushButton;
import org.openremote.model.Constants;
+import org.openremote.model.asset.Asset;
import org.openremote.model.asset.AssetType;
-import org.openremote.model.attribute.AttributeType;
import org.openremote.model.geo.GeoJSON;
+import org.openremote.model.util.Pair;
import org.openremote.model.value.ObjectValue;
import javax.inject.Inject;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Date;
+import java.util.*;
public class AssetEditImpl extends FormViewImpl implements AssetEdit {
interface UI extends UiBinder<FlexSplitPanel, AssetEditImpl> {
}
- interface Style extends CssResource {
+ interface Style extends CssResource, AttributeView.Style {
String navItem();
@@ -64,27 +64,29 @@ public class AssetEditImpl extends FormViewImpl implements AssetEdit {
String mapWidget();
String nameInput();
- }
-
- interface AttributesEditorStyle extends CssResource, AttributesEditor.Style {
- String numberEditor();
+ String newAttributeFormGroup();
String stringEditor();
+ String numberEditor();
+
String booleanEditor();
String regularAttribute();
String highlightAttribute();
+
+ String metaItemNameEditor();
+
+ String metaItemValueEditor();
+
+ String agentLinkEditor();
}
@UiField
Style style;
- @UiField
- AttributesEditorStyle attributesEditorStyle;
-
@UiField
FlexSplitPanel splitPanel;
@@ -137,7 +139,7 @@ public class AssetEditImpl extends FormViewImpl implements AssetEdit {
@UiField
Label customTypeInfoLabel;
@UiField
- FlowPanel attributesEditorContainer;
+ FlowPanel attributeViewContainer;
/* ############################################################################ */
@@ -163,23 +165,26 @@ public class AssetEditImpl extends FormViewImpl implements AssetEdit {
final AssetBrowser assetBrowser;
final Provider<JsonEditor> jsonEditorProvider;
+ final Environment environment;
Presenter presenter;
- AttributesEditor attributesEditor;
+ Asset asset;
+ final List<AttributeView> attributeViews = new ArrayList<>();
@Inject
public AssetEditImpl(AssetBrowser assetBrowser,
Provider<Confirmation> confirmationDialogProvider,
Provider<JsonEditor> jsonEditorProvider,
- ManagerMessages managerMessages) {
+ Environment environment) {
super(confirmationDialogProvider);
this.jsonEditorProvider = jsonEditorProvider;
this.assetBrowser = assetBrowser;
+ this.environment = environment;
parentAssetSelector = new AssetSelector(
assetBrowser.getPresenter(),
- managerMessages,
- managerMessages.parentAsset(),
- managerMessages.selectAssetDescription(),
+ environment.getMessages(),
+ environment.getMessages().parentAsset(),
+ environment.getMessages().selectAssetDescription(),
false,
treeNode -> {
if (presenter != null) {
@@ -189,14 +194,14 @@ public class AssetEditImpl extends FormViewImpl implements AssetEdit {
) {
@Override
public void beginSelection() {
- AssetEditImpl.this.setOpaque(true);
+ AssetEditImpl.this.setDisabled(true);
super.beginSelection();
}
@Override
public void endSelection() {
super.endSelection();
- AssetEditImpl.this.setOpaque(false);
+ AssetEditImpl.this.setDisabled(false);
}
};
@@ -206,7 +211,7 @@ public class AssetEditImpl extends FormViewImpl implements AssetEdit {
public String render(AssetType assetType) {
if (assetType == null)
assetType = AssetType.CUSTOM;
- return managerMessages.assetTypeLabel(assetType.name());
+ return environment.getMessages().assetTypeLabel(assetType.name());
}
}
);
@@ -250,9 +255,9 @@ public class AssetEditImpl extends FormViewImpl implements AssetEdit {
customTypeInfoLabel.setVisible(false);
showDroppedPin(GeoJSON.EMPTY_FEATURE_COLLECTION);
hideMapPopup();
- setOpaque(false);
- attributesEditorContainer.clear();
- attributesEditor = null;
+ setDisabled(false);
+ attributeViewContainer.clear();
+ attributeViews.clear();
newAttributeFormGroup.setError(false);
newAttributeNameInputText.setValue(null);
newAttributeTypeListBox.clear();
@@ -263,6 +268,11 @@ public class AssetEditImpl extends FormViewImpl implements AssetEdit {
}
}
+ @Override
+ public AttributeView.Style getStyle() {
+ return style;
+ }
+
@Override
public void setFormBusy(boolean busy) {
super.setFormBusy(busy);
@@ -275,15 +285,21 @@ public class AssetEditImpl extends FormViewImpl implements AssetEdit {
&& viewAssetLink.getTargetHistoryToken().length() > 0
&& !busy
);
+ addAttributeButton.setEnabled(!busy);
}
@Override
- public void setAssetViewHistoryToken(String token) {
+ public void setHistoryToken(String token) {
viewAssetLink.setTargetHistoryToken(token);
}
/* ############################################################################ */
+ @Override
+ public void setAsset(Asset asset) {
+ this.asset = asset;
+ }
+
@Override
public void setName(String name) {
nameInput.setValue(name);
@@ -365,6 +381,50 @@ public class AssetEditImpl extends FormViewImpl implements AssetEdit {
}
}
+ @Override
+ public void setAttributeViews(List<AttributeView> attributeViews) {
+ this.attributeViews.clear();
+ this.attributeViews.addAll(attributeViews);
+ refreshAttributeViewContainer();
+ }
+
+ @Override
+ public void addAttributeViews(List<AttributeView> attributeViews) {
+ this.attributeViews.addAll(attributeViews);
+ refreshAttributeViewContainer();
+ }
+
+ @Override
+ public void removeAttributeViews(List<AttributeView> attributeViews) {
+ this.attributeViews.removeAll(attributeViews);
+ refreshAttributeViewContainer();
+ }
+
+ @Override
+ public List<AttributeView> getAttributeViews() {
+ return attributeViews;
+ }
+
+ protected void refreshAttributeViewContainer() {
+ attributeViewContainer.clear();
+
+ if (attributeViews.size() == 0) {
+ Label emptyLabel = new Label(environment.getMessages().noAttributes());
+ emptyLabel.addStyleName(environment.getWidgetStyle().FormListEmptyMessage());
+ attributeViewContainer.add(emptyLabel);
+ } else {
+ sortAttributeViews();
+ attributeViews.forEach(
+ attributeView -> attributeViewContainer.add(attributeView)
+ );
+ }
+ }
+
+ protected void sortAttributeViews() {
+ // Sort by label/name ascending
+ attributeViews.sort(Comparator.comparing(o -> o.getAttribute().getLabelOrName().orElse("")));
+ }
+
@UiHandler("centerMapButton")
void centerMapClicked(ClickEvent e) {
if (presenter != null)
@@ -413,56 +473,28 @@ public class AssetEditImpl extends FormViewImpl implements AssetEdit {
}
@Override
- public AttributesEditor.Container getAttributesEditorContainer() {
- return new AttributesEditor.Container() {
- @Override
- public AttributesEditor.Style getStyle() {
- return attributesEditorStyle;
- }
-
- @Override
- public InsertPanel getPanel() {
- return attributesEditorContainer;
- }
-
- @Override
- public JsonEditor getJsonEditor() {
- return jsonEditorProvider.get();
- }
-
- @Override
- public ManagerMessages getMessages() {
- return managerMessages;
- }
- };
- }
-
- @Override
- public void setAttributesEditor(AttributesEditor editor) {
- this.attributesEditor = editor;
- attributesEditorContainer.clear();
- }
-
- @Override
- public void setNewAttributeError(boolean error) {
- newAttributeFormGroup.setError(error);
- }
-
- @Override
- public void setAvailableAttributeTypes(AttributeType[] types) {
+ public void setAvailableAttributeTypes(List<Pair<String,String>> displayNamesAndTypes) {
newAttributeTypeListBox.clear();
- newAttributeTypeListBox.addItem(managerMessages.selectType());
- for (AttributeType attributeType: types) {
- newAttributeTypeListBox.addItem(
- managerMessages.attributeType(attributeType.name())
- );
- }
+ newAttributeTypeListBox.addItem(managerMessages.selectType(), "");
+ displayNamesAndTypes.forEach(
+ displayNameAndType ->
+ newAttributeTypeListBox.addItem(
+ displayNameAndType.key, displayNameAndType.value
+ )
+ );
}
@UiHandler("addAttributeButton")
public void addAttributeButtonClicked(ClickEvent e) {
- if (presenter != null)
- presenter.addAttribute(newAttributeNameInputText.getValue(), newAttributeTypeListBox.getSelectedIndex()-1);
+ if (presenter != null) {
+ if (presenter.addAttribute(
+ newAttributeNameInputText.getValue(),
+ newAttributeTypeListBox.getSelectedValue()
+ )) {
+ newAttributeNameInputText.setValue(null);
+ newAttributeTypeListBox.setSelectedIndex(0);
+ }
+ }
}
/* ############################################################################ */
@@ -507,15 +539,15 @@ public class AssetEditImpl extends FormViewImpl implements AssetEdit {
/* ############################################################################ */
- protected void setOpaque(boolean opaque) {
- nameGroup.setOpaque(opaque);
- createdOnGroup.setOpaque(opaque);
- locationGroup.setOpaque(opaque);
- mapWidget.setOpaque(opaque);
- typeGroup.setOpaque(opaque);
- if (attributesEditor != null)
- attributesEditor.setOpaque(opaque);
- newAttributeFormGroup.setOpaque(opaque);
- submitButtonGroup.setOpaque(opaque);
+ protected void setDisabled(boolean disabled) {
+ nameGroup.setDisabled(disabled);
+ createdOnGroup.setDisabled(disabled);
+ locationGroup.setDisabled(disabled);
+ mapWidget.setOpaque(disabled);
+ typeGroup.setDisabled(disabled);
+ newAttributeFormGroup.setDisabled(disabled);
+ submitButtonGroup.setDisabled(disabled);
+
+ attributeViews.forEach(attributeView -> attributeView.setDisabled(disabled));
}
}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditImpl.ui.xml b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditImpl.ui.xml
index 10c277c73..92a7d341d 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditImpl.ui.xml
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditImpl.ui.xml
@@ -26,16 +26,12 @@
.newAttributeFormGroup {
-
}
- </ui:style>
- <ui:style field="attributesEditorStyle"
- type="org.openremote.manager.client.assets.asset.AssetEditImpl.AttributesEditorStyle">
.stringEditor {
- min-width: 5em;
- width: 100%;
- }
+ min-width: 5em;
+ width: 100%;
+ }
.numberEditor {
min-width: 5em;
@@ -54,17 +50,22 @@
.metaItemNameEditor {
min-width: 5em;
- width: 35em;
+ width: 40%;
+ max-width: 30em;
}
.metaItemValueEditor {
+ min-width: 5em;
+ }
+
+ .agentLinkEditor {
}
</ui:style>
<w:FlexSplitPanel ui:field="splitPanel"
handleStyle="{widgetStyle.SplitPanelHandle}"
- firstPanelWidth="200"
+ firstPanelWidth="250"
firstPanelMinWidth="0"
secondPanelMinWidth="400">
@@ -230,7 +231,7 @@
</g:HTMLPanel>
- <g:FlowPanel ui:field="attributesEditorContainer"
+ <g:FlowPanel ui:field="attributeViewContainer"
styleName="flex layout vertical {widgetStyle.MainContent} {widgetStyle.FormList}"/>
<g:HTMLPanel styleName="flex-none layout vertical {widgetStyle.MainContent}">
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetView.java b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetView.java
index 25456c3ee..d053ef82c 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetView.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetView.java
@@ -19,21 +19,9 @@
*/
package org.openremote.manager.client.assets.asset;
-import com.google.gwt.user.client.ui.IsWidget;
-import org.openremote.manager.client.assets.attributes.AttributesBrowser;
-import org.openremote.manager.client.assets.browser.BrowserTreeNode;
-import org.openremote.model.geo.GeoJSON;
-import org.openremote.model.value.ObjectValue;
+public interface AssetView extends AssetBaseView<AssetView.Presenter> {
-import java.util.Date;
-
-public interface AssetView extends IsWidget {
-
- interface Presenter {
-
- void onMapReady();
-
- void centerMap();
+ interface Presenter extends AssetBaseView.Presenter {
void enableLiveUpdates(boolean enable);
@@ -44,29 +32,5 @@ public interface AssetView extends IsWidget {
void setFormBusy(boolean busy);
- void setAssetEditHistoryToken(String token);
-
- void setName(String name);
-
- void setCreatedOn(Date createdOn);
-
- void setParentNode(BrowserTreeNode treeNode);
-
- void initialiseMap(ObjectValue mapOptions);
-
- boolean isMapInitialised();
-
- void setLocation(double[] coordinates);
-
- void showDroppedPin(GeoJSON geoFeature);
-
- void flyTo(double[] coordinates);
-
void setIconAndType(String icon, String type);
-
- AttributesBrowser.Container getAttributesBrowserContainer();
-
- void setAttributesBrowser(AttributesBrowser attributesBrowser);
-
- boolean isLiveUpdatesEnabled();
}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewActivity.java b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewActivity.java
index 49220a0a8..eb4cf3c7a 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewActivity.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewActivity.java
@@ -19,51 +19,64 @@
*/
package org.openremote.manager.client.assets.asset;
-import com.google.gwt.user.client.ui.AcceptsOneWidget;
+import com.google.inject.Provider;
import org.openremote.manager.client.Environment;
+import org.openremote.manager.client.app.dialog.JsonEditor;
import org.openremote.manager.client.assets.AssetMapper;
-import org.openremote.manager.client.assets.attributes.AttributesBrowser;
+import org.openremote.manager.client.assets.attributes.AbstractAttributeViewExtension;
+import org.openremote.manager.client.assets.attributes.AttributeView;
+import org.openremote.manager.client.assets.attributes.AttributeViewImpl;
import org.openremote.manager.client.assets.browser.AssetBrowser;
-import org.openremote.manager.client.assets.browser.AssetBrowserSelection;
-import org.openremote.manager.client.assets.browser.AssetTreeNode;
-import org.openremote.manager.client.assets.browser.TenantTreeNode;
-import org.openremote.manager.client.assets.tenant.AssetsTenantPlace;
+import org.openremote.manager.client.datapoint.DatapointBrowser;
import org.openremote.manager.client.datapoint.NumberDatapointArrayMapper;
import org.openremote.manager.client.interop.value.ObjectValueMapper;
+import org.openremote.manager.client.simulator.Simulator;
+import org.openremote.manager.client.widget.FormButton;
import org.openremote.manager.shared.asset.AssetResource;
import org.openremote.manager.shared.datapoint.AssetDatapointResource;
import org.openremote.manager.shared.map.MapResource;
import org.openremote.manager.shared.security.Tenant;
+import org.openremote.model.Constants;
import org.openremote.model.asset.AssetAttribute;
+import org.openremote.model.asset.ReadAssetAttributesEvent;
+import org.openremote.model.asset.agent.ProtocolConfiguration;
+import org.openremote.model.attribute.AttributeEvent;
+import org.openremote.model.attribute.AttributeExecuteStatus;
+import org.openremote.model.attribute.AttributeRef;
+import org.openremote.model.datapoint.Datapoint;
import org.openremote.model.datapoint.DatapointInterval;
import org.openremote.model.datapoint.NumberDatapoint;
-import org.openremote.model.event.bus.EventBus;
-import org.openremote.model.event.bus.EventRegistration;
+import org.openremote.model.simulator.SimulatorState;
+import org.openremote.model.value.ValueType;
import javax.inject.Inject;
-import java.util.Collection;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Optional;
import java.util.function.Consumer;
import static org.openremote.manager.client.http.RequestExceptionHandler.handleRequestException;
+import static org.openremote.model.attribute.Attribute.isAttributeTypeEqualTo;
+import static org.openremote.model.util.TextUtil.isNullOrEmpty;
public class AssetViewActivity
- extends AbstractAssetActivity<AssetViewPlace>
+ extends AbstractAssetActivity<AssetView.Presenter, AssetView, AssetViewPlace>
implements AssetView.Presenter {
- final AssetView view;
+ protected final static String READ_BUTTON_CLASS = "or-internal-read-button";
final AssetResource assetResource;
final AssetMapper assetMapper;
final AssetDatapointResource assetDatapointResource;
final NumberDatapointArrayMapper numberDatapointArrayMapper;
- final MapResource mapResource;
- final ObjectValueMapper objectValueMapper;
-
- AttributesBrowser attributesBrowser;
+ final protected List<AttributeRef> activeSimulators = new ArrayList<>();
+ protected static boolean liveUpdates;
@Inject
public AssetViewActivity(Environment environment,
Tenant currentTenant,
AssetBrowser.Presenter assetBrowserPresenter,
+ Provider<JsonEditor> jsonEditorProvider,
AssetView view,
AssetResource assetResource,
AssetMapper assetMapper,
@@ -71,81 +84,45 @@ public class AssetViewActivity
NumberDatapointArrayMapper numberDatapointArrayMapper,
MapResource mapResource,
ObjectValueMapper objectValueMapper) {
- super(environment, currentTenant, assetBrowserPresenter);
+ super(environment, currentTenant, assetBrowserPresenter, jsonEditorProvider, objectValueMapper, mapResource, false);
+ this.presenter = this;
this.view = view;
this.assetResource = assetResource;
this.assetMapper = assetMapper;
this.assetDatapointResource = assetDatapointResource;
this.numberDatapointArrayMapper = numberDatapointArrayMapper;
- this.mapResource = mapResource;
- this.objectValueMapper = objectValueMapper;
- }
-
- @Override
- public void start(AcceptsOneWidget container, EventBus eventBus, Collection<EventRegistration> registrations) {
- view.setPresenter(this);
- container.setWidget(view.asWidget());
-
- registrations.add(eventBus.register(
- AssetBrowserSelection.class, event -> {
- if (event.getSelectedNode() instanceof TenantTreeNode) {
- environment.getPlaceController().goTo(
- new AssetsTenantPlace(event.getSelectedNode().getId())
- );
- } else if (event.getSelectedNode() instanceof AssetTreeNode) {
- if (this.assetId == null || !this.assetId.equals(event.getSelectedNode().getId())) {
- environment.getPlaceController().goTo(
- new AssetViewPlace(event.getSelectedNode().getId())
- );
- }
- }
- }
- ));
-
- if (!view.isMapInitialised()) {
- environment.getRequestService().execute(
- objectValueMapper,
- mapResource::getSettings,
- 200,
- view::initialiseMap,
- ex -> handleRequestException(ex, environment)
- );
- } else {
- onMapReady();
- }
}
@Override
public void onStop() {
super.onStop();
- if (attributesBrowser != null) {
- attributesBrowser.close();
- }
+
+ subscribeLiveUpdates(false);
+
+ view.removeAttributeViews(attributeViews);
view.setPresenter(null);
}
@Override
- public void onMapReady() {
- asset = null;
- if (assetId != null) {
- assetBrowserPresenter.loadAsset(assetId, loadedAsset -> {
- this.asset = loadedAsset;
- assetBrowserPresenter.selectAsset(asset);
- writeAssetToView();
- writeAttributesBrowserToView();
- // TODO This fails if the user is restricted, can't just load parent and assume we have access
- if (asset.getParentId() != null) {
- assetBrowserPresenter.loadAsset(asset.getParentId(), loadedParentAsset -> {
- this.parentAsset = loadedParentAsset;
- writeParentToView();
- view.setFormBusy(false);
- });
- } else {
- writeParentToView();
- view.setFormBusy(false);
- }
- });
+ public void start() {
+ if (asset == null) {
+ // Something went wrong loading the asset
+ return;
}
+
+ if (liveUpdates) {
+ subscribeLiveUpdates(true);
+ }
+
+ registrations.add(environment.getEventBus().register(
+ AttributeEvent.class,
+ this::onAttributeEvent
+ ));
+
+
+ writeAssetToView();
+ writeAttributesToView();
+ loadParent();
}
@Override
@@ -155,65 +132,239 @@ public class AssetViewActivity
@Override
public void enableLiveUpdates(boolean enable) {
- if (attributesBrowser != null) {
- attributesBrowser.subscribeToLiveUpdates(enable);
+ liveUpdates = enable;
+
+ // TODO: make this a bit more efficient
+ for (AttributeView attributeView : attributeViews) {
+ if (attributeView instanceof AttributeViewImpl) {
+ ((AttributeViewImpl)attributeView).getActionButtons().forEach(button -> {
+ if (button.getStyleName().contains(READ_BUTTON_CLASS)) {
+ (button).setEnabled(!enable);
+ }
+ });
+ }
+ }
+
+ if (enable) {
+ // Poll all values once so we have some state
+ readAllAttributeValues();
+ }
+
+ subscribeLiveUpdates(true);
+ }
+
+ protected void subscribeLiveUpdates(boolean subscribe) {
+ if (subscribe) {
+ // TODO: Can the event service and bus be unified
+ // TODO: return event handle so we can unregister on stop
+ environment.getEventService().subscribe(
+ AttributeEvent.class,
+ new AttributeEvent.EntityIdFilter(asset.getId())
+ );
+ } else {
+ environment.getEventService().unsubscribe(
+ AttributeEvent.class
+ );
}
}
@Override
public void refresh() {
- if (attributesBrowser != null) {
- attributesBrowser.readAllAttributeValues();
+ for (AttributeView attributeView : attributeViews) {
+ attributeView.onAttributeChanged();
}
}
- protected void writeAssetToView() {
- view.setAssetEditHistoryToken(environment.getPlaceHistoryMapper().getToken(new AssetEditPlace(assetId)));
- view.setName(asset.getName());
- view.setCreatedOn(asset.getCreatedOn());
- view.setLocation(asset.getCoordinates());
- view.showDroppedPin(asset.getGeoFeature(20));
- view.flyTo(asset.getCoordinates());
+ @Override
+ protected void onAttributeModified(AssetAttribute attribute) {
+ // Called when a view has modified the attribute so we need to do validation
+ validateAttribute(true, attribute, result -> processValidationResults(Collections.singletonList(result)));
+ }
+
+ protected void onAttributeEvent(AttributeEvent attributeEvent) {
+ for (AttributeView attributeView : attributeViews) {
+ AssetAttribute assetAttribute = attributeView.getAttribute();
+ Optional<AttributeRef> assetAttributeRef = assetAttribute.getReference();
+
+ if (assetAttributeRef.map(ref -> ref.equals(attributeEvent.getAttributeRef())).orElse(false)) {
+ assetAttribute.setValue(attributeEvent.getValue().orElse(null), attributeEvent.getTimestamp());
+ attributeView.onAttributeChanged();
+ break;
+ }
+ }
+ }
+
+ @Override
+ public void writeAssetToView() {
+ super.writeAssetToView();
view.setIconAndType(asset.getWellKnownType().getIcon(), asset.getType());
}
- protected void writeParentToView() {
- if (parentAsset != null) {
- view.setParentNode(new AssetTreeNode(parentAsset));
+ protected List<FormButton> createAttributeActions(AssetAttribute attribute, AttributeViewImpl view) {
+ List<FormButton> actionButtons = new ArrayList<>();
+
+ if (attribute.isExecutable()) {
+ // A command is executed by writing a special value
+ FormButton startButton = new FormButton();
+ startButton.setEnabled(!attribute.isReadOnly());
+ startButton.setText(environment.getMessages().start());
+ startButton.setPrimary(true);
+ startButton.setIcon("play-circle");
+ startButton.addClickHandler(clickEvent -> {
+ attribute.setValue(AttributeExecuteStatus.REQUEST_START.asValue());
+ writeAttributeValue(attribute);
+ });
+ actionButtons.add(startButton);
+
+ FormButton repeatButton = new FormButton();
+ repeatButton.setEnabled(!attribute.isReadOnly());
+ repeatButton.setText(environment.getMessages().repeat());
+ repeatButton.setPrimary(true);
+ repeatButton.setIcon("repeat");
+ repeatButton.addClickHandler(clickEvent -> {
+ attribute.setValue(AttributeExecuteStatus.REQUEST_REPEATING.asValue());
+ writeAttributeValue(attribute);
+ });
+ actionButtons.add(repeatButton);
+
+ FormButton cancelButton = new FormButton();
+ cancelButton.setEnabled(!attribute.isReadOnly());
+ cancelButton.setText(environment.getMessages().cancel());
+ cancelButton.setPrimary(true);
+ cancelButton.setIcon("stop-circle");
+ cancelButton.addClickHandler(clickEvent -> {
+ attribute.setValue(AttributeExecuteStatus.REQUEST_CANCEL.asValue());
+ writeAttributeValue(attribute);
+ });
+ actionButtons.add(cancelButton);
+
+ FormButton readStatusButton = new FormButton();
+ readStatusButton.setText(environment.getMessages().getStatus());
+ readStatusButton.setIcon("cloud-download");
+ readStatusButton.addStyleName(READ_BUTTON_CLASS);
+ readStatusButton.setEnabled(!liveUpdates);
+ readStatusButton.addClickHandler(clickEvent -> readAttributeValue(attribute));
+ actionButtons.add(readStatusButton);
+
} else {
- view.setParentNode(
- new TenantTreeNode(
- new Tenant(asset.getRealmId(), asset.getTenantRealm(), asset.getTenantDisplayName(), true)
- )
+ // Default read/write actions
+ FormButton writeValueButton = new FormButton();
+ writeValueButton.setEnabled(!attribute.isReadOnly());
+ writeValueButton.setText(environment.getMessages().write());
+ writeValueButton.setPrimary(true);
+ writeValueButton.setIcon("cloud-upload");
+ writeValueButton.addClickHandler(clickEvent -> writeAttributeValue(attribute));
+ actionButtons.add(writeValueButton);
+
+ FormButton readValueButton = new FormButton();
+ readValueButton.addStyleName(READ_BUTTON_CLASS);
+ readValueButton.setText(environment.getMessages().read());
+ readValueButton.setIcon("cloud-download");
+ readValueButton.setEnabled(!liveUpdates);
+ readValueButton.addClickHandler(clickEvent -> readAttributeValue(attribute));
+ actionButtons.add(readValueButton);
+ }
+
+ return actionButtons;
+ }
+
+ protected List<AbstractAttributeViewExtension> createAttributeExtensions(AssetAttribute attribute, AttributeViewImpl view) {
+ List<AbstractAttributeViewExtension> viewExtensions = new ArrayList<>();
+
+ if (Datapoint.isDatapointsCapable(attribute) && attribute.isStoreDatapoints()) {
+ viewExtensions.add(
+ createDatapointBrowser(attribute, view)
+ );
+ }
+
+ if (environment.getSecurityService().isSuperUser() &&
+ ProtocolConfiguration.isProtocolConfiguration(attribute) &&
+ ProtocolConfiguration.getProtocolName(attribute)
+ .map(name -> name.equals(Constants.PROTOCOL_NAMESPACE + ":simulator"))
+ .orElse(false)) {
+ viewExtensions.add(
+ createSimulator(attribute, view)
);
}
+
+ return viewExtensions;
}
- protected void writeAttributesBrowserToView() {
- attributesBrowser = new AttributesBrowser(
- environment,
- view.getAttributesBrowserContainer(),
- asset
- ) {
- @Override
- protected void getNumberDatapoints(AssetAttribute attribute,
- DatapointInterval interval,
- long timestamp,
- Consumer<NumberDatapoint[]> consumer) {
- environment.getRequestService().execute(
- numberDatapointArrayMapper,
- requestParams -> assetDatapointResource.getNumberDatapoints(
- requestParams, assetId, attribute.getName().orElse(null), interval, timestamp
- ),
- 200,
- consumer,
- ex -> handleRequestException(ex, environment)
- );
+ protected void readAllAttributeValues() {
+ environment.getEventService().dispatch(
+ new ReadAssetAttributesEvent(asset.getId())
+ );
+ }
+
+ protected void readAttributeValue(AssetAttribute attribute) {
+ attribute.getReference().ifPresent(attributeRef ->
+ environment.getEventService().dispatch(
+ new ReadAssetAttributesEvent(attributeRef.getEntityId(), attributeRef.getAttributeName())
+ )
+ );
+ }
+
+ /*###########################################################################################*/
+ /*#### EXTENSIONS BELOW ####*/
+ /*###########################################################################################*/
+ protected DatapointBrowser createDatapointBrowser(AssetAttribute attribute, AttributeViewImpl view) {
+ return new DatapointBrowser(environment, this.view.getStyle(), view, attribute, 675, 200) {
+ @SuppressWarnings("ConstantConditions")
+ @Override
+ protected void queryDatapoints(DatapointInterval interval,
+ long timestamp,
+ Consumer<NumberDatapoint[]> consumer) {
+ queryDataPoints(attribute.getName().get(), interval, timestamp, consumer);
}
};
- view.setAttributesBrowser(attributesBrowser);
- attributesBrowser.build();
- attributesBrowser.subscribeToLiveUpdates(view.isLiveUpdatesEnabled());
}
+
+ protected void queryDataPoints(String attributeName, DatapointInterval interval, long timestamp, Consumer<NumberDatapoint[]> consumer) {
+ if (!isNullOrEmpty(attributeName)) {
+ environment.getRequestService().execute(
+ numberDatapointArrayMapper,
+ requestParams -> assetDatapointResource.getNumberDatapoints(
+ requestParams, this.asset.getId(), attributeName, interval, timestamp
+ ),
+ 200,
+ consumer,
+ ex -> handleRequestException(ex, environment)
+ );
+ }
+ }
+
+ protected Simulator createSimulator(AssetAttribute attribute, AttributeViewImpl view) {
+ AttributeRef protocolConfigurationRef = attribute.getReferenceOrThrow();
+
+ return new Simulator(
+ environment,
+ this.view.getStyle(),
+ view,
+ attribute,
+ protocolConfigurationRef,
+ () -> {
+ activeSimulators.add(protocolConfigurationRef);
+ updateSimulatorSubscription();
+ },
+ () -> {
+ activeSimulators.remove(protocolConfigurationRef);
+ updateSimulatorSubscription();
+ }
+ );
+ }
+
+ protected void updateSimulatorSubscription() {
+ if (activeSimulators.size() > 0) {
+ environment.getEventService().subscribe(
+ SimulatorState.class, new SimulatorState.ConfigurationFilter(
+ activeSimulators.toArray(new AttributeRef[activeSimulators.size()])
+ )
+ );
+ } else {
+ environment.getEventService().unsubscribe(SimulatorState.class);
+ }
+ }
+
+
}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewImpl.java b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewImpl.java
index 121b7f48f..fbfd919d3 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewImpl.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewImpl.java
@@ -29,10 +29,11 @@ import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTMLPanel;
-import com.google.gwt.user.client.ui.InsertPanel;
+import com.google.gwt.user.client.ui.Label;
import com.google.inject.Provider;
+import org.openremote.manager.client.Environment;
import org.openremote.manager.client.app.dialog.JsonEditor;
-import org.openremote.manager.client.assets.attributes.AttributesBrowser;
+import org.openremote.manager.client.assets.attributes.AttributeView;
import org.openremote.manager.client.assets.browser.AssetBrowser;
import org.openremote.manager.client.assets.browser.AssetSelector;
import org.openremote.manager.client.assets.browser.BrowserTreeNode;
@@ -40,36 +41,44 @@ import org.openremote.manager.client.i18n.ManagerMessages;
import org.openremote.manager.client.style.WidgetStyle;
import org.openremote.manager.client.widget.*;
import org.openremote.model.Constants;
+import org.openremote.model.asset.Asset;
import org.openremote.model.asset.AssetType;
+import org.openremote.model.attribute.AttributeEvent;
+import org.openremote.model.event.bus.EventRegistration;
import org.openremote.model.geo.GeoJSON;
import org.openremote.model.value.ObjectValue;
import javax.inject.Inject;
+import java.util.ArrayList;
import java.util.Date;
+import java.util.List;
public class AssetViewImpl extends Composite implements AssetView {
interface UI extends UiBinder<FlexSplitPanel, AssetViewImpl> {
}
- interface Style extends CssResource {
+ interface Style extends CssResource, AttributeView.Style {
String navItem();
String mapWidget();
- }
- interface AttributesBrowserStyle extends CssResource, AttributesBrowser.Style {
+ String stringEditor();
String numberEditor();
- String stringEditor();
-
String booleanEditor();
String regularAttribute();
String highlightAttribute();
+
+ String metaItemValueEditor();
+
+ String metaItemNameEditor();
+
+ String agentLinkEditor();
}
@UiField
@@ -81,9 +90,6 @@ public class AssetViewImpl extends Composite implements AssetView {
@UiField
Style style;
- @UiField
- AttributesBrowserStyle attributesBrowserStyle;
-
@UiField
FlexSplitPanel splitPanel;
@@ -136,20 +142,25 @@ public class AssetViewImpl extends Composite implements AssetView {
PushButton liveUpdatesOffButton;
@UiField
- FlowPanel attributesBrowserContainer;
+ FlowPanel attributeViewContainer;
/* ############################################################################ */
final AssetBrowser assetBrowser;
final Provider<JsonEditor> jsonEditorProvider;
- Presenter presenter;
- AttributesBrowser attributesBrowser;
+ final Environment environment;
+ final List<AttributeView> attributeViews = new ArrayList<>();
+ protected Presenter presenter;
+ protected Asset asset;
+ protected EventRegistration<AttributeEvent> eventRegistration;
@Inject
public AssetViewImpl(AssetBrowser assetBrowser,
+ Environment environment,
Provider<JsonEditor> jsonEditorProvider) {
this.assetBrowser = assetBrowser;
this.jsonEditorProvider = jsonEditorProvider;
+ this.environment = environment;
UI ui = GWT.create(UI.class);
initWidget(ui.createAndBindUi(this));
@@ -176,8 +187,14 @@ public class AssetViewImpl extends Composite implements AssetView {
locationOutput.setCoordinates(null, null);
mapWidget.setVisible(false);
showDroppedPin(GeoJSON.EMPTY_FEATURE_COLLECTION);
- attributesBrowserContainer.clear();
- attributesBrowser = null;
+
+ if (eventRegistration != null) {
+ environment.getEventBus().remove(eventRegistration);
+ eventRegistration = null;
+ }
+
+ attributeViews.clear();
+ attributeViewContainer.clear();
if (presenter != null) {
assetBrowser.asWidget().removeFromParent();
@@ -201,10 +218,20 @@ public class AssetViewImpl extends Composite implements AssetView {
/* ############################################################################ */
@Override
- public void setAssetEditHistoryToken(String token) {
+ public void setHistoryToken(String token) {
editAssetLink.setTargetHistoryToken(token);
}
+ @Override
+ public AttributeView.Style getStyle() {
+ return style;
+ }
+
+ @Override
+ public void setAsset(Asset asset) {
+ this.asset = asset;
+ }
+
@Override
public void setName(String name) {
headline.setText(name);
@@ -264,13 +291,29 @@ public class AssetViewImpl extends Composite implements AssetView {
}
}
- @UiHandler("centerMapButton")
- void centerMapClicked(ClickEvent e) {
- if (presenter != null)
- presenter.centerMap();
+ @Override
+ public void setAttributeViews(List<AttributeView> attributeViews) {
+ this.attributeViews.clear();
+ this.attributeViews.addAll(attributeViews);
+ refreshAttributeViewContainer();
}
- /* ############################################################################ */
+ @Override
+ public void addAttributeViews(List<AttributeView> attributeViews) {
+ this.attributeViews.addAll(attributeViews);
+ refreshAttributeViewContainer();
+ }
+
+ @Override
+ public void removeAttributeViews(List<AttributeView> attributeViews) {
+ this.attributeViews.removeAll(attributeViews);
+ refreshAttributeViewContainer();
+ }
+
+ @Override
+ public List<AttributeView> getAttributeViews() {
+ return attributeViews;
+ }
@Override
public void setIconAndType(String icon, String type) {
@@ -284,36 +327,40 @@ public class AssetViewImpl extends Composite implements AssetView {
}
}
- @Override
- public AttributesBrowser.Container getAttributesBrowserContainer() {
- return new AttributesBrowser.Container() {
+ protected void refreshAttributeViewContainer() {
+ attributeViewContainer.clear();
- @Override
- public AttributesBrowser.Style getStyle() {
- return attributesBrowserStyle;
- }
-
- @Override
- public InsertPanel getPanel() {
- return attributesBrowserContainer;
- }
-
- @Override
- public JsonEditor getJsonEditor() {
- return jsonEditorProvider.get();
- }
+ if (attributeViews.size() == 0) {
+ Label emptyLabel = new Label(environment.getMessages().noAttributes());
+ emptyLabel.addStyleName(environment.getWidgetStyle().FormListEmptyMessage());
+ attributeViewContainer.add(emptyLabel);
+ } else {
+ sortAttributeViews();
+ attributeViews.forEach(
+ attributeView -> attributeViewContainer.add(attributeView)
+ );
+ }
+ }
- @Override
- public ManagerMessages getMessages() {
- return managerMessages;
+ protected void sortAttributeViews() {
+ // Executable commands first, then sort by label/name ascending
+ attributeViews.sort((o1, o2) -> {
+ if (o1.getAttribute().isExecutable() && !o2.getAttribute().isExecutable()) {
+ return -1;
+ } else if (!o1.getAttribute().isExecutable() && o2.getAttribute().isExecutable()) {
+ return 1;
+ } else {
+ return o1.getAttribute().getLabelOrName().orElse("").compareTo(o2.getAttribute().getLabelOrName().orElse(""));
}
- };
+ });
}
- @Override
- public void setAttributesBrowser(AttributesBrowser browser) {
- this.attributesBrowser = browser;
- attributesBrowserContainer.clear();
+ /* ############################################################################ */
+
+ @UiHandler("centerMapButton")
+ void centerMapClicked(ClickEvent e) {
+ if (presenter != null)
+ presenter.centerMap();
}
@UiHandler("refreshButton")
@@ -322,11 +369,6 @@ public class AssetViewImpl extends Composite implements AssetView {
presenter.refresh();
}
- @Override
- public boolean isLiveUpdatesEnabled() {
- return liveUpdatesOnButton.isVisible();
- }
-
@UiHandler("liveUpdatesOnButton")
public void onLiveUpdatesOnButtonClicked(ClickEvent e) {
if (presenter != null)
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewImpl.ui.xml b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewImpl.ui.xml
index 9ffe82721..05d9d4bc1 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewImpl.ui.xml
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewImpl.ui.xml
@@ -15,14 +15,11 @@
margin: 0 0 1em 1em;
height: 15em;
}
- </ui:style>
- <ui:style field="attributesBrowserStyle"
- type="org.openremote.manager.client.assets.asset.AssetViewImpl.AttributesBrowserStyle">
.stringEditor {
- min-width: 5em;
- width: 100%;
- }
+ min-width: 5em;
+ width: 100%;
+ }
.numberEditor {
min-width: 5em;
@@ -39,11 +36,23 @@
.highlightAttribute {
border-left: 4px solid;
}
+
+ .metaItemValueEditor {
+
+ }
+
+ .metaItemNameEditor {
+
+ }
+
+ .agentLinkEditor {
+
+ }
</ui:style>
<w:FlexSplitPanel ui:field="splitPanel"
handleStyle="{widgetStyle.SplitPanelHandle}"
- firstPanelWidth="300"
+ firstPanelWidth="250"
firstPanelMinWidth="0"
secondPanelMinWidth="400">
@@ -167,7 +176,7 @@
</g:HTMLPanel>
- <g:FlowPanel ui:field="attributesBrowserContainer"
+ <g:FlowPanel ui:field="attributeViewContainer"
addStyleNames="flex layout vertical {widgetStyle.MainContent} {widgetStyle.FormList}"/>
</w:Form>
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AbstractAttributeViewExtension.java b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AbstractAttributeViewExtension.java
new file mode 100644
index 000000000..6e98063c4
--- /dev/null
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AbstractAttributeViewExtension.java
@@ -0,0 +1,90 @@
+/*
+ * 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.assets.attributes;
+
+import org.openremote.manager.client.Environment;
+import org.openremote.manager.client.widget.FormSection;
+import org.openremote.model.ValidationFailure;
+import org.openremote.model.ValueHolder;
+import org.openremote.model.asset.AssetAttribute;
+
+import java.util.function.Consumer;
+
+public abstract class AbstractAttributeViewExtension extends FormSection implements AttributeView {
+
+ protected Environment environment;
+ protected AssetAttribute attribute;
+ protected Consumer<AssetAttribute> attributeModifiedCallback;
+ protected ValueEditorSupplier valueEditorSupplier;
+ protected boolean editMode;
+ protected AttributeView.Style style;
+ protected AttributeView parentView;
+ protected ValidationErrorConsumer validationErrorConsumer;
+
+ public AbstractAttributeViewExtension(Environment environment, AttributeView.Style style, AttributeView parentView, AssetAttribute attribute, String label) {
+ super(label);
+ this.environment = environment;
+ this.style = style;
+ this.parentView = parentView;
+ this.attribute = attribute;
+ }
+
+ @Override
+ public AssetAttribute getAttribute() {
+ return attribute;
+ }
+
+ @Override
+ public void setAttributeModifiedCallback(Consumer<AssetAttribute> attributeModifiedCallback) {
+ this.attributeModifiedCallback = attributeModifiedCallback;
+ }
+
+ @Override
+ public void setEditMode(boolean editMode) {
+ this.editMode = editMode;
+ }
+
+ protected void notifyAttributeModified() {
+ if (attributeModifiedCallback != null) {
+ attributeModifiedCallback.accept(attribute);
+ }
+ }
+
+ @Override
+ public void setValueEditorSupplier(ValueEditorSupplier valueEditorSupplier) {
+ this.valueEditorSupplier = valueEditorSupplier;
+ }
+
+ @Override
+ public void setValidationErrorConsumer(ValidationErrorConsumer validationErrorConsumer) {
+ this.validationErrorConsumer = validationErrorConsumer;
+ }
+
+ @Override
+ public void setDisabled(boolean disabled) {
+ super.setDisabled(disabled);
+ }
+
+ 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/AttributeValidationResultMapper.java b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributeValidationResultMapper.java
new file mode 100644
index 000000000..9f58ff481
--- /dev/null
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributeValidationResultMapper.java
@@ -0,0 +1,34 @@
+/*
+ * 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.manager.client.assets.attributes;
+
+import com.github.nmorel.gwtjackson.client.ObjectMapper;
+import com.github.nmorel.gwtjackson.client.annotation.JsonMixIns;
+import org.openremote.manager.client.interop.jackson.DefaultJsonMixin;
+import org.openremote.manager.shared.http.EntityReader;
+import org.openremote.manager.shared.http.EntityWriter;
+import org.openremote.model.asset.Asset;
+import org.openremote.model.attribute.AttributeValidationResult;
+
+@JsonMixIns({@JsonMixIns.JsonMixIn(target = AttributeValidationResult.class, mixIn = DefaultJsonMixin.class)})
+public interface AttributeValidationResultMapper
+ extends ObjectMapper<AttributeValidationResult>,
+ EntityReader<AttributeValidationResult> {
+}
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
new file mode 100644
index 000000000..4fffcd777
--- /dev/null
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributeView.java
@@ -0,0 +1,113 @@
+/*
+ * 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.assets.attributes;
+
+import com.google.gwt.user.client.ui.IsWidget;
+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.ValueType;
+
+import java.util.function.Consumer;
+
+/**
+ * The presenter will deal with validating the {@link AssetAttribute}s and will notify the individual
+ * {@link AttributeView}s when the validation state changes for an attribute.
+ */
+public interface AttributeView extends IsWidget {
+
+ @FunctionalInterface
+ interface ValidationErrorConsumer {
+ void accept(String attributeName, String metaItemName, ValidationFailure validationFailure);
+ }
+
+ @FunctionalInterface
+ interface ValueEditorSupplier {
+ IsWidget createValueEditor(ValueHolder valueHolder, ValueType valueType, AttributeView.Style style, Runnable onValueModified);
+ }
+
+ interface Style {
+
+ String stringEditor();
+
+ String numberEditor();
+
+ String booleanEditor();
+
+ String regularAttribute();
+
+ String highlightAttribute();
+
+ String metaItemNameEditor();
+
+ String metaItemValueEditor();
+
+ String agentLinkEditor();
+ }
+
+ /**
+ * Get the attribute associated with this view.
+ */
+ AssetAttribute getAttribute();
+
+ /**
+ * This callback should be used by the view to notify the presenter that the attribute has been modified. Could be
+ * a value change or meta item create, update or delete.
+ */
+ void setAttributeModifiedCallback(Consumer<AssetAttribute> attributeModifiedCallback);
+
+ /**
+ * This {@link ValueEditorSupplier} should be used to get a basic value editor/viewer for a {@link ValueHolder}.
+ */
+ void setValueEditorSupplier(ValueEditorSupplier valueEditorSupplier);
+
+ /**
+ * This should be used by the view to display failure messages to the user in a standard way.
+ */
+ void setValidationErrorConsumer(ValidationErrorConsumer validationErrorConsumer);
+
+ /**
+ * Called when the validation state of the attribute changes. {@link AttributeValidationResult#isValid()} will be
+ * true when the attribute is valid.
+ */
+ void onValidationStateChange(AttributeValidationResult validationResult);
+
+ /**
+ * Called by the presenter when the attribute has changed outside of the system (i.e. it has changed on the server).
+ */
+ void onAttributeChanged();
+
+ /**
+ * Called by the presenter to indicate that some operation that affects the attribute linked to the view is pending
+ * or has finished.
+ */
+ void setBusy(boolean busy);
+
+ /**
+ * Set the view to a disabled state
+ */
+ void setDisabled(boolean disabled);
+
+ /**
+ * Indicates if current activity is edit mode or view mode.
+ */
+ void setEditMode(boolean editMode);
+}
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
new file mode 100644
index 000000000..58661973d
--- /dev/null
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributeViewImpl.java
@@ -0,0 +1,251 @@
+/*
+ * 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.assets.attributes;
+
+import com.google.gwt.user.client.ui.IsWidget;
+import com.google.gwt.user.client.ui.Label;
+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.ValueHolder;
+import org.openremote.model.asset.AssetAttribute;
+import org.openremote.model.asset.AssetMeta;
+import org.openremote.model.attribute.AttributeType;
+import org.openremote.model.attribute.AttributeValidationResult;
+import org.openremote.model.attribute.MetaItem;
+
+import java.util.List;
+import java.util.Optional;
+import java.util.function.Consumer;
+
+/**
+ * This is an implementation of {@link AttributeView} that always shows the attribute value with configurable
+ * action buttons and also supports view extensions in a collapsible panel.
+ */
+public class AttributeViewImpl extends FormGroup implements AttributeView {
+
+ protected final Environment environment;
+ protected final AttributeView.Style style;
+ protected Consumer<AssetAttribute> attributeModifiedCallback;
+ protected AssetAttribute attribute;
+ protected List<FormButton> attributeActions;
+ protected List<AbstractAttributeViewExtension> attributeExtensions;
+ protected boolean editMode;
+ protected ValueEditorSupplier valueEditorSupplier;
+ protected ValidationErrorConsumer validationErrorConsumer;
+
+ public AttributeViewImpl(Environment environment,
+ AttributeView.Style style,
+ AssetAttribute attribute) {
+ this.environment = environment;
+ this.style = style;
+ this.attribute = attribute;
+
+ addStyleName("flex-none");
+ addStyleName(environment.getWidgetStyle().FormListItem());
+
+ FormLabel formLabel = new FormLabel();
+ formLabel.addStyleName("larger");
+ setFormLabel(formLabel);
+
+ Label infoLabel = new Label();
+ addInfolabel(infoLabel);
+
+ FormField formField = new FormField();
+ setFormField(formField);
+
+ FormGroupActions formGroupActions = new FormGroupActions();
+ setFromGroupActions(formGroupActions);
+ }
+
+ public void setAttributeActions(List<FormButton> attributeActions) {
+ this.attributeActions = attributeActions;
+
+ if (attributeActions != null) {
+ for (FormButton attributeAction : attributeActions) {
+ formGroupActions.add(attributeAction);
+ }
+ }
+ }
+
+ public void setAttributeExtensions(List<AbstractAttributeViewExtension> attributeExtensions) {
+ this.attributeExtensions = attributeExtensions;
+ super.clearExtensions();
+
+ if (attributeExtensions != null && !attributeExtensions.isEmpty()) {
+ attributeExtensions.forEach(super::addExtension);
+ }
+ }
+
+ @Override
+ protected void onAttach() {
+ super.onAttach();
+ refresh();
+ }
+
+ @Override
+ public AssetAttribute getAttribute() {
+ return attribute;
+ }
+
+ public List<FormButton> getActionButtons() {
+ return attributeActions;
+ }
+
+ public List<AbstractAttributeViewExtension> getExtensions() {
+ return attributeExtensions;
+ }
+
+ @Override
+ public void setAttributeModifiedCallback(Consumer<AssetAttribute> attributeModifiedCallback) {
+ this.attributeModifiedCallback = attributeModifiedCallback;
+ }
+
+ @Override
+ public void setValueEditorSupplier(ValueEditorSupplier valueEditorSupplier) {
+ this.valueEditorSupplier = valueEditorSupplier;
+ }
+
+ @Override
+ public void setValidationErrorConsumer(ValidationErrorConsumer validationErrorConsumer) {
+ this.validationErrorConsumer = validationErrorConsumer;
+ }
+
+ @Override
+ public void onValidationStateChange(AttributeValidationResult validationResult) {
+ setError(!validationResult.isValid());
+ setErrorInExtension(validationResult.getMetaFailures() != null && validationResult.getMetaFailures().size() > 0);
+
+ // Notify extensions
+ getExtensions().forEach(viewExtension -> viewExtension.onValidationStateChange(validationResult));
+ }
+
+ @Override
+ public void onAttributeChanged() {
+ if (!editMode) {
+ getFormField().clear();
+ getFormField().add(createAttributeValueEditor());
+
+ // "Blink" the value editor so users know there might be a new value
+ addStyleName(environment.getWidgetStyle().HighlightBackground());
+ Browser.getWindow().setTimeout(() -> removeStyleName(environment.getWidgetStyle().HighlightBackground()), 250);
+
+ // Notify extensions
+ getExtensions().forEach(AttributeView::onAttributeChanged);
+ }
+ }
+
+ @Override
+ public void setBusy(boolean busy) {
+
+ }
+
+ @Override
+ public void setEditMode(boolean editMode) {
+ this.editMode = editMode;
+ }
+
+ @Override
+ public Widget asWidget() {
+ return this;
+ }
+
+ protected void notifyAttributeModified() {
+ if (attributeModifiedCallback != null) {
+ attributeModifiedCallback.accept(attribute);
+ }
+ }
+
+ protected IsWidget createAttributeValueEditor() {
+ return valueEditorSupplier.createValueEditor(attribute,
+ attribute.getType().map(AttributeType::getValueType).orElse(null),
+ style,
+ this::notifyAttributeModified);
+ }
+
+ protected String getAttributeLabel() {
+ return attribute == null ? "" : (editMode ? attribute.getName() : attribute.getLabelOrName())
+ .orElse("");
+ }
+
+ protected Optional<String> getAttributeDescription() {
+ return attribute == null ? Optional.empty() : attribute.getDescription();
+ }
+
+ protected void refresh() {
+ removeStyleName(style.highlightAttribute());
+ removeStyleName(environment.getWidgetStyle().HighlightBorder());
+ removeStyleName(style.regularAttribute());
+ removeStyleName(environment.getWidgetStyle().RegularBorder());
+ getFormLabel().setIcon(null);
+ getFormLabel().setText(null);
+ getInfoLabel().setText(null);
+ getFormField().clear();
+
+ if (attribute == null) {
+ return;
+ }
+
+ if (attribute.hasAgentLink() || attribute.isProtocolConfiguration()) {
+ addStyleName(style.highlightAttribute());
+ addStyleName(environment.getWidgetStyle().HighlightBorder());
+ } else {
+ addStyleName(style.regularAttribute());
+ addStyleName(environment.getWidgetStyle().RegularBorder());
+ }
+
+ if (attribute.isExecutable()) {
+ formLabel.setIcon("cog");
+ } else if (attribute.isProtocolConfiguration()) {
+ formLabel.setIcon("gears");
+ } else {
+ formLabel.setIcon(attribute.getType().map(AttributeType::getIcon).orElse(AttributeType.DEFAULT_ICON));
+ }
+
+ getFormLabel().setText(getAttributeLabel());
+
+ StringBuilder infoText = new StringBuilder();
+ if (attribute.isExecutable()) {
+ infoText.append(environment.getMessages().executable());
+ } else if (attribute.isProtocolConfiguration()) {
+ infoText.append(environment.getMessages().protocolConfiguration());
+ } else if (attribute.getType().isPresent()) {
+ infoText.append(environment.getMessages().attributeType(attribute.getType().get().name()));
+ }
+ getAttributeDescription()
+ .ifPresent(description -> {
+ if (infoText.length() > 0)
+ infoText.append(" - ");
+ infoText.append(description);
+ });
+
+ getInfoLabel().setText(infoText.toString());
+
+ 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/AttributesBrowser.java b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesBrowser.java
deleted file mode 100644
index 61676cc66..000000000
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesBrowser.java
+++ /dev/null
@@ -1,361 +0,0 @@
-/*
- * Copyright 2016, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.manager.client.assets.attributes;
-
-import com.google.gwt.user.client.ui.IsWidget;
-import elemental.client.Browser;
-import org.openremote.manager.client.Environment;
-import org.openremote.manager.client.datapoint.DatapointBrowser;
-import org.openremote.manager.client.simulator.Simulator;
-import org.openremote.manager.client.util.CollectionsUtil;
-import org.openremote.manager.client.widget.*;
-import org.openremote.model.Constants;
-import org.openremote.model.asset.Asset;
-import org.openremote.model.asset.AssetAttribute;
-import org.openremote.model.asset.ReadAssetAttributesEvent;
-import org.openremote.model.asset.agent.ProtocolConfiguration;
-import org.openremote.model.attribute.AttributeEvent;
-import org.openremote.model.attribute.AttributeExecuteStatus;
-import org.openremote.model.attribute.AttributeRef;
-import org.openremote.model.attribute.AttributeState;
-import org.openremote.model.datapoint.Datapoint;
-import org.openremote.model.datapoint.DatapointInterval;
-import org.openremote.model.datapoint.NumberDatapoint;
-import org.openremote.model.event.bus.EventRegistration;
-import org.openremote.model.simulator.SimulatorState;
-
-import java.util.ArrayList;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.function.Consumer;
-
-public abstract class AttributesBrowser
- extends AttributesView<AttributesBrowser.Container, AttributesBrowser.Style> {
-
- public interface Container extends AttributesView.Container<AttributesBrowser.Style> {
-
- }
-
- public interface Style extends AttributesView.Style {
-
- }
-
- final protected Asset asset;
- final protected List<FormButton> readButtons = new ArrayList<>();
- final protected List<AttributeRef> activeSimulators = new ArrayList<>();
-
- protected FormGroup liveUpdatesGroup;
- protected EventRegistration<AttributeEvent> eventRegistration;
-
- public AttributesBrowser(Environment environment, Container container, Asset asset) {
- super(environment, container, asset.getAttributesList());
- this.asset = asset;
-
- eventRegistration = environment.getEventBus().register(
- AttributeEvent.class,
- event -> {
- for (AssetAttribute assetAttribute : attributeGroups.keySet()) {
- if (assetAttribute.getReference().map(ref -> ref.equals(event.getAttributeRef())).orElse(false)) {
- assetAttribute.setValue(event.getValue().orElse(null), event.getTimestamp());
- refreshAttribute(assetAttribute);
- break;
- }
- }
- }
- );
- }
-
- @Override
- protected void sortAttributes(LinkedHashMap<AssetAttribute, FormGroup> attributeGroups) {
- // Executable commands first, then sort form groups by label text ascending
- CollectionsUtil.sortMap(attributeGroups, (o1, o2) -> {
- if (o1.getKey().isExecutable() && !o2.getKey().isExecutable()) {
- return -1;
- } else if (!o1.getKey().isExecutable() && o2.getKey().isExecutable()) {
- return 1;
- } else {
- return o1.getValue().getFormLabel().getText().compareTo(o2.getValue().getFormLabel().getText());
- }
- }
- );
- }
-
- @Override
- protected boolean isEditorReadOnly(AssetAttribute attribute) {
- return attribute.isExecutable() || super.isEditorReadOnly(attribute);
- }
-
- @Override
- public void setOpaque(boolean opaque) {
- super.setOpaque(opaque);
- liveUpdatesGroup.setOpaque(opaque);
- }
-
- @Override
- public void close() {
- super.close();
-
- if (eventRegistration != null) {
- environment.getEventBus().remove(eventRegistration);
- eventRegistration = null;
- }
-
- subscribeToLiveUpdates(false);
- }
-
- @Override
- protected void addAttributeActions(AssetAttribute attribute,
- FormGroup formGroup,
- FormField formField,
- FormGroupActions formGroupActions) {
-
- if (attribute.isExecutable()) {
- // A command is executed by writing a special value
- FormButton startButton = new FormButton();
- startButton.setEnabled(!attribute.isReadOnly());
- startButton.setText(container.getMessages().start());
- startButton.setPrimary(true);
- startButton.setIcon("play-circle");
- startButton.addClickHandler(clickEvent -> {
- attribute.setValue(AttributeExecuteStatus.REQUEST_START.asValue());
- writeAttributeValue(attribute);
- });
- formGroupActions.add(startButton);
-
- FormButton repeatButton = new FormButton();
- repeatButton.setEnabled(!attribute.isReadOnly());
- repeatButton.setText(container.getMessages().repeat());
- repeatButton.setPrimary(true);
- repeatButton.setIcon("repeat");
- repeatButton.addClickHandler(clickEvent -> {
- attribute.setValue(AttributeExecuteStatus.REQUEST_REPEATING.asValue());
- writeAttributeValue(attribute);
- });
- formGroupActions.add(repeatButton);
-
- FormButton cancelButton = new FormButton();
- cancelButton.setEnabled(!attribute.isReadOnly());
- cancelButton.setText(container.getMessages().cancel());
- cancelButton.setPrimary(true);
- cancelButton.setIcon("stop-circle");
- cancelButton.addClickHandler(clickEvent -> {
- attribute.setValue(AttributeExecuteStatus.REQUEST_CANCEL.asValue());
- writeAttributeValue(attribute);
- });
- formGroupActions.add(cancelButton);
-
- FormButton readStatusButton = new FormButton();
- readStatusButton.setText(container.getMessages().getStatus());
- readStatusButton.setIcon("cloud-download");
- readStatusButton.addClickHandler(clickEvent -> readAttributeValue(attribute));
- readButtons.add(readStatusButton);
- formGroupActions.add(readStatusButton);
-
- } else {
- // Default read/write actions
- FormButton writeValueButton = new FormButton();
- writeValueButton.setEnabled(!attribute.isReadOnly());
- writeValueButton.setText(container.getMessages().write());
- writeValueButton.setPrimary(true);
- writeValueButton.setIcon("cloud-upload");
- writeValueButton.addClickHandler(clickEvent -> writeAttributeValue(attribute));
- formGroupActions.add(writeValueButton);
-
- FormButton readValueButton = new FormButton();
- readValueButton.setText(container.getMessages().read());
- readValueButton.setIcon("cloud-download");
- readValueButton.addClickHandler(clickEvent -> readAttributeValue(attribute));
- readButtons.add(readValueButton);
- formGroupActions.add(readValueButton);
- }
- }
-
- @Override
- protected void addAttributeExtensions(AssetAttribute attribute,
- FormGroup formGroup) {
-
- boolean haveExtensions = false;
-
- IsWidget datapointBrowser = createDatapointBrowser(attribute);
- if (datapointBrowser != null) {
- FormSectionLabel sectionLabel = new FormSectionLabel(environment.getMessages().historicalData());
- formGroup.addExtension(sectionLabel);
- formGroup.addExtension(datapointBrowser);
- haveExtensions = true;
- }
-
- IsWidget simulator = createSimulator(attribute);
- if (simulator != null) {
- FormSectionLabel sectionLabel = new FormSectionLabel(environment.getMessages().simulator());
- formGroup.addExtension(sectionLabel);
- formGroup.addExtension(simulator);
- haveExtensions = true;
- }
-
-
- if (!haveExtensions) {
- formGroup.showDisabledExtensionToggle();
- }
- }
-
- /* ####################################################################### */
-
- public void subscribeToLiveUpdates(boolean enable) {
- for (FormButton readButton : readButtons) {
- readButton.setEnabled(!enable);
- }
-
- if (enable) {
-
- // Poll all values once so we have some state
- readAllAttributeValues();
-
- environment.getEventService().subscribe(
- AttributeEvent.class,
- new AttributeEvent.EntityIdFilter(asset.getId())
- );
- } else {
- environment.getEventService().unsubscribe(
- AttributeEvent.class
- );
- }
- }
-
- public void readAllAttributeValues() {
- environment.getEventService().dispatch(
- new ReadAssetAttributesEvent(asset.getId())
- );
- }
-
- protected void readAttributeValue(AssetAttribute attribute) {
- attribute.getReference().ifPresent(attributeRef ->
- environment.getEventService().dispatch(
- new ReadAssetAttributesEvent(attributeRef.getEntityId(), attributeRef.getAttributeName())
- )
- );
- }
-
- protected void writeAttributeValue(AssetAttribute attribute) {
-
- // Let the server set the timestamp by setting it to 0
- attribute.setValueTimestamp(0);
-
- if (!validateAttribute(attribute, true)) {
- return;
- }
-
- attribute
- .getReference()
- .map(attributeRef -> new AttributeState(attributeRef, attribute.getValue().orElse(null)))
- .map(attributeState -> new AttributeEvent(attributeState, attribute.getValueTimestamp().orElse(0L)))
- .ifPresent(attributeEvent -> {
- environment.getEventService().dispatch(attributeEvent);
- if (attribute.isExecutable()) {
- showSuccess(container.getMessages().commandRequestSent(attributeEvent.getAttributeName()));
- } else {
- showSuccess(container.getMessages().attributeWriteSent(attributeEvent.getAttributeName()));
- }
- });
- }
-
- protected void refreshAttribute(AssetAttribute attribute) {
-
- // Rebuild editor
- FormGroup formGroup = attributeGroups.get(attribute);
- if (formGroup == null)
- return;
- FormField formField = formGroup.getFormField();
- if (formField.getWidgetCount() > 0) {
- formField.getWidget(0).removeFromParent();
- }
- final IsWidget editor = createAttributeValueEditor(attribute, formGroup);
- formField.add(editor);
-
- // "Blink" the editor so users know there might be a new value
- formGroup.addStyleName(environment.getWidgetStyle().HighlightBackground());
- Browser.getWindow().setTimeout(() -> formGroup.removeStyleName(environment.getWidgetStyle().HighlightBackground()), 250);
-
- // Refresh extensions
- FormGroup attributeFormGroup = attributeGroups.get(attribute);
- if (attributeFormGroup != null) {
- attributeFormGroup.forExtension(widget -> {
- if (widget instanceof DatapointBrowser) {
- // Refresh charts, jump to current time so the new value is visible
- DatapointBrowser datapointBrowser = (DatapointBrowser) widget;
- datapointBrowser.refresh(System.currentTimeMillis());
- }
- });
- }
- }
-
- protected DatapointBrowser createDatapointBrowser(AssetAttribute attribute) {
- if (Datapoint.isDatapointsCapable(attribute) && attribute.isStoreDatapoints()) {
- return new DatapointBrowser(environment.getMessages(), 675, 200) {
- @Override
- protected void queryDatapoints(DatapointInterval interval,
- long timestamp,
- Consumer<NumberDatapoint[]> consumer) {
- getNumberDatapoints(attribute, interval, timestamp, consumer);
- }
- };
- }
- return null;
- }
-
- protected Simulator createSimulator(AssetAttribute attribute) {
- AttributeRef protocolConfigurationRef = attribute.getReferenceOrThrow();
- return environment.getSecurityService().isSuperUser() && ProtocolConfiguration.isProtocolConfiguration(attribute)
- ? ProtocolConfiguration.getProtocolName(attribute)
- .filter(name -> name.equals(Constants.PROTOCOL_NAMESPACE + ":simulator"))
- .map(name -> new Simulator(
- environment,
- protocolConfigurationRef
- ,
- () -> {
- activeSimulators.add(protocolConfigurationRef);
- updateSimulatorSubscription();
- },
- () -> {
- activeSimulators.remove(protocolConfigurationRef);
- updateSimulatorSubscription();
- }
- )).orElse(null) : null;
- }
-
- protected void updateSimulatorSubscription() {
- if (activeSimulators.size() > 0) {
- environment.getEventService().subscribe(
- SimulatorState.class, new SimulatorState.ConfigurationFilter(
- activeSimulators.toArray(new AttributeRef[activeSimulators.size()])
- )
- );
- } else {
- environment.getEventService().unsubscribe(SimulatorState.class);
- }
- }
-
-
- /* ####################################################################### */
-
- abstract protected void getNumberDatapoints(AssetAttribute assetAttribute,
- DatapointInterval interval,
- long timestamp,
- Consumer<NumberDatapoint[]> consumer);
-}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesEditor.java b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesEditor.java
deleted file mode 100644
index b1c3572e2..000000000
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesEditor.java
+++ /dev/null
@@ -1,499 +0,0 @@
-/*
- * Copyright 2016, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.manager.client.assets.attributes;
-
-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.widget.*;
-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.asset.AssetMeta;
-import org.openremote.model.attribute.AttributeType;
-import org.openremote.model.attribute.MetaItem;
-import org.openremote.model.util.Pair;
-import org.openremote.model.util.TextUtil;
-import org.openremote.model.value.*;
-
-import java.util.Arrays;
-import java.util.List;
-import java.util.Optional;
-import java.util.function.BiConsumer;
-import java.util.function.Consumer;
-
-import static org.openremote.manager.client.widget.ValueEditors.*;
-import static org.openremote.model.attribute.Attribute.ATTRIBUTE_NAME_VALIDATOR;
-import static org.openremote.model.attribute.Attribute.isAttributeNameEqualTo;
-import static org.openremote.model.util.TextUtil.isNullOrEmpty;
-
-public class AttributesEditor
- extends AttributesView<AttributesEditor.Container, AttributesEditor.Style> {
-
- public interface Container extends AttributesView.Container<AttributesEditor.Style> {
-
- }
-
- public interface Style extends AttributesView.Style {
- String metaItemNameEditor();
-
- String metaItemValueEditor();
- }
-
- final protected boolean isCreate;
- protected final BiConsumer<ValueHolder, Consumer<Asset[]>> assetSupplier;
- protected final BiConsumer<Pair<ValueHolder, Asset>, Consumer<AssetAttribute[]>> attributeSupplier;
- protected static final List<ValueType> valueTypes = Arrays.asList(ValueType.values());
-
- public AttributesEditor(Environment environment, Container container, List<AssetAttribute> attributes, boolean isCreate, BiConsumer<ValueHolder, Consumer<Asset[]>> assetSupplier, BiConsumer<Pair<ValueHolder, Asset>, Consumer<AssetAttribute[]>> attributeSupplier) {
- super(environment, container, attributes);
- this.isCreate = isCreate;
- this.assetSupplier = assetSupplier;
- this.attributeSupplier = attributeSupplier;
- }
-
- protected FormLabel createAttributeLabel(AssetAttribute attribute) {
- FormLabel formLabel = new FormLabel(TextUtil.ellipsize(getAttributeLabel(attribute), 30));
- formLabel.getElement().getStyle().setWidth(20, com.google.gwt.dom.client.Style.Unit.EM);
- return formLabel;
- }
-
- @Override
- protected String getAttributeLabel(AssetAttribute attribute) {
- return attribute.getName().orElse("");
- }
-
- @Override
- protected Optional<String> getAttributeDescription(AssetAttribute attribute) {
- return Optional.empty();
- }
-
- @Override
- protected void addAttributeActions(AssetAttribute attribute,
- FormGroup formGroup,
- FormField formField,
- FormGroupActions formGroupActions) {
-
- FormButton deleteButton = new FormButton();
- deleteButton.setText(container.getMessages().deleteAttribute());
- deleteButton.setIcon("remove");
- deleteButton.addClickHandler(clickEvent -> {
- removeAttribute(attribute);
- attribute.getName()
- .ifPresent(name ->
- showInfo(environment.getMessages().attributeDeleted(name))
- );
- });
- formGroupActions.add(deleteButton);
- }
-
- @Override
- protected void addAttributeExtensions(AssetAttribute attribute, FormGroup formGroup) {
- formGroup.addExtension(new MetaEditor(attribute));
- }
-
- @Override
- protected boolean isEditorReadOnly(AssetAttribute attribute) {
- return false; // Always allow editing of attribute value
- }
-
- @Override
- protected boolean isShowTimestamp(AssetAttribute attribute) {
- return false;
- }
-
- /* ####################################################################### */
-
- public boolean addAttribute(String name, AttributeType type) {
-
- if (getAttributes().stream().anyMatch(isAttributeNameEqualTo(name))) {
- showValidationError(environment, environment.getMessages().duplicateAttributeName());
- return false;
- }
-
- if (!ATTRIBUTE_NAME_VALIDATOR.test(name)) {
- showValidationError(environment, environment.getMessages().invalidAttributeName());
- return false;
- }
-
- AssetAttribute attribute = new AssetAttribute();
- attribute.setName(name);
- if (type != null) {
- attribute.setType(type);
- }
-
- // Tell the server to set the timestamp when saving because we don't want to use browser time
- attribute.setValueTimestamp(0);
-
- List<ValidationFailure> failures = attribute.getValidationFailures();
- if (!failures.isEmpty()) {
- for (ValidationFailure failure : failures) {
- showValidationError(environment, attribute.getLabelOrName().orElse(null), failure);
- }
- return false;
- }
-
- attribute.getType().ifPresent(attributeType ->
- attribute.addMeta(attributeType.getDefaultMetaItems())
- );
- getAttributes().add(attribute);
-
- showInfo(environment.getMessages().attributeAdded(name));
-
- build();
-
- return true;
- }
-
- /* ####################################################################### */
-
- public class MetaEditor extends FlowPanel {
-
- final protected AssetAttribute attribute;
- final protected FormSectionLabel itemListSectionLabel = new FormSectionLabel(environment.getMessages().metaItems());
- final protected FlowPanel itemListPanel = new FlowPanel();
- final protected FormSectionLabel itemEditorSectionLabel = new FormSectionLabel(environment.getMessages().newItem());
- final protected FlowPanel itemEditorPanel = new FlowPanel();
-
- public MetaEditor(AssetAttribute attribute) {
- this.attribute = attribute;
- add(itemListSectionLabel);
- add(itemListPanel);
- buildItemList();
-
- add(itemEditorSectionLabel);
- add(itemEditorPanel);
- buildNewItemEditor();
- }
-
- protected void buildItemList() {
- itemListPanel.clear();
-
- if (attribute.getMeta().isEmpty()) {
- itemListSectionLabel.setVisible(false);
- return;
- }
- itemListSectionLabel.setVisible(true);
-
- List<MetaItem> items = attribute.getMeta();
- for (int i = 0; i < items.size(); i++) {
- MetaItem item = items.get(i);
- MetaItemEditor metaItemEditor = new MetaItemEditor(this, item, false);
- itemListPanel.add(metaItemEditor);
- }
- }
-
- protected void addItem(MetaItem item) {
- attribute.getMeta().add(item);
- MetaItemEditor metaItemEditor = new MetaItemEditor(this, item, false);
- itemListPanel.add(metaItemEditor);
- }
-
- protected void removeItem(MetaItemEditor itemEditor) {
- int index = itemListPanel.getWidgetIndex(itemEditor);
- itemListPanel.remove(itemEditor);
- attributeGroups.get(attribute).setErrorInExtension(false);
- attribute.getMeta().remove(index);
- }
-
- protected void buildNewItemEditor() {
- MetaItem item = new MetaItem();
- MetaItemEditor metaItemEditor = new MetaItemEditor(this, item, true);
- itemEditorPanel.add(metaItemEditor);
- }
- }
-
- public class MetaItemEditor extends FormGroup {
- protected MetaEditor parentEditor;
- protected MetaItem item;
- protected FormField field;
- protected FormListBox nameList;
- protected FormListBox typeList;
- protected FormInputText nameInput;
- protected FormGroupActions formGroupActions;
- protected IsWidget valueEditor;
- protected boolean isNewItem;
-
- public MetaItemEditor(MetaEditor parentEditor, MetaItem item, boolean isNewItem) {
- this.parentEditor = parentEditor;
- this.item = item;
- this.isNewItem = isNewItem;
- boolean isSuperUser = environment.getSecurityService().isSuperUser();
- Optional<AssetMeta> currentWellknown = item.getName().flatMap(AssetMeta::getAssetMeta);
- field = new FormField();
- this.addFormField(field);
-
- nameList = new FormListBox();
- field.add(nameList);
- nameList.addItem(environment.getMessages().customItem(), "");
- AssetMeta[] availableMeta = isSuperUser ? AssetMeta.values() : AssetMeta.unRestricted();
- int selectedNameIndex = 0;
-
- for (int i=0; i<availableMeta.length; i++) {
- AssetMeta wellknown = availableMeta[i];
- nameList.addItem(environment.getMessages().assetMetaDisplayName(wellknown.name()), wellknown.getUrn());
- if (currentWellknown.map(current -> current.getUrn().equals(wellknown.getUrn())).orElse(false)) {
- selectedNameIndex = i+1;
- }
- }
-
- nameList.addChangeHandler(event -> {
- onNameChanged(true);
- });
-
- nameInput = new FormInputText();
- field.add(nameInput);
- nameInput.addStyleName(container.getStyle().metaItemNameEditor());
- nameInput.setPlaceholder(environment.getMessages().enterCustomAssetAttributeMetaName());
- nameInput.addKeyUpHandler(event -> {
- if (isNullOrEmpty(nameInput.getValue())) {
- item.clearName();
- } else {
- item.setName(nameInput.getValue());
- }
- onValidation(item.getValidationFailures());
- });
- nameInput.addValueChangeHandler(event -> {
- if (isNullOrEmpty(event.getValue())) {
- item.clearName();
- } else {
- item.setName(event.getValue());
- }
- onValidation(item.getValidationFailures());
- });
-
- typeList = new FormListBox();
- field.add(typeList);
- typeList.addItem(environment.getMessages().selectType(), "");
- int selectedTypeIndex = 0;
- ValueType currentValueType = currentWellknown.map(AssetMeta::getValueType).orElse(item.getValue().map(Value::getType).orElse(null));
- for (int i=0; i<valueTypes.size(); i++) {
- ValueType valueType = valueTypes.get(i);
- typeList.addItem(environment.getMessages().valueTypeDisplayName(valueType.name()), valueType.name());
- if (currentValueType == valueType) {
- selectedTypeIndex = i+1;
- }
- }
-
- typeList.addChangeHandler(event -> {
- onTypeChanged(true);
- });
-
- formGroupActions = new FormGroupActions();
- FormButton button = new FormButton();
- button.setText(isNewItem ? container.getMessages().addItem() : container.getMessages().deleteItem());
- button.setIcon(isNewItem ? "plus" : "remove");
- button.addClickHandler(clickEvent -> {
- if (isNewItem) {
- // We ask the attribute for validation failures instead of the
- // item, because the item must be valid in its context
- List<ValidationFailure> failures = parentEditor.attribute.getMetaItemValidationFailures(item);
-
- if (failures.isEmpty()) {
- parentEditor.addItem(item.copy());
- this.setError(false);
- reset();
- } else {
- this.setError(true);
- for (ValidationFailure failure : failures) {
- showValidationError(environment, item.getName().orElse(null), failure);
- }
- }
- } else {
- parentEditor.removeItem(this);
- }
- });
- formGroupActions.add(button);
- this.addFormGroupActions(formGroupActions);
-
- nameList.setSelectedIndex(selectedNameIndex);
- nameInput.setValue(item.getName().orElse(null));
- typeList.setSelectedIndex(selectedTypeIndex);
- onNameChanged(false);
- }
-
- protected IsWidget createItemValueEditor() {
- // Determine editor based on name then value type
- Optional<AssetMeta> assetMeta = AssetMeta.getAssetMeta(item.getName().orElse(null));
- AttributesEditor.Style style = container.getStyle();
- ValueType valueType = valueTypes.get(typeList.getSelectedIndex()-1);
-
- // Super users can edit any meta items but other users can only edit non-restricted meta items
- // Individual instances of meta items can be set to restricted by a super user.
- boolean isEditable = environment.getSecurityService().isSuperUser() ||
- (item.hasRestrictedFlag() && !item.isRestricted()) ||
- assetMeta.map(AssetMeta::isRestricted).orElse(true);
-
- switch(valueType) {
- case OBJECT:
- ObjectValue valueObj = item.getValueAsObject().orElse(null);
- String label = environment.getMessages().jsonObject();
- String title = environment.getMessages().edit() + " " + environment.getMessages().jsonObject();
- return createObjectEditor(
- item, valueObj, false, label, title, container.getJsonEditor(), this, false, this::onValidation
- );
- case ARRAY:
- if (assetMeta.map(am -> am == AssetMeta.AGENT_LINK).orElse(false)) {
- String assetWatermark = environment.getMessages().selectAgent();
- String attributeWatermark = environment.getMessages().selectProtocolConfiguration();
- return createAttributeRefEditor(item, false, this, assetSupplier, attributeSupplier, assetWatermark, attributeWatermark, this::onValidation);
- }
-
- ArrayValue valueArray = item.getValueAsArray().orElse(null);
- label = environment.getMessages().jsonArray();
- title = environment.getMessages().edit() + " " + environment.getMessages().jsonArray();
- return createArrayEditor(
- item, valueArray, false, label, title, container.getJsonEditor(), this, false, this::onValidation
- );
- case STRING:
- String valueStr = item.getValue().map(Object::toString).orElse(null);
- return createStringEditor(
- item, valueStr, false, style.stringEditor(), this, false, this::onValidation
- );
- case NUMBER:
- valueStr = item.getValue().map(Object::toString).orElse(null);
- return createNumberEditor(
- item, valueStr, false, style.numberEditor(), this, false, this::onValidation
- );
- case BOOLEAN:
- Boolean valueBool = item.getValueAsBoolean().orElse(null);
- return createBooleanEditor(
- item, valueBool, false, style.booleanEditor(), this, false, this::onValidation
- );
- default:
- return new FormOutputText(
- environment.getMessages().unsupportedMetaItemType(valueType.name())
- );
- }
- }
-
- protected void onValidation(List<ValidationFailure> failures) {
- // If we are not creating a new meta item, validate again in context of attribute
- if (!isNewItem && failures.isEmpty()) {
- failures = parentEditor.attribute.getMetaItemValidationFailures(item);
- }
- if (!failures.isEmpty()) {
- this.setError(true);
- if (isNewItem) {
- formGroupActions.forEach(widget -> {
- if (widget instanceof FormButton) {
- ((FormButton) widget).setEnabled(false);
- }
- });
- }
- for (ValidationFailure failure : failures) {
- showValidationError(environment, item.getName().orElse(null), failure);
- }
- } else {
- this.setError(false);
- if (isNewItem) {
- formGroupActions.forEach(widget -> {
- if (widget instanceof FormButton) {
- ((FormButton) widget).setEnabled(true);
- }
- });
- }
- }
- // Validation failure of meta item marks the attribute form extension as error state
- if (!isNewItem) {
- FormGroup formGroup = attributeGroups.get(parentEditor.attribute);
- if (formGroup != null) {
- formGroup.setErrorInExtension(!failures.isEmpty());
- }
- }
- }
-
- protected void onNameChanged(boolean updateItem) {
- if (updateItem && nameList.getSelectedIndex() == 0) {
- nameInput.setValue(null);
- }
-
- String urn = nameList.getSelectedIndex() > 0 ? nameList.getSelectedValue() : nameInput.getValue();
-
- if (updateItem) {
- item.clearValue();
- if (isNullOrEmpty(urn)) {
- item.clearName();
- } else {
- item.setName(urn);
- }
- }
-
- nameInput.setValue(urn);
-
- if (nameList.getSelectedIndex() > 0) {
- nameInput.setVisible(false);
- typeList.setVisible(false);
- @SuppressWarnings("ConstantConditions")
- AssetMeta assetMeta = AssetMeta.getAssetMeta(nameList.getSelectedValue()).get();
- typeList.setSelectedIndex(valueTypes.indexOf(assetMeta.getValueType()) + 1);
- } else {
- nameInput.setVisible(true);
- typeList.setSelectedIndex(
- item.getValue()
- .map(Value::getType)
- .map(valueType -> valueTypes.indexOf(valueType) + 1)
- .orElse(0)
- );
- typeList.setVisible(true);
- }
-
- onTypeChanged(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 = typeList.getSelectedIndex() > 0 ? valueTypes.get(typeList.getSelectedIndex()-1) : null;
- if (valueType == ValueType.BOOLEAN && initialValue == null) {
- initialValue = Values.create(false);
- }
-
- item.setValue(initialValue);
- onValidation(item.getValidationFailures());
- }
- updateValueEditor(assetMeta.map(AssetMeta::isValueFixed).orElse(false));
- }
-
- protected void updateValueEditor(boolean hideEditor) {
- if (valueEditor != null) {
- field.remove(valueEditor);
- }
-
- if (!hideEditor && typeList.getSelectedIndex() > 0) {
- valueEditor = createItemValueEditor();
- field.add(valueEditor);
- }
- }
-
- protected void reset() {
- item.clearName();
- item.clearValue();
- nameList.setSelectedIndex(0);
- nameInput.setValue(null);
- typeList.setSelectedIndex(0);
- onNameChanged(false);
- }
- }
-}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesView.java b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesView.java
deleted file mode 100644
index 401789428..000000000
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesView.java
+++ /dev/null
@@ -1,353 +0,0 @@
-/*
- * Copyright 2016, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.manager.client.assets.attributes;
-
-import com.google.gwt.user.client.ui.*;
-import org.openremote.manager.client.Environment;
-import org.openremote.manager.client.app.dialog.JsonEditor;
-import org.openremote.manager.client.event.ShowFailureEvent;
-import org.openremote.manager.client.event.ShowInfoEvent;
-import org.openremote.manager.client.event.ShowSuccessEvent;
-import org.openremote.manager.client.i18n.ManagerMessages;
-import org.openremote.manager.client.util.CollectionsUtil;
-import org.openremote.manager.client.widget.*;
-import org.openremote.model.AbstractValueHolder;
-import org.openremote.model.ValidationFailure;
-import org.openremote.model.asset.AssetAttribute;
-import org.openremote.model.asset.AssetMeta;
-import org.openremote.model.attribute.AttributeType;
-import org.openremote.model.attribute.MetaItem;
-import org.openremote.model.util.TextUtil;
-import org.openremote.model.value.*;
-
-import java.util.*;
-import java.util.function.Consumer;
-import java.util.function.Supplier;
-import java.util.logging.Logger;
-
-import static org.openremote.manager.client.widget.ValueEditors.*;
-
-public abstract class AttributesView<
- C extends AttributesView.Container<S>,
- S extends AttributesView.Style
- > {
-
- private static final Logger LOG = Logger.getLogger(AttributesView.class.getName());
-
- public interface Container<S extends AttributesView.Style> {
- S getStyle();
-
- InsertPanel getPanel();
-
- JsonEditor getJsonEditor();
-
- ManagerMessages getMessages();
- }
-
- public interface Style {
-
- String stringEditor();
-
- String numberEditor();
-
- String booleanEditor();
-
- String regularAttribute();
-
- String highlightAttribute();
- }
-
- final protected Environment environment;
- final protected C container;
- final protected List<AssetAttribute> attributes;
- final protected LinkedHashMap<AssetAttribute, FormGroup> attributeGroups = new LinkedHashMap<>();
-
- public AttributesView(Environment environment, C container, List<AssetAttribute> attributes) {
- this.environment = environment;
- this.container = container;
- this.attributes = attributes;
- }
-
- public List<AssetAttribute> getAttributes() {
- return attributes;
- }
-
- public void clear() {
- while (container.getPanel().getWidgetCount() > 0) {
- container.getPanel().remove(0);
- }
- attributeGroups.clear();
- }
-
- public void build() {
- clear();
- createAttributeGroups();
- }
-
- public void setOpaque(boolean opaque) {
- for (FormGroup formGroup : attributeGroups.values()) {
- formGroup.setOpaque(opaque);
- }
- }
-
- public boolean validateAttributes() {
- boolean isValid = true;
- for (AssetAttribute attribute : attributes) {
- if (!validateAttribute(attribute, false))
- isValid = false;
- }
- if (!isValid) {
- showValidationError(environment, environment.getMessages().invalidAssetAttributes());
- }
- return isValid;
- }
-
- public boolean validateAttribute(AssetAttribute attribute, boolean showValidationFailureMessage) {
- // If there is already an error displayed, don't do other validation
- FormGroup formGroup = attributeGroups.get(attribute);
- if (formGroup.isError()) {
- return false;
- }
-
- List<ValidationFailure> failures = attribute.getValidationFailures();
- if (!failures.isEmpty()) {
- LOG.fine("Invalid " + attribute + ": " + failures);
- attributeGroups.get(attribute).setError(true);
- if (showValidationFailureMessage) {
- for (ValidationFailure failure : failures) {
- showValidationError(environment, attribute.getLabelOrName().orElse(null), failure);
- }
- }
- return false;
- }
- return true;
- }
-
- public void close() {
- // Subclasses can manage lifecycle
- }
-
- /* ####################################################################### */
-
- protected void addAttributeActions(AssetAttribute attribute,
- FormGroup formGroup,
- FormField formField,
- FormGroupActions formGroupActions) {
- }
-
- protected void addAttributeExtensions(AssetAttribute attribute,
- FormGroup formGroup) {
- }
-
- /* ####################################################################### */
-
- protected void createAttributeGroups() {
- for (AssetAttribute attribute : attributes) {
- FormGroup formGroup = createAttributeGroup(attribute);
- if (formGroup != null) {
- attributeGroups.put(attribute, formGroup);
- }
- }
-
- sortAttributes(attributeGroups);
-
- if (attributeGroups.size() == 0) {
- Label emptyLabel = new Label(environment.getMessages().noAttributes());
- emptyLabel.addStyleName(environment.getWidgetStyle().FormListEmptyMessage());
- container.getPanel().add(emptyLabel);
- } else {
- for (FormGroup attributeGroup : attributeGroups.values()) {
- container.getPanel().add(attributeGroup);
- }
- }
- }
-
- protected FormGroup createAttributeGroup(AssetAttribute attribute) {
- FormGroup formGroup = new FormGroup();
-
- formGroup.addStyleName("flex-none");
- formGroup.addStyleName(environment.getWidgetStyle().FormListItem());
-
- if (attribute.hasAgentLink() || attribute.isProtocolConfiguration()) {
- formGroup.addStyleName(container.getStyle().highlightAttribute());
- formGroup.addStyleName(environment.getWidgetStyle().HighlightBorder());
- } else {
- formGroup.addStyleName(container.getStyle().regularAttribute());
- formGroup.addStyleName(environment.getWidgetStyle().RegularBorder());
- }
-
- FormLabel formLabel = createAttributeLabel(attribute);
- if (attribute.isExecutable()) {
- formLabel.setIcon("cog");
- } else if (attribute.isProtocolConfiguration()) {
- formLabel.setIcon("gears");
- } else {
- formLabel.setIcon(attribute.getType().map(AttributeType::getIcon).orElse(AttributeType.DEFAULT_ICON));
- }
- formGroup.addFormLabel(formLabel);
-
- StringBuilder infoText = new StringBuilder();
- if (attribute.isExecutable()) {
- infoText.append(environment.getMessages().executable());
- } else if (attribute.isProtocolConfiguration()) {
- infoText.append(environment.getMessages().protocolConfiguration());
- } else if (attribute.getType().isPresent()) {
- infoText.append(environment.getMessages().attributeType(attribute.getType().get().name()));
- }
- getAttributeDescription(attribute)
- .ifPresent(description -> {
- if (infoText.length() > 0)
- infoText.append(" - ");
- infoText.append(description);
- });
- if (infoText.length() > 0) {
- formGroup.addInfolabel(new Label(infoText.toString()));
- }
-
- FormGroupActions formGroupActions = new FormGroupActions();
-
- FormField formField = new FormField();
- formField.add(createAttributeValueEditor(attribute, formGroup));
-
- addAttributeActions(attribute, formGroup, formField, formGroupActions);
-
- formGroup.addFormField(formField);
- formGroup.addFormGroupActions(formGroupActions);
-
- addAttributeExtensions(attribute, formGroup);
-
- return formGroup;
- }
-
- protected FormLabel createAttributeLabel(AssetAttribute attribute) {
- FormLabel formLabel = new FormLabel(TextUtil.ellipsize(getAttributeLabel(attribute), 100));
- formLabel.addStyleName("larger");
- return formLabel;
- }
-
- protected String getAttributeLabel(AssetAttribute attribute) {
- return attribute
- .getLabel()
- .orElse(attribute.getName().orElse(""));
- }
-
- protected Optional<String> getAttributeDescription(AssetAttribute attribute) {
- return attribute.getDescription();
- }
-
- protected IsWidget createAttributeValueEditor(AssetAttribute attribute, FormGroup formGroup) {
- S style = container.getStyle();
-
- AttributeType attributeType = attribute.getType().orElse(null);
- if (attributeType == null)
- return null;
-
- boolean readOnly = isEditorReadOnly(attribute);
- boolean showTimestamp = isShowTimestamp(attribute);
-
- Consumer<List<ValidationFailure>> validationResultConsumer = failures -> {
- for (ValidationFailure failure : failures) {
- showValidationError(environment, attribute.getLabelOrName().orElse(null), failure);
- }
- };
-
- IsWidget editor;
- if (attributeType == AttributeType.STRING || attributeType.getValueType() == ValueType.STRING) {
- String currentValue = attribute.getValue().map(Object::toString).orElse(null);
- editor = createStringEditor(
- attribute, currentValue, readOnly, style.stringEditor(), formGroup, showTimestamp, validationResultConsumer
- );
- } else if (attributeType == AttributeType.NUMBER || attributeType.getValueType() == ValueType.NUMBER) {
- String currentValue = attribute.getValue().map(Object::toString).orElse(null);
- editor = createNumberEditor(
- attribute, currentValue, readOnly, style.numberEditor(), formGroup, showTimestamp, validationResultConsumer
- );
- } else if (attributeType == AttributeType.BOOLEAN || attributeType.getValueType() == ValueType.BOOLEAN) {
- Boolean currentValue = attribute.getValueAsBoolean().orElse(null);
- editor = createBooleanEditor(
- attribute, currentValue, readOnly, style.booleanEditor(), formGroup, showTimestamp, validationResultConsumer
- );
- } else if (attributeType == AttributeType.OBJECT || attributeType.getValueType() == ValueType.OBJECT) {
- ObjectValue currentValue = attribute.getValue().flatMap(Values::getObject).orElse(null);
- String label = environment.getMessages().jsonObject();
- String title = !readOnly
- ? environment.getMessages().edit() + " " + environment.getMessages().jsonObject()
- : environment.getMessages().jsonObject();
-
- editor = createObjectEditor(
- attribute, currentValue, readOnly, label, title, container.getJsonEditor(), formGroup, showTimestamp, validationResultConsumer
- );
- } else if (attributeType == AttributeType.ARRAY || attributeType.getValueType() == ValueType.ARRAY) {
- ArrayValue currentValue = attribute.getValue().flatMap(Values::getArray).orElse(null);
- String label = environment.getMessages().jsonArray();
- String title = !readOnly
- ? environment.getMessages().edit() + " " + environment.getMessages().jsonArray()
- : environment.getMessages().jsonArray();
- editor = createArrayEditor(
- attribute, currentValue, readOnly, label, title, container.getJsonEditor(), formGroup, showTimestamp, validationResultConsumer
- );
- } else {
- editor = new FormOutputText(
- environment.getMessages().unsupportedAttributeType(
- attribute.getType().map(AttributeType::name).orElse(null)
- )
- );
- }
- return editor;
- }
-
- protected boolean isEditorReadOnly(AssetAttribute attribute) {
- return attribute.isReadOnly();
- }
-
- protected boolean isShowTimestamp(AssetAttribute attribute) {
- return true;
- }
-
- protected void sortAttributes(LinkedHashMap<AssetAttribute, FormGroup> attributeGroups) {
- // Sort form groups by label text ascending
- CollectionsUtil.sortMap(attributeGroups, Comparator.comparing(
- entry -> entry.getValue().getFormLabel().getText())
- );
- }
-
- protected void removeAttribute(AssetAttribute attribute) {
- attributes.remove(attribute);
-
- int attributeGroupIndex = container.getPanel().getWidgetIndex(attributeGroups.get(attribute));
- container.getPanel().remove(attributeGroupIndex);
- attributeGroups.remove(attribute);
-
- if (attributeGroups.size() == 0) {
- Label emptyLabel = new Label(environment.getMessages().noAttributes());
- emptyLabel.addStyleName(environment.getWidgetStyle().FormListEmptyMessage());
- container.getPanel().add(emptyLabel);
- }
- }
-
- protected void showInfo(String text) {
- environment.getEventBus().dispatch(new ShowInfoEvent(text));
- }
-
- protected void showSuccess(String text) {
- environment.getEventBus().dispatch(new ShowSuccessEvent(text));
- }
-
-}
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
new file mode 100644
index 000000000..360c2ec55
--- /dev/null
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/MetaEditor.java
@@ -0,0 +1,544 @@
+/*
+ * 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.assets.attributes;
+
+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.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;
+import org.openremote.model.asset.agent.ProtocolDescriptor;
+import org.openremote.model.attribute.AttributeValidationResult;
+import org.openremote.model.attribute.MetaItem;
+import org.openremote.model.attribute.MetaItemDescriptor;
+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 org.openremote.model.value.Values;
+
+import java.util.*;
+import java.util.function.Supplier;
+
+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 {
+
+ public class MetaItemEditor extends FormGroup {
+ protected MetaEditor parentEditor;
+ protected MetaItem item;
+ protected FormField field;
+ protected FormListBox nameList;
+ protected FormListBox typeList;
+ protected FormInputText nameInput;
+ protected FormGroupActions formGroupActions;
+ protected IsWidget valueEditor;
+ protected boolean isNewItem;
+ protected MetaItemDescriptor currentDescriptor;
+
+ public MetaItemEditor(MetaEditor parentEditor, MetaItem item, boolean isNewItem) {
+ this.parentEditor = parentEditor;
+ this.item = item;
+ this.isNewItem = isNewItem;
+ field = new FormField();
+ this.setFormField(field);
+
+ // Don't show protocol configuration item in main section
+ if (!isNewItem && item.getName()
+ .map(name -> AssetMeta.PROTOCOL_CONFIGURATION.getUrn().equals(name))
+ .orElse(false)) {
+ setVisible(false);
+ }
+
+ nameList = new FormListBox();
+ field.add(nameList);
+
+ final int[] currentIndex = {0};
+ final int[] selectedIndex = {0};
+ final MetaItemDescriptor[] currentMetaItemDescriptor = {null};
+
+ nameList.addItem(environment.getMessages().customItem(), "");
+
+ Arrays.stream(metaItemDescriptors)
+ .forEach(metaItemDescriptor -> {
+ String name = getMetaItemDisplayName(environment, metaItemDescriptor.name());
+ nameList.addItem(name, metaItemDescriptor.getUrn());
+
+ if (item.getName().map(n -> n.equals(metaItemDescriptor.getUrn())).orElse(false)) {
+ currentMetaItemDescriptor[0] = metaItemDescriptor;
+ selectedIndex[0] = currentIndex[0] + 1;
+ }
+ currentIndex[0]++;
+ });
+
+ nameList.setSelectedIndex(selectedIndex[0]);
+ nameList.addChangeHandler(event -> onNameChanged(true));
+
+ nameInput = new FormInputText();
+ field.add(nameInput);
+ nameInput.addStyleName(style.metaItemNameEditor());
+ nameInput.setPlaceholder(environment.getMessages().enterCustomAssetAttributeMetaName());
+ nameInput.addKeyUpHandler(event -> {
+ if (isNullOrEmpty(nameInput.getValue())) {
+ item.clearName();
+ } else {
+ item.setName(nameInput.getValue());
+ }
+ notifyAttributeModified();
+ notifyAttributeModified();
+ });
+ nameInput.addValueChangeHandler(event -> {
+ if (isNullOrEmpty(event.getValue())) {
+ item.clearName();
+ } else {
+ item.setName(event.getValue());
+ }
+ notifyAttributeModified();
+ });
+
+ 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))
+ .forEach(typeEntry -> typeList.addItem(typeEntry.key, typeEntry.value));
+
+ typeList.addChangeHandler(event -> onTypeChanged(true));
+
+ formGroupActions = new FormGroupActions();
+ FormButton button = new FormButton();
+ button.setText(isNewItem ? environment.getMessages().addItem() : environment.getMessages().deleteItem());
+ button.setIcon(isNewItem ? "plus" : "remove");
+ button.addClickHandler(clickEvent -> {
+ if (isNewItem) {
+ if (parentEditor.addItem(item.copy(), false)) {
+ reset();
+ }
+ } else {
+ parentEditor.removeItem(this);
+ }
+ });
+
+ formGroupActions.add(button);
+ this.setFromGroupActions(formGroupActions);
+ nameInput.setValue(item.getName().orElse(null));
+ onNameChanged(false);
+ }
+
+ protected IsWidget createItemValueEditor() {
+ return valueEditorSupplier.createValueEditor(item,
+ valueTypes.get(typeList.getSelectedIndex()-1),
+ style,
+ this::onModified);
+ }
+
+ protected void onNameChanged(boolean updateItem) {
+ if (updateItem) {
+ nameInput.setValue(nameList.getSelectedValue());
+ }
+
+ String urn = nameInput.getValue().trim();
+ Optional<MetaItemDescriptor> currentMetaItemDescriptor = Arrays.stream(metaItemDescriptors)
+ .filter(metaItemDescriptor -> metaItemDescriptor.getUrn().equals(urn))
+ .findFirst();
+
+ this.currentDescriptor = currentMetaItemDescriptor.orElse(null);
+
+ int typeIndex = currentMetaItemDescriptor
+ .map(MetaItemDescriptor::getValueType)
+ .map(valueType -> valueTypes.indexOf(valueType) + 1)
+ .orElseGet(() ->
+ item.getValue()
+ .map(Value::getType)
+ .map(valueType -> valueTypes.indexOf(valueType) + 1)
+ .orElse(1)
+ );
+
+ if (updateItem) {
+ item.clearValue();
+ if (isNullOrEmpty(urn)) {
+ item.clearName();
+ } else {
+ item.setName(urn);
+ }
+ }
+
+ nameInput.setVisible(!currentMetaItemDescriptor.isPresent());
+ typeList.setVisible(!currentMetaItemDescriptor.isPresent());
+ typeList.setSelectedIndex(typeIndex);
+ onTypeChanged(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() {
+ if (valueEditor != null) {
+ field.remove(valueEditor);
+ }
+
+ if (typeList.getSelectedIndex() > 0) {
+ valueEditor = createItemValueEditor();
+ 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();
+ }
+ }
+
+ protected void reset() {
+ item.clearName();
+ item.clearValue();
+ nameList.setSelectedIndex(0);
+ nameInput.setValue(null);
+ typeList.setSelectedIndex(0);
+ onNameChanged(false);
+ }
+ }
+
+ protected static final List<ValueType> valueTypes = Arrays.asList(ValueType.values());
+ protected final AssetAttribute attribute;
+ final protected FlowPanel itemListPanel = new FlowPanel();
+ final protected FlowPanel itemEditorPanel = new FlowPanel();
+ final protected FormSectionLabel itemEditorSectionLabel;
+ protected MetaItemDescriptor[] metaItemDescriptors;
+ 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());
+ this.attribute = attribute;
+ this.style = style;
+ isProtocolConfiguration = attribute.hasMetaItem(AssetMeta.PROTOCOL_CONFIGURATION);
+ List<MetaItemDescriptor> metaItemDescriptors = new ArrayList<>();
+
+ if (isProtocolConfiguration) {
+ protocolDescriptorSupplier.get()
+ .stream()
+ .filter(protocolDescriptor -> protocolDescriptor
+ .getName()
+ .equals(attribute.getValueAsString().orElse(null)))
+ .findFirst()
+ .ifPresent(protocolDescriptor -> {
+ if (protocolDescriptor.getProtocolConfigurationMetaItems() != null) {
+ metaItemDescriptors.addAll(protocolDescriptor.getProtocolConfigurationMetaItems());
+ }
+ });
+ } else {
+ if (AgentLink.hasAgentLink(attribute)) {
+ protocolDescriptorSupplier.get()
+ .forEach(protocolDescriptor -> {
+ if (protocolDescriptor.getLinkedAttributeMetaItems() != null) {
+ protocolDescriptor.getLinkedAttributeMetaItems().forEach(newDescriptor -> {
+ if (metaItemDescriptors.stream().noneMatch(md -> md.getUrn().equals(newDescriptor.getUrn()))) {
+ metaItemDescriptors.add(newDescriptor);
+ }
+ });
+ }
+ });
+ }
+ }
+
+ metaItemDescriptors.addAll(
+ Arrays.asList(environment.getSecurityService().isSuperUser() ? AssetMeta.values() : AssetMeta.unRestricted())
+ );
+
+ this.metaItemDescriptors = metaItemDescriptors.stream()
+ .filter(metaItemDescriptor -> {
+ // Always add protocol configuration using protocol from attribute drop down
+ return metaItemDescriptor != AssetMeta.PROTOCOL_CONFIGURATION &&
+ // Agent link shouldn't be allowed on protocol configurations
+ (!isProtocolConfiguration || metaItemDescriptor != AssetMeta.AGENT_LINK);
+ })
+ .sorted(Comparator.comparing(MetaItemDescriptor::name))
+ .toArray(MetaItemDescriptor[]::new);
+
+ itemEditorSectionLabel = new FormSectionLabel(environment.getMessages().newItem());
+ add(itemListPanel);
+ add(itemEditorSectionLabel);
+ add(itemEditorPanel);
+ }
+
+ @Override
+ protected void onAttach() {
+ super.onAttach();
+ buildItemList();
+ buildNewItemEditor();
+ }
+
+ protected void buildItemList() {
+ itemListPanel.clear();
+
+ List<MetaItem> items = attribute.getMeta();
+ for (MetaItem item : items) {
+ addItem(item, true);
+ }
+ }
+
+ protected void buildNewItemEditor() {
+ itemEditorPanel.clear();
+ MetaItem item = new MetaItem();
+ MetaItemEditor metaItemEditor = new MetaItemEditor(this, item, true);
+ itemEditorPanel.add(metaItemEditor);
+ }
+
+ protected boolean addItem(MetaItem item, boolean viewOnly) {
+
+ if (!viewOnly) {
+ MetaItemDescriptor[] descriptor = new MetaItemDescriptor[1];
+
+ // Check item can be added
+ boolean canAdd = Arrays.stream(metaItemDescriptors)
+ .filter(metaItemDescriptor -> metaItemDescriptor.getUrn().equals(item.getName().orElse(null)))
+ .findFirst()
+ .map(metaItemDescriptor -> {
+ descriptor[0] = metaItemDescriptor;
+ return metaItemDescriptor.getMaxPerAttribute();
+ })
+ .map(maxCount -> attribute
+ .getMeta()
+ .stream()
+ .filter(metaItem -> metaItem
+ .getName()
+ .map(name -> name.equals(item.getName().orElse(null)))
+ .orElse(false))
+ .count() < maxCount)
+ .orElse(true);
+
+ if (!canAdd) {
+ showValidationError(attribute.getName().orElse(""), null, new ValidationFailure(MetaItem.MetaItemFailureReason.META_ITEM_DUPLICATION, getMetaItemDisplayName(environment, descriptor[0].name())));
+ return false;
+ }
+
+ attribute.getMeta().add(item);
+
+ // Notify the presenter that the attribute has changed
+ notifyAttributeModified();
+ }
+
+ int index = itemListPanel.getWidgetCount();
+ MetaItemEditor metaItemEditor = new MetaItemEditor(this, item, false);
+ itemListPanel.add(metaItemEditor);
+
+ // Check if we have a validation failure for this editor
+ if (lastValidationResult != null && lastValidationResult.getMetaFailures() != null) {
+ List<ValidationFailure> failures = lastValidationResult.getMetaFailures().get(index);
+ if (failures != null && !failures.isEmpty()) {
+ metaItemEditor.setError(true);
+ }
+ }
+ return true;
+ }
+
+ protected void removeItem(MetaItemEditor itemEditor) {
+ int index = itemListPanel.getWidgetIndex(itemEditor);
+ itemListPanel.remove(itemEditor);
+ attribute.getMeta().remove(index);
+
+ // Notify the presenter that the attribute has changed
+ notifyAttributeModified();
+ }
+
+ @Override
+ public void onValidationStateChange(AttributeValidationResult validationResult) {
+ 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);
+ }
+
+ 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("")
+ )
+ )
+ );
+ }
+ }
+ }
+ }
+
+ protected void updateEditorFailures(MetaItemEditor editor, List<ValidationFailure> failures) {
+ boolean hasFailures = failures != null && !failures.isEmpty();
+ editor.setError(hasFailures);
+
+ if (hasFailures) {
+ Optional<ValueType> valueType = EnumUtil.enumFromString(ValueType.class, editor.typeList.getSelectedValue());
+ showMetaItemFailure(editor.item, valueType, failures);
+ }
+ }
+
+ protected void showMetaItemFailure(MetaItem metaItem, Optional<ValueType> valueType, List<ValidationFailure> failures) {
+ Optional<MetaItemDescriptor> optionalMetaItemDescriptor = metaItem.getName()
+ .flatMap(this::getMetaItemDescriptor);
+
+ String displayName = optionalMetaItemDescriptor
+ .map(metaItemDescriptor -> getMetaItemDisplayName(environment, metaItemDescriptor.name()))
+ .orElse(metaItem.getName().orElse(""));
+
+ if (failures != null) {
+ failures.forEach(failure ->
+ showValidationError(
+ attribute.getName().orElse(""),
+ displayName,
+ mapValidationFailure(
+ failure,
+ valueType.orElse(optionalMetaItemDescriptor
+ .map(MetaItemDescriptor::getValueType)
+ .orElse(null))
+ )
+ )
+ );
+ }
+ }
+
+ protected Optional<MetaItemDescriptor> getMetaItemDescriptor(String metaItemName) {
+ return Arrays.stream(metaItemDescriptors)
+ .filter(metaItemDescriptor -> metaItemDescriptor.getUrn().equals(metaItemName))
+ .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) {
+
+ 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();
+ }
+
+ @Override
+ public void setBusy(boolean busy) {
+
+ }
+
+ public static String getMetaItemDisplayName(Environment environment, String name) {
+ String displayName = environment.getMessages().metaItemDisplayName(name);
+
+ if (isNullOrEmpty(displayName)) {
+ displayName = name;
+ }
+ return displayName;
+ }
+
+
+}
+
+
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/ProtocolLinksEditor.java b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/ProtocolLinksEditor.java
new file mode 100644
index 000000000..506f9617c
--- /dev/null
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/ProtocolLinksEditor.java
@@ -0,0 +1,89 @@
+/*
+ * 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.assets.attributes;
+
+import com.google.gwt.dom.client.Style;
+import com.google.gwt.user.client.ui.Grid;
+import com.google.gwt.user.client.ui.Label;
+import org.openremote.manager.client.Environment;
+import org.openremote.manager.client.widget.FormSectionLabel;
+import org.openremote.model.asset.AssetAttribute;
+import org.openremote.model.asset.agent.ProtocolDescriptor;
+import org.openremote.model.attribute.AttributeValidationResult;
+
+public class ProtocolLinksEditor extends AbstractAttributeViewExtension {
+
+ protected final ProtocolDescriptor protocolDescriptor;
+ protected final Grid panel;
+ protected final boolean discovery;
+
+ public ProtocolLinksEditor(
+ Environment environment,
+ Style style,
+ AttributeViewImpl parentView,
+ AssetAttribute attribute,
+ ProtocolDescriptor protocolDescriptor,
+ boolean discovery) {
+
+ super(environment, style, parentView, attribute, discovery ? environment.getMessages().deviceDiscovery() : environment.getMessages().protocolLinks());
+ this.protocolDescriptor = protocolDescriptor;
+ this.discovery = discovery;
+
+ panel = new Grid(1, 2);
+ panel.setHeight("500px");
+ panel.setWidth("100%");
+ panel.getCellFormatter().setWidth(0,0,"40%");
+ add(panel);
+
+ // Asset/Attribute Tree
+ Label assetTree = new Label(discovery ? "Discovered Asset/Attribute tree here" : "Linked Asset/Attribute tree here");
+ assetTree.setHeight("100%");
+ assetTree.getElement().getStyle().setBorderColor("black");
+ assetTree.getElement().getStyle().setBorderStyle(com.google.gwt.dom.client.Style.BorderStyle.SOLID);
+ assetTree.getElement().getStyle().setBorderWidth(1, com.google.gwt.dom.client.Style.Unit.PX);
+
+ // Link editor
+ Label linkEditor = new Label(discovery ?
+ "Parent selector here with import button - will create assets/attributes under specified parent" :
+ "Link editor here - when attribute selected on the left this shows agent link related meta items in a meta editor");
+ linkEditor.setHeight("100%");
+ linkEditor.getElement().getStyle().setBorderColor("black");
+ linkEditor.getElement().getStyle().setBorderStyle(com.google.gwt.dom.client.Style.BorderStyle.SOLID);
+ linkEditor.getElement().getStyle().setBorderWidth(1, com.google.gwt.dom.client.Style.Unit.PX);
+
+ panel.setWidget(0, 0, assetTree);
+ panel.setWidget(0, 1, linkEditor);
+ }
+
+ @Override
+ public void onValidationStateChange(AttributeValidationResult validationResult) {
+
+ }
+
+ @Override
+ public void onAttributeChanged() {
+
+ }
+
+ @Override
+ public void setBusy(boolean busy) {
+
+ }
+}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetBrowser.java b/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetBrowser.java
index 3be1e4e2a..1e4a67768 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetBrowser.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetBrowser.java
@@ -21,9 +21,15 @@ package org.openremote.manager.client.assets.browser;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.view.client.HasData;
+import org.openremote.model.ValidationFailure;
+import org.openremote.model.ValueHolder;
import org.openremote.model.asset.Asset;
+import org.openremote.model.util.Pair;
+import org.openremote.model.value.Value;
+import java.util.List;
import java.util.function.Consumer;
+import java.util.function.Supplier;
/**
* Browse tenants and assets in a tree view.
@@ -60,7 +66,6 @@ public interface AssetBrowser extends IsWidget {
* If not-null, the presenter will send selection change events to this instead of the event bus.
*/
void useSelector(AssetSelector assetSelector);
-
}
void setPresenter(Presenter presenter);
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetSelector.java b/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetSelector.java
index c5f010923..bfcb745df 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetSelector.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetSelector.java
@@ -45,9 +45,9 @@ public abstract class AssetSelector extends FormGroup {
this.managerMessages = managerMessages;
this.selectionConsumer = selectionConsumer;
this.enableClearSelection = enableClearSelection;
- addFormLabel(label);
- addFormField(field);
- addFormGroupActions(actions);
+ setFormLabel(label);
+ setFormField(field);
+ setFromGroupActions(actions);
addInfolabel(infoLabel);
field.add(fieldContainer);
fieldContainer.setStyleName("layout vertical");
diff --git a/manager/client/src/main/java/org/openremote/manager/client/datapoint/DatapointBrowser.java b/manager/client/src/main/java/org/openremote/manager/client/datapoint/DatapointBrowser.java
index bf99ef2eb..08a8c1189 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/datapoint/DatapointBrowser.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/datapoint/DatapointBrowser.java
@@ -24,11 +24,16 @@ import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.text.shared.AbstractRenderer;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Label;
-import org.openremote.manager.client.i18n.ManagerMessages;
+import org.openremote.manager.client.Environment;
+import org.openremote.manager.client.assets.attributes.AbstractAttributeViewExtension;
+import org.openremote.manager.client.assets.attributes.AttributeView;
+import org.openremote.manager.client.assets.attributes.AttributeViewImpl;
import org.openremote.manager.client.interop.chartjs.Chart;
import org.openremote.manager.client.interop.chartjs.ChartUtil;
import org.openremote.manager.client.widget.*;
import org.openremote.model.Constants;
+import org.openremote.model.asset.AssetAttribute;
+import org.openremote.model.attribute.AttributeValidationResult;
import org.openremote.model.datapoint.DatapointInterval;
import org.openremote.model.datapoint.NumberDatapoint;
@@ -39,9 +44,9 @@ import java.util.function.Consumer;
import static com.google.gwt.dom.client.Style.Unit.EM;
import static com.google.gwt.dom.client.Style.Unit.PX;
-public abstract class DatapointBrowser extends FlowPanel {
+public abstract class DatapointBrowser extends AbstractAttributeViewExtension {
- final ManagerMessages messages;
+ final Environment environment;
final int width;
final int height;
@@ -53,26 +58,46 @@ public abstract class DatapointBrowser extends FlowPanel {
FormOutputText timeOutput;
FormButton nextButton;
- public DatapointBrowser(ManagerMessages messages, int width, int height) {
- this(messages, width, height, DatapointInterval.HOUR, System.currentTimeMillis());
+ public DatapointBrowser(Environment environment, AttributeView.Style style, AttributeViewImpl parentView, AssetAttribute attribute, int width, int height) {
+ this(environment, style, parentView, attribute, width, height, DatapointInterval.HOUR, System.currentTimeMillis());
}
- public DatapointBrowser(ManagerMessages messages, int width, int height, DatapointInterval interval, long timestamp) {
- this.messages = messages;
+ public DatapointBrowser(Environment environment, AttributeView.Style style, AttributeViewImpl parentView, AssetAttribute attribute, int width, int height, DatapointInterval interval, long timestamp) {
+ super(environment, style, parentView, attribute, environment.getMessages().historicalData());
+ this.environment = environment;
this.width = width;
this.height = height;
this.interval = interval;
this.timestamp = timestamp;
setStyleName("layout vertical center or-DatapointBrowser");
+ }
+
+ @Override
+ protected void onAttach() {
+ super.onAttach();
+ createChart();
+ }
+
+ @Override
+ protected void onDetach() {
+ super.onDetach();
+ destroyChart();
+ }
+
+ @Override
+ public void onValidationStateChange(AttributeValidationResult validationResult) {
+
+ }
+
+ @Override
+ public void onAttributeChanged() {
+
+ }
+
+ @Override
+ public void setBusy(boolean busy) {
- addAttachHandler(event -> {
- if (event.isAttached()) {
- createChart();
- } else {
- destroyChart();
- }
- });
}
public void refresh(long timestamp) {
@@ -105,7 +130,7 @@ public abstract class DatapointBrowser extends FlowPanel {
Canvas canvas = Canvas.createIfSupported();
if (canvas == null) {
- add(new Label(messages.canvasNotSupported()));
+ add(new Label(environment.getMessages().canvasNotSupported()));
return;
}
@@ -125,17 +150,17 @@ public abstract class DatapointBrowser extends FlowPanel {
FormGroup controlFormGroup = new FormGroup();
controlForm.add(controlFormGroup);
- FormLabel controlFormLabel = new FormLabel(messages.showChartAggregatedFor());
+ FormLabel controlFormLabel = new FormLabel(environment.getMessages().showChartAggregatedFor());
controlFormLabel.addStyleName("end-justified");
- controlFormGroup.addFormLabel(controlFormLabel);
+ controlFormGroup.setFormLabel(controlFormLabel);
FormField controlFormField = new FormField();
- controlFormGroup.addFormField(controlFormField);
+ controlFormGroup.setFormField(controlFormField);
intervalListBox = new FormValueListBox<>(
new AbstractRenderer<DatapointInterval>() {
@Override
public String render(DatapointInterval interval) {
- return messages.datapointInterval(interval.name());
+ return environment.getMessages().datapointInterval(interval.name());
}
}
);
@@ -151,17 +176,17 @@ public abstract class DatapointBrowser extends FlowPanel {
controlFormField.add(timeOutput);
FormGroupActions controlFormActions = new FormGroupActions();
- controlFormGroup.addFormGroupActions(controlFormActions);
+ controlFormGroup.setFromGroupActions(controlFormActions);
FormButton previousButton = new FormButton();
previousButton.setIcon("arrow-circle-left");
- previousButton.setText(messages.previous());
+ previousButton.setText(environment.getMessages().previous());
previousButton.addClickHandler(event -> refresh(calculateTimestamp(true)));
controlFormActions.add(previousButton);
nextButton = new FormButton();
nextButton.setIcon("arrow-circle-right");
- nextButton.setText(messages.next());
+ nextButton.setText(environment.getMessages().next());
nextButton.addClickHandler(event -> refresh(calculateTimestamp(false)));
controlFormActions.add(nextButton);
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 b932946d4..6c828b99b 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
@@ -21,8 +21,6 @@ package org.openremote.manager.client.i18n;
import com.google.gwt.i18n.client.LocalizableResource;
import com.google.gwt.i18n.client.Messages;
-import org.openremote.model.asset.AssetMeta;
-import org.openremote.model.value.ValueType;
@LocalizableResource.DefaultLocale
public interface ManagerMessages extends Messages {
@@ -151,8 +149,6 @@ public interface ManagerMessages extends Messages {
String unsupportedValueType(String name);
- String emptyMetaItem();
-
String loadingAssets();
String assetName();
@@ -191,8 +187,6 @@ public interface ManagerMessages extends Messages {
String invalidAssetParent();
- String invalidAssetAttributes();
-
String centerMap();
String showHistory();
@@ -227,6 +221,10 @@ public interface ManagerMessages extends Messages {
String metaItems();
+ String protocolLinks();
+
+ String deviceDiscovery();
+
String or();
String and();
@@ -239,7 +237,7 @@ public interface ManagerMessages extends Messages {
String valueTypeDisplayName(@Select String valueType);
- String assetMetaDisplayName(@Select String assetMetaName);
+ String metaItemDisplayName(@Select String metaItemName);
String attributeDeleted(String name);
@@ -295,6 +293,8 @@ public interface ManagerMessages extends Messages {
String invalidAttributeName();
+ String invalidAttributeType();
+
String editAsset();
String viewAsset();
@@ -335,11 +335,13 @@ public interface ManagerMessages extends Messages {
String attributeType(@Select String name);
- String validationFailed();
+ String validationFailureOnAttribute(String attributeName);
+
+ String validationFailureOnMetaItem(String attributeName, String metaItemName);
- String validationFailedFor(String field);
+ String validationFailure(@Optional String parameter, @Select String name);
- String validationFailure(@Select String name);
+ String validationFailureParameter(@Select String parameter);
String syslog();
diff --git a/manager/client/src/main/java/org/openremote/manager/client/interop/jackson/MetaItemDescriptorDeserializer.java b/manager/client/src/main/java/org/openremote/manager/client/interop/jackson/MetaItemDescriptorDeserializer.java
new file mode 100644
index 000000000..bd64e1acc
--- /dev/null
+++ b/manager/client/src/main/java/org/openremote/manager/client/interop/jackson/MetaItemDescriptorDeserializer.java
@@ -0,0 +1,47 @@
+/*
+ * 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.manager.client.interop.jackson;
+
+import com.github.nmorel.gwtjackson.client.JsonDeserializationContext;
+import com.github.nmorel.gwtjackson.client.JsonDeserializer;
+import com.github.nmorel.gwtjackson.client.JsonDeserializerParameters;
+import com.github.nmorel.gwtjackson.client.stream.JsonReader;
+import com.google.gwt.core.client.GWT;
+import com.google.gwt.core.client.JavaScriptObject;
+import org.openremote.manager.client.assets.MetaItemDescriptorMapper;
+import org.openremote.model.ValidationFailure;
+import org.openremote.model.attribute.MetaItemDescriptor;
+import org.openremote.model.attribute.MetaItemDescriptorImpl;
+
+public class MetaItemDescriptorDeserializer extends JsonDeserializer<MetaItemDescriptor> {
+
+ private static final MetaItemDescriptorDeserializer INSTANCE = new MetaItemDescriptorDeserializer();
+ private static final MetaItemDescriptorMapper MAPPER = GWT.create(MetaItemDescriptorMapper.class);
+
+ public static MetaItemDescriptorDeserializer getInstance() {
+ return INSTANCE;
+ }
+
+ @Override
+ protected MetaItemDescriptor doDeserialize(JsonReader reader, JsonDeserializationContext ctx, JsonDeserializerParameters params) {
+ // Read entire object in
+ return MAPPER.read(reader.nextValue());
+ }
+}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/interop/jackson/SerializationConfiguration.java b/manager/client/src/main/java/org/openremote/manager/client/interop/jackson/SerializationConfiguration.java
index 5e3fc2f24..65c4aa4dc 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/interop/jackson/SerializationConfiguration.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/interop/jackson/SerializationConfiguration.java
@@ -21,6 +21,8 @@ package org.openremote.manager.client.interop.jackson;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.github.nmorel.gwtjackson.client.AbstractConfiguration;
+import org.openremote.model.ValidationFailure;
+import org.openremote.model.attribute.MetaItemDescriptor;
import org.openremote.model.value.*;
/**
@@ -30,11 +32,14 @@ public class SerializationConfiguration extends AbstractConfiguration {
@Override
protected void configure() {
+
fieldVisibility(JsonAutoDetect.Visibility.ANY);
getterVisibility(JsonAutoDetect.Visibility.NONE);
setterVisibility(JsonAutoDetect.Visibility.NONE);
isGetterVisibility(JsonAutoDetect.Visibility.NONE);
- creatorVisibility(JsonAutoDetect.Visibility.NONE);
+ creatorVisibility(JsonAutoDetect.Visibility.ANY);
+ type(ValidationFailure.Reason.class).deserializer(ValidationFailureReasonDeserializer.class);
+ type(MetaItemDescriptor.class).deserializer(MetaItemDescriptorDeserializer.class);
type(Value.class).serializer(ModelValueSerializer.class).deserializer(ModelValueDeserializer.class);
type(ObjectValue.class).serializer(ModelValueSerializer.class).deserializer(ModelValueDeserializer.class);
type(ArrayValue.class).serializer(ModelValueSerializer.class).deserializer(ModelValueDeserializer.class);
diff --git a/manager/client/src/main/java/org/openremote/manager/client/interop/jackson/ValidationFailureReasonDeserializer.java b/manager/client/src/main/java/org/openremote/manager/client/interop/jackson/ValidationFailureReasonDeserializer.java
new file mode 100644
index 000000000..310f6e50b
--- /dev/null
+++ b/manager/client/src/main/java/org/openremote/manager/client/interop/jackson/ValidationFailureReasonDeserializer.java
@@ -0,0 +1,46 @@
+/*
+ * 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.manager.client.interop.jackson;
+
+import com.github.nmorel.gwtjackson.client.JsonDeserializationContext;
+import com.github.nmorel.gwtjackson.client.JsonDeserializer;
+import com.github.nmorel.gwtjackson.client.JsonDeserializerParameters;
+import com.github.nmorel.gwtjackson.client.stream.JsonReader;
+import org.openremote.model.ValidationFailure;
+import org.openremote.model.value.Value;
+import org.openremote.model.value.Values;
+
+public class ValidationFailureReasonDeserializer extends JsonDeserializer<ValidationFailure.Reason> {
+
+ private static final ValidationFailureReasonDeserializer INSTANCE = new ValidationFailureReasonDeserializer();
+
+ public static ValidationFailureReasonDeserializer getInstance() {
+ return INSTANCE;
+ }
+
+ @Override
+ protected ValidationFailure.Reason doDeserialize(JsonReader reader, JsonDeserializationContext ctx, JsonDeserializerParameters params) {
+ reader.beginObject();
+ reader.nextName();
+ String name = reader.nextString();
+ reader.endObject();
+ return new ValidationFailure.ReasonImpl(name);
+ }
+}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/rules/RulesEditorImpl.java b/manager/client/src/main/java/org/openremote/manager/client/rules/RulesEditorImpl.java
index ee49932c4..f561ce851 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/rules/RulesEditorImpl.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/rules/RulesEditorImpl.java
@@ -268,10 +268,10 @@ public class RulesEditorImpl extends FormViewImpl implements RulesEditor {
}
protected void setOpaque(boolean opaque) {
- nameGroup.setOpaque(opaque);
- optionsGroup.setOpaque(opaque);
+ nameGroup.setDisabled(opaque);
+ optionsGroup.setDisabled(opaque);
rulesTextArea.setOpaque(opaque);
- submitButtonGroup.setOpaque(opaque);
+ submitButtonGroup.setDisabled(opaque);
}
}
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 7304f6560..f1746ca4d 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
@@ -19,15 +19,21 @@
*/
package org.openremote.manager.client.simulator;
-import com.google.gwt.dom.client.Style;
-import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.IsWidget;
import elemental.client.Browser;
import org.openremote.manager.client.Environment;
+import org.openremote.manager.client.assets.attributes.AbstractAttributeViewExtension;
+import org.openremote.manager.client.assets.attributes.AttributeView;
+import org.openremote.manager.client.assets.attributes.AttributeViewImpl;
import org.openremote.manager.client.event.ShowSuccessEvent;
-import org.openremote.manager.client.widget.*;
+import org.openremote.manager.client.widget.FormButton;
+import org.openremote.manager.client.widget.FormField;
+import org.openremote.manager.client.widget.FormGroup;
+import org.openremote.manager.client.widget.FormLabel;
import org.openremote.model.ValidationFailure;
+import org.openremote.model.asset.AssetAttribute;
import org.openremote.model.attribute.AttributeRef;
+import org.openremote.model.attribute.AttributeValidationResult;
import org.openremote.model.event.bus.EventRegistration;
import org.openremote.model.simulator.RequestSimulatorState;
import org.openremote.model.simulator.SimulatorElement;
@@ -35,11 +41,8 @@ import org.openremote.model.simulator.SimulatorState;
import org.openremote.model.value.ValueType;
import java.util.*;
-import java.util.function.Consumer;
-import static org.openremote.manager.client.widget.ValueEditors.*;
-
-public class Simulator extends FlowPanel implements IsWidget {
+public class Simulator extends AbstractAttributeViewExtension {
final protected Environment environment;
final protected AttributeRef protocolConfiguration;
@@ -48,22 +51,29 @@ public class Simulator extends FlowPanel implements IsWidget {
protected EventRegistration<SimulatorState> eventRegistration;
protected SimulatorState simulatorState;
protected Map<AttributeRef, FormGroup> formGroups = new HashMap<>();
+ final protected AttributeView.Style style;
- public Simulator(Environment environment, AttributeRef protocolConfiguration, Runnable onCreate, Runnable onClose) {
+ public Simulator(Environment environment, AttributeView.Style style, AttributeViewImpl parentView, AssetAttribute attribute, AttributeRef protocolConfiguration, Runnable onCreate, Runnable onClose) {
+ super(environment, style, parentView, attribute, environment.getMessages().simulator());
this.environment = environment;
+ this.style = style;
this.protocolConfiguration = protocolConfiguration;
this.onCreate = onCreate;
this.onClose = onClose;
setStyleName("layout vertical center or-Simulator");
+ }
- addAttachHandler(event -> {
- if (event.isAttached()) {
- createSimulator();
- } else {
- destroySimulator();
- }
- });
+ @Override
+ protected void onAttach() {
+ super.onAttach();
+ createSimulator();
+ }
+
+ @Override
+ protected void onDetach() {
+ super.onDetach();
+ destroySimulator();
}
protected void createSimulator() {
@@ -90,67 +100,45 @@ public class Simulator extends FlowPanel implements IsWidget {
formGroups.clear();
List<SimulatorElement> sortedElements = Arrays.asList(simulatorState.getElements());
- Collections.sort(sortedElements, Comparator.comparing(o -> simulatorState.getElementName(o)));
+ sortedElements.sort(Comparator.comparing(o -> simulatorState.getElementName(o)));
for (SimulatorElement element : sortedElements) {
FormGroup formGroup = new FormGroup();
- formGroup.getElement().getStyle().setWidth(80, Style.Unit.PCT);
+ formGroup.getElement().getStyle().setWidth(80, com.google.gwt.dom.client.Style.Unit.PCT);
String elementName = simulatorState.getElementName(element);
FormLabel formLabel = new FormLabel(elementName);
formLabel.addStyleName("larger");
- formGroup.addFormLabel(formLabel);
+ formGroup.setFormLabel(formLabel);
FormField formField = new FormField();
- formGroup.addFormField(formField);
+ formGroup.setFormField(formField);
- Consumer<List<ValidationFailure>> validationResultConsumer =
- failures -> {
- for (ValidationFailure failure : failures) {
- showValidationError(environment, elementName, failure);
- }
- };
+ // 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 = () -> {
+ List<ValidationFailure> failures = element.getValidationFailures();
+ formGroup.setError(failures != null && !failures.isEmpty());
+ };
- IsWidget editor;
ValueType valueType = element.getExpectedType().getValueType();
- if (valueType.equals(ValueType.STRING)) {
- String currentValue = element.getValue().map(Object::toString).orElse(null);
- editor = createStringEditor(
- element, currentValue, false, "or-SimulatorElement", formGroup, false, validationResultConsumer
- );
- } else if (valueType.equals(ValueType.NUMBER)) {
- String currentValue = element.getValue().map(Object::toString).orElse(null);
- editor = createNumberEditor(
- element, currentValue, false, "or-SimulatorElement", formGroup, false, validationResultConsumer
- );
- } else if (valueType.equals(ValueType.BOOLEAN)) {
- Boolean currentValue = element.getValueAsBoolean().orElse(null);
- editor = createBooleanEditor(
- element, currentValue, false, "or-SimulatorElement", formGroup, false, validationResultConsumer
- );
- // TODO Support JSON editors
- } else {
- editor= new FormOutputText(
- environment.getMessages().unsupportedValueType(valueType.name())
- );
- }
+ IsWidget editor = valueEditorSupplier.createValueEditor(element, valueType, style, onModified);
formField.add(editor);
-
formGroups.put(element.getAttributeRef(), formGroup);
add(formGroup);
}
FormGroup submitGroup = new FormGroup();
- submitGroup.getElement().getStyle().setWidth(80, Style.Unit.PCT);
+ submitGroup.getElement().getStyle().setWidth(80, com.google.gwt.dom.client.Style.Unit.PCT);
FormField submitField = new FormField();
- submitGroup.addFormField(submitField);
+ submitGroup.setFormField(submitField);
FormButton writeButton = new FormButton(environment.getMessages().writeSimulatorState());
writeButton.setPrimary(true);
writeButton.addClickHandler(event -> {
- if (validateElements()) {
+ if (isValid()) {
environment.getEventService().dispatch(simulatorState);
environment.getEventBus().dispatch(
new ShowSuccessEvent(environment.getMessages().simulatorStateSubmitted())
@@ -171,29 +159,24 @@ public class Simulator extends FlowPanel implements IsWidget {
}, 250);
}
- protected boolean validateElements() {
- boolean isValid = true;
- for (SimulatorElement element : simulatorState.getElements()) {
- if (!validateElement(element))
- isValid = false;
- }
- if (!isValid) {
- showValidationError(environment, environment.getMessages().invalidValues());
- }
- return isValid;
+ protected boolean isValid() {
+ return formGroups.values()
+ .stream()
+ .noneMatch(FormGroup::isError);
}
- public boolean validateElement(SimulatorElement element) {
- // If there is already an error displayed, don't do other validation
- FormGroup formGroup = formGroups.get(element.getAttributeRef());
- if (formGroup.isError()) {
- return false;
- }
- List<ValidationFailure> failures = element.getValidationFailures();
- if (!failures.isEmpty()) {
- formGroups.get(element.getAttributeRef()).setError(true);
- }
- return true;
+ @Override
+ public void onValidationStateChange(AttributeValidationResult validationResult) {
+ // Ignore any validation on the parent attribute
+ }
+
+ @Override
+ public void onAttributeChanged() {
+ // the host attribute change doesn't impact the simulator
}
+ @Override
+ public void setBusy(boolean busy) {
+
+ }
}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/widget/FormGroup.java b/manager/client/src/main/java/org/openremote/manager/client/widget/FormGroup.java
index 716f1bd78..506f6357f 100644
--- a/manager/client/src/main/java/org/openremote/manager/client/widget/FormGroup.java
+++ b/manager/client/src/main/java/org/openremote/manager/client/widget/FormGroup.java
@@ -21,9 +21,11 @@ package org.openremote.manager.client.widget;
import com.google.gwt.dom.client.Style;
import com.google.gwt.uibinder.client.UiChild;
-import com.google.gwt.user.client.ui.*;
+import com.google.gwt.user.client.ui.FlowPanel;
+import com.google.gwt.user.client.ui.HasWidgets;
+import com.google.gwt.user.client.ui.IsWidget;
+import com.google.gwt.user.client.ui.Label;
-import java.util.function.Consumer;
import java.util.logging.Logger;
/**
@@ -77,7 +79,7 @@ public class FormGroup extends FlowPanel implements HasWidgets {
}
@UiChild(tagname = "label", limit = 1)
- public void addFormLabel(FormLabel formLabel) {
+ public void setFormLabel(FormLabel formLabel) {
if (this.formLabel != null)
throw new IllegalStateException("Form label already set");
this.formLabel = formLabel;
@@ -85,7 +87,7 @@ public class FormGroup extends FlowPanel implements HasWidgets {
}
@UiChild(tagname = "field", limit = 1)
- public void addFormField(FormField formField) {
+ public void setFormField(FormField formField) {
if (this.formField != null)
throw new IllegalStateException("Form field already set");
this.formField = formField;
@@ -101,7 +103,10 @@ public class FormGroup extends FlowPanel implements HasWidgets {
}
@UiChild(tagname = "actions", limit = 1)
- public void addFormGroupActions(FormGroupActions formGroupActions) {
+ public void setFromGroupActions(FormGroupActions formGroupActions) {
+ if (this.formGroupActions != null) {
+ mainPanel.remove(this.formGroupActions);
+ }
this.formGroupActions = formGroupActions;
mainPanel.insert(formGroupActions, mainPanel.getWidgetIndex(toggleExtensionButton));
}
@@ -122,32 +127,13 @@ public class FormGroup extends FlowPanel implements HasWidgets {
extensionPanel.add(widget);
}
- public void showDisabledExtensionToggle() {
- toggleExtensionButton.setVisible(true);
- toggleExtensionButton.setEnabled(false);
- }
-
- public int getExtensionWidgetIndex(Widget widget) {
- return extensionPanel.getWidgetIndex(widget);
+ public void clearExtensions() {
+ extensionPanel.clear();
}
- public void insertExtension(Widget widget, int beforeIndex) {
+ public void showDisabledExtensionToggle() {
toggleExtensionButton.setVisible(true);
- toggleExtensionButton.setEnabled(true);
- extensionPanel.insert(widget, beforeIndex);
- }
-
- public boolean removeExtension(Widget widget) {
- boolean removed = extensionPanel.remove(widget);
- if (removed && extensionPanel.getWidgetCount() == 0)
- toggleExtensionButton.setVisible(false);
- return removed;
- }
-
- public void forExtension(Consumer<Widget> extension) {
- for (int i = 0; i < extensionPanel.getWidgetCount(); i++) {
- extension.accept(extensionPanel.getWidget(i));
- }
+ toggleExtensionButton.setEnabled(false);
}
public FormLabel getFormLabel() {
@@ -162,6 +148,10 @@ public class FormGroup extends FlowPanel implements HasWidgets {
return infoLabel;
}
+ public FormGroupActions getFormGroupActions() {
+ return formGroupActions;
+ }
+
public Style getStyle() {
return getElement().getStyle();
}
@@ -201,9 +191,9 @@ public class FormGroup extends FlowPanel implements HasWidgets {
}
}
- public void setOpaque(boolean opaque) {
+ public void setDisabled(boolean disabled) {
removeStyleName("opaque");
- if (opaque) {
+ if (disabled) {
addStyleName("opaque");
}
}
diff --git a/manager/client/src/main/java/org/openremote/manager/client/widget/FormSection.java b/manager/client/src/main/java/org/openremote/manager/client/widget/FormSection.java
new file mode 100644
index 000000000..d527f1a7d
--- /dev/null
+++ b/manager/client/src/main/java/org/openremote/manager/client/widget/FormSection.java
@@ -0,0 +1,45 @@
+/*
+ * 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 com.google.gwt.user.client.ui.IsWidget;
+
+import static org.openremote.model.util.TextUtil.isNullOrEmpty;
+
+/**
+ * Represents a {@link FormSectionLabel} and one or more {@link com.google.gwt.user.client.ui.Widget}s to be displayed
+ * inside a {@link FormGroup}.
+ */
+public class FormSection extends FlowPanel {
+ protected FormSectionLabel label = new FormSectionLabel();
+
+ public FormSection(String label) {
+ this.label.setText(label);
+ add(this.label);
+ }
+
+ public void setDisabled(boolean disabled) {
+ removeStyleName("opaque");
+ if (disabled) {
+ addStyleName("opaque");
+ }
+ }
+}
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 97da3e007..ff8346901 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
@@ -19,13 +19,9 @@
*/
package org.openremote.manager.client.widget;
-import com.google.gwt.dom.client.Document;
-import com.google.gwt.event.dom.client.ChangeEvent;
-import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.IsWidget;
-import com.google.gwt.user.client.ui.ListBox;
import org.openremote.manager.client.Environment;
import org.openremote.manager.client.app.dialog.JsonEditor;
import org.openremote.manager.client.event.ShowFailureEvent;
@@ -46,7 +42,8 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
-import java.util.function.*;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
import static org.openremote.model.util.TextUtil.isNullOrEmpty;
@@ -55,8 +52,8 @@ import static org.openremote.model.util.TextUtil.isNullOrEmpty;
*/
public final class ValueEditors {
- public enum ConversionValidationFailure implements ValidationFailure {
- NOT_A_VALID_NUMBER
+ public enum ConversionFailureReason implements ValidationFailure.Reason {
+ CONVERSION_NOT_A_VALID_NUMBER
}
/**
@@ -65,15 +62,13 @@ public final class ValueEditors {
* validation failure results. If there are no validation failures, the update was successful.
*/
private static class ValueUpdate<T> {
- final FormGroup formGroup;
final ValueHolder valueHolder;
- final Consumer<List<ValidationFailure>> resultConsumer;
+ final Runnable onValueModified;
final T rawValue;
- public ValueUpdate(FormGroup formGroup, ValueHolder valueHolder, Consumer<List<ValidationFailure>> resultConsumer, T rawValue) {
- this.formGroup = formGroup;
+ public ValueUpdate(ValueHolder valueHolder, Runnable onValueModified, T rawValue) {
this.valueHolder = valueHolder;
- this.resultConsumer = resultConsumer;
+ this.onValueModified = onValueModified;
this.rawValue = rawValue;
}
}
@@ -85,8 +80,6 @@ public final class ValueEditors {
@Override
public void accept(ValueUpdate<T> valueUpdate) {
- valueUpdate.formGroup.setError(false);
- List<ValidationFailure> failures = new ArrayList<>();
try {
valueUpdate.valueHolder.setValue(
valueUpdate.rawValue != null ? createValue(valueUpdate.rawValue) : null
@@ -97,22 +90,18 @@ public final class ValueEditors {
AbstractValueTimestampHolder timestampHolder = (AbstractValueTimestampHolder) valueUpdate.valueHolder;
timestampHolder.setValueTimestamp(0);
}
-
- failures.addAll(valueUpdate.valueHolder.getValidationFailures());
- } catch (IllegalArgumentException ex) {
- failures.add(ex::getMessage);
- }
- if (!failures.isEmpty()) {
- valueUpdate.formGroup.setError(true);
- }
- if (valueUpdate.resultConsumer != null) {
- valueUpdate.resultConsumer.accept(failures);
+ } 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 {
@@ -126,7 +115,7 @@ public final class ValueEditors {
try {
return Values.create(Double.valueOf(rawValue));
} catch (NumberFormatException ex) {
- throw new IllegalArgumentException(ConversionValidationFailure.NOT_A_VALID_NUMBER.name());
+ throw new IllegalArgumentException(ConversionFailureReason.CONVERSION_NOT_A_VALID_NUMBER.name());
}
}
};
@@ -167,18 +156,17 @@ public final class ValueEditors {
}
public static IsWidget createStringEditor(ValueHolder valueHolder,
- String currentValue,
+ Runnable onValueModified,
boolean readOnly,
- String styleName,
- FormGroup formGroup,
boolean showTimestamp,
- Consumer<List<ValidationFailure>> validationResultConsumer) {
+ String currentValue,
+ String styleName) {
Consumer<String> updateConsumer = !readOnly
- ? rawValue -> STRING_UPDATER.accept(new ValueUpdate<>(formGroup, valueHolder, validationResultConsumer, rawValue))
+ ? rawValue -> STRING_UPDATER.accept(new ValueUpdate<>(valueHolder, onValueModified, rawValue))
: null;
FlowPanel panel = new FlowPanel();
panel.setStyleName("flex layout horizontal center or-ValueEditor or-StringValueEditor");
- IsWidget widget = ValueEditors.createStringEditorWidget(styleName, currentValue, updateConsumer);
+ IsWidget widget = ValueEditors.createStringEditorWidget(styleName, readOnly, currentValue, updateConsumer);
FlowPanel widgetWrapper = new FlowPanel();
widgetWrapper.setStyleName("flex layout horizontal center");
widgetWrapper.add(widget);
@@ -190,20 +178,19 @@ public final class ValueEditors {
public static IsWidget createNumberEditor(ValueHolder valueHolder,
- String currentValue,
+ Runnable onValueModified,
boolean readOnly,
- String styleName,
- FormGroup formGroup,
boolean showTimestamp,
- Consumer<List<ValidationFailure>> validationResultConsumer) {
+ String currentValue,
+ String styleName) {
Consumer<String> updateConsumer = !readOnly
- ? rawValue -> DOUBLE_UPDATER.accept(new ValueUpdate<>(formGroup, valueHolder, validationResultConsumer, rawValue))
+ ? rawValue -> DOUBLE_UPDATER.accept(new ValueUpdate<>(valueHolder, onValueModified, rawValue))
: null;
FlowPanel panel = new FlowPanel();
panel.setStyleName("flex layout horizontal center or-ValueEditor or-NumberValueEditor");
- IsWidget widget = ValueEditors.createStringEditorWidget(styleName, currentValue, updateConsumer);
+ IsWidget widget = createStringEditorWidget(styleName, readOnly, currentValue, updateConsumer);
FlowPanel widgetWrapper = new FlowPanel();
widgetWrapper.setStyleName("flex layout horizontal center");
widgetWrapper.add(widget);
@@ -214,19 +201,18 @@ public final class ValueEditors {
}
public static IsWidget createBooleanEditor(ValueHolder valueHolder,
- Boolean currentValue,
+ Runnable onValueModified,
boolean readOnly,
- String styleName,
- FormGroup formGroup,
boolean showTimestamp,
- Consumer<List<ValidationFailure>> validationResultConsumer) {
+ Boolean currentValue,
+ String styleName) {
Consumer<Boolean> updateConsumer = !readOnly
- ? rawValue -> BOOLEAN_UPDATER.accept(new ValueUpdate<>(formGroup, valueHolder, validationResultConsumer, rawValue))
+ ? rawValue -> BOOLEAN_UPDATER.accept(new ValueUpdate<>(valueHolder, onValueModified, rawValue))
: null;
FlowPanel panel = new FlowPanel();
panel.setStyleName("flex layout horizontal center or-ValueEditor or-BooleanValueEditor");
- IsWidget widget = ValueEditors.createBooleanEditorWidget(styleName, currentValue, updateConsumer);
+ IsWidget widget = ValueEditors.createBooleanEditorWidget(styleName, readOnly, currentValue, updateConsumer);
FlowPanel widgetWrapper = new FlowPanel();
widgetWrapper.setStyleName("flex layout horizontal center");
widgetWrapper.add(widget);
@@ -237,21 +223,20 @@ public final class ValueEditors {
}
public static IsWidget createObjectEditor(ValueHolder valueHolder,
- ObjectValue currentValue,
+ Runnable onValueModified,
boolean readOnly,
+ boolean showTimestamp,
+ ObjectValue currentValue,
String label,
String title,
- JsonEditor jsonEditor,
- FormGroup formGroup,
- boolean showTimestamp,
- Consumer<List<ValidationFailure>> validationResultConsumer) {
+ JsonEditor jsonEditor) {
Consumer<Value> updateConsumer = !readOnly
- ? rawValue -> VALUE_UPDATER.accept(new ValueUpdate<>(formGroup, valueHolder, validationResultConsumer, rawValue))
+ ? rawValue -> VALUE_UPDATER.accept(new ValueUpdate<>(valueHolder, onValueModified, rawValue))
: null;
FlowPanel panel = new FlowPanel();
panel.setStyleName("flex layout horizontal center or-ValueEditor or-ObjectValueEditor");
IsWidget widget = createJsonEditorWidget(
- jsonEditor, label, title, currentValue, updateConsumer
+ jsonEditor, readOnly, label, title, currentValue, updateConsumer
);
FlowPanel widgetWrapper = new FlowPanel();
widgetWrapper.setStyleName("flex layout horizontal center");
@@ -263,16 +248,16 @@ public final class ValueEditors {
}
public static IsWidget createAttributeRefEditor(ValueHolder valueHolder,
+ Runnable onValueModified,
boolean readOnly,
- FormGroup formGroup,
BiConsumer<ValueHolder, Consumer<Asset[]>> assetSupplier,
BiConsumer<Pair<ValueHolder, Asset>, Consumer<AssetAttribute[]>> attributeSupplier,
String assetWatermark,
String attributeWatermark,
- Consumer<List<ValidationFailure>> validationResultConsumer) {
+ String styleName) {
Consumer<AttributeRef> updateConsumer = !readOnly
- ? rawValue -> ATTRIBUTE_REF_UPDATER.accept(new ValueUpdate<>(formGroup, valueHolder, validationResultConsumer, rawValue))
+ ? rawValue -> ATTRIBUTE_REF_UPDATER.accept(new ValueUpdate<>(valueHolder, onValueModified, rawValue))
: null;
FlowPanel panel = new FlowPanel();
@@ -283,7 +268,9 @@ public final class ValueEditors {
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)
@@ -366,22 +353,21 @@ public final class ValueEditors {
}
public static IsWidget createArrayEditor(ValueHolder valueHolder,
- ArrayValue currentValue,
+ Runnable onValueModified,
boolean readOnly,
+ boolean showTimestamp,
+ ArrayValue currentValue,
String label,
String title,
- JsonEditor jsonEditor,
- FormGroup formGroup,
- boolean showTimestamp,
- Consumer<List<ValidationFailure>> validationResultConsumer) {
+ JsonEditor jsonEditor) {
Consumer<Value> updateConsumer = !readOnly
- ? rawValue -> VALUE_UPDATER.accept(new ValueUpdate<>(formGroup, valueHolder, validationResultConsumer, rawValue))
+ ? rawValue -> VALUE_UPDATER.accept(new ValueUpdate<>(valueHolder, onValueModified, rawValue))
: null;
FlowPanel panel = new FlowPanel();
panel.setStyleName("flex layout horizontal center or-ValueEditor or-ArrayValueEditor");
IsWidget widget = createJsonEditorWidget(
- jsonEditor, label, title, currentValue, updateConsumer
+ jsonEditor, readOnly, label, title, currentValue, updateConsumer
);
FlowPanel widgetWrapper = new FlowPanel();
widgetWrapper.setStyleName("flex layout horizontal center");
@@ -392,21 +378,6 @@ public final class ValueEditors {
return () -> panel;
}
- public static void showValidationError(Environment environment, String error) {
- environment.getEventBus().dispatch(new ShowFailureEvent(error, 5000));
- }
-
- public static void showValidationError(Environment environment, String fieldLabel, ValidationFailure validationFailure) {
- StringBuilder error = new StringBuilder();
- if (fieldLabel != null)
- error.append(environment.getMessages().validationFailedFor(fieldLabel));
- else
- error.append(environment.getMessages().validationFailed());
- if (validationFailure != null)
- error.append(": ").append(environment.getMessages().validationFailure(validationFailure.name()));
- showValidationError(environment, error.toString());
- }
-
private static void addTimestampLabel(ValueHolder valueHolder, FlowPanel editorPanel) {
if (valueHolder instanceof AbstractValueTimestampHolder) {
AbstractValueTimestampHolder timestampHolder = (AbstractValueTimestampHolder) valueHolder;
@@ -416,6 +387,7 @@ public final class ValueEditors {
}
private static IsWidget createStringEditorWidget(String styleName,
+ boolean readOnly,
String value,
Consumer<String> updateConsumer) {
FormInputText input = new FormInputText();
@@ -425,7 +397,7 @@ public final class ValueEditors {
} else if (updateConsumer == null) {
input.setValue("-");
}
- if (updateConsumer != null) {
+ if (updateConsumer != null && !readOnly) {
// Both keyup and change (e.g. after pasting) must be used
input.addKeyUpHandler(event ->
updateConsumer.accept(input.getValue() == null || input.getValue().length() == 0 ? null : input.getValue()));
@@ -438,10 +410,12 @@ public final class ValueEditors {
}
private static IsWidget createBooleanEditorWidget(String styleName,
+ boolean readOnly,
Boolean value,
Consumer<Boolean> updateConsumer) {
FormCheckBox input = new FormCheckBox();
input.addStyleName(styleName);
+ input.setEnabled(!readOnly);
if (value == null && updateConsumer == null) {
return new FormOutputText("-");
@@ -458,6 +432,7 @@ public final class ValueEditors {
}
private static IsWidget createJsonEditorWidget(JsonEditor jsonEditor,
+ boolean readOnly,
String label,
String title,
Value currentValue,
@@ -475,7 +450,7 @@ public final class ValueEditors {
jsonEditor.setOnReset(() -> jsonEditor.setValue(currentValue));
- if (updateConsumer != null) {
+ if (updateConsumer != null && !readOnly) {
jsonEditor.setOnApply(updateConsumer);
}
return button;
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 64d31cec2..0c7477a93 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
@@ -102,6 +102,7 @@ assetTypeLabel[FLOOR]=Floor
assetTypeLabel[RESIDENCE]=Residence
assetTypeLabel[ROOM]=Room
assetTypeLabel[FLIGHT]=Flight
+assetTypeLabel[PIER]=Pier
assetTypeLabel[AGENT]=Agent
assetTypeLabel[THING]=Thing
enterCustomAssetType=Enter a custom type value
@@ -117,6 +118,8 @@ addItem=Add item
type=Type
value=Value
metaItems=Attribute configuration
+protocolLinks=Protocol Links
+deviceDiscovery=Device Discovery
or=or
and=and
customItem=Custom item
@@ -147,6 +150,7 @@ editTenantRuleset=Edit tenant ruleset
editAssetRuleset=Edit asset ruleset
attributeWriteSent=Attribute write sent to server: {0}
invalidAttributeName=Invalid attribute name, use only alphanumeric and underscore characters.
+invalidAttributeType=Invalid attribute type
duplicateAttributeName=Duplicate attribute name, please change it.
editAsset=Edit asset
viewAsset=View asset
@@ -176,8 +180,8 @@ attributeType=Unknown attribute type
attributeType[STRING]=Text
attributeType[NUMBER]=Number
attributeType[BOOLEAN]=On/Off toggle
-attributeType[OBJECT]=JSON Object
-attributeType[ARRAY]=JSON Array
+attributeType[OBJECT]=JSON object
+attributeType[ARRAY]=JSON array
attributeType[PERCENTAGE]=Percentage
attributeType[TIMESTAMP_MILLIS]=Timestamp milliseconds since epoch
attributeType[DATETIME]=Timestamp in ISO 8601
@@ -210,22 +214,45 @@ attributeType[FLOW_SCCM]=Flow in cubic centimetres per minute
attributeType[FLOW_CFPS]=Flow in cubic feet per second
attributeType[FLOW_GPM]=Flow in gallons per minute
attributeType[RULES_TEMPLATE_FILTER]=Rules template filter
-emptyMetaItem=Empty item
-invalidAssetAttributes=Invalid asset attributes, please correct input.
-validationFailed=Validation failed
-validationFailedFor=Validation failed for {0}
+validationFailureOnAttribute=Attribute error on ''{0}''
+validationFailureOnMetaItem=Meta item error on ''{0}'' meta item ''{1}''
validationFailure=Unknown validation failure.
-validationFailure[NAME_IS_REQUIRED]=Name is required.
-validationFailure[VALUE_IS_REQUIRED]=Value is required.
-validationFailure[INVALID_ATTRIBUTE_NAME]=Invalid attribute name.
-validationFailure[MISSING_ATTRIBUTE_TYPE]=Missing attribute type.
-validationFailure[MISSING_ATTRIBUTE_VALUE_TIMESTAMP]=Missing attribute value timestamp.
-validationFailure[VALUE_DOES_NOT_MATCH_ATTRIBUTE_TYPE]=Value does not match attribute type.
-validationFailure[PERCENTAGE_OUT_OF_RANGE]=Percentage value must be a number between 0 and 100.
-validationFailure[VALUE_DOES_NOT_MATCH_ASSET_META_TYPE]=Value does not match well-known meta item''s expected type.
-validationFailure[NOT_A_VALID_NUMBER]=Must be a number.
-validationFailure[WRONG_COLOR_FORMAT]=Wrong color format.
-validationFailure[TEMPERATURE_OUT_OF_RANGE]=Temperature out of scale''s range.
+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.
+validationFailure[VALUE_TEMPERATURE_OUT_OF_RANGE]=Temperature out of scale''s range.
+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_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[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.
+validationFailureParameter=
+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_POSITIVE]=Positive decimal
+validationFailureParameter[DOUBLE_NEGATIVE]=Negative decimal
+validationFailureParameter[DOUBLE_NON_ZERO]=Non zero decimal
+validationFailureParameter[DOUBLE_POSITIVE_NON_ZERO]=Positive non zero decimal
+validationFailureParameter[DOUBLE_NEGATIVE_NON_ZERO]=Negative non zero decimal
syslog=System Log
pauseLog=Pause
continueLog=Continue
@@ -266,26 +293,50 @@ valueTypeDisplayName=Unknown value type
valueTypeDisplayName[OBJECT]=JSON object
valueTypeDisplayName[ARRAY]=JSON array
valueTypeDisplayName[NUMBER]=Number
-valueTypeDisplayName[BOOLEAN]=Toggle
-valueTypeDisplayName[STRING]=String
-assetMetaDisplayName=INVALID
-assetMetaDisplayName[PROTOCOL_CONFIGURATION]=Protocol configuration
-assetMetaDisplayName[AGENT_LINK]=Agent link
-assetMetaDisplayName[ATTRIBUTE_LINK]=Attribute link
-assetMetaDisplayName[LABEL]=Label
-assetMetaDisplayName[SHOW_ON_DASHBOARD]=Show on dashboard
-assetMetaDisplayName[FORMAT]=Format
-assetMetaDisplayName[DESCRIPTION]=Description
-assetMetaDisplayName[ABOUT]=About
-assetMetaDisplayName[READ_ONLY]=Read only
-assetMetaDisplayName[PROTECTED]=Protected
-assetMetaDisplayName[RANGE_MIN]=Min value
-assetMetaDisplayName[RANGE_MAX]=Max value
-assetMetaDisplayName[STEP]=Step
-assetMetaDisplayName[PATTERN]=Pattern
-assetMetaDisplayName[STORE_DATA_POINTS]=Store data points
-assetMetaDisplayName[RULE_STATE]=Rule state
-assetMetaDisplayName[RULE_EVENT]=Rule event
-assetMetaDisplayName[RULE_EVENT_EXPIRES]=Rule event expires
-assetMetaDisplayName[DISABLED]=Disabled
-assetMetaDisplayName[EXECUTABLE]=Executable
+valueTypeDisplayName[BOOLEAN]=On/Off toggle
+valueTypeDisplayName[STRING]=Text
+metaItemDisplayName=
+metaItemDisplayName[PROTOCOL_CONFIGURATION]=Protocol configuration
+metaItemDisplayName[AGENT_LINK]=Agent link
+metaItemDisplayName[ATTRIBUTE_LINK]=Attribute link
+metaItemDisplayName[LABEL]=Label
+metaItemDisplayName[SHOW_ON_DASHBOARD]=Show on dashboard
+metaItemDisplayName[FORMAT]=Format
+metaItemDisplayName[DESCRIPTION]=Description
+metaItemDisplayName[ABOUT]=About
+metaItemDisplayName[READ_ONLY]=Read only
+metaItemDisplayName[PROTECTED]=Protected
+metaItemDisplayName[RANGE_MIN]=Min value
+metaItemDisplayName[RANGE_MAX]=Max value
+metaItemDisplayName[STEP]=Step
+metaItemDisplayName[PATTERN]=Pattern
+metaItemDisplayName[STORE_DATA_POINTS]=Store data points
+metaItemDisplayName[RULE_STATE]=Rule state
+metaItemDisplayName[RULE_EVENT]=Rule event
+metaItemDisplayName[RULE_EVENT_EXPIRES]=Rule event expires
+metaItemDisplayName[DISABLED]=Disabled
+metaItemDisplayName[EXECUTABLE]=Executable
+metaItemDisplayName[PROTOCOL_MACRO_ACTION]=Macro Action
+metaItemDisplayName[PROTOCOL_MACRO_ACTION_INDEX]=Macro Action Index
+metaItemDisplayName[PROTOCOL_VELBUS_TIME_INJECTION_INTERVAL_SECONDS]=VELBUS Time Injection (s)
+metaItemDisplayName[PROTOCOL_VELBUS_SOCKET_HOST]=VELBUS Host
+metaItemDisplayName[PROTOCOL_VELBUS_SOCKET_PORT]=VELBUS Port
+metaItemDisplayName[PROTOCOL_VELBUS_SERIAL_PORT]=VELBUS Port
+metaItemDisplayName[PROTOCOL_VELBUS_SERIAL_BAUDRATE]=VELBUS Baudrate
+metaItemDisplayName[PROTOCOL_VELBUS_DEVICE_ADDRESS]=VELBUS Device Address
+metaItemDisplayName[PROTOCOL_VELBUS_DEVICE_LINK]=VELBUS Device Link
+metaItemDisplayName[PROTOCOL_KNX_IP]=KNX Gateway Host
+metaItemDisplayName[PROTOCOL_KNX_PORT]=KNX Gateway Port
+metaItemDisplayName[PROTOCOL_KNX_USENAT]=KNX Use NAT
+metaItemDisplayName[PROTOCOL_KNX_CONNECTION_TYPE]=KNX Connection Type
+metaItemDisplayName[PROTOCOL_KNX_LOCAL_BUS_ADDRESS]=KNX Local BUS Address
+metaItemDisplayName[PROTOCOL_KNX_LOCAL_IP]=KNX Local Host
+metaItemDisplayName[PROTOCOL_KNX_ACTION_GA]=KNX Actuator Group Address
+metaItemDisplayName[PROTOCOL_KNX_STATUS_GA]=KNX Status Group Address
+metaItemDisplayName[PROTOCOL_KNX_DPT]=KNX DPT
+metaItemDisplayName[PROTOCOL_TIMER_ACTION]=Timer Action
+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
diff --git a/manager/server/src/main/java/org/openremote/manager/server/agent/AgentConnector.java b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentConnector.java
new file mode 100644
index 000000000..e28d08983
--- /dev/null
+++ b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentConnector.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.manager.server.agent;
+
+import org.openremote.model.asset.Asset;
+import org.openremote.model.asset.AssetAttribute;
+import org.openremote.model.asset.agent.ProtocolDescriptor;
+import org.openremote.model.attribute.AttributeValidationResult;
+
+/**
+ * This is an interface for communicating with an agent. It
+ * should be stateless and re-usable.
+ */
+public interface AgentConnector {
+ ProtocolDescriptor[] getProtocolDescriptors(Asset agent);
+
+ AttributeValidationResult validateProtocolConfiguration(AssetAttribute protocolConfiguration);
+}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/agent/AgentResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentResourceImpl.java
new file mode 100644
index 000000000..1cadee6fd
--- /dev/null
+++ b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentResourceImpl.java
@@ -0,0 +1,119 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.manager.server.agent;
+
+import org.openremote.manager.server.asset.AssetResourceImpl;
+import org.openremote.manager.server.asset.ServerAsset;
+import org.openremote.manager.server.web.ManagerWebService;
+import org.openremote.manager.shared.agent.AgentResource;
+import org.openremote.manager.shared.http.RequestParams;
+import org.openremote.model.asset.Asset;
+import org.openremote.model.asset.AssetAttribute;
+import org.openremote.model.asset.AssetType;
+import org.openremote.model.asset.agent.ProtocolDescriptor;
+import org.openremote.model.attribute.AttributeValidationResult;
+import org.openremote.model.util.Pair;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.logging.Logger;
+
+public class AgentResourceImpl extends ManagerWebService implements AgentResource {
+
+ private static final Logger LOG = Logger.getLogger(AssetResourceImpl.class.getName());
+ protected AgentService agentService;
+
+ public AgentResourceImpl(AgentService agentService) {
+ this.agentService = agentService;
+ }
+
+ @Override
+ public ProtocolDescriptor[] getSupportedProtocols(RequestParams requestParams, String agentId) {
+ Asset[] agentFinal = new Asset[1];
+
+ return findAgent(agentId)
+ .flatMap(agent -> {
+ agentFinal[0] = agent;
+ return agentService.getAgentConnector(agent);
+ })
+ .map(agentConnector -> {
+ LOG.finer("Asking connector '" + agentConnector.getClass().getSimpleName() + "' for protocol descriptors");
+ return agentConnector.getProtocolDescriptors(agentFinal[0]);
+ })
+ .orElseThrow(() -> {
+ LOG.warning("Agent connector not found for agent ID: " + agentId);
+ return new IllegalStateException("Agent connector not found or returned invalid response");
+ });
+ }
+
+ @Override
+ public Map<String, ProtocolDescriptor[]> getAllSupportedProtocols(RequestParams requestParams) {
+ Map<String, ProtocolDescriptor[]> agentDescriptorMap = new HashMap<>(agentService.getAgents().size());
+ agentService.getAgents().forEach((id, agent) -> {
+
+ agentDescriptorMap.put(
+ id,
+ agentService.getAgentConnector(agent)
+ .map(agentConnector -> {
+ LOG.finer("Asking connector '" + agentConnector.getClass().getSimpleName() + "' for protocol descriptors");
+ return agentConnector.getProtocolDescriptors(agent);
+ })
+ .orElseThrow(() -> {
+ LOG.warning("Agent connector not found for agent ID: " + id);
+ return new IllegalStateException("Agent connector not found or returned invalid response");
+ })
+ );
+ });
+
+ return agentDescriptorMap;
+ }
+
+ @Override
+ public AssetAttribute[] getDiscoveredProtocolConfigurations(RequestParams requestParams, String agentId, String protocolName) {
+ return new AssetAttribute[0];
+ }
+
+ @Override
+ public AttributeValidationResult validateProtocolConfiguration(RequestParams requestParams, String agentId, AssetAttribute protocolConfiguration) {
+ return findAgent(agentId)
+ .flatMap(agent -> agentService.getAgentConnector(agent))
+ .map(agentConnector -> {
+ LOG.finer("Asking connector '" + agentConnector.getClass().getSimpleName() + "' to validate protocol configuration: " + protocolConfiguration);
+ return agentConnector.validateProtocolConfiguration(protocolConfiguration);
+ })
+ .orElseThrow(() -> {
+ LOG.warning("Agent connector not found for agent ID: " + agentId);
+ return new IllegalStateException("Agent connector not found or returned invalid response");
+ });
+ }
+
+ protected Optional<Asset> findAgent(String agentId) {
+ // Find the agent
+ LOG.finer("Find agent: " + agentId);
+ Asset agent = agentService.getAgents().get(agentId);
+ if (agent == null || agent.getWellKnownType() != AssetType.AGENT) {
+ LOG.warning("Failed to find agent with ID: " + agentId);
+ throw new IllegalArgumentException("Agent not found");
+ }
+ return Optional.of(agent);
+ }
+}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java
index e24cd8051..bb9eb6957 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java
@@ -28,11 +28,13 @@ import org.openremote.container.ContainerService;
import org.openremote.container.message.MessageBrokerService;
import org.openremote.container.message.MessageBrokerSetupService;
import org.openremote.container.persistence.PersistenceEvent;
+import org.openremote.container.web.WebService;
import org.openremote.manager.server.asset.AssetProcessingService;
import org.openremote.manager.server.asset.AssetStorageService;
import org.openremote.manager.server.asset.ServerAsset;
import org.openremote.model.AbstractValueTimestampHolder;
import org.openremote.model.asset.*;
+import org.openremote.model.asset.agent.Agent;
import org.openremote.model.asset.agent.AgentLink;
import org.openremote.model.asset.agent.ProtocolConfiguration;
import org.openremote.model.attribute.AttributeEvent;
@@ -78,6 +80,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons
protected final Map<AttributeRef, Pair<AssetAttribute, ConnectionStatus>> protocolConfigurations = new HashMap<>();
protected final Map<String, Protocol> protocols = new HashMap<>();
protected final List<AttributeRef> linkedAttributes = new ArrayList<>();
+ protected LocalAgentConnector localAgentConnector;
protected Map<String, Asset> agentMap;
@Override
@@ -86,6 +89,11 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons
assetProcessingService = container.getService(AssetProcessingService.class);
assetStorageService = container.getService(AssetStorageService.class);
messageBrokerService = container.getService(MessageBrokerService.class);
+ localAgentConnector = new LocalAgentConnector(this);
+
+ container.getService(WebService.class).getApiSingletons().add(
+ new AgentResourceImpl(this)
+ );
}
@Override
@@ -229,14 +237,14 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons
switch (persistenceEvent.getCause()) {
case INSERT:
-
+ addReplaceAgent(agent);
agent.getAttributesStream()
.filter(ProtocolConfiguration::isProtocolConfiguration)
.forEach(this::linkProtocolConfiguration);
break;
case UPDATE:
-
+ addReplaceAgent(agent);
// Check if any protocol config attributes have been added/removed or modified
int attributesIndex = Arrays.asList(persistenceEvent.getPropertyNames()).indexOf("attributes");
if (attributesIndex < 0) {
@@ -285,7 +293,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons
break;
case DELETE:
-
+ removeAgent(agent);
// Unlink any attributes that have an agent link to this agent
agent.getAttributesStream()
.filter(ProtocolConfiguration::isProtocolConfiguration)
@@ -398,7 +406,6 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons
}
protected void linkProtocolConfiguration(AssetAttribute protocolConfiguration) {
- LOG.fine("Linking all attributes that use protocol attribute: " + protocolConfiguration);
AttributeRef protocolAttributeRef = protocolConfiguration.getReferenceOrThrow();
Protocol protocol = getProtocol(protocolConfiguration);
@@ -459,7 +466,6 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons
}
protected void unlinkProtocolConfiguration(AssetAttribute protocolConfiguration) {
- LOG.fine("Unlinking all attributes that use protocol attribute: " + protocolConfiguration);
AttributeRef protocolAttributeRef = protocolConfiguration.getReferenceOrThrow();
// Get all assets that have attributes that use this protocol configuration
@@ -525,6 +531,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons
}
protected void linkAttributes(AssetAttribute protocolConfiguration, Collection<AssetAttribute> attributes) {
+ LOG.fine("Linking all attributes that use protocol attribute: " + protocolConfiguration);
Protocol protocol = getProtocol(protocolConfiguration);
if (protocol == null) {
@@ -548,6 +555,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons
}
protected void unlinkAttributes(AssetAttribute protocolConfiguration, Collection<AssetAttribute> attributes) {
+ LOG.fine("Unlinking all attributes that use protocol attribute: " + protocolConfiguration);
Protocol protocol = getProtocol(protocolConfiguration);
if (protocol == null) {
@@ -659,7 +667,23 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons
}
}
- protected synchronized Map<String, Asset> getAgents() {
+ public Optional<AgentConnector> getAgentConnector(Asset agent) {
+ if (agent == null || agent.getWellKnownType() != AGENT) {
+ return Optional.empty();
+ }
+
+ return !Agent.hasUrl(agent) ? Optional.of(localAgentConnector) : Optional.empty();
+ }
+
+ protected synchronized void addReplaceAgent(Asset agent) {
+ getAgents().put(agent.getId(), agent);
+ }
+
+ protected synchronized void removeAgent(Asset agent) {
+ getAgents().remove(agent.getId());
+ }
+
+ public synchronized Map<String, Asset> getAgents() {
if (agentMap == null) {
agentMap = assetStorageService.findAll(new AssetQuery()
.select(new AssetQuery.Select(AssetQuery.Include.ALL, false))
diff --git a/manager/server/src/main/java/org/openremote/manager/server/agent/LocalAgentConnector.java b/manager/server/src/main/java/org/openremote/manager/server/agent/LocalAgentConnector.java
new file mode 100644
index 000000000..57283fd00
--- /dev/null
+++ b/manager/server/src/main/java/org/openremote/manager/server/agent/LocalAgentConnector.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.manager.server.agent;
+
+import org.openremote.agent.protocol.Protocol;
+import org.openremote.model.ValidationFailure;
+import org.openremote.model.asset.Asset;
+import org.openremote.model.asset.AssetAttribute;
+import org.openremote.model.asset.agent.ProtocolConfiguration;
+import org.openremote.model.asset.agent.ProtocolDescriptor;
+import org.openremote.model.attribute.AttributeValidationResult;
+
+import java.util.Collections;
+
+public class LocalAgentConnector implements AgentConnector {
+
+ protected AgentService agentService;
+
+ public LocalAgentConnector(AgentService agentService) {
+ this.agentService = agentService;
+ }
+
+ @Override
+ public ProtocolDescriptor[] getProtocolDescriptors(Asset agent) {
+ return agentService.protocols
+ .values()
+ .stream()
+ .map(Protocol::getProtocolDescriptor).toArray(ProtocolDescriptor[]::new);
+ }
+
+ @Override
+ public AttributeValidationResult validateProtocolConfiguration(AssetAttribute protocolConfiguration) {
+ return agentService.protocols
+ .values()
+ .stream()
+ .filter(protocol -> protocol.getProtocolName().equals(protocolConfiguration.getValueAsString().orElse(null)))
+ .findFirst()
+ .map(protocol -> protocol.validateProtocolConfiguration(protocolConfiguration))
+ .orElse(new AttributeValidationResult(
+ protocolConfiguration.getName().orElse(null),
+ Collections.singletonList(
+ new ValidationFailure(
+ ProtocolConfiguration.ValidationFailureReason.VALUE_NOT_A_VALID_PROTOCOL_URN
+ )),
+ null));
+ }
+}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoKNXSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoKNXSetup.java
index 6e11def5a..7e8ac678c 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoKNXSetup.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoKNXSetup.java
@@ -39,8 +39,6 @@ import org.openremote.model.attribute.AttributeType;
import org.openremote.model.attribute.MetaItem;
import org.openremote.model.value.Values;
-import com.vividsolutions.jts.geom.Coordinate;
-
public class ManagerDemoKNXSetup extends AbstractManagerSetup {
public String masterRealmId;
@@ -66,7 +64,7 @@ public class ManagerDemoKNXSetup extends AbstractManagerSetup {
knxAgent.setAttributes(
initProtocolConfiguration(new AssetAttribute("knxConfig"), KNXProtocol.PROTOCOL_NAME)
.addMeta(
- new MetaItem(KNXProtocol.KNX_GATEWAY_IP, Values.create("192.168.100.10"))
+ new MetaItem(KNXProtocol.META_KNX_GATEWAY_IP, Values.create("192.168.100.10"))
)
);
knxAgent.setRealmId(masterTenant.getId());
@@ -78,27 +76,27 @@ public class ManagerDemoKNXSetup extends AbstractManagerSetup {
.setMeta(
new MetaItem(LABEL, Values.create("Light 1 (Switch)")),
new MetaItem(DESCRIPTION, Values.create("Light 1 connected to a KNX switch actuator")),
- new MetaItem(KNXProtocol.ACTION_GA, Values.create("1/0/17")),
- new MetaItem(KNXProtocol.STATUS_GA, Values.create("0/4/14")),
- new MetaItem(KNXProtocol.DPT, Values.create("1.001")),
+ new MetaItem(KNXProtocol.META_KNX_ACTION_GA, Values.create("1/0/17")),
+ new MetaItem(KNXProtocol.META_KNX_STATUS_GA, Values.create("0/4/14")),
+ new MetaItem(KNXProtocol.META_KNX_DPT, Values.create("1.001")),
new MetaItem(AssetMeta.AGENT_LINK, new AttributeRef(knxAgent.getId(), "knxConfig").toArrayValue())
),
new AssetAttribute("Light2_Switch", AttributeType.BOOLEAN)
.setMeta(
new MetaItem(LABEL, Values.create("Light 2 (Switch)")),
new MetaItem(DESCRIPTION, Values.create("Light 2 connected to a KNX dimming actuator")),
- new MetaItem(KNXProtocol.ACTION_GA, Values.create("1/0/11")),
- new MetaItem(KNXProtocol.STATUS_GA, Values.create("0/4/10")),
- new MetaItem(KNXProtocol.DPT, Values.create("1.001")),
+ new MetaItem(KNXProtocol.META_KNX_ACTION_GA, Values.create("1/0/11")),
+ new MetaItem(KNXProtocol.META_KNX_STATUS_GA, Values.create("0/4/10")),
+ new MetaItem(KNXProtocol.META_KNX_DPT, Values.create("1.001")),
new MetaItem(AssetMeta.AGENT_LINK, new AttributeRef(knxAgent.getId(), "knxConfig").toArrayValue())
),
new AssetAttribute("Light2_Dimming", AttributeType.PERCENTAGE)
.setMeta(
new MetaItem(LABEL, Values.create("Light 2 (Dimming)")),
new MetaItem(DESCRIPTION, Values.create("Light 2 connected to a KNX dimming actuator")),
- new MetaItem(KNXProtocol.ACTION_GA, Values.create("1/0/13")),
- new MetaItem(KNXProtocol.STATUS_GA, Values.create("0/4/11")),
- new MetaItem(KNXProtocol.DPT, Values.create("5.001")),
+ new MetaItem(KNXProtocol.META_KNX_ACTION_GA, Values.create("1/0/13")),
+ new MetaItem(KNXProtocol.META_KNX_STATUS_GA, Values.create("0/4/11")),
+ new MetaItem(KNXProtocol.META_KNX_DPT, Values.create("5.001")),
new MetaItem(AssetMeta.AGENT_LINK, new AttributeRef(knxAgent.getId(), "knxConfig").toArrayValue())
),
new AssetAttribute("Temperature", AttributeType.TEMPERATURE_CELCIUS)
@@ -106,8 +104,8 @@ public class ManagerDemoKNXSetup extends AbstractManagerSetup {
new MetaItem(LABEL, Values.create("Temperature")),
new MetaItem(DESCRIPTION, Values.create("Temperature given by a KNX sensor")),
new MetaItem(READ_ONLY, Values.create(true)),
- new MetaItem(KNXProtocol.STATUS_GA, Values.create("4/1/10")),
- new MetaItem(KNXProtocol.DPT, Values.create("9.001")),
+ new MetaItem(KNXProtocol.META_KNX_STATUS_GA, Values.create("4/1/10")),
+ new MetaItem(KNXProtocol.META_KNX_DPT, Values.create("9.001")),
new MetaItem(AssetMeta.AGENT_LINK, new AttributeRef(knxAgent.getId(), "knxConfig").toArrayValue())
),
new AssetAttribute("Presence", AttributeType.BOOLEAN)
@@ -115,8 +113,8 @@ public class ManagerDemoKNXSetup extends AbstractManagerSetup {
new MetaItem(LABEL, Values.create("Presence")),
new MetaItem(DESCRIPTION, Values.create("KNX presence detector")),
new MetaItem(READ_ONLY, Values.create(true)),
- new MetaItem(KNXProtocol.STATUS_GA, Values.create("4/0/2")),
- new MetaItem(KNXProtocol.DPT, Values.create("1.001")),
+ new MetaItem(KNXProtocol.META_KNX_STATUS_GA, Values.create("4/0/2")),
+ new MetaItem(KNXProtocol.META_KNX_DPT, Values.create("1.001")),
new MetaItem(AssetMeta.AGENT_LINK, new AttributeRef(knxAgent.getId(), "knxConfig").toArrayValue())
),
new AssetAttribute("WindowStatus", AttributeType.BOOLEAN)
@@ -124,8 +122,8 @@ public class ManagerDemoKNXSetup extends AbstractManagerSetup {
new MetaItem(LABEL, Values.create("Window status")),
new MetaItem(DESCRIPTION, Values.create("KNX binary input")),
new MetaItem(READ_ONLY, Values.create(true)),
- new MetaItem(KNXProtocol.STATUS_GA, Values.create("4/0/16")),
- new MetaItem(KNXProtocol.DPT, Values.create("1.001")),
+ new MetaItem(KNXProtocol.META_KNX_STATUS_GA, Values.create("4/0/16")),
+ new MetaItem(KNXProtocol.META_KNX_DPT, Values.create("1.001")),
new MetaItem(AssetMeta.AGENT_LINK, new AttributeRef(knxAgent.getId(), "knxConfig").toArrayValue())
)
);
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/agent/AgentResource.java b/manager/shared/src/main/java/org/openremote/manager/shared/agent/AgentResource.java
new file mode 100644
index 000000000..aeccaa9fd
--- /dev/null
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/agent/AgentResource.java
@@ -0,0 +1,99 @@
+/*
+ * 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.shared.agent;
+
+import jsinterop.annotations.JsType;
+import org.openremote.manager.shared.http.RequestParams;
+import org.openremote.manager.shared.http.SuccessStatusCode;
+import org.openremote.model.asset.AssetAttribute;
+import org.openremote.model.asset.agent.ProtocolDescriptor;
+import org.openremote.model.attribute.AttributeValidationResult;
+
+import javax.annotation.security.RolesAllowed;
+import javax.ws.rs.*;
+
+import java.util.Map;
+
+import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
+
+/**
+ * This resource is for Agent specific tasks; normal asset/attribute CRUD operations should still use
+ * {@link org.openremote.manager.shared.asset.AssetResource}.
+ *
+ *
+ *
+ */
+@Path("agent")
+@JsType(isNative = true)
+public interface AgentResource {
+
+ /**
+ * Retrieve all the protocols that the specified agent supports
+ */
+ @GET
+ @Path("protocol/{agentId}")
+ @Produces(APPLICATION_JSON)
+ @SuccessStatusCode(200)
+ @RolesAllowed({"read:assets"})
+ ProtocolDescriptor[] getSupportedProtocols(
+ @BeanParam RequestParams requestParams,
+ @PathParam("agentId") String agentId
+ );
+
+ /**
+ * Retrieve all the protocols for all the agents
+ */
+ @GET
+ @Path("protocol")
+ @Produces(APPLICATION_JSON)
+ @SuccessStatusCode(200)
+ @RolesAllowed({"read:assets"})
+ Map<String, ProtocolDescriptor[]> getAllSupportedProtocols(
+ @BeanParam RequestParams requestParams
+ );
+
+ /**
+ * Retrieve discovered protocol configurations for the specified protocol on the specified agent
+ */
+ @GET
+ @Path("configuration/{agentId}/{protocolName}")
+ @Produces(APPLICATION_JSON)
+ @SuccessStatusCode(200)
+ @RolesAllowed({"read:assets"})
+ AssetAttribute[] getDiscoveredProtocolConfigurations(
+ @BeanParam RequestParams requestParams,
+ @PathParam("agentId") String agentId,
+ @PathParam("protocolName") String protocolName
+ );
+
+ /**
+ * Ask the appropriate protocol on the specified agent to validate the supplied {@link org.openremote.model.asset.agent.ProtocolConfiguration}
+ */
+ @POST
+ @Path("validate/{agentId}")
+ @Consumes(APPLICATION_JSON)
+ @Produces(APPLICATION_JSON)
+ @SuccessStatusCode(200)
+ AttributeValidationResult validateProtocolConfiguration(
+ @BeanParam RequestParams requestParams,
+ @PathParam("agentId") String agentId,
+ AssetAttribute protocolConfiguration
+ );
+}
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/asset/AssetResource.java b/manager/shared/src/main/java/org/openremote/manager/shared/asset/AssetResource.java
index 6590a6fde..9ff4c8e55 100644
--- a/manager/shared/src/main/java/org/openremote/manager/shared/asset/AssetResource.java
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/asset/AssetResource.java
@@ -118,7 +118,7 @@ public interface AssetResource {
* the system upon insert. Regular users can only create assets in their authenticated realm, the superuser can
* create assets in other (all) realms. A 403 status is returned if a regular user tries to create an asset in a
* realm different than its authenticated realm, or if the user is restricted. A 400 status is returned if the
- * asset's parent or realm doesn't exist.
+ * asset's parent or realm doesn't exist or if an ID is provided and an asset with this ID already exists.
*/
@POST
@Consumes(APPLICATION_JSON)
diff --git a/manager/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy
index 018cbee14..7da9aebe5 100644
--- a/manager/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy
@@ -68,10 +68,20 @@ class AssetProcessingTest extends Specification implements ManagerContainerTrait
sendToActuatorEvents.add(event)
}
+ @Override
+ String getVersion() {
+ return "1.0"
+ }
+
@Override
String getProtocolName() {
return mockProtocolName
}
+
+ @Override
+ String getProtocolDisplayName() {
+ return "Mock"
+ }
}
and: "mock attribute state consumers"
diff --git a/manager/test/src/test/groovy/org/openremote/test/model/SerialisationTest.groovy b/manager/test/src/test/groovy/org/openremote/test/model/SerialisationTest.groovy
new file mode 100644
index 000000000..083eace16
--- /dev/null
+++ b/manager/test/src/test/groovy/org/openremote/test/model/SerialisationTest.groovy
@@ -0,0 +1,95 @@
+/*
+ * 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.test.model
+
+import org.openremote.agent.protocol.simulator.SimulatorProtocol
+import org.openremote.container.Container
+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.ProtocolConfiguration
+import org.openremote.model.attribute.AttributeValidationResult
+import org.openremote.model.attribute.MetaItem
+import org.openremote.model.value.Values
+import spock.lang.Specification
+
+class SerialisationTest extends Specification {
+
+ def "Serialize/Deserialize AssetAttribute"() {
+ given:
+ AssetAttribute attribute = new AssetAttribute("testAttribute")
+ ProtocolConfiguration.initProtocolConfiguration(attribute, SimulatorProtocol.PROTOCOL_NAME)
+ attribute.addMeta(
+ new MetaItem(AssetMeta.READ_ONLY, Values.create(true)),
+ new MetaItem(AssetMeta.LABEL, Values.create("Test Attribute"))
+ )
+
+ String str = Container.JSON.writeValueAsString(attribute)
+ attribute = Container.JSON.readValue(str, AssetAttribute.class)
+
+ expect:
+ attribute.getName().isPresent()
+ attribute.getName().get().equals("testAttribute")
+ attribute.getValueAsString().isPresent()
+ attribute.getValueAsString().get().equals(SimulatorProtocol.PROTOCOL_NAME)
+ attribute.getMetaItem(AssetMeta.PROTOCOL_CONFIGURATION).isPresent()
+ attribute.getMetaItem(AssetMeta.PROTOCOL_CONFIGURATION).get().getValueAsBoolean().isPresent()
+ attribute.getMetaItem(AssetMeta.PROTOCOL_CONFIGURATION).get().getValueAsBoolean().get()
+ attribute.getMetaItem(AssetMeta.READ_ONLY).isPresent()
+ attribute.getMetaItem(AssetMeta.READ_ONLY).get().getValueAsBoolean().isPresent()
+ attribute.getMetaItem(AssetMeta.READ_ONLY).get().getValueAsBoolean().get()
+ attribute.getMetaItem(AssetMeta.LABEL).isPresent()
+ attribute.getMetaItem(AssetMeta.LABEL).get().getValueAsString().isPresent()
+ attribute.getMetaItem(AssetMeta.LABEL).get().getValueAsString().get().equals("Test Attribute")
+ }
+
+ def "Serialize/Deserialize AttributeValidationResult"() {
+ given:
+ AttributeValidationResult result = new AttributeValidationResult(
+ "myAttribute",
+ [
+ new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_INVALID, "Test")
+ ],
+ [
+ 1: [new ValidationFailure(MetaItem.MetaItemFailureReason.META_ITEM_DUPLICATION)],
+ 2: [new ValidationFailure(MetaItem.MetaItemFailureReason.META_ITEM_MISSING, "my:meta")]
+ ]
+ )
+
+ String str = Container.JSON.writeValueAsString(result)
+ result = Container.JSON.readValue(str, AttributeValidationResult.class)
+
+ expect:
+ !result.isValid()
+ result.getAttributeFailures().size() == 1
+ result.getAttributeFailures().get(0).reason.name() == ValueHolder.ValueFailureReason.VALUE_INVALID.name()
+ result.getAttributeFailures().get(0).parameter.isPresent()
+ result.getAttributeFailures().get(0).parameter.get().equals("Test")
+ result.getMetaFailures().size() == 2
+ result.getMetaFailures()[1].size() == 1
+ result.getMetaFailures()[2].size() == 1
+ result.getMetaFailures()[1].get(0).reason.name() == MetaItem.MetaItemFailureReason.META_ITEM_DUPLICATION.name()
+ !result.getMetaFailures()[1].get(0).parameter.isPresent()
+ result.getMetaFailures()[2].get(0).reason.name() == MetaItem.MetaItemFailureReason.META_ITEM_MISSING.name()
+ result.getMetaFailures()[2].get(0).parameter.isPresent()
+ result.getMetaFailures()[2].get(0).parameter.get().equals("my:meta")
+ }
+}
diff --git a/manager/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovy b/manager/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovy
index 4f5d734a0..b3f0f0442 100644
--- a/manager/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovy
@@ -100,13 +100,13 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait {
if (!attribute.getMetaItem("MOCK_ATTRIBUTE_REQUIRED_META").isPresent()) {
// This tests exception handling during linking of attributes
- throw new IllegalStateException("Attribute is not valid");
+ throw new IllegalStateException("Attribute is not valid")
}
protocolLinkedAttributes[protocolConfiguration.getName().orElse("")] << attribute
- def deploymentStatus = getStatus(protocolConfiguration);
+ def deploymentStatus = getStatus(protocolConfiguration)
if (deploymentStatus == ConnectionStatus.CONNECTED) {
- String attributeName = attribute.getName().orElse("");
+ String attributeName = attribute.getName().orElse("")
if (attributeName.startsWith("lightToggle")) {
// Set all lights to on
updateLinkedAttribute(new AttributeState(attribute.getReferenceOrThrow(), Values.create(true)))
@@ -134,10 +134,20 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait {
protocolWriteAttributeEvents.add(event)
}
+ @Override
+ String getVersion() {
+ return "1.0"
+ }
+
@Override
String getProtocolName() {
return mockProtocolName
}
+
+ @Override
+ String getProtocolDisplayName() {
+ return "Mock"
+ }
}
and: "the container is started with the mock protocol"
diff --git a/manager/test/src/test/groovy/org/openremote/test/protocol/KNXProtocolTest.groovy b/manager/test/src/test/groovy/org/openremote/test/protocol/KNXProtocolTest.groovy
index df7a651e1..0b8e257ab 100644
--- a/manager/test/src/test/groovy/org/openremote/test/protocol/KNXProtocolTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/protocol/KNXProtocolTest.groovy
@@ -24,8 +24,6 @@ import tuwien.auto.calimero.server.knxnetip.DefaultServiceContainer
import static org.openremote.model.asset.AssetMeta.DESCRIPTION
import static org.openremote.model.asset.AssetMeta.LABEL
-import org.apache.camel.language.simple.ast.BlockStart
-import org.openremote.agent.protocol.AbstractProtocol
import org.openremote.agent.protocol.knx.KNXProtocol
import org.openremote.agent.protocol.ConnectionStatus
import org.openremote.manager.server.agent.AgentService
@@ -41,7 +39,6 @@ import org.openremote.model.attribute.*
import org.openremote.model.value.Values
import org.openremote.test.KNXTestingNetworkLink
import org.openremote.test.ManagerContainerTrait
-import spock.lang.Ignore
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
import tuwien.auto.calimero.server.Launcher
@@ -94,13 +91,13 @@ class KNXProtocolTest extends Specification implements ManagerContainerTrait {
knxAgent.setAttributes(
ProtocolConfiguration.initProtocolConfiguration(new AssetAttribute("knxConfig"), KNXProtocol.PROTOCOL_NAME)
.addMeta(
- new MetaItem(KNXProtocol.KNX_GATEWAY_IP, Values.create("localhost")),
- new MetaItem(KNXProtocol.KNX_LOCAL_IP, Values.create("localhost"))
+ new MetaItem(KNXProtocol.META_KNX_GATEWAY_IP, Values.create("localhost")),
+ new MetaItem(KNXProtocol.META_KNX_LOCAL_IP, Values.create("localhost"))
),
ProtocolConfiguration.initProtocolConfiguration(new AssetAttribute("knxConfigError1"), KNXProtocol.PROTOCOL_NAME),
ProtocolConfiguration.initProtocolConfiguration(new AssetAttribute("knxConfigError2"), KNXProtocol.PROTOCOL_NAME)
.addMeta(
- new MetaItem(KNXProtocol.KNX_IP_CONNECTION_TYPE, Values.create("dummy"))
+ new MetaItem(KNXProtocol.META_KNX_IP_CONNECTION_TYPE, Values.create("dummy"))
)
)
knxAgent.setRealmId(Constants.MASTER_REALM)
@@ -125,9 +122,9 @@ class KNXProtocolTest extends Specification implements ManagerContainerTrait {
.setMeta(
new MetaItem(LABEL, Values.create("Light 1 Toggle On/Off")),
new MetaItem(DESCRIPTION, Values.create("Light 1 for living room")),
- new MetaItem(KNXProtocol.ACTION_GA, Values.create("1/0/17")),
- new MetaItem(KNXProtocol.STATUS_GA, Values.create("0/4/14")),
- new MetaItem(KNXProtocol.DPT, Values.create("1.001")),
+ new MetaItem(KNXProtocol.META_KNX_ACTION_GA, Values.create("1/0/17")),
+ new MetaItem(KNXProtocol.META_KNX_STATUS_GA, Values.create("0/4/14")),
+ new MetaItem(KNXProtocol.META_KNX_DPT, Values.create("1.001")),
new MetaItem(AssetMeta.AGENT_LINK, new AttributeRef(knxAgent.getId(), "knxConfig").toArrayValue())
)
)
diff --git a/model/src/main/java/org/openremote/model/AbstractValueHolder.java b/model/src/main/java/org/openremote/model/AbstractValueHolder.java
index 80c44fde2..baf086466 100644
--- a/model/src/main/java/org/openremote/model/AbstractValueHolder.java
+++ b/model/src/main/java/org/openremote/model/AbstractValueHolder.java
@@ -19,10 +19,10 @@
*/
package org.openremote.model;
+import com.fasterxml.jackson.annotation.JsonProperty;
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.List;
@@ -38,16 +38,24 @@ public abstract class AbstractValueHolder implements ValueHolder {
protected static final String VALUE_FIELD_NAME = "value";
- final protected ObjectValue objectValue;
+ protected ObjectValue objectValue;
public AbstractValueHolder(ObjectValue objectValue) {
this.objectValue = Objects.requireNonNull(objectValue);
}
+ // JsonProperty needed by GWT jackson
+ @JsonProperty
public ObjectValue getObjectValue() {
return objectValue;
}
+ // JsonProperty needed by GWT jackson
+ @JsonProperty
+ private void setObjectValue(ObjectValue objectValue) {
+ this.objectValue = objectValue;
+ }
+
@Override
public void clearValue() {
objectValue.remove(VALUE_FIELD_NAME);
diff --git a/model/src/main/java/org/openremote/model/ValidationFailure.java b/model/src/main/java/org/openremote/model/ValidationFailure.java
index d2c8c388a..e34b6bcf9 100644
--- a/model/src/main/java/org/openremote/model/ValidationFailure.java
+++ b/model/src/main/java/org/openremote/model/ValidationFailure.java
@@ -19,11 +19,64 @@
*/
package org.openremote.model;
+import com.fasterxml.jackson.annotation.*;
+import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
+import com.fasterxml.jackson.databind.annotation.JsonSerialize;
+
+import java.util.Optional;
+
/**
- * Unified naming of value holder validation failures. Names are supposed to be
- * unique so user-readable strings can be created from names with I18N mapping.
+ * Unified naming of value holder validation failures. {@link Reason} names are supposed to be
+ * unique so user-readable strings can be created from names with I18N mapping. The parameter can be
+ * used to convey more specific failure information (is dependent on I18N implementation) e.g. Missing
+ * meta item 'my.custom.meta.item'.
*/
-public interface ValidationFailure {
-
- String name();
+public class ValidationFailure {
+
+ @JsonSerialize(as = Reason.class)
+ @JsonDeserialize(as = ReasonImpl.class)
+ public interface Reason {
+ @JsonProperty("name")
+ String name();
+ }
+
+ public static class ReasonImpl implements Reason {
+ @JsonProperty("name")
+ protected final String name;
+
+ @JsonCreator
+ public ReasonImpl(@JsonProperty("name") String name) {
+ this.name = name;
+ }
+
+ @Override
+ public String name() {
+ return name;
+ }
+ }
+
+ @JsonProperty
+ protected Reason reason;
+ @JsonProperty // This is called param because GWT Jackson is crap at resolving annotations
+ protected String param;
+
+ public ValidationFailure(Reason reason) {
+ this(reason, null);
+ }
+
+ @JsonCreator
+ public ValidationFailure(@JsonProperty("reason") Reason reason, @JsonProperty("param") String parameter) {
+ this.reason = reason;
+ this.param = parameter;
+ }
+
+ @JsonIgnore
+ public Reason getReason() {
+ return reason;
+ }
+
+ @JsonIgnore
+ public Optional<String> getParameter() {
+ return Optional.ofNullable(param);
+ }
}
diff --git a/model/src/main/java/org/openremote/model/ValueHolder.java b/model/src/main/java/org/openremote/model/ValueHolder.java
index 08317201b..76322595e 100644
--- a/model/src/main/java/org/openremote/model/ValueHolder.java
+++ b/model/src/main/java/org/openremote/model/ValueHolder.java
@@ -19,6 +19,7 @@
*/
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;
@@ -31,6 +32,22 @@ import java.util.Optional;
*/
public interface ValueHolder {
+ enum ValueFailureReason implements ValidationFailure.Reason {
+ VALUE_PERCENTAGE_OUT_OF_RANGE,
+ VALUE_INVALID_COLOR_FORMAT,
+ VALUE_TEMPERATURE_OUT_OF_RANGE,
+ 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
+ }
+
void clearValue();
Optional<Value> getValue();
diff --git a/model/src/main/java/org/openremote/model/asset/Asset.java b/model/src/main/java/org/openremote/model/asset/Asset.java
index bc34fd0cb..27b516c28 100644
--- a/model/src/main/java/org/openremote/model/asset/Asset.java
+++ b/model/src/main/java/org/openremote/model/asset/Asset.java
@@ -19,12 +19,14 @@
*/
package org.openremote.model.asset;
+import com.fasterxml.jackson.annotation.JsonIgnore;
import org.hibernate.annotations.Formula;
import org.openremote.model.IdentifiableEntity;
import org.openremote.model.attribute.Attribute;
import org.openremote.model.geo.GeoJSON;
import org.openremote.model.geo.GeoJSONFeature;
import org.openremote.model.geo.GeoJSONGeometry;
+import org.openremote.model.util.ObservableList;
import org.openremote.model.util.TextUtil;
import org.openremote.model.value.ObjectValue;
import org.openremote.model.value.Values;
@@ -34,11 +36,9 @@ import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.math.BigDecimal;
import java.math.RoundingMode;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.List;
-import java.util.Optional;
+import java.util.*;
import java.util.function.Predicate;
+import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -264,6 +264,10 @@ public class Asset implements IdentifiableEntity {
@Transient
protected double[] coordinates;
+ @Transient
+ @JsonIgnore
+ protected ObservableList<AssetAttribute> attributeList;
+
// The following are expensive to query, so if they are null, they might not have been loaded
@Formula("get_asset_tree_path(ID)")
@@ -331,10 +335,6 @@ public class Asset implements IdentifiableEntity {
public void addAttributes(AssetAttribute... attributes) throws IllegalArgumentException {
- if (this.attributes == null) {
- this.attributes = Values.createObject();
- }
-
Arrays.asList(attributes).forEach(
attribute -> {
if (getAttributesStream().anyMatch(attr -> isAttributeNameEqualTo(attr, attribute.getName().orElse(null)))) {
@@ -354,18 +354,14 @@ public class Asset implements IdentifiableEntity {
throw new IllegalArgumentException("Attribute cannot be null and must have a name and type");
attribute.assetId = getId();
- if (attributes == null) {
- attributes = Values.createObject();
- }
- attributes.put(attribute.getName().get(), attribute.getObjectValue());
+ List<AssetAttribute> attributeList = getAttributesList();
+ attributeList.removeIf(attr -> attr.getName().orElse("").equals(attribute.getName().orElse("")));
+ attributeList.add(attribute);
}
public void removeAttribute(String name) {
- if (attributes == null) {
- return;
- }
-
- attributes.remove(name);
+ List<AssetAttribute> attributeList = getAttributesList();
+ attributeList.removeIf(attr -> attr.getName().orElse("").equals(name));
}
public String getId() {
@@ -538,11 +534,16 @@ public class Asset implements IdentifiableEntity {
}
public Stream<AssetAttribute> getAttributesStream() {
- return attributesFromJson(attributes, id);
+ return getAttributesList().stream();
}
public List<AssetAttribute> getAttributesList() {
- return getAttributesStream().collect(Collectors.toList());
+ if (attributeList == null) {
+ attributeList = new ObservableList<>(attributesFromJson(attributes, id).collect(Collectors.toList()), () -> {
+ this.attributes = attributesToJson(attributeList).orElse(Values.createObject());
+ });
+ }
+ return attributeList;
}
public boolean hasAttribute(String name) {
@@ -555,11 +556,12 @@ public class Asset implements IdentifiableEntity {
}
public void setAttributes(ObjectValue attributes) {
- this.attributes = attributes;
+ setAttributes(attributesFromJson(attributes, id).collect(Collectors.toList()));
}
public void setAttributes(List<AssetAttribute> attributes) {
- this.attributes = attributesToJson(attributes).orElse(Values.createObject());
+ ((ObservableList)getAttributesList()).clear(false);
+ getAttributesList().addAll(attributes);
}
public void setAttributes(AssetAttribute... attributes) {
@@ -642,8 +644,6 @@ public class Asset implements IdentifiableEntity {
if (asset == null)
return;
- List<AssetAttribute> attributes = asset.getAttributesList();
- attributes.removeIf(filter);
- asset.setAttributes(attributes);
+ asset.getAttributesList().removeIf(filter);
}
}
\ No newline at end of file
diff --git a/model/src/main/java/org/openremote/model/asset/AssetAttribute.java b/model/src/main/java/org/openremote/model/asset/AssetAttribute.java
index b6fea2382..5f2217d71 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetAttribute.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetAttribute.java
@@ -19,6 +19,8 @@
*/
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.*;
@@ -31,7 +33,6 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
-import java.util.function.Predicate;
import java.util.stream.Stream;
import static org.openremote.model.asset.AssetMeta.*;
@@ -88,6 +89,7 @@ public class AssetAttribute extends Attribute {
setAssetId(assetId);
}
+ @JsonIgnore
public Optional<String> getAssetId() {
return Optional.ofNullable(assetId);
}
@@ -119,12 +121,7 @@ public class AssetAttribute extends Attribute {
@Override
public List<ValidationFailure> getMetaItemValidationFailures(MetaItem item) {
- List<ValidationFailure> failures = super.getMetaItemValidationFailures(item);
-
- // Validate well-known meta items
- AssetMeta.getValidationFailure(item).ifPresent(failures::add);
-
- return failures;
+ return super.getMetaItemValidationFailures(item);
}
@Override
@@ -374,8 +371,8 @@ public class AssetAttribute extends Attribute {
public AssetAttribute deepCopy() {
AssetAttribute copy = new AssetAttribute(getObjectValue().deepCopy());
- copy.assetId = assetId;
copy.name = name;
+ copy.assetId = assetId;
return copy;
}
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 d227b1a14..ed89602c4 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetMeta.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetMeta.java
@@ -19,11 +19,11 @@
*/
package org.openremote.model.asset;
-import org.openremote.model.HasUniqueResourceName;
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.util.Pair;
+import org.openremote.model.attribute.MetaItemDescriptor;
import org.openremote.model.value.Value;
import org.openremote.model.value.ValueType;
import org.openremote.model.value.Values;
@@ -32,9 +32,11 @@ import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
+import java.util.function.Function;
import static org.openremote.model.Constants.ASSET_META_NAMESPACE;
-import static org.openremote.model.asset.AssetMeta.AssetMetaValidationFailure.VALUE_DOES_NOT_MATCH_ASSET_META_TYPE;
+import static org.openremote.model.attribute.MetaItem.MetaItemFailureReason.META_ITEM_VALUE_MISMATCH;
+import static org.openremote.model.util.TextUtil.REGEXP_PATTERN_DOUBLE;
import static org.openremote.model.util.TextUtil.isNullOrEmpty;
/**
@@ -43,95 +45,204 @@ import static org.openremote.model.util.TextUtil.isNullOrEmpty;
* <p>
* TODO https://people.eecs.berkeley.edu/~arka/papers/buildsys2015_metadatasurvey.pdf
*/
-public enum AssetMeta implements HasUniqueResourceName {
+public enum AssetMeta implements MetaItemDescriptor {
/**
* Marks an attribute of an agent asset as a {@link org.openremote.model.asset.agent.ProtocolConfiguration}.
* The attribute value is a protocol URN.
*/
- PROTOCOL_CONFIGURATION(ASSET_META_NAMESPACE + ":protocolConfiguration", new Access(false, false, true), ValueType.BOOLEAN, Values.create(true), true),
+ PROTOCOL_CONFIGURATION(
+ ASSET_META_NAMESPACE + ":protocolConfiguration", new Access(false, false, true),
+ ValueType.BOOLEAN,
+ null,
+ null,
+ Values.create(true),
+ true),
/**
* Links the attribute to an agent's {@link org.openremote.model.asset.agent.ProtocolConfiguration}, connecting it
* to a sensor and/or actuator.
*/
- AGENT_LINK(ASSET_META_NAMESPACE + ":agentLink", new Access(false, false, true), ValueType.ARRAY),
+ AGENT_LINK(
+ ASSET_META_NAMESPACE + ":agentLink",
+ new Access(false, false, true),
+ ValueType.ARRAY,
+ null,
+ null,
+ null,
+ false,
+ value ->
+ Optional.ofNullable(AttributeRef.isAttributeRef(value)
+ ? null
+ : new ValidationFailure(META_ITEM_VALUE_MISMATCH, AttributeRef.class.getSimpleName()))
+ ),
/**
* Links the attribute to another attribute, so an attribute event on the attribute triggers the same attribute
* event on the linked attribute.
*/
- ATTRIBUTE_LINK(ASSET_META_NAMESPACE + ":attributeLink", new Access(false, false, true), ValueType.OBJECT),
+ ATTRIBUTE_LINK(
+ ASSET_META_NAMESPACE + ":attributeLink",
+ new Access(false, false, true),
+ ValueType.OBJECT,
+ null,
+ null,
+ null,
+ false),
/**
* A human-friendly string that can be displayed in UI instead of the raw attribute name.
*/
- LABEL(ASSET_META_NAMESPACE + ":label", new Access(true, true, true), ValueType.STRING),
+ LABEL(
+ ASSET_META_NAMESPACE + ":label",
+ new Access(true, true, true),
+ ValueType.STRING,
+ null,
+ null,
+ null,
+ false),
/**
* If there is a dashboard, some kind of attribute overview, should this attribute be shown.
*/
- SHOW_ON_DASHBOARD(ASSET_META_NAMESPACE + ":showOnDashboard", new Access(true, true, true), ValueType.BOOLEAN, Values.create(true), true),
+ SHOW_ON_DASHBOARD(
+ ASSET_META_NAMESPACE + ":showOnDashboard",
+ new Access(true, true, true),
+ ValueType.BOOLEAN,
+ null,
+ null,
+ Values.create(true),
+ true),
/**
* Format string that can be used to render the attribute value, see https://github.com/alexei/sprintf.js.
*/
- FORMAT(ASSET_META_NAMESPACE + ":format", new Access(true, false, true), ValueType.STRING),
+ FORMAT(
+ ASSET_META_NAMESPACE + ":format",
+ new Access(true, false, true),
+ ValueType.STRING,
+ null,
+ null,
+ null,
+ false),
/**
* A human-friendly string describing the purpose of an attribute, useful when rendering editors.
*/
- DESCRIPTION(ASSET_META_NAMESPACE + ":description", new Access(true, false, true), ValueType.STRING),
+ DESCRIPTION(
+ ASSET_META_NAMESPACE + ":description",
+ new Access(true, false, true),
+ ValueType.STRING,
+ null,
+ null,
+ null,
+ false),
/**
* Points to semantic description of the attribute, typically a URI.
*/
- ABOUT(ASSET_META_NAMESPACE + ":about", new Access(true, false, true), ValueType.STRING),
+ ABOUT(
+ ASSET_META_NAMESPACE + ":about",
+ new Access(true, false, true),
+ ValueType.STRING,
+ null,
+ null,
+ null,
+ false),
/**
* Marks the attribute as read-only for clients. South-bound changes of the attribute are not possible.
* North-bound attribute updates made by protocols and changes made by rules are possible.
*/
- READ_ONLY(ASSET_META_NAMESPACE + ":readOnly", new Access(true, false, true), ValueType.BOOLEAN, Values.create(true), true),
+ READ_ONLY(
+ ASSET_META_NAMESPACE + ":readOnly",
+ new Access(true, false, true),
+ ValueType.BOOLEAN,
+ null,
+ null,
+ Values.create(true),
+ true),
/**
* Marks the attribute as protected and accessible to restricted users, see {@link UserAsset}.
* TODO: Shouldn't this mean the opposite if something is protected then you need elevated privileges to access it
*/
- PROTECTED(ASSET_META_NAMESPACE + ":protected", new Access(false, false, true), ValueType.BOOLEAN, Values.create(true), true),
-
- /**
- * RT: This wasn't used anywhere and not really sure when it would be useful so removing for now.
- */
- /**
- * Default value that might be used when editing an attribute.
- */
+ PROTECTED(
+ ASSET_META_NAMESPACE + ":protected",
+ new Access(false, false, true),
+ ValueType.BOOLEAN,
+ null,
+ null,
+ Values.create(true),
+ true),
+
+// /**
+// * RT: This wasn't used anywhere and not really sure when it would be useful so removing for now.
+// */
+// /**
+// * Default value that might be used when editing an attribute.
+// */
//DEFAULT(ASSET_META_NAMESPACE + ":default", new Access(false, false, false), ValueType.STRING),
/**
* Minimum range constraint for numeric attribute values.
*/
- RANGE_MIN(ASSET_META_NAMESPACE + ":rangeMin", new Access(true, false, true), ValueType.NUMBER),
+ RANGE_MIN(
+ ASSET_META_NAMESPACE + ":rangeMin",
+ new Access(true, false, true),
+ ValueType.NUMBER,
+ REGEXP_PATTERN_DOUBLE,
+ PatternFailure.DOUBLE.name(),
+ null,
+ false),
/**
* Maximum range constraint for numeric attribute values.
*/
- RANGE_MAX(ASSET_META_NAMESPACE + ":rangeMax", new Access(true, false, true), ValueType.NUMBER),
+ RANGE_MAX(
+ ASSET_META_NAMESPACE + ":rangeMax",
+ new Access(true, false, true),
+ ValueType.NUMBER,
+ REGEXP_PATTERN_DOUBLE,
+ PatternFailure.DOUBLE.name(),
+ null,
+ false),
/**
* Step increment/decrement constraint for numeric attribute values.
*/
- STEP(ASSET_META_NAMESPACE + ":step", new Access(true, false, true), ValueType.NUMBER),
+ STEP(
+ ASSET_META_NAMESPACE + ":step",
+ new Access(true, false, true),
+ ValueType.NUMBER,
+ REGEXP_PATTERN_DOUBLE,
+ PatternFailure.DOUBLE.name(),
+ null,
+ false),
/**
* Regex (Java syntax) constraint for string attribute values.
*/
- PATTERN(ASSET_META_NAMESPACE + ":pattern", new Access(true, false, true), ValueType.STRING),
+ PATTERN(
+ ASSET_META_NAMESPACE + ":pattern",
+ new Access(true, false, true),
+ ValueType.STRING,
+ null,
+ null,
+ null,
+ false),
/**
* Should attribute values be stored in time series database
*/
- STORE_DATA_POINTS(ASSET_META_NAMESPACE + ":storeDataPoints", new Access(true, false, true), ValueType.BOOLEAN, Values.create(true), true),
+ STORE_DATA_POINTS(
+ ASSET_META_NAMESPACE + ":storeDataPoints",
+ new Access(true, false, true),
+ ValueType.BOOLEAN,
+ null,
+ null,
+ Values.create(true),
+ true),
/**
* Should attribute writes be processed by the rules engines as {@link AssetState} facts in knowledge sessions,
@@ -140,7 +251,14 @@ public enum AssetMeta implements HasUniqueResourceName {
* when the attribute is updated. If you want two types of facts in your rules knowledge session for a single
* attribute, with state and event behavior, combine this with {@link #RULE_EVENT}.
*/
- RULE_STATE(ASSET_META_NAMESPACE + ":ruleState", new Access(true, false, true), ValueType.BOOLEAN, Values.create(true), true),
+ RULE_STATE(
+ ASSET_META_NAMESPACE + ":ruleState",
+ new Access(true, false, true),
+ ValueType.BOOLEAN,
+ null,
+ null,
+ Values.create(true),
+ true),
/**
* Should attribute writes be processed by the rules engines as events in knowledge sessions. Any attribute
@@ -149,48 +267,80 @@ public enum AssetMeta implements HasUniqueResourceName {
* If you want two types of facts in your rules knowledge session for a single attribute, with state and event
* behavior, combine this with {@link #RULE_STATE}.
*/
- RULE_EVENT(ASSET_META_NAMESPACE + ":ruleEvent", new Access(true, false, true), ValueType.BOOLEAN, Values.create(true), true),
+ RULE_EVENT(
+ ASSET_META_NAMESPACE + ":ruleEvent",
+ new Access(true, false, true),
+ ValueType.BOOLEAN,
+ null,
+ null,
+ Values.create(true),
+ true),
/**
* Set maximum lifetime of {@link AssetEvent} facts in knowledge sessions, for example "1h30m". The rules
* engine will remove {@link AssetEvent} facts from the rules sessions if they are older than this value
* (using event source timestamp, not event processing time).
*/
- RULE_EVENT_EXPIRES(ASSET_META_NAMESPACE + ":ruleEventExpires", new Access(true, false, true), ValueType.STRING),
+ RULE_EVENT_EXPIRES(
+ ASSET_META_NAMESPACE + ":ruleEventExpires",
+ new Access(true, false, true),
+ ValueType.STRING,
+ "^([+-])?((\\d+)[Dd])?\\s*((\\d+)[Hh])?\\s*((\\d+)[Mm])?\\s*((\\d+)[Ss])?\\s*((\\d+)([Mm][Ss])?)?$", // From DROOLS
+ PatternFailure.DAYS_HOURS_MINS_SECONDS.name(),
+ null,
+ false),
/**
* Disabled flag to be used by asset attributes that could require this functionality (e.g. {@link org.openremote.model.asset.agent.ProtocolConfiguration})
*/
- DISABLED(ASSET_META_NAMESPACE + ":disabled", new Access(true, false, true), ValueType.BOOLEAN, Values.create(true), true),
+ DISABLED(
+ ASSET_META_NAMESPACE + ":disabled",
+ new Access(true, false, true),
+ ValueType.BOOLEAN,
+ null,
+ null,
+ Values.create(true),
+ true),
/**
* Marks an attribute as being executable so it then supports values of type {@link AttributeExecuteStatus}.
*/
- EXECUTABLE(ASSET_META_NAMESPACE + ":executable", new Access(true, false, true), ValueType.BOOLEAN, Values.create(true), true);
-
- public enum AssetMetaValidationFailure implements ValidationFailure {
- VALUE_DOES_NOT_MATCH_ASSET_META_TYPE
- }
+ EXECUTABLE(
+ ASSET_META_NAMESPACE + ":executable",
+ new Access(true, false, true),
+ ValueType.BOOLEAN,
+ null,
+ null,
+ Values.create(true),
+ true);
final protected String urn;
final protected Access access;
final protected ValueType valueType;
final protected Value initialValue;
final protected boolean valueFixed;
-
- AssetMeta(String urn, Access access, ValueType valueType) {
- this(urn, access, valueType, null, false);
+ final protected Integer maxPerAttribute = 1; // All asset meta so far are single instance
+ final protected boolean required = false; // All asset meta so far are not mandatory
+ final protected String pattern;
+ final protected String patternFailureMessage;
+ final protected Function<Value, Optional<ValidationFailure>> validator;
+
+ AssetMeta(String urn, Access access, ValueType valueType, String pattern, String patternFailureMessage, Value initialValue, boolean valueFixed) {
+ this(urn, access, valueType, pattern, patternFailureMessage, initialValue, valueFixed, null);
}
- AssetMeta(String urn, Access access, ValueType valueType, Value initialValue, boolean valueFixed) {
+ AssetMeta(String urn, Access access, ValueType valueType, String pattern, String patternFailureMessage, Value initialValue, boolean valueFixed, Function<Value, Optional<ValidationFailure>> validator) {
if (initialValue != null && initialValue.getType() != valueType) {
throw new IllegalStateException("Initial asset meta value must be of the same type as the asset meta");
}
+ this.validator = validator;
this.urn = urn;
this.access = access;
this.valueType = valueType;
this.initialValue = initialValue;
this.valueFixed = valueFixed;
+ this.pattern = pattern;
+ this.patternFailureMessage = patternFailureMessage;
}
public String getUrn() {
@@ -205,6 +355,32 @@ public enum AssetMeta implements HasUniqueResourceName {
return valueType;
}
+ @Override
+ public boolean isRequired() {
+ return required;
+ }
+
+ @Override
+ public String getPattern() {
+ return pattern;
+ }
+
+ public String getPatternFailureMessage() {
+ return patternFailureMessage;
+ }
+
+ @Override
+ public Integer getMaxPerAttribute() {
+ return maxPerAttribute;
+ }
+
+ @Override
+ public Optional<ValidationFailure> validateValue(Value value) {
+ return Optional.ofNullable(MetaItemDescriptor
+ .validateValue(value, this)
+ .orElse(validator != null ? validator.apply(value).orElse(null) : null));
+ }
+
public Value getInitialValue() {
return initialValue;
}
@@ -220,20 +396,6 @@ public enum AssetMeta implements HasUniqueResourceName {
return access != null && access.restricted;
}
- /**
- * If this is a well-known item, the value must match the defined type.
- * Third-party items are always valid.
- */
- public Optional<ValidationFailure> isValidValue(Value value) {
- if (value == null) {
- return Optional.empty();
- }
- if (getValueType() != value.getType()) {
- return Optional.of(VALUE_DOES_NOT_MATCH_ASSET_META_TYPE);
- }
- return Optional.empty();
- }
-
public static AssetMeta[] unRestricted() {
List<AssetMeta> list = new ArrayList<>();
for (AssetMeta meta : values()) {
@@ -277,14 +439,6 @@ public enum AssetMeta implements HasUniqueResourceName {
return Optional.empty();
}
- public static Optional<ValidationFailure> getValidationFailure(MetaItem item) {
- return item.getName()
- .flatMap(AssetMeta::getAssetMeta)
- .map(assetMeta -> new Pair<>(assetMeta, item.getValue()))
- .filter(pair -> pair.value.isPresent())
- .flatMap(pair -> pair.key.isValidValue(pair.value.get()));
- }
-
/**
* Some well-known items can be protected readable.
*
diff --git a/model/src/main/java/org/openremote/model/asset/agent/Agent.java b/model/src/main/java/org/openremote/model/asset/agent/Agent.java
new file mode 100644
index 000000000..d720ba598
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/asset/agent/Agent.java
@@ -0,0 +1,125 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.asset.agent;
+
+import org.kie.api.task.model.User;
+import org.openremote.model.AbstractValueHolder;
+import org.openremote.model.asset.Asset;
+import org.openremote.model.asset.AssetAttribute;
+import org.openremote.model.asset.AssetType;
+import org.openremote.model.attribute.AttributeType;
+import org.openremote.model.security.UserPasswordCredentials;
+import org.openremote.model.value.Values;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+import static org.openremote.model.util.TextUtil.isNullOrEmpty;
+
+/**
+ * An agent is a special type of {@link Asset} with an AssetType of {@link AssetType#AGENT}.
+ * <p>
+ * If the agent doesn't have an attribute with the name {@link #URL_ATTRIBUTE_NAME} then it is assumed that the agent is
+ * running in the current VM (i.e. a local agent).
+ * <p>
+ * Currently only local agents are supported.
+ */
+public final class Agent {
+
+ protected static final String URL_ATTRIBUTE_NAME = "url";
+ protected static final String CREDENTIALS_ATTRIBUTE_NAME = "credentials";
+ protected Asset asset;
+
+ private Agent() {
+ }
+
+ public static void initAgent(Asset asset) {
+ asset.setType(AssetType.AGENT);
+ }
+
+ public static boolean hasUrl(Asset asset) {
+ return asset != null && asset
+ .getAttribute(URL_ATTRIBUTE_NAME)
+ .flatMap(AbstractValueHolder::getValueAsString)
+ .isPresent();
+ }
+
+ public static Optional<String> getUrl(Asset asset) {
+ return asset == null ? Optional.empty() : asset
+ .getAttribute(URL_ATTRIBUTE_NAME)
+ .flatMap(AbstractValueHolder::getValueAsString);
+ }
+
+ public static void setUrl(Asset asset, String url) {
+ if (asset != null) {
+ if (isNullOrEmpty(url)) {
+ asset.removeAttribute(URL_ATTRIBUTE_NAME);
+ } else {
+ asset.replaceAttribute(new AssetAttribute(URL_ATTRIBUTE_NAME, AttributeType.STRING, Values.create(url)));
+ }
+ }
+ }
+
+ public static boolean hasCredentials(Asset asset) {
+ return asset != null && asset
+ .getAttribute(CREDENTIALS_ATTRIBUTE_NAME)
+ .filter(UserPasswordCredentials::isUserPasswordCredentials)
+ .isPresent();
+ }
+
+ public static Optional<UserPasswordCredentials> getCredentials(Asset asset) {
+ return asset == null ? Optional.empty() : asset
+ .getAttribute(CREDENTIALS_ATTRIBUTE_NAME)
+ .flatMap(AbstractValueHolder::getValueAsObject)
+ .flatMap(UserPasswordCredentials::fromValue);
+ }
+
+ public static void setCredentials(Asset asset, UserPasswordCredentials credentials) {
+ if (asset != null) {
+ if (Objects.isNull(credentials)) {
+ asset.removeAttribute(CREDENTIALS_ATTRIBUTE_NAME);
+ } else {
+ asset.replaceAttribute(new AssetAttribute(CREDENTIALS_ATTRIBUTE_NAME, AttributeType.OBJECT, credentials.toObjectValue()));
+ }
+ }
+ }
+
+ public static Optional<AssetAttribute> getProtocolConfiguration(Asset asset, String protocolConfigurationName) {
+ if (asset == null || isNullOrEmpty(protocolConfigurationName)) {
+ return Optional.empty();
+ }
+
+ return asset.getAttribute(protocolConfigurationName)
+ .filter(ProtocolConfiguration::isProtocolConfiguration);
+ }
+
+ public static List<AssetAttribute> getProtocolConfigurations(Asset asset) {
+ if (asset == null) {
+ return Collections.emptyList();
+ }
+
+ return asset.getAttributesStream()
+ .filter(ProtocolConfiguration::isProtocolConfiguration)
+ .collect(Collectors.toList());
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/asset/agent/ProtocolConfiguration.java b/model/src/main/java/org/openremote/model/asset/agent/ProtocolConfiguration.java
index 43f24ffdd..098cffdce 100644
--- a/model/src/main/java/org/openremote/model/asset/agent/ProtocolConfiguration.java
+++ b/model/src/main/java/org/openremote/model/asset/agent/ProtocolConfiguration.java
@@ -19,6 +19,7 @@
*/
package org.openremote.model.asset.agent;
+import org.openremote.model.ValidationFailure;
import org.openremote.model.asset.AssetAttribute;
import org.openremote.model.attribute.AttributeType;
import org.openremote.model.attribute.MetaItem;
@@ -42,6 +43,10 @@ import static org.openremote.model.attribute.MetaItem.isMetaNameEqualTo;
*/
final public class ProtocolConfiguration {
+ public enum ValidationFailureReason implements ValidationFailure.Reason {
+ VALUE_NOT_A_VALID_PROTOCOL_URN
+ }
+
private ProtocolConfiguration() {
}
@@ -73,7 +78,6 @@ final public class ProtocolConfiguration {
public static boolean isProtocolConfiguration(AssetAttribute attribute) {
return getProtocolName(attribute).isPresent()
- && attribute.getMetaStream().anyMatch(isMetaNameEqualTo(PROTOCOL_CONFIGURATION))
&& attribute.getMetaStream().filter(isMetaNameEqualTo(PROTOCOL_CONFIGURATION))
.findFirst()
.map(metaItem -> metaItem.getValueAsBoolean().orElse(false))
@@ -81,6 +85,10 @@ final public class ProtocolConfiguration {
}
public static Optional<String> getProtocolName(AssetAttribute attribute) {
+ if (attribute == null) {
+ return Optional.empty();
+ }
+
return attribute
.getValueAsString()
.map(name -> isValidProtocolName(name) ? name : null);
diff --git a/model/src/main/java/org/openremote/model/asset/agent/ProtocolDescriptor.java b/model/src/main/java/org/openremote/model/asset/agent/ProtocolDescriptor.java
new file mode 100644
index 000000000..94e4f44ae
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/asset/agent/ProtocolDescriptor.java
@@ -0,0 +1,131 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.asset.agent;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.openremote.model.asset.AssetAttribute;
+import org.openremote.model.attribute.MetaItem;
+import org.openremote.model.attribute.MetaItemDescriptor;
+
+import java.util.List;
+
+public class ProtocolDescriptor {
+ protected String name;
+ protected String displayName;
+ protected String version;
+ protected boolean configurationDiscovery;
+ protected boolean configurationImport;
+ protected boolean deviceDiscovery;
+ protected boolean deviceImport;
+ protected AssetAttribute configurationTemplate;
+ protected List<MetaItemDescriptor> protocolConfigurationMetaItems;
+ protected List<MetaItemDescriptor> linkedAttributeMetaItems;
+
+ @JsonCreator
+ public ProtocolDescriptor(@JsonProperty("name") String name,
+ @JsonProperty("displayName") String displayName,
+ @JsonProperty("version") String version,
+ @JsonProperty("configurationDiscovery") boolean configurationDiscovery,
+ @JsonProperty("configurationImport") boolean configurationImport,
+ @JsonProperty("deviceDiscovery") boolean deviceDiscovery,
+ @JsonProperty("deviceImport") boolean deviceImport,
+ @JsonProperty("configurationTemplate") AssetAttribute configurationTemplate,
+ @JsonProperty("protocolConfigurationMetaItems") List<MetaItemDescriptor> protocolConfigurationMetaItems,
+ @JsonProperty("linkedAttributeMetaItems") List<MetaItemDescriptor> linkedAttributeMetaItems) {
+ this.name = name;
+ this.displayName = displayName;
+ this.version = version;
+ this.configurationDiscovery = configurationDiscovery;
+ this.configurationImport = configurationImport;
+ this.deviceDiscovery = deviceDiscovery;
+ this.deviceImport = deviceImport;
+ this.configurationTemplate = configurationTemplate;
+ this.protocolConfigurationMetaItems = protocolConfigurationMetaItems;
+ this.linkedAttributeMetaItems = linkedAttributeMetaItems;
+ }
+
+ /**
+ * Get the URN protocol name
+ */
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * Get the Display name
+ */
+ public String getDisplayName() {
+ return displayName;
+ }
+
+ /**
+ * Get the version
+ */
+ public String getVersion() {
+ return version;
+ }
+
+ /**
+ * Indicates if the protocol supports {@link ProtocolConfiguration} discovery
+ */
+ public boolean isConfigurationDiscovery() {
+ return configurationDiscovery;
+ }
+
+ /**
+ * Indicates if the protocol supports {@link ProtocolConfiguration} import by uploading protocol
+ * specific file(s)
+ */
+ public boolean isConfigurationImport() {
+ return configurationImport;
+ }
+
+ /**
+ * Indicates if the protocol supports device {@link org.openremote.model.asset.Asset} discovery
+ */
+ public boolean isDeviceDiscovery() {
+ return deviceDiscovery;
+ }
+
+ public boolean isDeviceImport() {
+ return deviceImport;
+ }
+
+ public AssetAttribute getConfigurationTemplate() {
+ return configurationTemplate;
+ }
+
+ /**
+ * Get the {@link MetaItemDescriptor}s that describe {@link MetaItem}s that can be used on {@link ProtocolConfiguration}s
+ * of this protocol (for UI purposes)
+ */
+ public List<MetaItemDescriptor> getProtocolConfigurationMetaItems() {
+ return protocolConfigurationMetaItems;
+ }
+
+ /**
+ * Get the {@link MetaItemDescriptor}s that describe {@link MetaItem}s that can be used on {@link AssetAttribute}s
+ * linked to this protocol (for UI purposes)
+ */
+ public List<MetaItemDescriptor> getLinkedAttributeMetaItems() {
+ return linkedAttributeMetaItems;
+ }
+}
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 329c8b63a..549ebf7ae 100644
--- a/model/src/main/java/org/openremote/model/attribute/Attribute.java
+++ b/model/src/main/java/org/openremote/model/attribute/Attribute.java
@@ -19,20 +19,20 @@
*/
package org.openremote.model.attribute;
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.gwt.regexp.shared.RegExp;
import org.openremote.model.AbstractValueTimestampHolder;
import org.openremote.model.HasUniqueResourceName;
import org.openremote.model.ValidationFailure;
-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 org.openremote.model.util.EnumUtil;
+import org.openremote.model.value.*;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Stream;
-import static org.openremote.model.attribute.Attribute.AttributeValidationFailure.*;
+import static org.openremote.model.attribute.Attribute.AttributeFailureReason.*;
import static org.openremote.model.attribute.MetaItem.isMetaNameEqualTo;
import static org.openremote.model.util.TextUtil.requireNonNullAndNonEmpty;
@@ -41,10 +41,10 @@ import static org.openremote.model.util.TextUtil.requireNonNullAndNonEmpty;
*/
public abstract class Attribute extends AbstractValueTimestampHolder {
- public enum AttributeValidationFailure implements ValidationFailure {
- INVALID_ATTRIBUTE_NAME,
- MISSING_ATTRIBUTE_TYPE,
- MISSING_ATTRIBUTE_VALUE_TIMESTAMP
+ public enum AttributeFailureReason implements ValidationFailure.Reason {
+ ATTRIBUTE_NAME_INVALID,
+ ATTRIBUTE_TYPE_MISSING,
+ ATTRIBUTE_VALUE_TIMESTAMP_MISSING
}
/**
@@ -59,6 +59,10 @@ public abstract class Attribute extends AbstractValueTimestampHolder {
public static final String TYPE_FIELD_NAME = "type";
public static final String META_FIELD_NAME = "meta";
+ @JsonIgnore
+ protected Meta meta;
+
+ @JsonProperty
protected String name;
protected Attribute(ObjectValue objectValue) {
@@ -87,10 +91,17 @@ public abstract class Attribute extends AbstractValueTimestampHolder {
setValue(value);
}
+ @JsonIgnore
public Optional<String> getName() {
return Optional.ofNullable(name);
}
+ // Only here for GWT jackson
+ @JsonProperty("name")
+ private String getNamePrivate() {
+ return name;
+ }
+
public void setName(String name) {
requireNonNullAndNonEmpty(name);
this.name = name;
@@ -101,7 +112,7 @@ public abstract class Attribute extends AbstractValueTimestampHolder {
}
public Optional<AttributeType> getType() {
- return getObjectValue().getString(TYPE_FIELD_NAME).flatMap(AttributeType::optionalValueOf);
+ return getObjectValue().getString(TYPE_FIELD_NAME).flatMap(name -> EnumUtil.enumFromString(AttributeType.class, name));
}
/**
@@ -128,15 +139,17 @@ public abstract class Attribute extends AbstractValueTimestampHolder {
}
public Meta getMeta() {
- if (!getObjectValue().hasKey(META_FIELD_NAME)) {
- // Create array object so don't have to call setMeta
- // can just update the collection like normal POJO behaviour
- getObjectValue().put(META_FIELD_NAME, Values.createArray());
+ if (meta == null) {
+ return new Meta(getObjectValue()
+ .getArray(META_FIELD_NAME)
+ .orElseGet(() -> {
+ ArrayValue arr = Values.createArray();
+ getObjectValue().put(META_FIELD_NAME, arr);
+ return arr;
+ })
+ );
}
- return new Meta(getObjectValue()
- .getArray(META_FIELD_NAME)
- .orElseThrow(() -> new IllegalStateException("Attribute " + META_FIELD_NAME + "' field is not an array"))
- );
+ return meta;
}
public Stream<MetaItem> getMetaStream() {
@@ -162,18 +175,19 @@ public abstract class Attribute extends AbstractValueTimestampHolder {
}
public void setMeta(List<MetaItem> metaItems) {
- if (metaItems != null) {
- Meta meta;
- if (metaItems instanceof Meta) {
- meta = (Meta) metaItems;
- } else {
- meta = new Meta();
- meta.addAll(metaItems);
- }
- getObjectValue().put(META_FIELD_NAME, meta.getArrayValue());
+ Meta meta;
+ if (metaItems == null) {
+ // Don't allow nulling meta
+ meta = new Meta();
+ } else if (metaItems instanceof Meta) {
+ meta = (Meta) metaItems;
} else {
- getObjectValue().remove(META_FIELD_NAME);
+ meta = new Meta();
+ meta.addAll(metaItems);
}
+
+ this.meta = meta;
+ getObjectValue().put(META_FIELD_NAME, meta.getArrayValue());
}
public Attribute setMeta(Meta meta) {
@@ -188,23 +202,29 @@ public abstract class Attribute extends AbstractValueTimestampHolder {
@Override
public List<ValidationFailure> getValidationFailures() {
+ return getValidationFailures(true);
+ }
+
+ public List<ValidationFailure> getValidationFailures(boolean includeMeta) {
List<ValidationFailure> failures = super.getValidationFailures();
if (!getName().isPresent() || !ATTRIBUTE_NAME_VALIDATOR.test(getName().get()))
- failures.add(INVALID_ATTRIBUTE_NAME);
+ failures.add(new ValidationFailure(ATTRIBUTE_NAME_INVALID));
if (!getType().isPresent())
- failures.add(MISSING_ATTRIBUTE_TYPE);
+ failures.add(new ValidationFailure(ATTRIBUTE_TYPE_MISSING));
if (!getValueTimestamp().isPresent())
- failures.add(MISSING_ATTRIBUTE_VALUE_TIMESTAMP);
+ failures.add(new ValidationFailure(ATTRIBUTE_VALUE_TIMESTAMP_MISSING));
// Value can be empty, if it's not it must validate with the type
getValue().flatMap(value ->
getType().flatMap(attributeType -> attributeType.isValidValue(value))
).ifPresent(failures::add);
- failures.addAll(getMetaItemsValidationFailures());
+ if (includeMeta) {
+ failures.addAll(getMetaItemsValidationFailures());
+ }
return failures;
}
diff --git a/model/src/main/java/org/openremote/model/attribute/AttributeType.java b/model/src/main/java/org/openremote/model/attribute/AttributeType.java
index 03929d1a2..2e25526c4 100644
--- a/model/src/main/java/org/openremote/model/attribute/AttributeType.java
+++ b/model/src/main/java/org/openremote/model/attribute/AttributeType.java
@@ -20,6 +20,7 @@
package org.openremote.model.attribute;
import org.openremote.model.ValidationFailure;
+import org.openremote.model.ValueHolder;
import org.openremote.model.asset.AssetMeta;
import org.openremote.model.rules.Ruleset;
import org.openremote.model.rules.template.TemplateFilter;
@@ -31,7 +32,8 @@ import java.util.Optional;
import java.util.function.Function;
import static org.openremote.model.asset.AssetMeta.FORMAT;
-import static org.openremote.model.attribute.AttributeType.AttributeTypeValidationFailure.*;
+import static org.openremote.model.attribute.AttributeType.AttributeTypeFailureReason.ATTRIBUTE_TYPE_INVALID_TEMPLATE_FILTER;
+import static org.openremote.model.attribute.AttributeType.AttributeTypeFailureReason.ATTRIBUTE_TYPE_VALUE_DOES_NOT_MATCH;
/**
* The type of an {@link Attribute}, how its {@link Value} should be
@@ -63,13 +65,13 @@ public enum AttributeType {
RULES_TEMPLATE_FILTER("filter", ValueType.ARRAY, value ->
TemplateFilter.fromModelValue("test", value).isPresent()
? Optional.empty()
- : Optional.of(INVALID_TEMPLATE_FILTER)
+ : Optional.of(new ValidationFailure(ATTRIBUTE_TYPE_INVALID_TEMPLATE_FILTER))
),
PERCENTAGE("percent", ValueType.NUMBER,
value -> Values.getNumber(value)
.filter(number -> number < 0 || number > 100)
- .map(number -> PERCENTAGE_OUT_OF_RANGE),
+ .map(number -> new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_PERCENTAGE_OUT_OF_RANGE)),
new MetaItem(AssetMeta.RANGE_MIN, Values.create(0)),
new MetaItem(AssetMeta.RANGE_MAX, Values.create(100)),
new MetaItem(AssetMeta.FORMAT, Values.create("%3d %%"))
@@ -81,33 +83,33 @@ public enum AttributeType {
COLOR_RGB("paint-brush", ValueType.ARRAY, value -> Values.getArray(value)
.filter(array -> array.length() != 3)
- .map(array -> WRONG_COLOR_FORMAT)
+ .map(array -> new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_INVALID_COLOR_FORMAT))
),
COLOR_ARGB("paint-brush", ValueType.ARRAY, value -> Values.getArray(value)
.filter(array -> array.length() != 4)
- .map(array -> WRONG_COLOR_FORMAT)
+ .map(array -> new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_INVALID_COLOR_FORMAT))
),
COLOR_HEX("paint-brush", ValueType.STRING, value -> Values.getString(value)
.filter(s -> !s.matches("[a-fA-F0-9]{6}"))
- .map(array -> WRONG_COLOR_FORMAT)
+ .map(array -> new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_INVALID_COLOR_FORMAT))
),
TEMPERATURE_CELCIUS("thermometer", ValueType.NUMBER, value -> Values.getNumber(value)
.filter(n -> n < -273.15)
- .map(n -> TEMPERATURE_OUT_OF_RANGE),
+ .map(n -> new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_TEMPERATURE_OUT_OF_RANGE)),
new MetaItem(FORMAT, Values.create("%0.1f C"))
),
TEMPERATURE_KELVIN("thermometer", ValueType.NUMBER, value -> Values.getNumber(value)
.filter(n -> n < 0)
- .map(n -> TEMPERATURE_OUT_OF_RANGE)
+ .map(n -> new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_TEMPERATURE_OUT_OF_RANGE))
),
TEMPERATURE_FAHRENHEIT("thermometer", ValueType.NUMBER, value -> Values.getNumber(value)
.filter(n -> n < -459.67)
- .map(n -> TEMPERATURE_OUT_OF_RANGE)
+ .map(n -> new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_TEMPERATURE_OUT_OF_RANGE))
),
DISTANCE_M("arrows-h", ValueType.NUMBER, value -> Optional.empty(),
@@ -140,7 +142,7 @@ public enum AttributeType {
HUMIDITY_PERCENTAGE("tint", ValueType.NUMBER, value -> Values.getNumber(value)
.filter(number -> number < 0 || number > 100)
- .map(number -> PERCENTAGE_OUT_OF_RANGE),
+ .map(number -> new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_PERCENTAGE_OUT_OF_RANGE)),
new MetaItem(AssetMeta.RANGE_MIN, Values.create(0)),
new MetaItem(AssetMeta.RANGE_MAX, Values.create(100)),
new MetaItem(FORMAT, Values.create("%3d %%"))
@@ -160,7 +162,7 @@ public enum AttributeType {
CHARGE_PERCENTAGE("battery-full", ValueType.NUMBER, value -> Values.getNumber(value)
.filter(number -> number < 0 || number > 100)
- .map(number -> PERCENTAGE_OUT_OF_RANGE),
+ .map(number -> new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_PERCENTAGE_OUT_OF_RANGE)),
new MetaItem(AssetMeta.RANGE_MIN, Values.create(0)),
new MetaItem(AssetMeta.RANGE_MAX, Values.create(100)),
new MetaItem(FORMAT, Values.create("%3d %%"))
@@ -202,12 +204,9 @@ public enum AttributeType {
public static final String DEFAULT_ICON = "circle-thin";
- public enum AttributeTypeValidationFailure implements ValidationFailure {
- VALUE_DOES_NOT_MATCH_ATTRIBUTE_TYPE,
- PERCENTAGE_OUT_OF_RANGE,
- INVALID_TEMPLATE_FILTER,
- WRONG_COLOR_FORMAT,
- TEMPERATURE_OUT_OF_RANGE
+ public enum AttributeTypeFailureReason implements ValidationFailure.Reason {
+ ATTRIBUTE_TYPE_VALUE_DOES_NOT_MATCH,
+ ATTRIBUTE_TYPE_INVALID_TEMPLATE_FILTER
}
final protected String icon;
@@ -215,17 +214,13 @@ public enum AttributeType {
final protected Function<Value, Optional<ValidationFailure>> validator;
final protected MetaItem[] defaultMetaItems;
- AttributeType(ValueType valueType, Function<Value, Optional<ValidationFailure>> validator, MetaItem... defaultMetaItems) {
- this(DEFAULT_ICON, valueType, validator, defaultMetaItems);
- }
-
AttributeType(String icon, ValueType valueType, Function<Value, Optional<ValidationFailure>> validator, MetaItem... defaultMetaItems) {
this.icon = icon;
this.valueType = valueType;
this.validator = value -> {
// Always perform some basic validation
if (value != null && getValueType() != value.getType())
- return Optional.of(VALUE_DOES_NOT_MATCH_ATTRIBUTE_TYPE);
+ return Optional.of(new ValidationFailure(ATTRIBUTE_TYPE_VALUE_DOES_NOT_MATCH, getValueType().name()));
// Custom attribute type validation
return validator.apply(value);
@@ -248,12 +243,4 @@ public enum AttributeType {
public Optional<ValidationFailure> isValidValue(Value value) {
return validator.apply(value);
}
-
- public static Optional<AttributeType> optionalValueOf(String name) {
- try {
- return Optional.of(valueOf(name));
- } catch (Exception ex) {
- return Optional.empty();
- }
- }
}
diff --git a/model/src/main/java/org/openremote/model/attribute/AttributeValidationResult.java b/model/src/main/java/org/openremote/model/attribute/AttributeValidationResult.java
new file mode 100644
index 000000000..cfb88208a
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/attribute/AttributeValidationResult.java
@@ -0,0 +1,105 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.attribute;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.openremote.model.ValidationFailure;
+import org.openremote.model.util.Pair;
+
+import java.util.*;
+
+/**
+ * Represents the validation result of an attribute.
+ * <p>
+ * {@link #getAttributeFailures} returns any attribute validation failures along with an optional failure message
+ * parameter for each failure.
+ * <p>
+ * {@link #getMetaFailures()} returns a map of meta item validation failures along with optional failure message
+ * parameter for each failure; the key represents the meta item index that has failed.
+ */
+public class AttributeValidationResult {
+
+ @JsonProperty
+ protected String attributeName;
+ @JsonProperty
+ protected List<ValidationFailure> attributeFailures;
+ @JsonProperty
+ protected Map<Integer, List<ValidationFailure>> metaFailures;
+
+ public AttributeValidationResult(String attributeName) {
+ this.attributeName = attributeName;
+ }
+
+ @JsonCreator
+ public AttributeValidationResult(@JsonProperty("attributeName") String attributeName,
+ @JsonProperty("attributeFailures") List<ValidationFailure> attributeFailures,
+ @JsonProperty("metaFailures") Map<Integer, List<ValidationFailure>> metaFailures) {
+ this.attributeName = attributeName;
+ this.attributeFailures = attributeFailures;
+ this.metaFailures = metaFailures;
+ }
+
+ public void addAttributeFailure(ValidationFailure attributeFailure) {
+ if (attributeFailures == null) {
+ attributeFailures = new ArrayList<>();
+ }
+
+ attributeFailures.add(attributeFailure);
+ }
+
+ public void addMetaFailure(ValidationFailure failure) {
+ addMetaFailure(-1, failure);
+ }
+
+ public void addMetaFailure(int metaItemindex, ValidationFailure failure) {
+ if (metaFailures == null) {
+ metaFailures = new HashMap<>();
+ }
+ if (!metaFailures.containsKey(metaItemindex)) {
+ metaFailures.put(metaItemindex, new ArrayList<>());
+ }
+ metaFailures.get(metaItemindex).add(failure);
+ }
+
+ public String getAttributeName() {
+ return attributeName;
+ }
+
+ public List<ValidationFailure> getAttributeFailures() {
+ return attributeFailures;
+ }
+
+ public Map<Integer, List<ValidationFailure>> getMetaFailures() {
+ return metaFailures;
+ }
+
+ public boolean hasAttributeFailures() {
+ return attributeFailures != null && !attributeFailures.isEmpty();
+ }
+
+ public boolean hasMetaFailures() {
+ return metaFailures != null && !metaFailures.isEmpty();
+ }
+
+ public boolean isValid() {
+ return !hasAttributeFailures() && !hasMetaFailures();
+ }
+}
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 26dbb9fe9..4970862d8 100644
--- a/model/src/main/java/org/openremote/model/attribute/MetaItem.java
+++ b/model/src/main/java/org/openremote/model/attribute/MetaItem.java
@@ -34,7 +34,8 @@ import java.util.Objects;
import java.util.Optional;
import java.util.function.Predicate;
-import static org.openremote.model.attribute.MetaItem.MetaItemValidationFailure.*;
+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;
/**
* A named arbitrary {@link Value}. A meta item must have a value to be stored.
@@ -43,9 +44,12 @@ import static org.openremote.model.attribute.MetaItem.MetaItemValidationFailure.
*/
public class MetaItem extends AbstractValueHolder {
- public enum MetaItemValidationFailure implements ValidationFailure {
- NAME_IS_REQUIRED,
- VALUE_IS_REQUIRED
+ public enum MetaItemFailureReason implements ValidationFailure.Reason {
+ META_ITEM_NAME_IS_REQUIRED,
+ META_ITEM_VALUE_IS_REQUIRED,
+ META_ITEM_MISSING,
+ META_ITEM_DUPLICATION,
+ META_ITEM_VALUE_MISMATCH
}
public MetaItem() {
@@ -101,11 +105,11 @@ public class MetaItem extends AbstractValueHolder {
List<ValidationFailure> failures = super.getValidationFailures();
if (!getName().isPresent())
- failures.add(NAME_IS_REQUIRED);
+ failures.add(new ValidationFailure(META_ITEM_NAME_IS_REQUIRED));
// Meta items must have a value, unlike attributes
if (!getValue().isPresent()) {
- failures.add(VALUE_IS_REQUIRED);
+ failures.add(new ValidationFailure(META_ITEM_VALUE_IS_REQUIRED));
}
return failures;
diff --git a/model/src/main/java/org/openremote/model/attribute/MetaItemDescriptor.java b/model/src/main/java/org/openremote/model/attribute/MetaItemDescriptor.java
new file mode 100644
index 000000000..d707e8e62
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/attribute/MetaItemDescriptor.java
@@ -0,0 +1,132 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.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;
+
+@JsonSerialize(as = MetaItemDescriptorImpl.class)
+@JsonDeserialize(as = MetaItemDescriptorImpl.class)
+public interface MetaItemDescriptor extends HasUniqueResourceName {
+
+ enum PatternFailure {
+ INTEGER,
+ INTEGER_NON_ZERO,
+ INTEGER_POSITIVE,
+ INTEGER_NEGATIVE,
+ INTEGER_POSITIVE_NON_ZERO,
+ INTEGER_NEGATIVE_NON_ZERO,
+ DOUBLE,
+ DOUBLE_POSITIVE,
+ DOUBLE_NEGATIVE,
+ DOUBLE_POSITIVE_NON_ZERO,
+ DOUBLE_NEGATIVE_NON_ZERO,
+ CRON_EXPRESSION,
+ 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();
+
+ ValueType getValueType();
+
+ /**
+ * Indicates if this meta item is always required
+ */
+ boolean isRequired();
+
+ /**
+ * A regex pattern that can be used for basic validation
+ */
+ String getPattern();
+
+ /**
+ * Get a parameter to show as part of validation feedback for when the pattern matching fails
+ * e.g. Meta Item value must be 'Positive Integer'.
+ * <p>
+ * Values defined in {@link PatternFailure} should support localisation.
+ */
+ String getPatternFailureMessage();
+
+ /**
+ * Gets the maximum number of these meta items allowed per attribute
+ */
+ Integer getMaxPerAttribute();
+
+ /**
+ * Gets the initial value for new instances of this meta item
+ */
+ Value getInitialValue();
+
+ /**
+ * Indicates if the value of this meta item is fixed
+ */
+ boolean isValueFixed();
+
+ /**
+ * Validate the supplied {@link MetaItem} against this {@link MetaItemDescriptor}
+ */
+ Optional<ValidationFailure> validateValue(Value value);
+}
diff --git a/model/src/main/java/org/openremote/model/attribute/MetaItemDescriptorImpl.java b/model/src/main/java/org/openremote/model/attribute/MetaItemDescriptorImpl.java
new file mode 100644
index 000000000..6b69b07d7
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/attribute/MetaItemDescriptorImpl.java
@@ -0,0 +1,112 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.attribute;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+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;
+
+public class MetaItemDescriptorImpl implements MetaItemDescriptor {
+
+ protected final String name;
+ protected final String urn;
+ protected final ValueType valueType;
+ protected final boolean required;
+ protected final String pattern;
+ protected final Integer maxPerAttribute;
+ protected final Value initialValue;
+ protected final boolean valueFixed;
+ protected final String patternFailureMessage;
+
+ @JsonCreator
+ public MetaItemDescriptorImpl(@JsonProperty("name") String name,
+ @JsonProperty("urn") String urn,
+ @JsonProperty("valueType") ValueType valueType,
+ @JsonProperty("required") boolean required,
+ @JsonProperty("pattern") String pattern,
+ @JsonProperty("patternFailureMessage") String patternFailureMessage,
+ @JsonProperty("maxPerAttribute") Integer maxPerAttribute,
+ @JsonProperty("initialValue") Value initialValue,
+ @JsonProperty("valueFixed") boolean valueFixed) {
+ this.name = name;
+ this.urn = urn;
+ this.valueType = valueType;
+ this.required = required;
+ this.pattern = pattern;
+ this.patternFailureMessage = patternFailureMessage;
+ this.maxPerAttribute = maxPerAttribute;
+ this.initialValue = initialValue;
+ this.valueFixed = valueFixed;
+ }
+
+ @Override
+ public String name() {
+ return name;
+ }
+
+ @Override
+ public String getUrn() {
+ return urn;
+ }
+
+ @Override
+ public ValueType getValueType() {
+ return valueType;
+ }
+
+ @Override
+ public boolean isRequired() {
+ return required;
+ }
+
+ @Override
+ public String getPattern() {
+ return pattern;
+ }
+
+ @Override
+ public String getPatternFailureMessage() {
+ return patternFailureMessage;
+ }
+
+ @Override
+ public Integer getMaxPerAttribute() {
+ return maxPerAttribute;
+ }
+
+ @Override
+ public Value getInitialValue() {
+ return initialValue;
+ }
+
+ @Override
+ public boolean isValueFixed() {
+ return valueFixed;
+ }
+
+ @Override
+ public Optional<ValidationFailure> validateValue(Value value) {
+ return MetaItemDescriptor.validateValue(value, this);
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/file/FileInfo.java b/model/src/main/java/org/openremote/model/file/FileInfo.java
new file mode 100644
index 000000000..384a06450
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/file/FileInfo.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.file;
+
+public class FileInfo {
+ protected String name;
+ protected byte[] contents;
+
+ public FileInfo(String name, byte[] contents) {
+ this.name = name;
+ this.contents = contents;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public byte[] getContents() {
+ return contents;
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/security/UserPasswordCredentials.java b/model/src/main/java/org/openremote/model/security/UserPasswordCredentials.java
new file mode 100644
index 000000000..eaa232e4c
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/security/UserPasswordCredentials.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.security;
+
+import org.openremote.model.AbstractValueHolder;
+import org.openremote.model.value.ObjectValue;
+import org.openremote.model.value.Value;
+import org.openremote.model.value.Values;
+
+import java.util.Optional;
+
+public class UserPasswordCredentials {
+
+ public static final String USERNAME_KEY = "username";
+ public static final String PASSWORD_KEY = "password";
+ protected String username;
+ protected String password;
+
+ protected UserPasswordCredentials() {
+ }
+
+ public UserPasswordCredentials(String username, String password) {
+ this.username = username;
+ this.password = password;
+ }
+
+ public String getUsername() {
+ return username;
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+ public ObjectValue toObjectValue() {
+ ObjectValue value = Values.createObject();
+ value.put(USERNAME_KEY, Values.create(getUsername()));
+ value.put(PASSWORD_KEY, Values.create(getPassword()));
+ return value;
+ }
+
+ public static boolean isUserPasswordCredentials(AbstractValueHolder valueHolder) {
+ return valueHolder != null
+ && valueHolder.getValueAsObject().filter(UserPasswordCredentials::isUserPasswordCredentials).isPresent();
+ }
+
+ public static boolean isUserPasswordCredentials(Value value) {
+ return Values.getObject(value)
+ .filter(objectValue ->
+ objectValue.getString(USERNAME_KEY).filter(s -> !s.isEmpty()).isPresent()
+ && objectValue.getString(PASSWORD_KEY).filter(s -> !s.isEmpty()).isPresent()
+ ).isPresent();
+ }
+
+ @SuppressWarnings("ConstantConditions")
+ public static Optional<UserPasswordCredentials> fromValue(Value value) {
+ return Values.getObject(value)
+ .filter(UserPasswordCredentials::isUserPasswordCredentials)
+ .map(objectValue ->
+ new UserPasswordCredentials(objectValue.getString(USERNAME_KEY).get(), objectValue.getString(PASSWORD_KEY).get())
+ );
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/simulator/element/NumberSimulatorElement.java b/model/src/main/java/org/openremote/model/simulator/element/NumberSimulatorElement.java
index 80874e71c..f67adf78d 100644
--- a/model/src/main/java/org/openremote/model/simulator/element/NumberSimulatorElement.java
+++ b/model/src/main/java/org/openremote/model/simulator/element/NumberSimulatorElement.java
@@ -29,10 +29,6 @@ import java.util.List;
public class NumberSimulatorElement extends SimulatorElement {
- public enum ValueValidationFailure implements ValidationFailure {
- NUMBER_OUT_OF_RANGE
- }
-
public static final String ELEMENT_NAME = "number";
public static final String ELEMENT_NAME_RANGE = "range";
@@ -66,7 +62,7 @@ public class NumberSimulatorElement extends SimulatorElement {
if (elementValue != null) {
if ((getMin() != null && Values.getNumber(elementValue).filter(v -> v < getMin()).isPresent())
&& (getMax() != null && Values.getNumber(elementValue).filter(v -> v > getMax()).isPresent())) {
- failures.add(ValueValidationFailure.NUMBER_OUT_OF_RANGE);
+ failures.add(new ValidationFailure(ValueFailureReason.VALUE_NUMBER_OUT_OF_RANGE, getMin() + "-" + getMax()));
}
}
return failures;
diff --git a/model/src/main/java/org/openremote/model/util/ObservableList.java b/model/src/main/java/org/openremote/model/util/ObservableList.java
new file mode 100644
index 000000000..615951c43
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/util/ObservableList.java
@@ -0,0 +1,151 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.util;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.function.Predicate;
+import java.util.function.UnaryOperator;
+
+public class ObservableList<T> extends ArrayList<T> {
+
+ protected Runnable onModified;
+
+ public ObservableList(int initialCapacity, Runnable onModified) {
+ super(initialCapacity);
+ this.onModified = onModified;
+ }
+
+ public ObservableList(Runnable onModified) {
+ this.onModified = onModified;
+ }
+
+ public ObservableList(Collection<? extends T> c, Runnable onModified) {
+ super(c);
+ this.onModified = onModified;
+ }
+
+ protected void notifyModified() {
+ if (onModified != null) {
+ onModified.run();
+ }
+ }
+
+ @Override
+ public T set(int index, T element) {
+ T result = super.set(index, element);
+ notifyModified();
+ return result;
+ }
+
+ @Override
+ public boolean add(T t) {
+ boolean result = super.add(t);
+ notifyModified();
+ return result;
+ }
+
+ @Override
+ public void add(int index, T element) {
+ super.add(index, element);
+ notifyModified();
+ }
+
+ @Override
+ public T remove(int index) {
+ T result = super.remove(index);
+ notifyModified();
+ return result;
+ }
+
+ @Override
+ public boolean remove(Object o) {
+ boolean result = super.remove(o);
+ if (result)
+ notifyModified();
+ return result;
+ }
+
+ @Override
+ public void clear() {
+ super.clear();
+ notifyModified();
+ }
+
+ public void clear(boolean notify) {
+ super.clear();
+ if (notify) {
+ notifyModified();
+ }
+ }
+
+ @Override
+ public boolean addAll(Collection<? extends T> c) {
+ boolean result = super.addAll(c);
+ if (result)
+ notifyModified();
+ return result;
+ }
+
+ @Override
+ public boolean addAll(int index, Collection<? extends T> c) {
+ boolean result = super.addAll(index, c);
+ if (result)
+ notifyModified();
+ return result;
+ }
+
+ @Override
+ protected void removeRange(int fromIndex, int toIndex) {
+ super.removeRange(fromIndex, toIndex);
+ notifyModified();
+ }
+
+ @Override
+ public boolean removeAll(Collection<?> c) {
+ boolean result = super.removeAll(c);
+ if (result)
+ notifyModified();
+ return result;
+ }
+
+ @Override
+ public boolean retainAll(Collection<?> c) {
+ boolean result = super.retainAll(c);
+ if (result)
+ notifyModified();
+ return result;
+ }
+
+ @Override
+ public boolean removeIf(Predicate<? super T> filter) {
+ boolean result = super.removeIf(filter);
+ if (result)
+ notifyModified();
+ return result;
+ }
+
+ @Override
+ public void replaceAll(UnaryOperator<T> operator) {
+ super.replaceAll(operator);
+ // May not have modified the list but just in case
+ notifyModified();
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/util/TextUtil.java b/model/src/main/java/org/openremote/model/util/TextUtil.java
index 530ebf374..f61fbacb3 100644
--- a/model/src/main/java/org/openremote/model/util/TextUtil.java
+++ b/model/src/main/java/org/openremote/model/util/TextUtil.java
@@ -31,6 +31,20 @@ public class TextUtil {
public static final String URN_PATTERN = "^urn:[a-zA-Z0-9][a-zA-Z0-9-]{0,31}:([a-zA-Z0-9()+,\\-.:=@;$_!*']|%[0-9a-f]{2})+$";
public static final RegExp URN_REGEXP = RegExp.compile(URN_PATTERN);
public static final Predicate<String> URN_VALIDATOR = name -> !isNullOrEmpty(name) && URN_REGEXP.test(name);
+ public static final String REGEXP_PATTERN_INTEGER = "^(-?[1-9]\\d*|0)$";
+ public static final String REGEXP_PATTERN_INTEGER_POSITIVE = "^\\d+$";
+ public static final String REGEXP_PATTERN_INTEGER_NEGATIVE = "^(-[1-9]\\d*|0)$";
+ public static final String REGEXP_PATTERN_INTEGER_NON_ZERO = "^-?[1-9]\\d*$";
+ public static final String REGEXP_PATTERN_INTEGER_POSITIVE_NON_ZERO = "^[1-9]\\d*$";
+ public static final String REGEXP_PATTERN_INTEGER_NEGATIVE_NON_ZERO = "^-[1-9]\\d*$";
+ public static final String REGEXP_PATTERN_DOUBLE = "^(-?([0-9]+$(\\.[0-9]+)|[1-9]\\d*)|0)$";
+ public static final String REGEXP_PATTERN_DOUBLE_POSITIVE = "^(([0-9]+(\\.[0-9]+)|[1-9]\\d*)|0)$";
+ public static final String REGEXP_PATTERN_DOUBLE_NEGATIVE = "^(-([0-9]+(\\.[0-9]+)|[1-9]\\d*)|0)$";
+ public static final String REGEXP_PATTERN_DOUBLE_NON_ZERO = "^-?(?!0*(\\.0+)?$)([0-9]+\\.[0-9]+|[1-9]\\d*)$";
+ public static final String REGEXP_PATTERN_DOUBLE_POSITIVE_NON_ZERO = "^(?!0*(\\.0+)?$)([0-9]+\\.[0-9]+|[1-9]\\d*)$";
+ public static final String REGEXP_PATTERN_DOUBLE_NEGATIVE_NON_ZERO = "^-(?!0*(\\.0+)?$)([0-9]+\\.[0-9]+|[1-9]\\d*)$";
+ // NOT TESTED
+ public static final String REGEXP_PATTERN_CRON_EXPRESSION = "^\\\\s*($|#|\\\\w+\\\\s*=|(\\\\?|\\\\*|(?:[0-5]?\\\\d)(?:(?:-|\\/|\\\\,)(?:[0-5]?\\\\d))?(?:,(?:[0-5]?\\\\d)(?:(?:-|\\/|\\\\,)(?:[0-5]?\\\\d))?)*)\\\\s+(\\\\?|\\\\*|(?:[0-5]?\\\\d)(?:(?:-|\\/|\\\\,)(?:[0-5]?\\\\d))?(?:,(?:[0-5]?\\\\d)(?:(?:-|\\/|\\\\,)(?:[0-5]?\\\\d))?)*)\\\\s+(\\\\?|\\\\*|(?:[01]?\\\\d|2[0-3])(?:(?:-|\\/|\\\\,)(?:[01]?\\\\d|2[0-3]))?(?:,(?:[01]?\\\\d|2[0-3])(?:(?:-|\\/|\\\\,)(?:[01]?\\\\d|2[0-3]))?)*)\\\\s+(\\\\?|\\\\*|(?:0?[1-9]|[12]\\\\d|3[01])(?:(?:-|\\/|\\\\,)(?:0?[1-9]|[12]\\\\d|3[01]))?(?:,(?:0?[1-9]|[12]\\\\d|3[01])(?:(?:-|\\/|\\\\,)(?:0?[1-9]|[12]\\\\d|3[01]))?)*)\\\\s+(\\\\?|\\\\*|(?:[1-9]|1[012])(?:(?:-|\\/|\\\\,)(?:[1-9]|1[012]))?(?:L|W)?(?:,(?:[1-9]|1[012])(?:(?:-|\\/|\\\\,)(?:[1-9]|1[012]))?(?:L|W)?)*|\\\\?|\\\\*|(?:JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)(?:(?:-)(?:JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC))?(?:,(?:JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)(?:(?:-)(?:JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC))?)*)\\\\s+(\\\\?|\\\\*|(?:[0-6])(?:(?:-|\\/|\\\\,|#)(?:[0-6]))?(?:L)?(?:,(?:[0-6])(?:(?:-|\\/|\\\\,|#)(?:[0-6]))?(?:L)?)*|\\\\?|\\\\*|(?:MON|TUE|WED|THU|FRI|SAT|SUN)(?:(?:-)(?:MON|TUE|WED|THU|FRI|SAT|SUN))?(?:,(?:MON|TUE|WED|THU|FRI|SAT|SUN)(?:(?:-)(?:MON|TUE|WED|THU|FRI|SAT|SUN))?)*)(|\\\\s)+(\\\\?|\\\\*|(?:|\\\\d{4})(?:(?:-|\\/|\\\\,)(?:|\\\\d{4}))?(?:,(?:|\\\\d{4})(?:(?:-|\\/|\\\\,)(?:|\\\\d{4}))?)*))$";
/**
* Converts a String which represents a pollingInterval into an int which can be used as delay
diff --git a/model/src/main/java/org/openremote/model/value/impl/NumberValueImpl.java b/model/src/main/java/org/openremote/model/value/impl/NumberValueImpl.java
index 7f0de658f..3f762f051 100644
--- a/model/src/main/java/org/openremote/model/value/impl/NumberValueImpl.java
+++ b/model/src/main/java/org/openremote/model/value/impl/NumberValueImpl.java
@@ -47,9 +47,10 @@ public class NumberValueImpl extends ValueImpl implements NumberValue {
return "null";
}
String toReturn = String.valueOf(number);
- if (toReturn.endsWith(".0")) {
- toReturn = toReturn.substring(0, toReturn.length() - 2);
- }
+ // RT - Not sure why this is here but it affects regex pattern validation so removing
+// if (toReturn.endsWith(".0")) {
+// toReturn = toReturn.substring(0, toReturn.length() - 2);
+// }
return toReturn;
}