100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Asset Editor (agent link support and general UI updates) AssetResource support for querying assets and implemented recursive asset queries Enum utilities added Code cleanup
Rich Turnerd83902625e8b
diff --git a/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.javaindex 7c73705f5..1b05ae502 100644--- a/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java+++ b/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java@@ -26,7 +26,6 @@ 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.HasUniqueResourceName;import org.openremote.model.asset.AssetAttribute;import org.openremote.model.asset.agent.AgentLink;import org.openremote.model.attribute.AttributeEvent;@@ -207,19 +206,17 @@ public abstract class AbstractProtocol implements Protocol {}/**- * Send an arbitrary {@link AttributeState} through the processing chain- * using the current system time as the timestamp. Use {@link #updateLinkedAttribute}- * to publish new sensor values, which performs additional verification and uses a- * different messaging queue.+ * Send an arbitrary {@link AttributeState} through the processing chain using the current system time as the+ * timestamp. Use {@link #updateLinkedAttribute} to publish new sensor values, which performs additional+ * verification and uses a different messaging queue.*/protected void sendAttributeEvent(AttributeState state) {sendAttributeEvent(new AttributeEvent(state, timerService.getCurrentTimeMillis()));}/**- * Send an arbitrary {@link AttributeEvent} through the processing chain.- * Use {@link #updateLinkedAttribute} to publish new sensor values, which performs- * additional verification and uses a different messaging queue.+ * Send an arbitrary {@link AttributeEvent} through the processing chain. Use {@link #updateLinkedAttribute} to+ * publish new sensor values, which performs additional verification and uses a different messaging queue.*/protected void sendAttributeEvent(AttributeEvent event) {// Don't allow updating linked attributes with this mechanism as it could cause an infinite loop@@ -248,25 +245,22 @@ public abstract class AbstractProtocol implements Protocol {}/**- * Update the value of a linked attribute, with the current system time as event time.- * Call this to publish new sensor values.+ * Update the value of a linked attribute, with the current system time as event time. Call this to publish new+ * sensor values.*/protected void updateLinkedAttribute(AttributeState state) {updateLinkedAttribute(state, timerService.getCurrentTimeMillis());}/**- * Update a linked protocol configuration; allows protocols to reconfigure their- * own protocol configurations to persist changing data e.g. authorization tokens.+ * Update a linked protocol configuration; allows protocols to reconfigure their own protocol configurations to+ * persist changing data e.g. authorization tokens. First this clones the existing protocolConfiguration and calls+ * the consumer to perform the modification.*/- protected void updateLinkedProtocolConfiguration(AssetAttribute protocolConfiguration, HasUniqueResourceName metaName, MetaItem... newMetaItem) {- updateLinkedProtocolConfiguration(protocolConfiguration, metaName.getUrn(), newMetaItem);- }-- protected void updateLinkedProtocolConfiguration(AssetAttribute protocolConfiguration, String metaName, MetaItem... newMetaItem) {+ protected void updateLinkedProtocolConfiguration(AssetAttribute protocolConfiguration, Consumer<AssetAttribute> protocolUpdater) {// Clone the protocol configuration rather than modify this oneAssetAttribute modifiedProtocolConfiguration = protocolConfiguration.deepCopy();- MetaItem.replaceMetaByName(modifiedProtocolConfiguration.getMeta(), metaName, Arrays.asList(newMetaItem));+ protocolUpdater.accept(modifiedProtocolConfiguration);assetService.updateProtocolConfiguration(modifiedProtocolConfiguration);}@@ -322,8 +316,7 @@ public abstract class AbstractProtocol implements Protocol {abstract protected void doUnlinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration);/**- * Attribute event (write) has been requested for an attribute linked to the specified- * protocol configuration.+ * Attribute event (write) has been requested for an attribute linked to the specified protocol configuration.*/abstract protected void processLinkedAttributeWrite(AttributeEvent event, AssetAttribute protocolConfiguration);}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.javaindex ef03b12a5..f734ceebd 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@@ -27,10 +27,7 @@ import org.openremote.model.util.Pair;import org.openremote.model.value.Value;import org.openremote.model.value.Values;-import java.util.Collections;-import java.util.HashMap;-import java.util.List;-import java.util.Map;+import java.util.*;import java.util.concurrent.ScheduledFuture;import java.util.logging.Logger;@@ -306,7 +303,10 @@ public class MacroProtocol extends AbstractProtocol {.map(MacroAction::toMetaItem).toArray(MetaItem[]::new);- updateLinkedProtocolConfiguration(protocolConfiguration, META_MACRO_ACTION, actionMeta);+ updateLinkedProtocolConfiguration(+ protocolConfiguration,+ protocolConfig -> MetaItem.replaceMetaByName(protocolConfig.getMeta(), META_MACRO_ACTION, Arrays.asList(actionMeta))+ );}}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.javaindex 12d5f7fd7..225ecf11f 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@@ -152,7 +152,10 @@ public class TimerProtocol extends AbstractProtocol {LOG.finer("Protocol configuration enabled status is already: " + enabled);} else {LOG.fine("Updating protocol configuration enabled status");- updateLinkedProtocolConfiguration(protocolConfiguration, AssetMeta.ENABLED, new MetaItem(AssetMeta.ENABLED, Values.create(enabled)));+ updateLinkedProtocolConfiguration(+ protocolConfiguration,+ protocolConfig -> protocolConfig.setDisabled(!enabled)+ );}break;case CRON_EXPRESSION:@@ -255,8 +258,13 @@ public class TimerProtocol extends AbstractProtocol {updateLinkedProtocolConfiguration(getLinkedProtocolConfiguration(state.getAttributeRef()),- META_TIMER_CRON_EXPRESSION,- new MetaItem(META_TIMER_CRON_EXPRESSION, state.getCurrentValue().orElse(null))+ protocolConfig -> {+ MetaItem.replaceMetaByName(+ protocolConfig.getMeta(),+ META_TIMER_CRON_EXPRESSION,+ state.getCurrentValue().orElse(null)+ );+ });}diff --git a/container/src/main/groovy/org/openremote/test/ContainerTrait.groovy b/container/src/main/groovy/org/openremote/test/ContainerTrait.groovyindex 4c8dda179..346f553cc 100644--- a/container/src/main/groovy/org/openremote/test/ContainerTrait.groovy+++ b/container/src/main/groovy/org/openremote/test/ContainerTrait.groovy@@ -46,7 +46,7 @@ import static java.util.concurrent.TimeUnit.SECONDStrait ContainerTrait {- private static Container container;+ private static Container containerstatic Container startContainer(Map<String, String> config, Iterable<ContainerService> services) {container = new Container(config, services)diff --git a/container/src/main/groovy/org/openremote/test/TestUtil.groovy b/container/src/main/groovy/org/openremote/test/TestUtil.groovyindex 94bf2070c..0916375b2 100644--- a/container/src/main/groovy/org/openremote/test/TestUtil.groovy+++ b/container/src/main/groovy/org/openremote/test/TestUtil.groovy@@ -6,10 +6,10 @@ class TestUtil {def message = "Task"def count = 1def threadsPerInterval = 1- def Closure task+ Closure task@Override- public String toString() {+ String toString() {return "\"message\": \"" + message + "\"" +", \"count\": " + count +", \"threadsPerInterval\": " + threadsPerInterval@@ -27,7 +27,7 @@ class TestUtil {def lastError@Override- public String toString() {+ String toString() {return "{" + execution +", \"startTimestamp\":" + startTimestamp +", \"endTimestamp\":" + endTimestamp +@@ -76,7 +76,7 @@ class TestUtil {return report}- public static void main(String[] args) {+ static void main(String[] args) {performTimed}diff --git a/container/src/main/java/org/openremote/container/json/EpochSecondsDeserializer.java b/container/src/main/java/org/openremote/container/json/EpochSecondsDeserializer.javaindex bd3e542a6..d3f1e46b5 100644--- a/container/src/main/java/org/openremote/container/json/EpochSecondsDeserializer.java+++ b/container/src/main/java/org/openremote/container/json/EpochSecondsDeserializer.java@@ -29,7 +29,7 @@ import java.util.Date;public class EpochSecondsDeserializer extends JsonDeserializer<Date> {@Override- public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {+ public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {String timestamp = p.getText().trim();try {return new Date(Long.valueOf(timestamp + "000"));diff --git a/container/src/main/java/org/openremote/container/json/EpochSecondsSerializer.java b/container/src/main/java/org/openremote/container/json/EpochSecondsSerializer.javaindex 4f7c69705..a3b7ecd19 100644--- a/container/src/main/java/org/openremote/container/json/EpochSecondsSerializer.java+++ b/container/src/main/java/org/openremote/container/json/EpochSecondsSerializer.java@@ -33,7 +33,7 @@ import java.util.Date;public class EpochSecondsSerializer extends JsonSerializer<Date> {@Override- public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {+ public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers) throws IOException {gen.writeNumber(Math.round(((double)value.getTime()) / 1000));}}diff --git a/container/src/main/java/org/openremote/container/web/jsapi/JSAPIServlet.java b/container/src/main/java/org/openremote/container/web/jsapi/JSAPIServlet.javaindex 3ca220791..1d8915038 100644--- a/container/src/main/java/org/openremote/container/web/jsapi/JSAPIServlet.java+++ b/container/src/main/java/org/openremote/container/web/jsapi/JSAPIServlet.java@@ -102,7 +102,7 @@ public class JSAPIServlet extends HttpServlet {for (Map.Entry<String, ResteasyDeployment> entry : deployments.entrySet()) {ResourceMethodRegistry registry = (ResourceMethodRegistry) entry.getValue().getRegistry();ResteasyProviderFactory providerFactory =- (ResteasyProviderFactory) entry.getValue().getProviderFactory();+ entry.getValue().getProviderFactory();ServiceRegistry service = new ServiceRegistry(null, registry, providerFactory, null);services.put(entry.getKey(), service);}diff --git a/container/src/main/java/org/openremote/container/web/jsapi/MethodParamMetaData.java b/container/src/main/java/org/openremote/container/web/jsapi/MethodParamMetaData.javaindex 7c48c3055..c5cfbe9e8 100644--- a/container/src/main/java/org/openremote/container/web/jsapi/MethodParamMetaData.java+++ b/container/src/main/java/org/openremote/container/web/jsapi/MethodParamMetaData.java@@ -20,7 +20,7 @@ import java.lang.annotation.Annotation;public class MethodParamMetaData {- public static enum MethodParamType {+ public enum MethodParamType {QUERY_PARAMETER, HEADER_PARAMETER, COOKIE_PARAMETER, PATH_PARAMETER, MATRIX_PARAMETER, FORM_PARAMETER, FORM, ENTITY_PARAMETER}diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/AssetQueryMapper.java b/manager/client/src/main/java/org/openremote/manager/client/assets/AssetQueryMapper.javanew file mode 100644index 000000000..e853f64bc--- /dev/null+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/AssetQueryMapper.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.AssetQuery;++@JsonMixIns({@JsonMixIns.JsonMixIn(target = AssetQuery.class, mixIn = DefaultJsonMixin.class)})+public interface AssetQueryMapper+ extends ObjectMapper<AssetQuery>,+ EntityReader<AssetQuery>,+ EntityWriter<AssetQuery> {+}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.javaindex 603f69638..86a3e7f67 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@@ -23,12 +23,17 @@ 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.function.Consumer;public interface AssetEdit extends FormView, IsWidget {@@ -51,6 +56,10 @@ public interface AssetEdit extends FormView, IsWidget {void create();void delete();++ void getLinkableAssets(ValueHolder value, Consumer<Asset[]> assetConsumer);++ void getLinkableAttributes(Pair<ValueHolder, Asset> valueAssetPair, Consumer<AssetAttribute[]> attributeConusmer);}void setAssetViewHistoryToken(String token);diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditActivity.java b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditActivity.javaindex 24adaeddd..682efee04 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@@ -21,7 +21,9 @@ package org.openremote.manager.client.assets.asset;import com.google.gwt.user.client.ui.AcceptsOneWidget;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.*;@@ -33,15 +35,21 @@ import org.openremote.manager.shared.asset.AssetResource;import org.openremote.manager.shared.map.MapResource;import org.openremote.manager.shared.security.Tenant;import org.openremote.manager.shared.validation.ConstraintViolation;-import org.openremote.model.asset.Asset;-import org.openremote.model.asset.AssetAttribute;-import org.openremote.model.asset.AssetType;+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.attribute.AttributeType;+import org.openremote.model.attribute.MetaItem;import org.openremote.model.event.bus.EventBus;import org.openremote.model.event.bus.EventRegistration;+import org.openremote.model.util.Pair;import javax.inject.Inject;+import java.util.ArrayList;import java.util.Collection;+import java.util.Collections;+import java.util.List;import java.util.function.Consumer;import java.util.stream.Collectors;@@ -54,9 +62,15 @@ public class AssetEditActivityfinal 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 List<Consumer<Asset[]>> agentAssetConsumers = new ArrayList<>();+ protected final List<Consumer<Asset[]>> allAssetConsumers = new ArrayList<>();+ protected Asset[] agentAssets;+ protected Asset[] allAssets;double[] selectedCoordinates;AttributesEditor attributesEditor;@@ -68,12 +82,16 @@ public class AssetEditActivityAssetEdit view,AssetResource assetResource,AssetMapper assetMapper,+ AssetArrayMapper assetArrayMapper,+ AssetQueryMapper assetQueryMapper,MapResource mapResource,ObjectValueMapper objectValueMapper) {super(environment, currentTenant, assetBrowserPresenter);this.view = view;this.assetResource = assetResource;this.assetMapper = assetMapper;+ this.assetArrayMapper = assetArrayMapper;+ this.assetQueryMapper = assetQueryMapper;this.mapResource = mapResource;this.objectValueMapper = objectValueMapper;@@ -272,6 +290,84 @@ public class AssetEditActivity);}+ @Override+ public void getLinkableAssets(ValueHolder value, Consumer<Asset[]> assetConsumer) {+ List<Consumer<Asset[]>> consumers;+ Asset[] retrievedAssets;+ Consumer<Asset[]> assetStore;+ AssetQuery query;++ if ((value instanceof MetaItem) && AgentLink.isAgentLink((MetaItem) value)) {+ consumers = agentAssetConsumers;+ retrievedAssets = agentAssets;+ assetStore = assets -> agentAssets = assets;+ query = new AssetQuery()+ // There shouldn't be many agents so retrieve their attributes to speed up getting+ // Protocol Configuration attribute names+ .select(new AssetQuery.Select(AssetQuery.Include.ONLY_ID_AND_NAME_AND_ATTRIBUTES))+ // Limit to agents+ .type(AssetType.AGENT);+ } else {+ consumers = allAssetConsumers;+ retrievedAssets = allAssets;+ assetStore = assets -> allAssets = assets;+ // Limit to assets that have the same realm as the asset being edited+ query = new AssetQuery()+ .select(new AssetQuery.Select(AssetQuery.Include.ONLY_ID_AND_NAME_AND_ATTRIBUTE_NAMES, true));+ }++ if (retrievedAssets != null) {+ // Already retrieved so return results+ assetConsumer.accept(retrievedAssets);+ return;+ }++ consumers.add(assetConsumer);++ if (consumers.size() == 1) {+ // Do request+ environment.getRequestService().execute(+ assetArrayMapper,+ assetQueryMapper,+ requestParams -> assetResource.queryAssets(requestParams, query),+ Collections.singletonList(200),+ assets -> {+ assetStore.accept(assets);+ consumers.forEach(consumer -> consumer.accept(assets));+ consumers.clear();+ },+ exception -> {+ Asset[] assets = new Asset[0];+ assetStore.accept(assets);+ consumers.forEach(consumer -> consumer.accept(assets));+ consumers.clear();+ }+ );+ }+ }++ @Override+ public void getLinkableAttributes(Pair<ValueHolder, Asset> valueAssetPair, Consumer<AssetAttribute[]> attributeConsumer) {+ ValueHolder value = valueAssetPair.key;+ Asset asset = valueAssetPair.value;++ if ((value instanceof MetaItem) && AgentLink.isAgentLink((MetaItem) value)) {+ // Asset should have fully populated attributes so filter them+ attributeConsumer.accept(+ asset.getAttributesStream()+ .filter(ProtocolConfiguration::isProtocolConfiguration)+ .toArray(AssetAttribute[]::new)+ );+ } else {+ // Asset should just have attribute names and labels loaded so return them+ attributeConsumer.accept(+ asset+ .getAttributesStream()+ .toArray(AssetAttribute[]::new)+ );+ }+ }+@Overridepublic void centerMap() {if (selectedCoordinates != null) {@@ -351,7 +447,9 @@ public class AssetEditActivityassetId == null? asset.getWellKnownType().getDefaultAttributes().collect(Collectors.toList()): asset.getAttributesList(),- assetId == null+ assetId == null,+ this::getLinkableAssets,+ this::getLinkableAttributes);view.setAttributesEditor(attributesEditor);attributesEditor.build();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.xmlindex 69be65b4f..10c277c73 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@@ -50,6 +50,16 @@.highlightAttribute {}+++ .metaItemNameEditor {+ min-width: 5em;+ width: 35em;+ }++ .metaItemValueEditor {++ }</ui:style><w:FlexSplitPanel ui:field="splitPanel"diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesEditor.java b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesEditor.javaindex 80768d8d8..b1c3572e2 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesEditor.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesEditor.java@@ -19,28 +19,31 @@*/package org.openremote.manager.client.assets.attributes;-import com.google.gwt.dom.client.Document;-import com.google.gwt.event.dom.client.DomEvent;import com.google.gwt.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 java.util.function.Supplier;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 AttributesEditorextends AttributesView<AttributesEditor.Container, AttributesEditor.Style> {@@ -50,14 +53,21 @@ public class AttributesEditor}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) {+ 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) {@@ -165,14 +175,13 @@ public class AttributesEditorpublic MetaEditor(AssetAttribute attribute) {this.attribute = attribute;-add(itemListSectionLabel);add(itemListPanel);buildItemList();add(itemEditorSectionLabel);add(itemEditorPanel);- buildItemEditor();+ buildNewItemEditor();}protected void buildItemList() {@@ -187,239 +196,304 @@ public class AttributesEditorList<MetaItem> items = attribute.getMeta();for (int i = 0; i < items.size(); i++) {MetaItem item = items.get(i);- FormGroup formGroup = new FormGroup();-- FormLabel label = new FormLabel(item.getName().orElse(null));- label.getElement().getStyle().setWidth(40, com.google.gwt.dom.client.Style.Unit.EM);- formGroup.addFormLabel(label);-- FormField formField = new FormField();-- // Determine editor based on value type- if (item.getValue().isPresent()) {- ValueType valueType = item.getValue().get().getType();- formField.add(createEditor(item, valueType, false, formGroup));- formGroup.addFormField(formField);- } else {- formField.add(noValueItemEditor(item));- formGroup.addFormField(formField);- }-- FormGroupActions formGroupActions = new FormGroupActions();+ MetaItemEditor metaItemEditor = new MetaItemEditor(this, item, false);+ itemListPanel.add(metaItemEditor);+ }+ }- FormButton deleteButton = new FormButton();- deleteButton.setText(container.getMessages().deleteItem());- deleteButton.setIcon("remove");- int index = i;- deleteButton.addClickHandler(clickEvent -> {- attributeGroups.get(attribute).setErrorInExtension(false);- attribute.getMeta().remove(index);- buildItemList();- });- formGroupActions.add(deleteButton);+ protected void addItem(MetaItem item) {+ attribute.getMeta().add(item);+ MetaItemEditor metaItemEditor = new MetaItemEditor(this, item, false);+ itemListPanel.add(metaItemEditor);+ }- formGroup.addFormGroupActions(formGroupActions);+ protected void removeItem(MetaItemEditor itemEditor) {+ int index = itemListPanel.getWidgetIndex(itemEditor);+ itemListPanel.remove(itemEditor);+ attributeGroups.get(attribute).setErrorInExtension(false);+ attribute.getMeta().remove(index);+ }- itemListPanel.add(formGroup);- }+ protected void buildNewItemEditor() {+ MetaItem item = new MetaItem();+ MetaItemEditor metaItemEditor = new MetaItemEditor(this, item, true);+ itemEditorPanel.add(metaItemEditor);}+ }- protected void buildItemEditor() {- itemEditorPanel.clear();+ 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;+ }+ }- MetaItem item = new MetaItem();+ nameList.addChangeHandler(event -> {+ onNameChanged(true);+ });- FormListBox valueTypeListBox = new FormListBox();- FormGroup itemNameEditorGroup = createItemNameEditor(item, valueTypeListBox);- itemEditorPanel.add(itemNameEditorGroup);-- FormGroup itemValueEditorGroup = createItemValueEditor(item, valueTypeListBox);- itemEditorPanel.add(itemValueEditorGroup);-- FormGroupActions formGroupActions = new FormGroupActions();- FormButton addButton = new FormButton();- addButton.setText(container.getMessages().addItem());- addButton.setIcon("plus");- addButton.addClickHandler(clickEvent -> {-- // We ask the attribute for validation failures instead of the- // item, because the item must be valid in its context- List<ValidationFailure> failures = attribute.getMetaItemValidationFailures(item);-- if (failures.isEmpty()) {- itemNameEditorGroup.setError(false);- itemValueEditorGroup.setError(false);- attribute.getMeta().add(item);- buildItemList();- buildItemEditor();+ 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 {- itemNameEditorGroup.setError(true);- itemValueEditorGroup.setError(true);- for (ValidationFailure failure : failures) {- showValidationError(environment, item.getName().orElse(null), failure);- }+ item.setName(nameInput.getValue());}+ onValidation(item.getValidationFailures());+ });+ nameInput.addValueChangeHandler(event -> {+ if (isNullOrEmpty(event.getValue())) {+ item.clearName();+ } else {+ item.setName(event.getValue());+ }+ onValidation(item.getValidationFailures());});- formGroupActions.add(addButton);- itemValueEditorGroup.addFormGroupActions(formGroupActions);- }- protected IsWidget createEditor(MetaItem item, ValueType valueType, boolean isNewMetaItem, FormGroup formGroup) {- AttributesEditor.Style style = container.getStyle();+ 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;+ }+ }- // For some meta items we know if we can edit them or not... custom items are always editable- boolean isEditable = item.getName().map(AssetMeta::isEditable).orElse(isNewMetaItem);+ typeList.addChangeHandler(event -> {+ onTypeChanged(true);+ });- Consumer<List<ValidationFailure>> validationResultConsumer =- failures -> {- // If we are not creating a new meta item, validate again in context of attribute- if (!isNewMetaItem && failures.isEmpty()) {- failures = attribute.getMetaItemValidationFailures(item);- }- if (!failures.isEmpty()) {- formGroup.setError(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);}}- // Validation failure of meta item marks the attribute form extension as error state- if (!isNewMetaItem) {- attributeGroups.get(attribute).setErrorInExtension(!failures.isEmpty());+ } 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);}- };- if (valueType.equals(ValueType.STRING)) {- String currentValue = item.getValue().map(Object::toString).orElse(null);- return createStringEditor(- item, currentValue, null, false, style.stringEditor(), formGroup, false, validationResultConsumer- );- } else if (valueType.equals(ValueType.NUMBER)) {- String currentValue = item.getValue().map(Object::toString).orElse(null);- return createNumberEditor(- item, currentValue, null, false, style.numberEditor(), formGroup, false, validationResultConsumer- );- } else if (valueType.equals(ValueType.BOOLEAN)) {- Boolean currentValue = item.getValueAsBoolean().orElse(null);- return createBooleanEditor(- item, currentValue, null, false, style.booleanEditor(), formGroup, false, validationResultConsumer- );- } else if (valueType.equals(ValueType.OBJECT)) {- ObjectValue currentValue = item.getValueAsObject().orElse(null);- String label = environment.getMessages().jsonObject();- String title = environment.getMessages().edit() + " " + environment.getMessages().jsonObject();- Supplier<Value> resetSupplier = () -> item.getValue().orElse(null);- return createObjectEditor(- attribute, currentValue, resetSupplier, false, label, title, container.getJsonEditor(), formGroup, false, validationResultConsumer- );- } else if (valueType.equals(ValueType.ARRAY)) {- ArrayValue currentValue = item.getValueAsArray().orElse(null);- String label = environment.getMessages().jsonArray();- String title = environment.getMessages().edit() + " " + environment.getMessages().jsonArray();- Supplier<Value> resetSupplier = () -> item.getValue().orElse(null);- return createArrayEditor(- attribute, currentValue, resetSupplier, false, label, title, container.getJsonEditor(), formGroup, false, validationResultConsumer- );- } else {- return new FormOutputText(- environment.getMessages().unsupportedMetaItemType(valueType.name())- );+ 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())+ );}}- /**- * This should actually never be called as we don't allow storing of empty meta items. But- * because we don't have proper database constraints, who knows...- */- protected IsWidget noValueItemEditor(MetaItem item) {- FormField field = new FormField();- field.add(new FormOutputText(environment.getMessages().emptyMetaItem()));- return () -> field;+ 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 FormGroup createItemNameEditor(MetaItem item, FormListBox typeListBox) {- FormGroup formGroup = new FormGroup();-- FormLabel label = new FormLabel(environment.getMessages().itemName());- label.addStyleName("larger");- formGroup.addFormLabel(label);+ protected void onNameChanged(boolean updateItem) {+ if (updateItem && nameList.getSelectedIndex() == 0) {+ nameInput.setValue(null);+ }- FormField formField = new FormField();- formGroup.addFormField(formField);+ String urn = nameList.getSelectedIndex() > 0 ? nameList.getSelectedValue() : nameInput.getValue();- FormListBox wellknownListBox = new FormListBox();- wellknownListBox.addItem(environment.getMessages().selectItem());- for (AssetMeta wellknown : AssetMeta.editable()) {- wellknownListBox.addItem(wellknown.name());- }- formField.add(wellknownListBox);-- formField.add(new FormOutputText(environment.getMessages().or()));-- FormInputText itemNameInput = new FormInputText();- itemNameInput.addStyleName(container.getStyle().stringEditor());- itemNameInput.setPlaceholder(environment.getMessages().enterCustomAssetAttributeMetaName());- itemNameInput.addValueChangeHandler(event -> item.setName(event.getValue()));- formField.add(itemNameInput);-- wellknownListBox.addChangeHandler(event -> {- if (wellknownListBox.getSelectedIndex() > 0) {- AssetMeta assetMeta = AssetMeta.editable()[wellknownListBox.getSelectedIndex() - 1];- itemNameInput.setText(assetMeta.getUrn());- item.setName(assetMeta.getUrn());- AssetMeta.EditableType editableType = AssetMeta.EditableType.byValueType(assetMeta.getValueType());- typeListBox.setSelectedIndex(- editableType != null ? editableType.ordinal() + 1 : 0- );+ if (updateItem) {+ item.clearValue();+ if (isNullOrEmpty(urn)) {+ item.clearName();} else {- itemNameInput.setText(null);- item.setName(null);- typeListBox.setSelectedIndex(0);+ item.setName(urn);}- DomEvent.fireNativeEvent(Document.get().createChangeEvent(), typeListBox);- });+ }- return formGroup;- }+ nameInput.setValue(urn);- protected FormGroup createItemValueEditor(MetaItem item, FormListBox typeListBox) {- FormGroup formGroup = new FormGroup();+ 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);+ }- FormLabel label = new FormLabel(environment.getMessages().value());- label.addStyleName("larger");- formGroup.addFormLabel(label);+ onTypeChanged(updateItem);+ }- FormField formField = new FormField();- formGroup.addFormField(formField);+ protected void onTypeChanged(boolean updateItem) {+ Optional<AssetMeta> assetMeta = AssetMeta.getAssetMeta(nameList.getSelectedValue());- typeListBox.addItem(environment.getMessages().selectType());- for (AssetMeta.EditableType metaEditableType : AssetMeta.EditableType.values()) {- typeListBox.addItem(metaEditableType.label, metaEditableType.name());- }- typeListBox.addChangeHandler(event -> resetItemValueEditor(item, formGroup, formField, typeListBox));+ 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);+ }- formField.add(typeListBox);+ item.setValue(initialValue);+ onValidation(item.getValidationFailures());+ }+ updateValueEditor(assetMeta.map(AssetMeta::isValueFixed).orElse(false));+ }- // Initial state- resetItemValueEditor(item, formGroup, formField, typeListBox);+ protected void updateValueEditor(boolean hideEditor) {+ if (valueEditor != null) {+ field.remove(valueEditor);+ }- return formGroup;+ if (!hideEditor && typeList.getSelectedIndex() > 0) {+ valueEditor = createItemValueEditor();+ field.add(valueEditor);+ }}- protected void resetItemValueEditor(MetaItem item, FormGroup formGroup, FormField formField, FormListBox typeListBox) {- // Remove the last used editor (last widget in form field)- if (formField.getWidgetCount() > 1)- formField.remove(formField.getWidget(formField.getWidgetCount() - 1));-- // Create and add new editor, default to empty STRING+ protected void reset() {+ item.clearName();item.clearValue();- ValueType valueType = typeListBox.getSelectedIndex() > 0- ? AssetMeta.EditableType.valueOf(typeListBox.getSelectedValue()).valueType- : ValueType.STRING;- if (valueType == ValueType.BOOLEAN) {- item.setValue(Values.create(false)); // Special case boolean editor, has an "initial" state, there is always a value- }- IsWidget editor = createEditor(item, valueType, true, formGroup);- formField.add(editor);+ 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.javaindex af8d06e8c..401789428 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesView.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesView.java@@ -253,7 +253,6 @@ public abstract class AttributesView<}protected IsWidget createAttributeValueEditor(AssetAttribute attribute, FormGroup formGroup) {- Optional<MetaItem> defaultValueItem = attribute.getMetaItem(AssetMeta.DEFAULT);S style = container.getStyle();AttributeType attributeType = attribute.getType().orElse(null);@@ -272,42 +271,37 @@ public abstract class AttributesView<IsWidget editor;if (attributeType == AttributeType.STRING || attributeType.getValueType() == ValueType.STRING) {String currentValue = attribute.getValue().map(Object::toString).orElse(null);- String defaultValue = defaultValueItem.flatMap(AbstractValueHolder::getValueAsString).orElse(null);editor = createStringEditor(- attribute, currentValue, defaultValue, readOnly, style.stringEditor(), formGroup, showTimestamp, validationResultConsumer+ 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);- String defaultValue = defaultValueItem.flatMap(AbstractValueHolder::getValueAsString).orElse(null);editor = createNumberEditor(- attribute, currentValue, defaultValue, readOnly, style.numberEditor(), formGroup, showTimestamp, validationResultConsumer+ attribute, currentValue, readOnly, style.numberEditor(), formGroup, showTimestamp, validationResultConsumer);} else if (attributeType == AttributeType.BOOLEAN || attributeType.getValueType() == ValueType.BOOLEAN) {Boolean currentValue = attribute.getValueAsBoolean().orElse(null);- Boolean defaultValue = defaultValueItem.flatMap(AbstractValueHolder::getValueAsBoolean).orElse(null);editor = createBooleanEditor(- attribute, currentValue, defaultValue, readOnly, style.booleanEditor(), formGroup, showTimestamp, validationResultConsumer+ 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);- Supplier<Value> resetSupplier = () -> attribute.getValue().orElse(null);String label = environment.getMessages().jsonObject();String title = !readOnly? environment.getMessages().edit() + " " + environment.getMessages().jsonObject(): environment.getMessages().jsonObject();editor = createObjectEditor(- attribute, currentValue, resetSupplier, readOnly, label, title, container.getJsonEditor(), formGroup, showTimestamp, validationResultConsumer+ 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);- Supplier<Value> resetSupplier = () -> attribute.getValue().orElse(null);String label = environment.getMessages().jsonArray();String title = !readOnly? environment.getMessages().edit() + " " + environment.getMessages().jsonArray(): environment.getMessages().jsonArray();editor = createArrayEditor(- attribute, currentValue, resetSupplier, readOnly, label, title, container.getJsonEditor(), formGroup, showTimestamp, validationResultConsumer+ attribute, currentValue, readOnly, label, title, container.getJsonEditor(), formGroup, showTimestamp, validationResultConsumer);} else {editor = new FormOutputText(diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetBrowserPresenter.java b/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetBrowserPresenter.javaindex 04b0c0b31..8feeb1ff0 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetBrowserPresenter.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetBrowserPresenter.java@@ -24,10 +24,12 @@ import org.openremote.manager.client.Environment;import org.openremote.manager.client.admin.TenantArrayMapper;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.shared.asset.AssetResource;import org.openremote.manager.shared.security.Tenant;import org.openremote.manager.shared.security.TenantResource;import org.openremote.model.asset.Asset;+import org.openremote.model.asset.AssetQuery;import org.openremote.model.asset.AssetTreeModifiedEvent;import org.openremote.model.event.bus.EventRegistration;@@ -50,6 +52,7 @@ public class AssetBrowserPresenter implements AssetBrowser.Presenter {final AssetBrowser view;final AssetResource assetResource;final AssetMapper assetMapper;+ final AssetQueryMapper assetQueryMapper;final AssetArrayMapper assetArrayMapper;final TenantResource tenantResource;final TenantArrayMapper tenantArrayMapper;@@ -66,6 +69,7 @@ public class AssetBrowserPresenter implements AssetBrowser.Presenter {AssetBrowser view,AssetResource assetResource,AssetMapper assetMapper,+ AssetQueryMapper assetQueryMapper,AssetArrayMapper assetArrayMapper,TenantResource tenantResource,TenantArrayMapper tenantArrayMapper) {@@ -76,6 +80,7 @@ public class AssetBrowserPresenter implements AssetBrowser.Presenter {this.tenantArrayMapper = tenantArrayMapper;this.assetResource = assetResource;this.assetMapper = assetMapper;+ this.assetQueryMapper = assetQueryMapper;this.assetArrayMapper = assetArrayMapper;view.setPresenter(this);@@ -235,18 +240,24 @@ public class AssetBrowserPresenter implements AssetBrowser.Presenter {// final Range range = display.getVisibleRange();environment.getRequestService().execute(assetArrayMapper,+ assetQueryMapper,requestParams -> {// This must be synchronous, so tree selection/searching worksrequestParams.setAsync(false);if (parent instanceof TenantTreeNode) {- assetResource.getRoot(requestParams, parent.getId());+ assetResource.queryAssets(+ requestParams,+ new AssetQuery()+ .tenant(new AssetQuery.TenantPredicate(parent.getId()))+ .parent(new AssetQuery.ParentPredicate(true))+ );} else if (parent instanceof RootTreeNode) {assetResource.getCurrentUserAssets(requestParams);} else {- assetResource.getChildren(requestParams, parent.getId(), false);+ assetResource.queryAssets(requestParams, new AssetQuery().parent(parent.getId()));}},- 200,+ Collections.singletonList(200),assets -> {List<BrowserTreeNode> treeNodes = new ArrayList<>();for (Asset asset : assets) {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.javaindex 0794490aa..b932946d4 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,6 +21,8 @@ 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.DefaultLocalepublic interface ManagerMessages extends Messages {@@ -229,12 +231,16 @@ public interface ManagerMessages extends Messages {String and();- String selectItem();+ String customItem();String enterCustomAssetAttributeMetaName();String selectType();+ String valueTypeDisplayName(@Select String valueType);++ String assetMetaDisplayName(@Select String assetMetaName);+String attributeDeleted(String name);String attributeAdded(String name);@@ -401,4 +407,9 @@ public interface ManagerMessages extends Messages {String simulatorStateSubmitted();+ String selectAgent();++ String selectAttribute();++ String selectProtocolConfiguration();}diff --git a/manager/client/src/main/java/org/openremote/manager/client/mvp/AppActivity.java b/manager/client/src/main/java/org/openremote/manager/client/mvp/AppActivity.javaindex c24ded8b4..722cde8da 100644--- a/manager/client/src/main/java/org/openremote/manager/client/mvp/AppActivity.java+++ b/manager/client/src/main/java/org/openremote/manager/client/mvp/AppActivity.java@@ -50,7 +50,7 @@ public abstract class AppActivity<P extends Place> {}}return init(place);- };+ }protected abstract AppActivity<P> init(P place);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.javaindex 02ca09508..7304f6560 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@@ -117,17 +117,17 @@ public class Simulator extends FlowPanel implements IsWidget {if (valueType.equals(ValueType.STRING)) {String currentValue = element.getValue().map(Object::toString).orElse(null);editor = createStringEditor(- element, currentValue, null, false, "or-SimulatorElement", formGroup, false, validationResultConsumer+ 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, null, false, "or-SimulatorElement", formGroup, false, validationResultConsumer+ element, currentValue, false, "or-SimulatorElement", formGroup, false, validationResultConsumer);} else if (valueType.equals(ValueType.BOOLEAN)) {Boolean currentValue = element.getValueAsBoolean().orElse(null);editor = createBooleanEditor(- element, currentValue, null, false, "or-SimulatorElement", formGroup, false, validationResultConsumer+ element, currentValue, false, "or-SimulatorElement", formGroup, false, validationResultConsumer);// TODO Support JSON editors} else {diff --git a/manager/client/src/main/java/org/openremote/manager/client/toast/PopupToastDisplay.java b/manager/client/src/main/java/org/openremote/manager/client/toast/PopupToastDisplay.javaindex e756f2da2..f06ac8d9b 100644--- a/manager/client/src/main/java/org/openremote/manager/client/toast/PopupToastDisplay.java+++ b/manager/client/src/main/java/org/openremote/manager/client/toast/PopupToastDisplay.java@@ -73,9 +73,7 @@ public class PopupToastDisplay implements ToastDisplay {Point point = (Point) o;if (x != point.x) return false;- if (y != point.y) return false;-- return true;+ return y == point.y;}@Overridediff --git a/manager/client/src/main/java/org/openremote/manager/client/widget/MapWidget.java b/manager/client/src/main/java/org/openremote/manager/client/widget/MapWidget.javaindex fe2c1d720..8dc8b0b4f 100644--- a/manager/client/src/main/java/org/openremote/manager/client/widget/MapWidget.java+++ b/manager/client/src/main/java/org/openremote/manager/client/widget/MapWidget.java@@ -71,7 +71,7 @@ public class MapWidget extends FlowPanel {LAYER_CIRCLE.put("paint", paint);}{- ObjectValue layout = Values.createObject();;+ ObjectValue layout = Values.createObject();layout.put("visibility", "visible");layout.put("text-field", "{title}");diff --git a/manager/client/src/main/java/org/openremote/manager/client/widget/PopupPanel.java b/manager/client/src/main/java/org/openremote/manager/client/widget/PopupPanel.javaindex a51646f17..447364d78 100644--- a/manager/client/src/main/java/org/openremote/manager/client/widget/PopupPanel.java+++ b/manager/client/src/main/java/org/openremote/manager/client/widget/PopupPanel.java@@ -120,7 +120,7 @@ public class PopupPanel extends SimplePanel implements SourcesPopupEvents,* <li>ROLL_DOWN - Expand from the top to the bottom, do not animate hiding</li>* </ul>*/- public static enum AnimationType {+ public enum AnimationType {CENTER, ONE_WAY_CORNER, ROLL_DOWN}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.javaindex 9f3df1e0b..97da3e007 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,9 +19,13 @@*/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;@@ -29,16 +33,22 @@ import org.openremote.model.AbstractValueTimestampHolder;import org.openremote.model.Constants;import org.openremote.model.ValidationFailure;import org.openremote.model.ValueHolder;+import org.openremote.model.asset.Asset;+import org.openremote.model.asset.AssetAttribute;+import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.util.Pair;import org.openremote.model.value.ArrayValue;import org.openremote.model.value.ObjectValue;import org.openremote.model.value.Value;import org.openremote.model.value.Values;import java.util.ArrayList;+import java.util.Arrays;import java.util.Date;import java.util.List;-import java.util.function.Consumer;-import java.util.function.Supplier;+import java.util.function.*;++import static org.openremote.model.util.TextUtil.isNullOrEmpty;/*** Collection of functions and types for {@link Value} editor UI.@@ -135,6 +145,13 @@ public final class ValueEditors {}};+ private static ValueUpdater<AttributeRef> ATTRIBUTE_REF_UPDATER = new ValueUpdater<AttributeRef>() {+ @Override+ Value createValue(AttributeRef rawValue) throws IllegalArgumentException {+ return rawValue != null ? rawValue.toArrayValue() : null;+ }+ };+private static class TimestampLabel extends FlowPanel {static protected DateTimeFormat dateFormat = DateTimeFormat.getFormat(Constants.DEFAULT_DATE_FORMAT);@@ -151,7 +168,6 @@ public final class ValueEditors {public static IsWidget createStringEditor(ValueHolder valueHolder,String currentValue,- String defaultValue,boolean readOnly,String styleName,FormGroup formGroup,@@ -162,7 +178,7 @@ public final class ValueEditors {: null;FlowPanel panel = new FlowPanel();panel.setStyleName("flex layout horizontal center or-ValueEditor or-StringValueEditor");- IsWidget widget = ValueEditors.createStringEditorWidget(styleName, currentValue, defaultValue, updateConsumer);+ IsWidget widget = ValueEditors.createStringEditorWidget(styleName, currentValue, updateConsumer);FlowPanel widgetWrapper = new FlowPanel();widgetWrapper.setStyleName("flex layout horizontal center");widgetWrapper.add(widget);@@ -175,7 +191,6 @@ public final class ValueEditors {public static IsWidget createNumberEditor(ValueHolder valueHolder,String currentValue,- String defaultValue,boolean readOnly,String styleName,FormGroup formGroup,@@ -188,7 +203,7 @@ public final class ValueEditors {FlowPanel panel = new FlowPanel();panel.setStyleName("flex layout horizontal center or-ValueEditor or-NumberValueEditor");- IsWidget widget = ValueEditors.createStringEditorWidget(styleName, currentValue, defaultValue, updateConsumer);+ IsWidget widget = ValueEditors.createStringEditorWidget(styleName, currentValue, updateConsumer);FlowPanel widgetWrapper = new FlowPanel();widgetWrapper.setStyleName("flex layout horizontal center");widgetWrapper.add(widget);@@ -200,7 +215,6 @@ public final class ValueEditors {public static IsWidget createBooleanEditor(ValueHolder valueHolder,Boolean currentValue,- Boolean defaultValue,boolean readOnly,String styleName,FormGroup formGroup,@@ -212,7 +226,7 @@ public final class ValueEditors {FlowPanel panel = new FlowPanel();panel.setStyleName("flex layout horizontal center or-ValueEditor or-BooleanValueEditor");- IsWidget widget = ValueEditors.createBooleanEditorWidget(styleName, currentValue, defaultValue, updateConsumer);+ IsWidget widget = ValueEditors.createBooleanEditorWidget(styleName, currentValue, updateConsumer);FlowPanel widgetWrapper = new FlowPanel();widgetWrapper.setStyleName("flex layout horizontal center");widgetWrapper.add(widget);@@ -224,7 +238,6 @@ public final class ValueEditors {public static IsWidget createObjectEditor(ValueHolder valueHolder,ObjectValue currentValue,- Supplier<Value> resetSupplier,boolean readOnly,String label,String title,@@ -238,7 +251,7 @@ public final class ValueEditors {FlowPanel panel = new FlowPanel();panel.setStyleName("flex layout horizontal center or-ValueEditor or-ObjectValueEditor");IsWidget widget = createJsonEditorWidget(- jsonEditor, label, title, currentValue, updateConsumer, resetSupplier+ jsonEditor, label, title, currentValue, updateConsumer);FlowPanel widgetWrapper = new FlowPanel();widgetWrapper.setStyleName("flex layout horizontal center");@@ -249,9 +262,111 @@ public final class ValueEditors {return () -> panel;}+ public static IsWidget createAttributeRefEditor(ValueHolder valueHolder,+ boolean readOnly,+ FormGroup formGroup,+ BiConsumer<ValueHolder, Consumer<Asset[]>> assetSupplier,+ BiConsumer<Pair<ValueHolder, Asset>, Consumer<AssetAttribute[]>> attributeSupplier,+ String assetWatermark,+ String attributeWatermark,+ Consumer<List<ValidationFailure>> validationResultConsumer) {++ Consumer<AttributeRef> updateConsumer = !readOnly+ ? rawValue -> ATTRIBUTE_REF_UPDATER.accept(new ValueUpdate<>(formGroup, valueHolder, validationResultConsumer, rawValue))+ : null;++ FlowPanel panel = new FlowPanel();+ panel.setStyleName("flex layout horizontal center or-ValueEditor or-AttributeRefEditor");+ FlowPanel widgetWrapper = new FlowPanel();+ widgetWrapper.setStyleName("flex layout horizontal center");+ panel.add(widgetWrapper);++ List<Asset> assets = new ArrayList<>();+ FormListBox assetList = new FormListBox();+ FormListBox attributeList = new FormListBox();+ String[] existingValue = valueHolder+ .getValueAsArray()+ .filter(arr -> arr.length() == 2)+ .map(arr -> new String[] {arr.getString(0).orElse(null), arr.getString(1).orElse(null)})+ .orElse(new String[2]);+ Runnable onAssetListChanged = () -> {+ int selectedIndex = assetList.getSelectedIndex();+ attributeList.clear();+ attributeList.addItem(attributeWatermark);+ if (selectedIndex == 0) {+ attributeList.setVisible(false);+ existingValue[0] = null;+ existingValue[1] = null;+ } else {+ if (!assetList.getSelectedValue().equals(existingValue[0])) {+ existingValue[0] = assetList.getSelectedValue();+ existingValue[1] = null;+ }++ attributeSupplier.accept(new Pair<>(valueHolder, assets.get(selectedIndex-1)), attributes -> {+ int attributeSelectedIndex = 0;++ for (int i=0; i<attributes.length; i++) {+ AssetAttribute attribute = attributes[i];+ attributeList.addItem(attribute.getLabelOrName().orElse(""), attribute.getName().orElse(""));+ if (attribute.getName().orElse("").equals(existingValue[1])) {+ attributeSelectedIndex = i+1;+ }+ }++ attributeList.setSelectedIndex(attributeSelectedIndex);+ attributeList.setVisible(true);+ });+ }+ if (updateConsumer != null) {+ updateConsumer.accept(!isNullOrEmpty(existingValue[0]) && !isNullOrEmpty(existingValue[1]) ? new AttributeRef(existingValue[0], existingValue[1]) : null);+ }+ };+ Runnable onAttributeListChanged = () -> {+ int selectedIndex = attributeList.getSelectedIndex();+ if (selectedIndex == 0) {+ existingValue[1] = null;+ } else {+ existingValue[1] = attributeList.getSelectedValue();+ }+ if (updateConsumer != null) {+ updateConsumer.accept(!isNullOrEmpty(existingValue[0]) && !isNullOrEmpty(existingValue[1]) ? new AttributeRef(existingValue[0], existingValue[1]) : null);+ }+ };+++ assetList.addItem(assetWatermark);+ attributeList.addItem(attributeWatermark);+ attributeList.setVisible(false);++ assetList.addChangeHandler(event -> onAssetListChanged.run());+ attributeList.addChangeHandler(event -> onAttributeListChanged.run());++ // Populate asset list+ assetSupplier.accept(valueHolder, retrievedAssets -> {+ assets.addAll(Arrays.asList(retrievedAssets));+ int assetSelectedIndex = 0;++ for (int i=0; i<assets.size(); i++) {+ Asset asset = assets.get(i);+ assetList.addItem(asset.getName(), asset.getId());+ if (asset.getId().equals(existingValue[0])) {+ assetSelectedIndex = i+1;+ }+ }++ assetList.setSelectedIndex(assetSelectedIndex);+ onAssetListChanged.run();+ });++ widgetWrapper.add(assetList);+ widgetWrapper.add(attributeList);++ return () -> panel;+ }+public static IsWidget createArrayEditor(ValueHolder valueHolder,ArrayValue currentValue,- Supplier<Value> resetSupplier,boolean readOnly,String label,String title,@@ -266,7 +381,7 @@ public final class ValueEditors {FlowPanel panel = new FlowPanel();panel.setStyleName("flex layout horizontal center or-ValueEditor or-ArrayValueEditor");IsWidget widget = createJsonEditorWidget(- jsonEditor, label, title, currentValue, updateConsumer, resetSupplier+ jsonEditor, label, title, currentValue, updateConsumer);FlowPanel widgetWrapper = new FlowPanel();widgetWrapper.setStyleName("flex layout horizontal center");@@ -301,15 +416,12 @@ public final class ValueEditors {}private static IsWidget createStringEditorWidget(String styleName,- String currentValue,- String defaultValue,+ String value,Consumer<String> updateConsumer) {FormInputText input = new FormInputText();input.addStyleName(styleName);- if (currentValue != null) {- input.setValue(currentValue);- } else if (defaultValue != null) {- input.setValue(defaultValue);+ if (value != null) {+ input.setValue(value);} else if (updateConsumer == null) {input.setValue("-");}@@ -326,18 +438,12 @@ public final class ValueEditors {}private static IsWidget createBooleanEditorWidget(String styleName,- Boolean currentValue,- Boolean defaultValue,+ Boolean value,Consumer<Boolean> updateConsumer) {FormCheckBox input = new FormCheckBox();input.addStyleName(styleName);- Boolean value = null;- if (currentValue != null) {- value = currentValue;- } else if (defaultValue != null) {- value = defaultValue;- } else if (updateConsumer == null) {+ if (value == null && updateConsumer == null) {return new FormOutputText("-");}@@ -355,8 +461,7 @@ public final class ValueEditors {String label,String title,Value currentValue,- Consumer<Value> updateConsumer,- Supplier<Value> resetSupplier) {+ Consumer<Value> updateConsumer) {jsonEditor.setTitle(title);if (currentValue != null) {@@ -368,7 +473,7 @@ public final class ValueEditors {button.setText(label);button.addClickHandler(event -> jsonEditor.show());- jsonEditor.setOnReset(() -> jsonEditor.setValue(resetSupplier.get()));+ jsonEditor.setOnReset(() -> jsonEditor.setValue(currentValue));if (updateConsumer != null) {jsonEditor.setOnApply(updateConsumer);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.propertiesindex 73608ae2e..64d31cec2 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@@ -119,7 +119,7 @@ value=ValuemetaItems=Attribute configurationor=orand=and-selectItem=Select item+customItem=Custom itementerCustomAssetAttributeMetaName=Enter a custom nameselectType=Select typeattributeDeleted=Attribute deleted, save asset to persist: {0}@@ -259,4 +259,33 @@ simulator=SimulatorinvalidValues=Invalid values, please correct.writeSimulatorState=Write simulator statesimulatorStateSubmitted=Simulator state submitted to server.-+selectAgent=Select agent+selectAttribute=Select attribute+selectProtocolConfiguration=Select protocol configuration+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]=Executablediff --git a/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.javaindex 692ab3f49..b421a66cc 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@@ -78,6 +78,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Consprotected 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 Map<String, Asset> agentMap;@Overridepublic void init(Container container) throws Exception {@@ -111,9 +112,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons});- List<ServerAsset> agents = assetStorageService.findAll(new AssetQuery()- .select(new AssetQuery.Select(true, false))- .type(AssetType.AGENT));+ Collection<Asset> agents = getAgents().values();LOG.fine("Deploy all agents in all realms: " + agents.size());/// For all agents, go through their protocol configurations and find@@ -425,7 +424,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons// Get all assets that have attributes that use this protocol configurationList<ServerAsset> assets = assetStorageService.findAll(new AssetQuery()- .select(new AssetQuery.Select(true, false))+ .select(new AssetQuery.Select(AssetQuery.Include.ALL, false)).attributeMeta(new AssetQuery.AttributeRefPredicate(AssetMeta.AGENT_LINK,@@ -454,7 +453,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons// Get all assets that have attributes that use this protocol configurationList<ServerAsset> assets = assetStorageService.findAll(new AssetQuery()- .select(new AssetQuery.Select(true, false))+ .select(new AssetQuery.Select(AssetQuery.Include.ALL, false)).attributeMeta(new AssetQuery.AttributeRefPredicate(AssetMeta.AGENT_LINK,@@ -647,4 +646,16 @@ public class AgentService extends RouteBuilder implements ContainerService, Consreturn deploymentStatusPair == null ? Optional.empty() : Optional.of(deploymentStatusPair.key);}}++ protected synchronized Map<String, Asset> getAgents() {+ if (agentMap == null) {+ agentMap = assetStorageService.findAll(new AssetQuery()+ .select(new AssetQuery.Select(AssetQuery.Include.ALL, false))+ .type(AssetType.AGENT))+ .stream()+ .collect(Collectors.toMap(Asset::getId, agent -> agent));+ }++ return agentMap;+ }}\ No newline at end of filediff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetAttributeLinkingService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetAttributeLinkingService.javaindex 1130be50a..4d2fcc4fc 100644--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetAttributeLinkingService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetAttributeLinkingService.java@@ -21,10 +21,7 @@ package org.openremote.manager.server.asset;import org.openremote.container.Container;import org.openremote.container.ContainerService;-import org.openremote.model.asset.AssetAttribute;-import org.openremote.model.asset.AssetMeta;-import org.openremote.model.asset.AssetQuery;-import org.openremote.model.asset.AssetState;+import org.openremote.model.asset.*;import org.openremote.model.attribute.AttributeEvent;import org.openremote.model.attribute.AttributeRef;import org.openremote.model.attribute.MetaItem;@@ -279,7 +276,7 @@ public class AssetAttributeLinkingService implements ContainerService, Consumer<ServerAsset asset = assetStorageService.find(new AssetQuery().id(attributeRef.getEntityId())- .select(new AssetQuery.Select(attributeRef.getAttributeName()).loadComplete(true))+ .select(new AbstractAssetQuery.Select(AbstractAssetQuery.Include.ALL, false, false, attributeRef.getAttributeName())));Optional<AssetAttribute> attribute = Optional.empty();diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.javaindex 2567cec93..4e644c116 100644--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java@@ -29,6 +29,7 @@ import org.openremote.manager.shared.http.RequestParams;import org.openremote.manager.shared.security.Tenant;import org.openremote.model.Constants;import org.openremote.model.asset.Asset;+import org.openremote.model.asset.AbstractAssetQuery;import org.openremote.model.asset.AssetQuery;import org.openremote.model.attribute.AttributeEvent;import org.openremote.model.attribute.AttributeRef;@@ -47,11 +48,13 @@ import java.util.logging.Logger;import static javax.ws.rs.core.Response.Status.BAD_REQUEST;import static javax.ws.rs.core.Response.Status.NOT_FOUND;import static org.openremote.model.attribute.AttributeEvent.Source.CLIENT;+import static org.openremote.model.util.TextUtil.isNullOrEmpty;public class AssetResourceImpl extends ManagerWebResource implements AssetResource {private static final Logger LOG = Logger.getLogger(AssetResourceImpl.class.getName());+ protected final static Asset[] EMPTY_ASSETS = new Asset[0];protected final AssetStorageService assetStorageService;protected final MessageBrokerService messageBrokerService;@@ -74,14 +77,14 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResourif (!isRestrictedUser()) {List<ServerAsset> result = assetStorageService.findAll(new AssetQuery()- .parent(new AssetQuery.ParentPredicate(true))- .tenant(new AssetQuery.TenantPredicate().realm(getAuthenticatedRealm()))+ .parent(new AbstractAssetQuery.ParentPredicate(true))+ .tenant(new AbstractAssetQuery.TenantPredicate().realm(getAuthenticatedRealm())));return result.toArray(new Asset[result.size()]);}List<ServerAsset> assets = assetStorageService.findAll(- new AssetQuery().select(new AssetQuery.Select(false, true)).userId(getUserId())+ new AssetQuery().select(new AbstractAssetQuery.Select(AbstractAssetQuery.Include.ALL_EXCEPT_PATH_AND_ATTRIBUTES, true)).userId(getUserId()));// Filter assets that might have been moved into a different realm and can no longer be accessed by user@@ -101,68 +104,6 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour}}- @Override- public Asset[] getRoot(RequestParams requestParams, String realmId) {- try {- Tenant tenant = realmId == null || realmId.length() == 0- ? getAuthenticatedTenant()- : identityService.getIdentityProvider().getTenantForRealmId(realmId);-- if (tenant == null) {- throw new WebApplicationException(NOT_FOUND);- }-- if (!isTenantActiveAndAccessible(tenant) || isRestrictedUser()) {- return new Asset[0];- }-- List<ServerAsset> result = assetStorageService.findAll(- new AssetQuery()- .parent(new AssetQuery.ParentPredicate(true))- .tenant(new AssetQuery.TenantPredicate(tenant.getId()))- );- return result.toArray(new Asset[result.size()]);-- } catch (IllegalStateException ex) {- throw new WebApplicationException(ex, Response.Status.BAD_REQUEST);- }- }-- @Override- public Asset[] getChildren(RequestParams requestParams, String parentId, boolean loadComplete) {- try {- if (isRestrictedUser()) {- return new Asset[0];- }-- AssetQuery query = new AssetQuery()- .parent(new AssetQuery.ParentPredicate(parentId));-- if (loadComplete) {- query = query.select(new AssetQuery.Select(true));- }-- if (isSuperUser()) {- List<ServerAsset> result = assetStorageService.findAll(- query- );- return result.toArray(new Asset[result.size()]);- } else {- Tenant tenant = getAuthenticatedTenant();- if (tenant == null || !tenant.isActive(timerService.getCurrentTimeMillis())) {- throw new WebApplicationException(NOT_FOUND);- }- List<ServerAsset> result = assetStorageService.findAll(- query- .tenant(new AssetQuery.TenantPredicate(tenant.getId()))- );- return result.toArray(new Asset[result.size()]);- }- } catch (IllegalStateException ex) {- throw new WebApplicationException(ex, Response.Status.BAD_REQUEST);- }- }-@Overridepublic Asset get(RequestParams requestParams, String assetId) {try {@@ -344,4 +285,39 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour}}+ @Override+ public Asset[] queryAssets(RequestParams requestParams, AbstractAssetQuery query) {+ try {+ if (query == null || isRestrictedUser()) {+ return EMPTY_ASSETS;+ }++ Tenant tenant = query.tenantPredicate != null+ ? !isNullOrEmpty(query.tenantPredicate.realmId)+ ? identityService.getIdentityProvider().getTenantForRealmId(query.tenantPredicate.realmId)+ : !isNullOrEmpty(query.tenantPredicate.realm)+ ? identityService.getIdentityProvider().getTenantForRealm(query.tenantPredicate.realm)+ : getAuthenticatedTenant()+ : getAuthenticatedTenant();++ if (tenant == null) {+ throw new WebApplicationException(NOT_FOUND);+ }++ if (!isTenantActiveAndAccessible(tenant)) {+ return EMPTY_ASSETS;+ }++ // This replicates behaviour of old getRoot and getChildren methods+ if (!isSuperUser() || query.parentPredicate == null || query.parentPredicate.noParent) {+ query.tenant(new AbstractAssetQuery.TenantPredicate(tenant.getId()));+ }++ List<ServerAsset> result = assetStorageService.findAll(query);+ return result.toArray(new Asset[result.size()]);++ } catch (IllegalStateException ex) {+ throw new WebApplicationException(ex, Response.Status.BAD_REQUEST);+ }+ }}diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.javaindex 90304a872..f9e90d06a 100644--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java@@ -39,7 +39,9 @@ import org.openremote.model.Constants;import org.openremote.model.ValidationFailure;import org.openremote.model.asset.*;import org.openremote.model.attribute.AttributeEvent;+import org.openremote.model.value.ObjectValue;import org.openremote.model.value.Value;+import org.openremote.model.value.Values;import org.postgresql.util.PGobject;import javax.persistence.EntityManager;@@ -56,6 +58,22 @@ import static org.openremote.manager.server.event.ClientEventService.getSessionKpublic class AssetStorageService extends RouteBuilder implements ContainerService, Consumer<AssetState> {+ protected class PreparedAssetQuery {+ protected String querySql;+ protected List<ParameterBinder> binders;++ public PreparedAssetQuery(String querySql, List<ParameterBinder> binders) {+ this.querySql = querySql;+ this.binders = binders;+ }++ protected void apply(PreparedStatement preparedStatement) {+ for (ParameterBinder binder : binders) {+ binder.accept(preparedStatement);+ }+ }+ }+private static final Logger LOG = Logger.getLogger(AssetStorageService.class.getName());protected TimerService timerService;@@ -215,7 +233,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicpublic ServerAsset find(String assetId, boolean loadComplete) {if (assetId == null)throw new IllegalArgumentException("Can't query null asset identifier");- return find(new AssetQuery().select(new AssetQuery.Select(loadComplete, false)).id(assetId));+ return find(new AssetQuery().select(new AssetQuery.Select(loadComplete ? AssetQuery.Include.ALL : AssetQuery.Include.ALL_EXCEPT_PATH_AND_ATTRIBUTES, false)).id(assetId));}/**@@ -225,21 +243,17 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicpublic ServerAsset find(String assetId, boolean loadComplete, boolean filterProtected) {if (assetId == null)throw new IllegalArgumentException("Can't query null asset identifier");- return find(new AssetQuery().select(new AssetQuery.Select(loadComplete, filterProtected)).id(assetId));+ return find(new AssetQuery().select(new AssetQuery.Select(loadComplete ? AssetQuery.Include.ALL : AssetQuery.Include.ALL_EXCEPT_PATH_AND_ATTRIBUTES, filterProtected)).id(assetId));}- public ServerAsset find(AssetQuery query) {+ public ServerAsset find(AbstractAssetQuery query) {return persistenceService.doReturningTransaction(em -> find(em, query));}- public List<ServerAsset> findAll(AssetQuery query) {+ public List<ServerAsset> findAll(AbstractAssetQuery query) {return persistenceService.doReturningTransaction(em -> findAll(em, query));}- public List<String> findAllIds(AssetQuery query) {- return persistenceService.doReturningTransaction(em -> findAllIdentifiersOnly(em, query));- }-public List<String> findNames(String... ids) {// TODO: Do this in a loop in reasonably sized batchesreturn persistenceService.doReturningTransaction(em -> {@@ -388,10 +402,10 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicprotected ServerAsset find(EntityManager em, String assetId, boolean loadComplete, boolean filterProtected) {if (assetId == null)throw new IllegalArgumentException("Can't query null asset identifier");- return find(em, new AssetQuery().select(new AssetQuery.Select(loadComplete, filterProtected)).id(assetId));+ return find(em, new AssetQuery().select(new AssetQuery.Select(loadComplete ? AssetQuery.Include.ALL : AssetQuery.Include.ALL_EXCEPT_PATH_AND_ATTRIBUTES, filterProtected)).id(assetId));}- public ServerAsset find(EntityManager em, AssetQuery query) {+ public ServerAsset find(EntityManager em, AbstractAssetQuery query) {List<ServerAsset> result = findAll(em, query);if (result.size() == 0)return null;@@ -402,23 +416,16 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic}- protected List<ServerAsset> findAll(EntityManager em, AssetQuery query) {- StringBuilder sb = new StringBuilder();- List<ParameterBinder> binders = new ArrayList<>();- sb.append(buildSelectString(query, false, binders));- sb.append(buildFromString(query));- String whereClause = buildWhereClause(query, binders);- sb.append(whereClause);- sb.append(buildOrderByString(query));- String querySql = sb.toString();+ protected List<ServerAsset> findAll(EntityManager em, AbstractAssetQuery query) {+ PreparedAssetQuery querySql = buildQuery(query);+return em.unwrap(Session.class).doReturningWork(new AbstractReturningWork<List<ServerAsset>>() {@Overridepublic List<ServerAsset> execute(Connection connection) throws SQLException {- LOG.fine("Executing: " + querySql);- PreparedStatement st = connection.prepareStatement(querySql);- for (ParameterBinder binder : binders) {- binder.accept(st);- }+ LOG.fine("Executing: " + querySql.querySql);+ PreparedStatement st = connection.prepareStatement(querySql.querySql);+ querySql.apply(st);+try (ResultSet rs = st.executeQuery()) {List<ServerAsset> result = new ArrayList<>();while (rs.next()) {@@ -430,75 +437,102 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic});}- protected List<String> findAllIdentifiersOnly(EntityManager em, AssetQuery query) {+ protected PreparedAssetQuery buildQuery(AbstractAssetQuery query) {StringBuilder sb = new StringBuilder();+ boolean recursive = query.select.recursive;List<ParameterBinder> binders = new ArrayList<>();- sb.append(buildSelectString(query, true, binders));- sb.append(buildFromString(query));- String whereClause = buildWhereClause(query, binders);- sb.append(whereClause);+ sb.append(buildSelectString(query, 1, binders));+ sb.append(buildFromString(query, 1));+ sb.append(buildWhereClause(query, 1, binders));++ if (recursive) {+ sb.insert(0, "WITH RECURSIVE top_level_assets AS ((");+ sb.append(") UNION (");+ sb.append(buildSelectString(query, 2, binders));+ sb.append(buildFromString(query, 2));+ sb.append(buildWhereClause(query, 2, binders));+ sb.append("))");+ sb.append(buildSelectString(query, 3, binders));+ sb.append(buildFromString(query, 3));+ sb.append(buildWhereClause(query, 3, binders));+ }+sb.append(buildOrderByString(query));- return em.unwrap(Session.class).doReturningWork(new AbstractReturningWork<List<String>>() {- @Override- public List<String> execute(Connection connection) throws SQLException {- PreparedStatement st = connection.prepareStatement(sb.toString());- for (ParameterBinder binder : binders) {- binder.accept(st);- }- try (ResultSet rs = st.executeQuery()) {- List<String> result = new ArrayList<>();- while (rs.next()) {- result.add(rs.getString("ID"));- }- return result;- }- }- });+ return new PreparedAssetQuery(sb.toString(), binders);}- protected String buildSelectString(AssetQuery query, boolean identifiersOnly, List<ParameterBinder> binders) {+ protected String buildSelectString(AbstractAssetQuery query, int level, List<ParameterBinder> binders) {+ // level = 1 is main query select+ // level = 2 is union select+ // level = 3 is CTE selectStringBuilder sb = new StringBuilder();+ AssetQuery.Include include = query.select.include;+ boolean recursive = query.select.recursive;+ boolean includeMainProperties = include == AssetQuery.Include.ALL ||+ include == AssetQuery.Include.ALL_EXCEPT_PATH ||+ include == AssetQuery.Include.ALL_EXCEPT_PATH_AND_ATTRIBUTES;- sb.append("select ");+ sb.append("select A.ID as ID, A.NAME as NAME");- if (identifiersOnly) {- sb.append(" A.ID as ID ");+ if (query.orderBy != null || includeMainProperties) {+ sb.append(", A.CREATED_ON AS CREATED_ON, A.ASSET_TYPE AS ASSET_TYPE, A.PARENT_ID AS PARENT_ID, A.REALM_ID AS REALM_ID");+ }++ if (include == AssetQuery.Include.ONLY_ID_AND_NAME) {return sb.toString();}+ switch (include) {+ case ALL_EXCEPT_PATH_AND_ATTRIBUTES:+ case ALL_EXCEPT_PATH:+ case ALL:+ sb.append(", A.OBJ_VERSION as OBJ_VERSION, A.LOCATION as LOCATION");+ sb.append(", P.NAME as PARENT_NAME, P.ASSET_TYPE as PARENT_TYPE");+ if (!recursive || level == 3) {+ sb.append(", R.NAME as TENANT_NAME, RA.VALUE as TENANT_DISPLAY_NAME");+ }+ break;+ }- sb.append("A.ID as ID, A.OBJ_VERSION as OBJ_VERSION, A.CREATED_ON as CREATED_ON, A.NAME as NAME, A.ASSET_TYPE as ASSET_TYPE, ");- sb.append("A.PARENT_ID as PARENT_ID, ");- sb.append(query.parentPredicate != null && query.parentPredicate.noParent- ? " NULL PARENT_NAME, NULL as PARENT_TYPE, "- : " P.NAME as PARENT_NAME, P.ASSET_TYPE as PARENT_TYPE, "- );- sb.append("A.REALM_ID as REALM_ID, R.NAME as TENANT_NAME, RA.VALUE as TENANT_DISPLAY_NAME, ");- sb.append("A.LOCATION as LOCATION");-- // TODO: Decide on behaviour of select query- // AssetPermissionsTest::Access assets as testuser3 assumes loadComplete(false) & filterProtected(true) returns no attributes- // But need to be able to select attributes without loading the path as well- if (query.select == null || !query.select.loadComplete) {- // Default to not returning path or attributes- sb.append(", NULL as PATH, NULL as ATTRIBUTES ");- } else {- sb.append(query.select.loadComplete ? ", get_asset_tree_path(A.ID) as PATH " : ", NULL as PATH ");- if (query.select.attributeNames != null || query.select.filterProtected) {- sb.append(", (");- sb.append(buildAttributeFilter(query.select.attributeNames, query.select.filterProtected, binders));- sb.append(") AS ATTRIBUTES ");+ if (!recursive || level == 3) {+ if (include == AssetQuery.Include.ALL) {+ sb.append(", get_asset_tree_path(A.ID) as PATH");} else {- sb.append(", A.ATTRIBUTES as ATTRIBUTES ");+ sb.append(", NULL as PATH");}}+ if (include != AssetQuery.Include.ALL_EXCEPT_PATH_AND_ATTRIBUTES) {++ if (recursive && level != 3) {+ sb.append(", A.ATTRIBUTES as ATTRIBUTES");+ } else {+ boolean namesOnly = include == AssetQuery.Include.ONLY_ID_AND_NAME_AND_ATTRIBUTE_NAMES;+ sb.append(buildAttributeSelect(query.select.attributeNames, query.select.filterProtected, namesOnly, binders));+ }+ } else {+ sb.append(", NULL as ATTRIBUTES");+ }+return sb.toString();}- protected String buildAttributeFilter(String[] attributeNames, boolean filterProtected, List<ParameterBinder> binders) {- StringBuilder sb = new StringBuilder();+ protected String buildAttributeSelect(String[] attributeNames, boolean filterProtected, boolean namesOnly, List<ParameterBinder> binders) {- if (filterProtected) {+ if (attributeNames == null && !filterProtected && !namesOnly) {+ return ", A.ATTRIBUTES as ATTRIBUTES";+ }++ StringBuilder sb = new StringBuilder();+ sb.append(", (");++ if (namesOnly) {+ sb.append("select json_object_agg(AX.key, jsonb_set('{}'::jsonb, '{meta}', (");+ sb.append("select jsonb_agg(AM.VALUE)");+ sb.append(" from jsonb_array_elements(AX.VALUE #> '{meta}') as AM");+ sb.append(" where AM.VALUE #>> '{name}' = '");+ sb.append(AssetMeta.LABEL.getUrn());+ sb.append("'))) from jsonb_each(A.attributes) as AX");+ } else if (filterProtected) {// Use sub-select for processing the attributes the meta inside each attribute is replaced with filtered metasb.append("select json_object_agg(AX.key, jsonb_set(AX.value, '{meta}', AMF.value, false)) from jsonb_each(A.attributes) as AX ");// Use implicit inner join on meta array set to only select attributes with a protected=true meta item@@ -510,15 +544,15 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicsb.append(protectedAssetMetaClause);sb.append(") as AMF ON true");} else {- sb.append("select json_object_agg(AX.key, AX.value) from jsonb_each(A.attributes) as AX ");+ sb.append("select json_object_agg(AX.key, AX.value) from jsonb_each(A.attributes) as AX");}- sb.append(" where true ");+ sb.append(" where true");if (attributeNames != null && attributeNames.length > 0) {sb.append(" AND AX.key IN (");for (int i = 0; i < attributeNames.length; i++) {- sb.append(i == attributeNames.length - 1 ? "?" : "?, ");+ sb.append(i == attributeNames.length - 1 ? "?" : "?,");final String attributeName = attributeNames[i];final int pos = binders.size() + 1;binders.add(st -> st.setString(pos, attributeName));@@ -534,37 +568,55 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic.itemValue(new AssetQuery.BooleanPredicate(true));sb.append(buildAttributeMetaFilter(protectedPredicate, binders));}++ sb.append(") AS ATTRIBUTES");return sb.toString();}- protected String buildFromString(AssetQuery query) {+ protected String buildFromString(AbstractAssetQuery query, int level) {+ // level = 1 is main query+ // level = 2 is union+ // level = 3 is CTEStringBuilder sb = new StringBuilder();+ boolean recursive = query.select.recursive;- sb.append(" from ASSET A ");- sb.append(" join REALM R on R.ID = A.REALM_ID ");- sb.append(" join REALM_ATTRIBUTE RA on RA.REALM_ID = R.ID and RA.NAME = 'displayName'");-- if (query.parentPredicate != null && !query.parentPredicate.noParent) {- sb.append(" cross join ASSET P ");+ if (level == 1) {+ sb.append(" from ASSET A ");+ } else if (level == 2) {+ sb.append(" from top_level_assets P ");+ sb.append("join ASSET A on A.PARENT_ID = P.ID ");} else {- sb.append(" left outer join ASSET P on A.PARENT_ID = P.ID ");+ sb.append(" from top_level_assets A ");}- if (query.id != null) {- return sb.toString();+ boolean includeRealmInfo = query.select.include != AssetQuery.Include.ONLY_ID_AND_NAME &&+ query.select.include != AssetQuery.Include.ONLY_ID_AND_NAME_AND_ATTRIBUTE_NAMES &&+ query.select.include != AssetQuery.Include.ONLY_ID_AND_NAME_AND_ATTRIBUTES;++ if ((!recursive || level == 3) && (includeRealmInfo || query.tenantPredicate != null)) {+ sb.append("join REALM R on R.ID = A.REALM_ID ");+ sb.append("join REALM_ATTRIBUTE RA on RA.REALM_ID = R.ID and RA.NAME = 'displayName' ");}- if (query.userId != null) {- sb.append(" cross join USER_ASSET ua ");+ if ((!recursive || level == 3) && query.id == null && query.userId != null) {+ sb.append("cross join USER_ASSET ua ");+ }++ if (level == 1) {+ if (query.parentPredicate != null && !query.parentPredicate.noParent) {+ sb.append("cross join ASSET P ");+ } else {+ sb.append("left outer join ASSET P on A.PARENT_ID = P.ID ");+ }}return sb.toString();}- protected String buildOrderByString(AssetQuery query) {+ protected String buildOrderByString(AbstractAssetQuery query) {StringBuilder sb = new StringBuilder();- if (query.id != null) {+ if (query.id != null && !query.select.recursive) {return sb.toString();}@@ -585,87 +637,99 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicsb.append(" A.PARENT_ID ");break;case REALM_ID:- sb.append(" A.REALM_ID");+ sb.append(" A.REALM_ID ");break;}- sb.append(query.orderBy.descending ? " desc" : " asc ");+ sb.append(query.orderBy.descending ? "desc " : "asc ");}return sb.toString();}- protected String buildWhereClause(AssetQuery query, List<ParameterBinder> binders) {+ protected String buildWhereClause(AbstractAssetQuery query, int level, List<ParameterBinder> binders) {+ // level = 1 is main query+ // level = 2 is union+ // level = 3 is CTEStringBuilder sb = new StringBuilder();- sb.append(" where true ");+ boolean recursive = query.select.recursive;+ sb.append(" where true");- if (query.id != null) {- sb.append(" and A.ID = ? ");+ if (level == 2) {+ return sb.toString();+ }++ if (level == 1 && query.id != null) {+ sb.append(" and A.ID = ?");final int pos = binders.size() + 1;binders.add(st -> st.setString(pos, query.id));}- if (query.name != null) {- sb.append(query.name.caseSensitive ? " and A.NAME " : " and upper(A.NAME) ");- sb.append(query.name.match == AssetQuery.Match.EXACT ? " = ? " : " like ? ");+ if (level == 1 && query.namePredicate != null) {+ sb.append(query.namePredicate.caseSensitive ? " and A.NAME " : " and upper(A.NAME)");+ sb.append(query.namePredicate.match == AssetQuery.Match.EXACT ? " = ?" : " like ?");final int pos = binders.size() + 1;- binders.add(st -> st.setString(pos, query.name.prepareValue()));+ binders.add(st -> st.setString(pos, query.namePredicate.prepareValue()));}if (query.parentPredicate != null) {- if (query.parentPredicate.id != null) {- sb.append(" and p.ID = a.PARENT_ID ");- sb.append(" and A.PARENT_ID = ? ");+ // Can only restrict recursive query parent by asset type+ if (level == 1 && query.parentPredicate.id != null) {+ sb.append(" and p.ID = a.PARENT_ID");+ sb.append(" and A.PARENT_ID = ?");final int pos = binders.size() + 1;binders.add(st -> st.setString(pos, query.parentPredicate.id));} else if (query.parentPredicate.type != null) {- sb.append(" and p.ID = a.PARENT_ID ");- sb.append(" and P.ASSET_TYPE = ? ");+ sb.append(" and p.ID = a.PARENT_ID");+ sb.append(" and P.ASSET_TYPE = ?");final int pos = binders.size() + 1;binders.add(st -> st.setString(pos, query.parentPredicate.type));- } else if (query.parentPredicate.noParent) {- sb.append(" and A.PARENT_ID is null ");+ } else if (level ==1 && query.parentPredicate.noParent) {+ sb.append(" and A.PARENT_ID is null");}}- if (query.pathPredicate != null && query.pathPredicate.hasPath()) {+ if (level == 1 && query.pathPredicate != null && query.pathPredicate.hasPath()) {sb.append(" and ? <@ get_asset_tree_path(A.ID)");final int pos = binders.size() + 1;binders.add(st -> st.setArray(pos, st.getConnection().createArrayOf("text", query.pathPredicate.path)));}- if (query.tenantPredicate != null && query.tenantPredicate.realmId != null) {- sb.append(" and R.ID = ? ");- final int pos = binders.size() + 1;- binders.add(st -> st.setString(pos, query.tenantPredicate.realmId));- } else if (query.tenantPredicate != null && query.tenantPredicate.realm != null) {- sb.append(" and R.NAME = ? ");- final int pos = binders.size() + 1;- binders.add(st -> st.setString(pos, query.tenantPredicate.realm));- }+ if (!recursive || level == 3) {+ if (query.tenantPredicate != null && query.tenantPredicate.realmId != null) {+ sb.append(" and R.ID = ?");+ final int pos = binders.size() + 1;+ binders.add(st -> st.setString(pos, query.tenantPredicate.realmId));+ } else if (query.tenantPredicate != null && query.tenantPredicate.realm != null) {+ sb.append(" and R.NAME = ?");+ final int pos = binders.size() + 1;+ binders.add(st -> st.setString(pos, query.tenantPredicate.realm));+ }- if (query.userId != null) {- sb.append(" and ua.ASSET_ID = a.ID and ua.USER_ID = ? ");- final int pos = binders.size() + 1;- binders.add(st -> st.setString(pos, query.userId));- }+ if (query.userId != null) {+ sb.append(" and ua.ASSET_ID = a.ID and ua.USER_ID = ?");+ final int pos = binders.size() + 1;+ binders.add(st -> st.setString(pos, query.userId));+ }- if (query.type != null) {- sb.append(query.type.caseSensitive ? " and A.ASSET_TYPE" : " and upper(A.ASSET_TYPE) ");- sb.append(query.type.match == AssetQuery.Match.EXACT ? " = ? " : " like ? ");- final int pos = binders.size() + 1;- binders.add(st -> st.setString(pos, query.type.prepareValue()));- }+ if (query.type != null) {+ sb.append(query.type.caseSensitive ? " and A.ASSET_TYPE" : " and upper(A.ASSET_TYPE)");+ sb.append(query.type.match == AssetQuery.Match.EXACT ? " = ? " : " like ? ");+ final int pos = binders.size() + 1;+ binders.add(st -> st.setString(pos, query.type.prepareValue()));+ }- if (query.attributeMetaPredicate != null) {- String attributeMetaFilter = buildAttributeMetaFilter(query.attributeMetaPredicate, binders);- if (attributeMetaFilter.length() > 0) {- sb.append(" and A.ID in (select A.ID from ");- sb.append(" jsonb_each(A.ATTRIBUTES) as AX, ");- sb.append(" jsonb_array_elements(AX.VALUE #> '{meta}') as AM ");- sb.append(" where true ");- sb.append(attributeMetaFilter);- sb.append(")");+ if (query.attributeMetaPredicate != null) {+ String attributeMetaFilter = buildAttributeMetaFilter(query.attributeMetaPredicate, binders);++ if (attributeMetaFilter.length() > 0) {+ sb.append(" and A.ID in (select A.ID from");+ sb.append(" jsonb_each(A.ATTRIBUTES) as AX,");+ sb.append(" jsonb_array_elements(AX.VALUE #> '{meta}') as AM");+ sb.append(" where true");+ sb.append(attributeMetaFilter);+ sb.append(")");+ }}}@@ -677,8 +741,8 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicif (attributeMetaPredicate.itemNamePredicate != null) {attributeMetaBuilder.append(attributeMetaPredicate.itemNamePredicate.caseSensitive- ? " and AM.VALUE #>> '{name}' "- : " and upper(AM.VALUE #>> '{name}') "+ ? " and AM.VALUE #>> '{name}'"+ : " and upper(AM.VALUE #>> '{name}')");attributeMetaBuilder.append(attributeMetaPredicate.itemNamePredicate.match == AssetQuery.Match.EXACT ? " = ? " : " like ? ");final int pos = binders.size() + 1;@@ -688,24 +752,26 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicif (attributeMetaPredicate.itemValuePredicate instanceof AssetQuery.StringPredicate) {AssetQuery.StringPredicate stringPredicate = (AssetQuery.StringPredicate) attributeMetaPredicate.itemValuePredicate;attributeMetaBuilder.append(stringPredicate.caseSensitive- ? " and AM.VALUE #>> '{value}' "- : " and upper(AM.VALUE #>> '{value}') "+ ? " and AM.VALUE #>> '{value}'"+ : " and upper(AM.VALUE #>> '{value}')");attributeMetaBuilder.append(stringPredicate.match == AssetQuery.Match.EXACT ? " = ? " : " like ? ");final int pos = binders.size() + 1;binders.add(st -> st.setString(pos, stringPredicate.prepareValue()));} else if (attributeMetaPredicate.itemValuePredicate instanceof AssetQuery.BooleanPredicate) {AssetQuery.BooleanPredicate booleanPredicate = (AssetQuery.BooleanPredicate) attributeMetaPredicate.itemValuePredicate;- attributeMetaBuilder.append(" and AM.VALUE #> '{value}' = to_jsonb(").append(booleanPredicate.predicate).append(") ");+ attributeMetaBuilder.append(" and AM.VALUE #> '{value}' = to_jsonb(")+ .append(booleanPredicate.predicate)+ .append(")");} else if (attributeMetaPredicate.itemValuePredicate instanceof AssetQuery.StringArrayPredicate) {AssetQuery.StringArrayPredicate stringArrayPredicate = (AssetQuery.StringArrayPredicate) attributeMetaPredicate.itemValuePredicate;for (int i = 0; i < stringArrayPredicate.predicates.length; i++) {AssetQuery.StringPredicate stringPredicate = stringArrayPredicate.predicates[i];attributeMetaBuilder.append(stringPredicate.caseSensitive? " and AM.VALUE #> '{value}' ->> " + i- : " and upper(AM.VALUE #> '{value}' ->> " + i + ") "+ : " and upper(AM.VALUE #> '{value}' ->> " + i + ")");- attributeMetaBuilder.append(stringPredicate.match == AssetQuery.Match.EXACT ? " = ? " : " like ? ");+ attributeMetaBuilder.append(stringPredicate.match == AssetQuery.Match.EXACT ? " = ?" : " like ?");final int pos = binders.size() + 1;binders.add(st -> st.setString(pos, stringPredicate.prepareValue()));}@@ -715,13 +781,31 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicreturn attributeMetaBuilder.toString();}- protected ServerAsset mapResultTuple(AssetQuery query, ResultSet rs) throws SQLException {- return new ServerAsset(- rs.getString("ID"), rs.getLong("OBJ_VERSION"), rs.getTimestamp("CREATED_ON"), rs.getString("NAME"), rs.getString("ASSET_TYPE"),- rs.getString("PARENT_ID"), rs.getString("PARENT_NAME"), rs.getString("PARENT_TYPE"),- rs.getString("REALM_ID"), rs.getString("TENANT_NAME"), rs.getString("TENANT_DISPLAY_NAME"),- rs.getObject("LOCATION"), rs.getArray("PATH"), rs.getString("ATTRIBUTES")- );+ protected ServerAsset mapResultTuple(AbstractAssetQuery query, ResultSet rs) throws SQLException {+ switch (query.select.include) {+ case ONLY_ID_AND_NAME:+ case ONLY_ID_AND_NAME_AND_ATTRIBUTES:+ case ONLY_ID_AND_NAME_AND_ATTRIBUTE_NAMES:+ ServerAsset asset = new ServerAsset();+ asset.setId(rs.getString("ID"));+ asset.setName(rs.getString("NAME"));+ if (query.select.include != AssetQuery.Include.ONLY_ID_AND_NAME) {+ if (rs.getString("ATTRIBUTES") != null) {+ asset.setAttributes(Values.instance().<ObjectValue>parse(rs.getString("ATTRIBUTES")).orElse(null));+ }+ }+ return asset;+ case ALL_EXCEPT_PATH_AND_ATTRIBUTES:+ case ALL_EXCEPT_PATH:+ case ALL:+ return new ServerAsset(+ rs.getString("ID"), rs.getLong("OBJ_VERSION"), rs.getTimestamp("CREATED_ON"), rs.getString("NAME"), rs.getString("ASSET_TYPE"),+ rs.getString("PARENT_ID"), rs.getString("PARENT_NAME"), rs.getString("PARENT_TYPE"),+ rs.getString("REALM_ID"), rs.getString("TENANT_NAME"), rs.getString("TENANT_DISPLAY_NAME"),+ rs.getObject("LOCATION"), rs.getArray("PATH"), rs.getString("ATTRIBUTES"));+ default:+ throw new UnsupportedOperationException("Select include option not supported: " + query.select.include);+ }}protected boolean storeAttributeValue(String assetId, String attributeName, Value value, String timestamp) {diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesEngine.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesEngine.javaindex 50cd34426..46a4c1a0f 100644--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesEngine.java+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesEngine.java@@ -609,7 +609,17 @@ public class RulesEngine<T extends Ruleset> {@Overridepublic List<String> getResults() {- return assetStorageService.findAllIds(this);+ Include oldValue = this.select.include;+ this.select.include = Include.ONLY_ID_AND_NAME;+ try {+ return assetStorageService+ .findAll(this)+ .stream()+ .map(Asset::getId)+ .collect(Collectors.toList());+ } finally {+ this.select.include = oldValue;+ }}@Override@@ -624,14 +634,14 @@ public class RulesEngine<T extends Ruleset> {};if (TenantRuleset.class.isAssignableFrom(rulesetType)) {- query.tenantPredicate = new AssetQuery.TenantPredicate(id);+ query.tenantPredicate = new AbstractAssetQuery.TenantPredicate(id);}if (AssetRuleset.class.isAssignableFrom(rulesetType)) {ServerAsset restrictedAsset = assetStorageService.find(id, true);if (restrictedAsset == null) {throw new IllegalStateException("Asset is no longer available for this deployment: " + id);}- query.pathPredicate = new AssetQuery.PathPredicate(restrictedAsset.getPath());+ query.pathPredicate = new AbstractAssetQuery.PathPredicate(restrictedAsset.getPath());}return query;}@@ -643,7 +653,7 @@ public class RulesEngine<T extends Ruleset> {for (AttributeEvent event : events) {// Check if the asset ID of the event can be found in the original query- AssetQuery checkQuery = query();+ AbstractAssetQuery checkQuery = query();checkQuery.id = event.getEntityId();if (assetStorageService.find(checkQuery) == null) {throw new IllegalArgumentException(diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.javaindex 0427b4574..f07be8b7e 100644--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java@@ -655,7 +655,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Consprotected Stream<Pair<ServerAsset, Stream<AssetAttribute>>> findRuleStateAttributes() {List<ServerAsset> assets = assetStorageService.findAll(new AssetQuery()- .select(new AssetQuery.Select(true))+ .select(new AssetQuery.Select(AssetQuery.Include.ALL)).attributeMeta(new AssetQuery.AttributeMetaPredicate(AssetMeta.RULE_STATE,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.javaindex c10468785..6590a6fde 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@@ -23,6 +23,7 @@ import jsinterop.annotations.JsType;import org.openremote.manager.shared.http.RequestParams;import org.openremote.manager.shared.http.SuccessStatusCode;import org.openremote.model.asset.Asset;+import org.openremote.model.asset.AbstractAssetQuery;import javax.annotation.security.RolesAllowed;import javax.validation.Valid;@@ -45,22 +46,19 @@ import static javax.ws.rs.core.MediaType.APPLICATION_JSON;* may have roles that allow read and/or write access to protected asset details (see* {@link org.openremote.model.asset.UserAsset}).* <p>- * The only operations a restricted user is able to perform are {@link #getCurrentUserAssets},- * {@link #get}, {@link #update}, and {@link #writeAttributeValue}.- * </li>- * </ul>+ * The only operations a restricted user is able to perform are {@link #getCurrentUserAssets}, {@link #get}, {@link+ * #update}, and {@link #writeAttributeValue}. </li> </ul>*/@Path("asset")@JsType(isNative = true)public interface AssetResource {/**- * Retrieve the linked assets of the currently authenticated user. If the request is made- * by the superuser, an empty result is returned. If the request is made by a regular user,- * but the user has no linked assets and is therefore not restricted, the assets without- * parent (root assets) of the authenticated realm are returned. Note that the assets returned- * from this operation are not completely loaded and the {@link Asset#path} and- * {@link Asset#attributes} are empty. Call {@link #get} to retrieve all asset details.+ * Retrieve the linked assets of the currently authenticated user. If the request is made by the superuser, an empty+ * result is returned. If the request is made by a regular user, but the user has no linked assets and is therefore+ * not restricted, the assets without parent (root assets) of the authenticated realm are returned. Note that the+ * assets returned from this operation are not completely loaded and the {@link Asset#path} and {@link+ * Asset#attributes} are empty. Call {@link #get} to retrieve all asset details.*/@GET@Path("user/current")@@ -70,40 +68,10 @@ public interface AssetResource {Asset[] getCurrentUserAssets(@BeanParam RequestParams requestParams);/**- * Retrieve the assets without parent (root assets) of the given realm, or if the realm argument- * is empty, of the authenticated realm. Regular users can only access assets in their authenticated- * realm. The superuser can access assets in other (all) realms. An empty result is returned if the user- * does not have access to the assets or if the user is restricted. Note that the assets returned- * from this operation are not completely loaded and the {@link Asset#path} and- * {@link Asset#attributes} are empty. Call {@link #get} to retrieve all asset details.- */- @GET- @Produces(APPLICATION_JSON)- @SuccessStatusCode(200)- @RolesAllowed({"read:assets"})- Asset[] getRoot(@BeanParam RequestParams requestParams, @QueryParam("realmId") String realmId);-- /**- * Retrieve the child assets of the given parent asset. If the authenticated user is the superuser,- * parent and child assets can be in any realm. Otherwise, assets must in the same realm as the- * authenticated user. An empty result is returned if the user does not have access to the assets- * or if the user is restricted. Note that the assets returned from this operation are not completely- * loaded and the {@link Asset#path} and {@link Asset#attributes} are empty. Call {@link #get} to- * retrieve all asset details.- */- @GET- @Path("{assetId}/children")- @Produces(APPLICATION_JSON)- @SuccessStatusCode(200)- @RolesAllowed({"read:assets"})- Asset[] getChildren(@BeanParam RequestParams requestParams, @PathParam("assetId") String parentId, @QueryParam("loadComplete") boolean loadComplete);-- /**- * Retrieve the asset. Regular users can only access assets in their authenticated realm,- * the superuser can access assets in other (all) realms. A 403 status is returned if a regular- * user tries to access an asset in a realm different than its authenticated realm, or if the- * user is restricted and the asset is not linked to the user. All asset details (path, attributes)- * will be populated, the asset is loaded completely.+ * Retrieve the asset. Regular users can only access assets in their authenticated realm, the superuser can access+ * assets in other (all) realms. A 403 status is returned if a regular user tries to access an asset in a realm+ * different than its authenticated realm, or if the user is restricted and the asset is not linked to the user. All+ * asset details (path, attributes) will be populated, the asset is loaded completely.*/@GET@Path("{assetId}")@@ -113,11 +81,10 @@ public interface AssetResource {Asset get(@BeanParam RequestParams requestParams, @PathParam("assetId") String assetId);/**- * Updates the asset. Regular users can only update assets in their authenticated realm,- * the superuser can update assets in other (all) realms. A 403 status is returned if a regular- * user tries to update an asset in a realm different than its authenticated realm, or if the- * user is restricted and the asset is not linked to the user. A 400 status is returned if- * the asset's parent or realm doesn't exist.+ * Updates the asset. Regular users can only update assets in their authenticated realm, the superuser can update+ * assets in other (all) realms. A 403 status is returned if a regular user tries to update an asset in a realm+ * different than its authenticated realm, or if the user is restricted and the asset is not linked to the user. A+ * 400 status is returned if the asset's parent or realm doesn't exist.*/@PUT@Path("{assetId}")@@ -127,17 +94,16 @@ public interface AssetResource {void update(@BeanParam RequestParams requestParams, @PathParam("assetId") String assetId, @Valid Asset asset);/**- * Updates an attribute of an asset. Regular users can only update assets in- * their authenticated realm, the superuser can update assets in other (all) realms. A 403 status- * is returned if a regular user tries to update an asset in a realm different than its- * authenticated realm, or if the user is restricted and the asset to update is not in the set of linked- * assets of the restricted user.+ * Updates an attribute of an asset. Regular users can only update assets in their authenticated realm, the+ * superuser can update assets in other (all) realms. A 403 status is returned if a regular user tries to update an+ * asset in a realm different than its authenticated realm, or if the user is restricted and the asset to update is+ * not in the set of linked assets of the restricted user.* <p>- * This operation is ultimately asynchronous, any call will return before the actual attribute value is- * changed in any storage or downstream processors. Thus any constraint violation or processing error- * will not be returned from this method, query the system later to determine the actual state- * and outcome of the write operation. The version of the asset entity will not be incremented by this- * operation, thus concurrent updates can overwrite data undetected ("last commit wins").+ * This operation is ultimately asynchronous, any call will return before the actual attribute value is changed in+ * any storage or downstream processors. Thus any constraint violation or processing error will not be returned from+ * this method, query the system later to determine the actual state and outcome of the write operation. The version+ * of the asset entity will not be incremented by this operation, thus concurrent updates can overwrite data+ * undetected ("last commit wins").*/@PUT@Path("{assetId}/attribute/{attributeName}")@@ -147,13 +113,12 @@ public interface AssetResource {void writeAttributeValue(@BeanParam RequestParams requestParams, @PathParam("assetId") String assetId, @PathParam("attributeName") String attributeName, String rawJson);/**- * Creates an asset. The identifier value of the asset can be provided, it should be a- * globally unique string value, and must be at least 22 characters long. If no identifier- * value is provided, a unique value will be generated by 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.+ * Creates an asset. The identifier value of the asset can be provided, it should be a globally unique string value,+ * and must be at least 22 characters long. If no identifier value is provided, a unique value will be generated by+ * 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.*/@POST@Consumes(APPLICATION_JSON)@@ -163,11 +128,10 @@ public interface AssetResource {void create(@BeanParam RequestParams requestParams, @Valid Asset asset);/**- * Deletes an asset. Regular users can only delete assets in their authenticated realm,- * the superuser can delete assets in other (all) realms. A 403 status is returned if a regular- * user tries to delete an asset in a realm different than its authenticated realm, or if the- * user is restricted. A 400 status code is returned if the asset has children and therefore- * can't be deleted.+ * Deletes an asset. Regular users can only delete assets in their authenticated realm, the superuser can delete+ * assets in other (all) realms. A 403 status is returned if a regular user tries to delete an asset in a realm+ * different than its authenticated realm, or if the user is restricted. A 400 status code is returned if the asset+ * has children and therefore can't be deleted.*/@DELETE@Path("{assetId}")@@ -175,4 +139,30 @@ public interface AssetResource {@SuccessStatusCode(204)@RolesAllowed({"write:assets"})void delete(@BeanParam RequestParams requestParams, @PathParam("assetId") String assetId);++ /**+ * Retrieve the child assets of the given parent asset (if parent is null then root assets are retrieved). If the+ * authenticated user is the superuser, parent and child assets can be in any realm. Otherwise, assets must in the+ * same realm as the authenticated user. An empty result is returned if the user does not have access to the assets+ * or if the user is restricted. Note that the assets returned from this operation are not completely loaded and the+ * {@link Asset#path} and {@link Asset#attributes} are empty. Call {@link #get} to retrieve all asset details.+ * <p>+ * Optionally return all decedents by setting the recursive query parameter to true.+ */++ /**+ * Retrieve assets using an {@link AbstractAssetQuery}.+ * <p>+ * If the authenticated user is the superuser then assets referenced in the query or returned by the query can be in+ * any realm. Otherwise assets must be in the same realm as the authenticated user. An empty result is returned if+ * the user does not have access to the assets or if the user is restricted. What is populated on the returned assets+ * is determined by the {@link AbstractAssetQuery#select} value.+ */+ @POST+ @Path("query")+ @Consumes(APPLICATION_JSON)+ @Produces(APPLICATION_JSON)+ @SuccessStatusCode(200)+ @RolesAllowed({"read:assets"})+ Asset[] queryAssets(@BeanParam RequestParams requestParams, AbstractAssetQuery query);}diff --git a/manager/test/src/main/groovy/org/openremote/test/ClientEventService.groovy b/manager/test/src/main/groovy/org/openremote/test/ClientEventService.groovyindex c6eb87201..4b0b2f17e 100644--- a/manager/test/src/main/groovy/org/openremote/test/ClientEventService.groovy+++ b/manager/test/src/main/groovy/org/openremote/test/ClientEventService.groovy@@ -59,7 +59,7 @@ class ClientEventService implements EventService {// Handle array of eventsSharedEvent[] events = objectMapper.readValue(data, SharedEvent[].class)for (SharedEvent event : events) {- eventBus.dispatch(event);+ eventBus.dispatch(event)}} else {SharedEvent event = objectMapper.readValue(data, SharedEvent.class)diff --git a/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy b/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovyindex c90b3e408..3b90f8822 100644--- a/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy+++ b/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy@@ -85,19 +85,19 @@ trait ManagerContainerTrait extends ContainerTrait {static Container startContainerNoDemoAssets(Map<String, String> config, Iterable<ContainerService> services) {config << [(SETUP_IMPORT_DEMO_ASSETS): "false"]- startContainer(config, services);+ startContainer(config, services)}static Container startContainerWithDemoScenesAndRules(Map<String, String> config, Iterable<ContainerService> services) {config << [(SETUP_IMPORT_DEMO_SCENES): "true"]config << [(SETUP_IMPORT_DEMO_RULES): "true"]- startContainer(config, services);+ startContainer(config, services)}static Container startContainerNoDemoImport(Map<String, String> config, Iterable<ContainerService> services) {config << [(SETUP_IMPORT_DEMO_ASSETS): "false"]config << [(SETUP_IMPORT_DEMO_USERS): "false"]- startContainer(config, services);+ startContainer(config, services)}/**diff --git a/manager/test/src/test/groovy/org/openremote/test/admin/AdminTenantsActivityTest.groovy b/manager/test/src/test/groovy/org/openremote/test/admin/AdminTenantsActivityTest.groovyindex 8947937a2..f87de7015 100644--- a/manager/test/src/test/groovy/org/openremote/test/admin/AdminTenantsActivityTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/admin/AdminTenantsActivityTest.groovy@@ -57,7 +57,7 @@ class AdminTenantsActivityTest extends Specification implements ManagerContainerdef resultCreateTenantHistoryToken = nulland: "An authenticated user and client security service"- def realm = MASTER_REALM;+ def realm = MASTER_REALMdef accessToken = {authenticate(container,@@ -130,7 +130,7 @@ class AdminTenantsActivityTest extends Specification implements ManagerContainerdef adminTenantsView = Mock(AdminTenants) {setTenants(_) >> {- resultTenants = it[0];+ resultTenants = it[0]}setCreateTenantHistoryToken(_) >> {resultCreateTenantHistoryToken = it[0]@@ -248,10 +248,10 @@ class AdminTenantsActivityTest extends Specification implements ManagerContainer"Test Name"}1 * adminTenantView.getTenantRealm() >> {- return null; // This will cause a constraint violation+ return null // This will cause a constraint violation}1 * adminTenantView.getTenantEnabled() >> {- return true;+ return true}and: "The form errors should be shown"@@ -276,7 +276,7 @@ class AdminTenantsActivityTest extends Specification implements ManagerContainerreturn "testrealm"}1 * adminTenantView.getTenantEnabled() >> {- return true;+ return true}and: "The success toast should be shown"@@ -288,7 +288,7 @@ class AdminTenantsActivityTest extends Specification implements ManagerContainerand: "The form should be cleared the activity stopped"1 * adminTenantView.setFormBusy(false)1 * adminTenantView.setPresenter(null)- 1 * adminTenantView.clearFormMessages();+ 1 * adminTenantView.clearFormMessages()1 * adminTenantView.setTenantDisplayNameError(false)1 * adminTenantView.setTenantRealmError(false)1 * adminTenantView.setTenantEnabledError(false)@@ -361,7 +361,7 @@ class AdminTenantsActivityTest extends Specification implements ManagerContainerreturn "master" // Note: This should be a conflict}1 * adminTenantView.getTenantEnabled() >> {- return true;+ return true}and: "The conflict toast should be shown"@@ -387,7 +387,7 @@ class AdminTenantsActivityTest extends Specification implements ManagerContainerreturn "testrealm2"}1 * adminTenantView.getTenantEnabled() >> {- return true;+ return true}and: "The form success should be shown"@@ -438,6 +438,6 @@ class AdminTenantsActivityTest extends Specification implements ManagerContainer}cleanup: "The server should be stopped"- stopContainer(container);+ stopContainer(container)}}diff --git a/manager/test/src/test/groovy/org/openremote/test/admin/AdminUsersActivityTest.groovy b/manager/test/src/test/groovy/org/openremote/test/admin/AdminUsersActivityTest.groovyindex e01ddd6a6..73a0ba65d 100644--- a/manager/test/src/test/groovy/org/openremote/test/admin/AdminUsersActivityTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/admin/AdminUsersActivityTest.groovy@@ -57,7 +57,7 @@ class AdminUsersActivityTest extends Specification implements ManagerContainerTrdef resultCreateUserHistoryToken = nulland: "An authenticated user and client security service"- def realm = MASTER_REALM;+ def realm = MASTER_REALMdef accessToken = {authenticate(container,@@ -657,6 +657,6 @@ class AdminUsersActivityTest extends Specification implements ManagerContainerTr}cleanup: "The server should be stopped"- stopContainer(container);+ stopContainer(container)}}diff --git a/manager/test/src/test/groovy/org/openremote/test/assets/AssetBrowserPresenterTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetBrowserPresenterTest.groovyindex 06c0f8470..1727b499c 100644--- a/manager/test/src/test/groovy/org/openremote/test/assets/AssetBrowserPresenterTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/assets/AssetBrowserPresenterTest.groovy@@ -9,6 +9,7 @@ import org.openremote.manager.client.ManagerHistoryMapperimport org.openremote.manager.client.admin.TenantArrayMapperimport org.openremote.manager.client.assets.AssetArrayMapperimport org.openremote.manager.client.assets.AssetMapper+import org.openremote.manager.client.assets.AssetQueryMapperimport org.openremote.manager.client.assets.browser.*import org.openremote.manager.client.event.SubscriptionFailureEventimport org.openremote.manager.client.i18n.ManagerMessages@@ -26,6 +27,7 @@ import org.openremote.manager.shared.security.Tenantimport org.openremote.manager.shared.security.TenantResourceimport org.openremote.manager.shared.validation.ConstraintViolationReportimport org.openremote.model.asset.Asset+import org.openremote.model.asset.AssetQueryimport org.openremote.model.asset.AssetTreeModifiedEventimport org.openremote.model.event.shared.SharedEventimport org.openremote.test.*@@ -52,7 +54,7 @@ class AssetBrowserPresenterTest extends Specification implements ManagerContainedef keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)and: "an authenticated user and client security service"- def realm = MASTER_REALM;+ def realm = MASTER_REALMdef accessToken = {authenticate(container,@@ -86,6 +88,7 @@ class AssetBrowserPresenterTest extends Specification implements ManagerContaineand: "the data mappers for client/server calls"def assetMapper = new ClientObjectMapper(container.JSON, Asset.class) as AssetMapper+ def assetQueryMapper = new ClientObjectMapper(container.JSON, AssetQuery.class) as AssetQueryMapperdef assetArrayMapper = new ClientObjectMapper(container.JSON, Asset[].class) as AssetArrayMapperdef tenantArrayMapper = new ClientObjectMapper(container.JSON, Tenant[].class) as TenantArrayMapper@@ -105,14 +108,14 @@ class AssetBrowserPresenterTest extends Specification implements ManagerContainedef placeController = createPlaceController(securityService, eventBus)def placeHistoryMapper = createPlaceHistoryMapper(ManagerHistoryMapper.getAnnotation(WithTokenizers.class))def environment = Environment.create(- securityService,- requestService,- clientEventService,- placeController,- placeHistoryMapper,- eventBus,- managerMessages,- new WidgetStyle()+ securityService,+ requestService,+ clientEventService,+ placeController,+ placeHistoryMapper,+ eventBus,+ managerMessages,+ new WidgetStyle())and: "The view and presenter to test"@@ -126,14 +129,15 @@ class AssetBrowserPresenterTest extends Specification implements ManagerContaineList<BrowserTreeNode> treeDisplayRowData = nullHasData<BrowserTreeNode> treeDisplay = Mock(HasData)def assetBrowserPresenter = new AssetBrowserPresenter(- environment,- currentTenant,- assetBrowser,- assetResource,- assetMapper,- assetArrayMapper,- tenantResource,- tenantArrayMapper+ environment,+ currentTenant,+ assetBrowser,+ assetResource,+ assetMapper,+ assetQueryMapper,+ assetArrayMapper,+ tenantResource,+ tenantArrayMapper)when: "the view is attached"@@ -210,7 +214,7 @@ class AssetBrowserPresenterTest extends Specification implements ManagerContaineclientEventService.close()and : "the server should be stopped"- stopContainer(container);+ stopContainer(container)}def "Browse assets as testuser1"() {@@ -225,7 +229,7 @@ class AssetBrowserPresenterTest extends Specification implements ManagerContainedef keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)and: "An authenticated user and client security service"- def realm = MASTER_REALM;+ def realm = MASTER_REALMdef accessToken = {authenticate(container,@@ -259,6 +263,7 @@ class AssetBrowserPresenterTest extends Specification implements ManagerContaineand: "the data mappers for client/server calls"def assetMapper = new ClientObjectMapper(container.JSON, Asset.class) as AssetMapper+ def assetQueryMapper = new ClientObjectMapper(container.JSON, AssetQuery.class) as AssetQueryMapperdef assetArrayMapper = new ClientObjectMapper(container.JSON, Asset[].class) as AssetArrayMapperdef tenantArrayMapper = new ClientObjectMapper(container.JSON, Tenant[].class) as TenantArrayMapper@@ -278,14 +283,14 @@ class AssetBrowserPresenterTest extends Specification implements ManagerContainedef placeController = createPlaceController(securityService, eventBus)def placeHistoryMapper = createPlaceHistoryMapper(ManagerHistoryMapper.getAnnotation(WithTokenizers.class))def environment = Environment.create(- securityService,- requestService,- clientEventService,- placeController,- placeHistoryMapper,- eventBus,- managerMessages,- new WidgetStyle()+ securityService,+ requestService,+ clientEventService,+ placeController,+ placeHistoryMapper,+ eventBus,+ managerMessages,+ new WidgetStyle())and: "The view and presenter to test"@@ -299,14 +304,15 @@ class AssetBrowserPresenterTest extends Specification implements ManagerContaineList<BrowserTreeNode> treeDisplayRowData = nullHasData<BrowserTreeNode> treeDisplay = Mock(HasData)def assetBrowserPresenter = new AssetBrowserPresenter(- environment,- currentTenant,- assetBrowser,- assetResource,- assetMapper,- assetArrayMapper,- tenantResource,- tenantArrayMapper+ environment,+ currentTenant,+ assetBrowser,+ assetResource,+ assetMapper,+ assetQueryMapper,+ assetArrayMapper,+ tenantResource,+ tenantArrayMapper)when: "the view is attached"@@ -389,7 +395,7 @@ class AssetBrowserPresenterTest extends Specification implements ManagerContaineclientEventService.close()and : "the server should be stopped"- stopContainer(container);+ stopContainer(container)}def "Browse assets as testuser3"() {@@ -402,7 +408,7 @@ class AssetBrowserPresenterTest extends Specification implements ManagerContainedef keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)and: "An authenticated user and client security service"- def realm = keycloakDemoSetup.customerATenant.realm;+ def realm = keycloakDemoSetup.customerATenant.realmdef accessToken = {authenticate(container,@@ -436,6 +442,7 @@ class AssetBrowserPresenterTest extends Specification implements ManagerContaineand: "the data mappers for client/server calls"def assetMapper = new ClientObjectMapper(container.JSON, Asset.class) as AssetMapper+ def assetQueryMapper = new ClientObjectMapper(container.JSON, AssetQuery.class) as AssetQueryMapperdef assetArrayMapper = new ClientObjectMapper(container.JSON, Asset[].class) as AssetArrayMapperdef tenantArrayMapper = new ClientObjectMapper(container.JSON, Tenant[].class) as TenantArrayMapper@@ -455,14 +462,14 @@ class AssetBrowserPresenterTest extends Specification implements ManagerContainedef placeController = createPlaceController(securityService, eventBus)def placeHistoryMapper = createPlaceHistoryMapper(ManagerHistoryMapper.getAnnotation(WithTokenizers.class))def environment = Environment.create(- securityService,- requestService,- clientEventService,- placeController,- placeHistoryMapper,- eventBus,- managerMessages,- new WidgetStyle()+ securityService,+ requestService,+ clientEventService,+ placeController,+ placeHistoryMapper,+ eventBus,+ managerMessages,+ new WidgetStyle())and: "The view and presenter to test"@@ -473,14 +480,15 @@ class AssetBrowserPresenterTest extends Specification implements ManagerContaine}}def assetBrowserPresenter = new AssetBrowserPresenter(- environment,- currentTenant,- assetBrowser,- assetResource,- assetMapper,- assetArrayMapper,- tenantResource,- tenantArrayMapper+ environment,+ currentTenant,+ assetBrowser,+ assetResource,+ assetMapper,+ assetQueryMapper,+ assetArrayMapper,+ tenantResource,+ tenantArrayMapper)when: "the view is attached"@@ -498,6 +506,6 @@ class AssetBrowserPresenterTest extends Specification implements ManagerContaineclientEventService.close()and : "the server should be stopped"- stopContainer(container);+ stopContainer(container)}}diff --git a/manager/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovyindex f3bbaf0c4..a09c020ac 100644--- a/manager/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy@@ -5,8 +5,10 @@ import org.openremote.manager.server.setup.SetupServiceimport org.openremote.manager.server.setup.builtin.KeycloakDemoSetupimport org.openremote.manager.server.setup.builtin.ManagerDemoSetupimport org.openremote.manager.shared.asset.AssetResource+import org.openremote.model.asset.AbstractAssetQueryimport org.openremote.model.asset.Assetimport org.openremote.model.asset.AssetMeta+import org.openremote.model.asset.AssetQueryimport org.openremote.model.asset.AssetTypeimport org.openremote.model.attribute.AttributeTypeimport org.openremote.model.attribute.Meta@@ -54,35 +56,53 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraiassets.length == 0when: "the root assets of the authenticated realm are retrieved"- assets = assetResource.getRoot(null, keycloakDemoSetup.masterTenant.id)+ assets = assetResource.queryAssets(null,+ new AssetQuery()+ .tenant(new AbstractAssetQuery.TenantPredicate(keycloakDemoSetup.masterTenant.id))+ .parent(new AbstractAssetQuery.ParentPredicate(true))+ )then: "result should match"assets.length == 1assets[0].id == managerDemoSetup.smartOfficeIdwhen: "the child assets of an asset in the authenticated realm are retrieved"- assets = assetResource.getChildren(null, assets[0].id)+ assets = assetResource.queryAssets(null,+ new AssetQuery()+ .parent(new AbstractAssetQuery.ParentPredicate(assets[0].id))+ )then: "result should match"assets.length == 1assets[0].id == managerDemoSetup.groundFloorIdwhen: "the root assets of the authenticated realm are retrieved"- assets = assetResource.getRoot(null, null)+ assets = assetResource.queryAssets(null,+ new AssetQuery()+ .tenant(new AbstractAssetQuery.TenantPredicate(keycloakDemoSetup.masterTenant.id))+ .parent(new AbstractAssetQuery.ParentPredicate(true))+ )then: "result should match"assets.length == 1assets[0].id == managerDemoSetup.smartOfficeIdwhen: "the root assets of the given realm are retrieved"- assets = assetResource.getRoot(null, keycloakDemoSetup.customerATenant.id)+ assets = assetResource.queryAssets(null,+ new AssetQuery()+ .tenant(new AbstractAssetQuery.TenantPredicate(keycloakDemoSetup.customerATenant.id))+ .parent(new AbstractAssetQuery.ParentPredicate(true))+ )then: "result should match"assets.length == 1assets[0].id == managerDemoSetup.smartHomeIdwhen: "the child assets of an asset in a foreign realm are retrieved"- assets = assetResource.getChildren(null, assets[0].id)+ assets = assetResource.queryAssets(null,+ new AssetQuery()+ .parent(new AbstractAssetQuery.ParentPredicate(assets[0].id))+ )then: "result should match"assets.length == 3@@ -233,21 +253,31 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraiassets[0].attributesList.size() == 0when: "the root assets of the authenticated realm are retrieved"- assets = assetResource.getRoot(null, keycloakDemoSetup.masterTenant.id)+ assets = assetResource.queryAssets(null,+ new AssetQuery()+ .tenant(new AbstractAssetQuery.TenantPredicate(keycloakDemoSetup.masterTenant.id))+ .parent(new AbstractAssetQuery.ParentPredicate(true))+ )then: "result should match"assets.length == 1assets[0].id == managerDemoSetup.smartOfficeIdwhen: "the child assets of an asset in the authenticated realm are retrieved"- assets = assetResource.getChildren(null, assets[0].id)+ assets = assetResource.queryAssets(null,+ new AssetQuery()+ .parent(new AbstractAssetQuery.ParentPredicate(assets[0].id))+ )then: "result should match"assets.length == 1assets[0].id == managerDemoSetup.groundFloorIdwhen: "the root assets of the authenticated realm are retrieved"- assets = assetResource.getRoot(null, null)+ assets = assetResource.queryAssets(null,+ new AssetQuery()+ .parent(new AbstractAssetQuery.ParentPredicate(true))+ )then: "result should match"assets.length == 1@@ -255,13 +285,20 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraiassets[0].realmId == keycloakDemoSetup.masterTenant.idwhen: "the root assets of the given realm are retrieved"- assets = assetResource.getRoot(null, keycloakDemoSetup.customerATenant.id)+ assets = assetResource.queryAssets(null,+ new AssetQuery()+ .tenant(new AbstractAssetQuery.TenantPredicate(keycloakDemoSetup.customerATenant.id))+ .parent(new AbstractAssetQuery.ParentPredicate(true))+ )then: "result should match"assets.length == 0when: "the child assets of an asset in a foreign realm are retrieved"- assets = assetResource.getChildren(null, managerDemoSetup.smartHomeId)+ assets = assetResource.queryAssets(null,+ new AssetQuery()+ .parent(new AbstractAssetQuery.ParentPredicate(managerDemoSetup.smartHomeId))+ )then: "result should be empty"assets.length == 0@@ -386,13 +423,20 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraiassets[0].attributesList.size() == 0when: "the root assets of a foreign realm are retrieved"- assets = assetResource.getRoot(null, keycloakDemoSetup.masterTenant.id)+ assets = assetResource.queryAssets(null,+ new AssetQuery()+ .tenant(new AbstractAssetQuery.TenantPredicate(keycloakDemoSetup.masterTenant.id))+ .parent(new AbstractAssetQuery.ParentPredicate(true))+ )then: "result should match"assets.length == 0when: "the root assets of the authenticated realm are retrieved"- assets = assetResource.getRoot(null, null)+ assets = assetResource.queryAssets(null,+ new AssetQuery()+ .parent(new AbstractAssetQuery.ParentPredicate(true))+ )then: "result should match"assets.length == 1@@ -400,13 +444,20 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraiassets[0].realmId == keycloakDemoSetup.customerATenant.idwhen: "the root assets of the given realm are retrieved"- assets = assetResource.getRoot(null, keycloakDemoSetup.customerBTenant.id)+ assets = assetResource.queryAssets(null,+ new AssetQuery()+ .tenant(new AbstractAssetQuery.TenantPredicate(keycloakDemoSetup.customerBTenant.id))+ .parent(new AbstractAssetQuery.ParentPredicate(true))+ )then: "result should match"assets.length == 0when: "the child assets of an asset in a foreign realm are retrieved"- assets = assetResource.getChildren(null, managerDemoSetup.thingId)+ assets = assetResource.queryAssets(null,+ new AssetQuery()+ .parent(new AbstractAssetQuery.ParentPredicate(managerDemoSetup.thingId))+ )then: "result should be empty"assets.length == 0@@ -537,37 +588,57 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraiapartment2.name == "Apartment 2"when: "the root assets of a foreign realm are retrieved"- assets = assetResource.getRoot(null, keycloakDemoSetup.masterTenant.id)+ assets = assetResource.queryAssets(null,+ new AssetQuery()+ .tenant(new AbstractAssetQuery.TenantPredicate(keycloakDemoSetup.masterTenant.id))+ .parent(new AbstractAssetQuery.ParentPredicate(true))+ )then: "result should match"assets.length == 0when: "the root assets of the authenticated realm are retrieved"- assets = assetResource.getRoot(null, null)+ assets = assetResource.queryAssets(null,+ new AssetQuery()+ .parent(new AbstractAssetQuery.ParentPredicate(true))+ )then: "result should match"assets.length == 0when: "the root assets of the given realm are retrieved"- assets = assetResource.getRoot(null, keycloakDemoSetup.customerBTenant.id)+ assets = assetResource.queryAssets(null,+ new AssetQuery()+ .tenant(new AbstractAssetQuery.TenantPredicate(keycloakDemoSetup.customerBTenant.id))+ .parent(new AbstractAssetQuery.ParentPredicate(true))+ )then: "result should match"assets.length == 0when: "the child assets of linked asset are retrieved"- assets = assetResource.getChildren(null, managerDemoSetup.apartment1Id)+ assets = assetResource.queryAssets(null,+ new AssetQuery()+ .parent(new AbstractAssetQuery.ParentPredicate(managerDemoSetup.apartment1Id))+ )then: "result should match"assets.length == 0when: "the child assets of an asset in the authenticated realm are retrieved"- assets = assetResource.getChildren(null, managerDemoSetup.smartHomeId)+ assets = assetResource.queryAssets(null,+ new AssetQuery()+ .parent(new AbstractAssetQuery.ParentPredicate(managerDemoSetup.smartHomeId))+ )then: "result should match"assets.length == 0when: "the child assets of an asset in a foreign realm are retrieved"- assets = assetResource.getChildren(null, managerDemoSetup.thingId)+ assets = assetResource.queryAssets(null,+ new AssetQuery()+ .parent(new AbstractAssetQuery.ParentPredicate(managerDemoSetup.thingId))+ )then: "result should be empty"assets.length == 0diff --git a/manager/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovyindex e6027cee1..22174f153 100644--- a/manager/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy@@ -15,8 +15,8 @@ import spock.lang.Specificationimport javax.persistence.EntityManagerimport java.util.function.Function-import static org.openremote.model.asset.AssetQuery.*-import static org.openremote.model.asset.AssetQuery.OrderBy.Property.NAME+import static org.openremote.model.asset.AbstractAssetQuery.*+import static org.openremote.model.asset.AbstractAssetQuery.OrderBy.Property.*import static org.openremote.model.asset.AssetType.THINGclass AssetQueryTest extends Specification implements ManagerContainerTrait {@@ -30,6 +30,89 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {def assetStorageService = container.getService(AssetStorageService.class)def persistenceService = container.getService(PersistenceService.class)+ when: "an agent filtering query is executed"+ def assets = assetStorageService.findAll(+ new AssetQuery()+ .select(new Select(Include.ONLY_ID_AND_NAME_AND_ATTRIBUTES))+ .type(AssetType.AGENT)+ .tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.id))+ )++ then: "agent assets should be retrieved"+ assets.size() == 1+ assets[0].id == managerDemoSetup.agentId+ assets[0].name == "Demo Agent"+ assets[0].type == null+ assets[0].parentId == null+ assets[0].parentName == null+ assets[0].parentType == null+ assets[0].realmId == null+ assets[0].tenantRealm == null+ assets[0].tenantDisplayName == null+ assets[0].coordinates == null+ assets[0].path == null++ when: "a user filtering query is executed that returns only IDs, names and attribute names"+ assets = assetStorageService.findAll(+ new AssetQuery()+ .select(new Select(Include.ONLY_ID_AND_NAME_AND_ATTRIBUTE_NAMES))+ .userId(keycloakDemoSetup.testuser3Id)+ )++ then: "only the users assets should be retrieved"+ assets.size() == 4+ assets.get(0).id == managerDemoSetup.apartment1Id+ assets.get(1).id == managerDemoSetup.apartment1LivingroomId+ assets.get(1).getAttributesList().size() == 7+ !assets.get(1).getAttribute("currentTemperature").get().getValue().isPresent()+ assets.get(1).getAttribute("currentTemperature").get().meta.size() == 1+ !assets.get(1).getAttribute("targetTemperature").get().getValue().isPresent()+ assets.get(1).getAttribute("targetTemperature").get().meta.size() == 1+ assets.get(2).id == managerDemoSetup.apartment1KitchenId+ assets.get(3).id == managerDemoSetup.apartment2Id++ when: "a recursive query is executed to select asset id, name and attribute names for apartment 1 assets"+ assets = assetStorageService.findAll(+ new AssetQuery()+ .id(managerDemoSetup.smartHomeId)+ .select(new Select(Include.ONLY_ID_AND_NAME_AND_ATTRIBUTE_NAMES, false, true))+ .orderBy(new OrderBy(CREATED_ON))+ )++ then: "result should contain only ids, names and attribute names and label meta"+ assets.size() == 10+ assets[0].id == managerDemoSetup.smartHomeId+ assets[0].name == "Smart Home"+ assets[1].id == managerDemoSetup.apartment1Id+ assets[1].version == 0+ assets[1].createdOn == null+ assets[1].name == "Apartment 1"+ assets[1].type == null+ assets[1].parentId == null+ assets[1].parentName == null+ assets[1].parentType == null+ assets[1].realmId == null+ assets[1].tenantRealm == null+ assets[1].tenantDisplayName == null+ assets[1].coordinates == null+ assets[1].path == null+ assets[1].getAttributesList().size() == 4+ assets[1].getAttribute("alarmEnabled").isPresent()+ assets[1].getAttribute("vacationUntil").isPresent()+ assets[1].getAttribute("autoSceneSchedule").isPresent()+ assets[1].getAttribute("lastExecutedScene").isPresent()+ assets[1].getAttribute("alarmEnabled").get().meta.size() == 1+ assets[1].getAttribute("alarmEnabled").get().getMetaItem(AssetMeta.LABEL).isPresent()+ assets[1].getAttribute("alarmEnabled").get().getLabelOrName().get() == "Alarm enabled"+ assets[2].id == managerDemoSetup.apartment1ServiceAgentId+ assets[3].id == managerDemoSetup.apartment1LivingroomId+ assets[4].id == managerDemoSetup.apartment1KitchenId+ assets[5].id == managerDemoSetup.apartment2Id+ assets[6].id == managerDemoSetup.apartment2LivingroomId+ assets[7].id == managerDemoSetup.apartment2BathroomId+ assets[8].id == managerDemoSetup.apartment3Id+ assets[9].id == managerDemoSetup.apartment3LivingroomId+when: "an asset is loaded by identifier through JPA"def asset = persistenceService.doReturningTransaction(new Function<EntityManager, ServerAsset>() {@Override@@ -81,7 +164,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {when: "a query is executed"asset = assetStorageService.find(new AssetQuery()- .select(new Select(true, false))+ .select(new Select(Include.ALL, false)).id(managerDemoSetup.smartOfficeId))@@ -103,7 +186,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {asset.getAttribute("geoStreet").get().getValueAsString().get() == "Torenallee 20"when: "a query is executed"- def assets = assetStorageService.findAll(+ assets = assetStorageService.findAll(new AssetQuery().parent(new ParentPredicate(true)).tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.id))@@ -129,7 +212,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {when: "a query is executed"assets = assetStorageService.findAll(new AssetQuery()- .select(new Select(true, false))+ .select(new Select(Include.ALL, false)).parent(new ParentPredicate(true)).tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.id)))@@ -241,7 +324,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {when: "a query is executed"assets = assetStorageService.findAll(- new AssetQuery().select(new Select(true, true)).userId(keycloakDemoSetup.testuser3Id)+ new AssetQuery().select(new Select(Include.ALL, true)).userId(keycloakDemoSetup.testuser3Id))then: "result should match"@@ -258,7 +341,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {when: "a query is executed"assets = assetStorageService.findAll(- new AssetQuery().select(new Select(true, true)).userId(keycloakDemoSetup.testuser2Id)+ new AssetQuery().select(new Select(Include.ALL, true)).userId(keycloakDemoSetup.testuser2Id))then: "result should match"@@ -414,7 +497,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {asset = assetStorageService.find(new AssetQuery().id(managerDemoSetup.apartment1LivingroomId)- .select(new Select("co2Level", "lastPresenceDetected", "motionSensor").loadComplete(true))+ .select(new Select(Include.ALL, false, false, "co2Level", "lastPresenceDetected", "motionSensor")))then: "result should match"@@ -443,7 +526,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {asset = assetStorageService.find(new AssetQuery().id(managerDemoSetup.apartment1LivingroomId)- .select(new Select("co2Level", "lastPresenceDetected", "motionSensor").loadComplete(true).filterProtected(true))+ .select(new Select(Include.ALL, false, false, "co2Level", "lastPresenceDetected", "motionSensor").filterProtected(true)))then: "result should contain only matches that are protected"diff --git a/manager/test/src/test/groovy/org/openremote/test/map/MapResourceTest.groovy b/manager/test/src/test/groovy/org/openremote/test/map/MapResourceTest.groovyindex 968e62e72..c51c8c650 100644--- a/manager/test/src/test/groovy/org/openremote/test/map/MapResourceTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/map/MapResourceTest.groovy@@ -7,17 +7,17 @@ import spock.lang.Specificationimport static org.openremote.container.util.MapAccess.getStringimport static org.openremote.manager.server.setup.AbstractKeycloakSetup.*-import static org.openremote.model.Constants.*;+import static org.openremote.model.Constants.*class MapResourceTest extends Specification implements ManagerContainerTrait {def "Retrieve map settings"() {given: "the server container is started"- def serverPort = findEphemeralPort();+ def serverPort = findEphemeralPort()def container = startContainerNoDemoImport(defaultConfig(serverPort), defaultServices())and: "an authenticated user"- def realm = MASTER_REALM;+ def realm = MASTER_REALMdef accessToken = authenticate(container,realm,@@ -27,24 +27,24 @@ class MapResourceTest extends Specification implements ManagerContainerTrait {).tokenand: "a test client target"- def clientTarget = getClientTarget(serverUri(serverPort), realm, accessToken);+ def clientTarget = getClientTarget(serverUri(serverPort), realm, accessToken)and: "the map resource"- def mapResource = clientTarget.proxy(MapResource.class);+ def mapResource = clientTarget.proxy(MapResource.class)when: "a request has been made"- def mapSettings = mapResource.getSettings(null);+ def mapSettings = mapResource.getSettings(null)then: "settings should be not-null"- mapSettings != null;+ mapSettings != nulland: "JSON content is valid"- def json = new JsonSlurper().parseText(mapSettings.toJson());- json.center.size() == 2;- json.maxBounds.size() == 4;- json.style != null;+ def json = new JsonSlurper().parseText(mapSettings.toJson())+ json.center.size() == 2+ json.maxBounds.size() == 4+ json.style != nullcleanup: "the server should be stopped"- stopContainer(container);+ stopContainer(container)}}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.groovyindex 0a1f2aab2..4f5d734a0 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@@ -164,7 +164,7 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait {ProtocolConfiguration.initProtocolConfiguration(new AssetAttribute("mockConfig4"), mockProtocolName).addMeta(new MetaItem("MOCK_REQUIRED_META", Values.create(true)),- new MetaItem(AssetMeta.ENABLED, Values.create(false))+ new MetaItem(AssetMeta.DISABLED, Values.create(true))))mockAgent.setRealmId(Constants.MASTER_REALM)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.groovyindex 9c1121cd9..df7a651e1 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@@ -65,7 +65,7 @@ class KNXProtocolTest extends Specification implements ManagerContainerTrait {sc.getControlEndpoint(),sc.getMediumSettings(),sc.reuseControlEndpoint(),- sc.isNetworkMonitoringAllowed());+ sc.isNetworkMonitoringAllowed())knxEmulationServer.xml.svcContainers.add(sc2)def netIf = knxEmulationServer.xml.subnetNetIf.remove(sc)knxEmulationServer.xml.subnetNetIf.put(sc2, netIf)@@ -75,9 +75,9 @@ class KNXProtocolTest extends Specification implements ManagerContainerTrait {knxEmulationServer.xml.groupAddressFilters.put(sc2, groupFilters)def addAddresses = knxEmulationServer.xml.additionalAddresses.remove(sc)knxEmulationServer.xml.additionalAddresses.put(sc2, addAddresses)- def knxServerThread = new Thread(knxEmulationServer);- knxServerThread.start();- def knxTestingNetwork = KNXTestingNetworkLink.getInstance();+ def knxServerThread = new Thread(knxEmulationServer)+ knxServerThread.start()+ def knxTestingNetwork = KNXTestingNetworkLink.getInstance()and: "the container is started"def serverPort = findEphemeralPort()diff --git a/manager/test/src/test/groovy/org/openremote/test/protocol/SocketMessageProcessorTest.groovy b/manager/test/src/test/groovy/org/openremote/test/protocol/SocketMessageProcessorTest.groovyindex 7f940fdea..6fcd658f7 100644--- a/manager/test/src/test/groovy/org/openremote/test/protocol/SocketMessageProcessorTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/protocol/SocketMessageProcessorTest.groovy@@ -41,8 +41,8 @@ class SocketMessageProcessorTest extends Specification implements ManagerContaindef conditions = new PollingConditions(timeout: 10, delay: 1)and: "a simple socket echo server"- def socketServerPort = findEphemeralPort();- def socketServer = new SimpleSocketServer(socketServerPort, true);+ def socketServerPort = findEphemeralPort()+ def socketServer = new SimpleSocketServer(socketServerPort, true)and: "the container is started"def serverPort = findEphemeralPort()@@ -57,7 +57,7 @@ class SocketMessageProcessorTest extends Specification implements ManagerContain@Overrideprotected void decode(ByteBuf buf, List<String> messages) throws Exception {- ByteBuf bytes = buf.readBytes(buf.readableBytes());+ ByteBuf bytes = buf.readBytes(buf.readableBytes())String msg = bytes.toString(CharsetUtil.UTF_8)bytes.release()messages.add(msg)@@ -71,7 +71,7 @@ class SocketMessageProcessorTest extends Specification implements ManagerContainand: "we add callback consumers to the message processor"def connectionStatus = messageProcessor.getConnectionStatus()- String lastMessage;+ String lastMessagemessageProcessor.addMessageConsumer({message -> lastMessage = message})@@ -193,6 +193,6 @@ class SocketMessageProcessorTest extends Specification implements ManagerContaincleanup: "the server should be stopped"messageProcessor.disconnect()socketServer.stop()- stopContainer(container);+ stopContainer(container)}}diff --git a/model/src/main/java/org/openremote/model/asset/AbstractAssetQuery.java b/model/src/main/java/org/openremote/model/asset/AbstractAssetQuery.javanew file mode 100644index 000000000..d184b65c9--- /dev/null+++ b/model/src/main/java/org/openremote/model/asset/AbstractAssetQuery.java@@ -0,0 +1,479 @@+/*+ * Copyright 2017, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.model.asset;++import org.openremote.model.attribute.AttributeRef;++import java.util.Locale;++/**+ * Encapsulate asset query restriction, projection, and ordering of results.+ */++public class AbstractAssetQuery<CHILD extends AbstractAssetQuery<CHILD>> {++ public enum Include {+ ALL_EXCEPT_PATH_AND_ATTRIBUTES,+ ALL_EXCEPT_PATH,+ ONLY_ID_AND_NAME,+ ONLY_ID_AND_NAME_AND_ATTRIBUTES,+ ONLY_ID_AND_NAME_AND_ATTRIBUTE_NAMES,+ ALL+ }++ public static class Select {+ public Include include = Include.ALL_EXCEPT_PATH_AND_ATTRIBUTES;+ public boolean filterProtected;+ public boolean recursive;+ public String[] attributeNames;++ public Select() {+ }++ public Select(Include include) {+ this(include, false);+ }++ public Select(Include include, boolean filterProtected) {+ this(include, filterProtected, false);+ }++ public Select(Include include, boolean filterProtected, boolean recursive) {+ this(include, filterProtected, recursive, (String[])null);+ }++ public Select(Include include, boolean filterProtected, boolean recursive, String... attributeNames) {+ if (include == null) {+ include = Include.ALL_EXCEPT_PATH_AND_ATTRIBUTES;+ }+ this.include = include;+ this.filterProtected = filterProtected;+ this.recursive = recursive;+ this.attributeNames = attributeNames;+ }++ public Select include(Include include) {+ this.include = include;+ return this;+ }++ public Select filterProtected(boolean filterProtected) {+ this.filterProtected = filterProtected;+ return this;+ }++ public Select filterAttributes(String... attributeNames) {+ this.attributeNames = attributeNames;+ return this;+ }+ }++ public enum Match {+ EXACT,+ BEGIN,+ END,+ CONTAINS;++ public String prepare(String string) {+ if (string == null)+ return null;+ switch (this) {+ case BEGIN:+ return string + "%";+ case CONTAINS:+ return "%" + string + "%";+ case END:+ return "%" + string;+ }+ return string;+ }+ }++ public interface ValuePredicate {+ }++ public static class StringPredicate implements ValuePredicate {+ public Match match = Match.EXACT;+ public boolean caseSensitive = true;+ public String value;++ public StringPredicate() {+ }++ public StringPredicate(String value) {+ this.value = value;+ }++ public StringPredicate(Match match, String value) {+ this.match = match;+ this.value = value;+ }++ public StringPredicate(Match match, boolean caseSensitive, String value) {+ this.match = match;+ this.caseSensitive = caseSensitive;+ this.value = value;+ }++ public StringPredicate match(Match match) {+ this.match = match;+ return this;+ }++ public StringPredicate caseSensitive(boolean caseSensitive) {+ this.caseSensitive = caseSensitive;+ return this;+ }++ public StringPredicate value(String value) {+ this.value = value;+ return this;+ }++ public String prepareValue() {+ String s = match.prepare(this.value);+ if (!caseSensitive)+ s = s.toUpperCase(Locale.ROOT);+ return s;+ }+ }++ public static class BooleanPredicate implements ValuePredicate {+ public boolean predicate;++ public BooleanPredicate() {+ }++ public BooleanPredicate(boolean predicate) {+ this.predicate = predicate;+ }++ public BooleanPredicate predicate(boolean predicate) {+ this.predicate = predicate;+ return this;+ }+ }++ public static class StringArrayPredicate implements ValuePredicate {+ public StringPredicate[] predicates = new StringPredicate[0];++ public StringArrayPredicate() {+ }++ public StringArrayPredicate(StringPredicate... predicates) {+ this.predicates = predicates;+ }++ public StringArrayPredicate predicates(StringPredicate... predicates) {+ this.predicates = predicates;+ return this;+ }+ }++ public static class ParentPredicate {+ public String id;+ public String type;+ public boolean noParent;++ public ParentPredicate() {+ }++ public ParentPredicate(String id) {+ this.id = id;+ }++ public ParentPredicate(boolean noParent) {+ this.noParent = noParent;+ }++ public ParentPredicate id(String id) {+ this.id = id;+ return this;+ }++ public ParentPredicate type(String type) {+ this.type = type;+ return this;+ }++ public ParentPredicate type(AssetType type) {+ return type(type.getValue());+ }++ public ParentPredicate noParent(boolean noParent) {+ this.noParent = noParent;+ return this;+ }+ }++ public static class PathPredicate {+ public String[] path;++ public PathPredicate() {+ }++ public PathPredicate(String[] path) {+ this.path = path;+ }++ public PathPredicate path(String[] path) {+ this.path = path;+ return this;+ }++ public boolean hasPath() {+ return path != null && path.length > 0;+ }+ }++ public static class TenantPredicate {+ public String realmId;+ public String realm;++ public TenantPredicate() {+ }++ public TenantPredicate(String realmId) {+ this.realmId = realmId;+ }++ public TenantPredicate realmId(String id) {+ this.realmId = id;+ return this;+ }++ public TenantPredicate realm(String name) {+ this.realm = name;+ return this;+ }+ }++ public static class AttributeMetaPredicate {+ public StringPredicate itemNamePredicate;+ public ValuePredicate itemValuePredicate;++ public AttributeMetaPredicate() {+ }++ public AttributeMetaPredicate(StringPredicate itemNamePredicate) {+ this.itemNamePredicate = itemNamePredicate;+ }++ public AttributeMetaPredicate(AssetMeta assetMeta) {+ this.itemNamePredicate = new StringPredicate(assetMeta.getUrn());+ }++ public AttributeMetaPredicate(ValuePredicate itemValuePredicate) {+ this.itemValuePredicate = itemValuePredicate;+ }++ public AttributeMetaPredicate(StringPredicate itemNamePredicate, ValuePredicate itemValuePredicate) {+ this.itemNamePredicate = itemNamePredicate;+ this.itemValuePredicate = itemValuePredicate;+ }++ public AttributeMetaPredicate(AssetMeta assetMeta, ValuePredicate itemValuePredicate) {+ this(new StringPredicate(assetMeta.getUrn()), itemValuePredicate);+ }++ public AttributeMetaPredicate itemName(StringPredicate itemNamePredicate) {+ this.itemNamePredicate = itemNamePredicate;+ return this;+ }++ public AttributeMetaPredicate itemName(AssetMeta assetMeta) {+ return itemName(new StringPredicate(assetMeta.getUrn()));+ }++ public AttributeMetaPredicate itemValue(ValuePredicate itemValuePredicate) {+ this.itemValuePredicate = itemValuePredicate;+ return this;+ }+ }++ public static class AttributeRefPredicate extends AttributeMetaPredicate {++ public AttributeRefPredicate() {+ }++ public AttributeRefPredicate(AttributeRef attributeRef) {+ this(attributeRef.getEntityId(), attributeRef.getAttributeName());+ }++ public AttributeRefPredicate(String entityId, String attributeName) {+ super(+ new StringArrayPredicate(+ new StringPredicate(entityId),+ new StringPredicate(attributeName)+ ));+ }++ public AttributeRefPredicate(String name, String entityId, String attributeName) {+ super(+ new StringPredicate(name),+ new StringArrayPredicate(+ new StringPredicate(entityId),+ new StringPredicate(attributeName)+ ));+ }++ public AttributeRefPredicate(AssetMeta assetMeta, String entityId, String attributeName) {+ this(assetMeta.getUrn(), entityId, attributeName);+ }++ public AttributeRefPredicate(StringPredicate name, AttributeRef attributeRef) {+ super(+ name,+ new StringArrayPredicate(+ new StringPredicate(attributeRef.getEntityId()),+ new StringPredicate(attributeRef.getAttributeName())+ ));+ }++ public AttributeRefPredicate(AssetMeta assetMeta, AttributeRef attributeRef) {+ this(new StringPredicate(assetMeta.getUrn()), attributeRef);+ }+ }++ public static class OrderBy {++ public enum Property {+ CREATED_ON,+ NAME,+ ASSET_TYPE,+ PARENT_ID,+ REALM_ID+ }++ public Property property;+ public boolean descending;++ public OrderBy() {+ }++ public OrderBy(Property property) {+ this.property = property;+ }++ public OrderBy(Property property, boolean descending) {+ this.property = property;+ this.descending = descending;+ }++ public OrderBy property(Property property) {+ this.property = property;+ return this;+ }++ public OrderBy descending(boolean descending) {+ this.descending = descending;+ return this;+ }+ }++ // Projection+ public Select select = new Select();++ // Restriction predicates+ public String id;+ public StringPredicate namePredicate;+ public ParentPredicate parentPredicate;+ public PathPredicate pathPredicate;+ public TenantPredicate tenantPredicate;+ public String userId;+ public StringPredicate type;+ public AttributeMetaPredicate attributeMetaPredicate;++ // Ordering+ public OrderBy orderBy = new OrderBy(OrderBy.Property.CREATED_ON);++ protected AbstractAssetQuery() {+ }++ public CHILD select(Select select) {+ if (select == null) {+ select = new Select();+ }++ this.select = select;+ return (CHILD) this;+ }++ public CHILD id(String id) {+ this.id = id;+ return (CHILD) this;+ }++ public CHILD name(String name) {+ return name(new StringPredicate(name));+ }++ public CHILD name(StringPredicate name) {+ this.namePredicate = name;+ return (CHILD) this;+ }++ public CHILD parent(String id) {+ return parent(new ParentPredicate(id));+ }++ public CHILD parent(AssetType assetType) {+ return parent(new ParentPredicate().type(assetType));+ }++ public CHILD parent(ParentPredicate parentPredicate) {+ this.parentPredicate = parentPredicate;+ return (CHILD) this;+ }++ public CHILD path(PathPredicate pathPredicate) {+ this.pathPredicate = pathPredicate;+ return (CHILD) this;+ }++ public CHILD tenant(TenantPredicate tenantPredicate) {+ this.tenantPredicate = tenantPredicate;+ return (CHILD) this;+ }++ public CHILD userId(String userId) {+ this.userId = userId;+ return (CHILD) this;+ }++ public CHILD type(StringPredicate type) {+ this.type = type;+ return (CHILD) this;+ }++ public CHILD type(AssetType assetType) {+ return type(new StringPredicate(assetType.getValue()));+ }++ public CHILD attributeMeta(AttributeMetaPredicate attributeMetaPredicate) {+ this.attributeMetaPredicate = attributeMetaPredicate;+ return (CHILD) this;+ }++ public CHILD orderBy(OrderBy orderBy) {+ this.orderBy = orderBy;+ return (CHILD) this;+ }+}diff --git a/model/src/main/java/org/openremote/model/asset/Asset.java b/model/src/main/java/org/openremote/model/asset/Asset.javaindex 0a7ef22fd..bc34fd0cb 100644--- a/model/src/main/java/org/openremote/model/asset/Asset.java+++ b/model/src/main/java/org/openremote/model/asset/Asset.java@@ -231,7 +231,7 @@ public class Asset implements IdentifiableEntity {@Temporal(TemporalType.TIMESTAMP)@Column(name = "CREATED_ON", updatable = false, nullable = false, columnDefinition = "TIMESTAMP WITH TIME ZONE")@org.hibernate.annotations.CreationTimestamp- protected Date createdOn = new Date();+ protected Date createdOn;@NotNull(message = "{Asset.name.NotNull}")@Size(min = 3, max = 1023, message = "{Asset.name.Size}")@@ -554,7 +554,7 @@ public class Asset implements IdentifiableEntity {.flatMap(objectValue -> AssetAttribute.attributeFromJson(objectValue, id, name));}- protected void setAttributes(ObjectValue attributes) {+ public void setAttributes(ObjectValue attributes) {this.attributes = attributes;}diff --git a/model/src/main/java/org/openremote/model/asset/AssetAttribute.java b/model/src/main/java/org/openremote/model/asset/AssetAttribute.javaindex 702511088..b6fea2382 100644--- a/model/src/main/java/org/openremote/model/asset/AssetAttribute.java+++ b/model/src/main/java/org/openremote/model/asset/AssetAttribute.java@@ -260,21 +260,21 @@ public class AssetAttribute extends Attribute {}/**- * Defaults to <code>true</code> if there is no {@link AssetMeta#ENABLED} item.+ * Defaults to <code>true</code> if there is no {@link AssetMeta#DISABLED} item.*/public boolean isEnabled() {return getMetaStream()- .filter(isMetaNameEqualTo(ENABLED))+ .filter(isMetaNameEqualTo(DISABLED)).findFirst()- .map(metaItem -> metaItem.getValueAsBoolean().orElse(false))+ .map(metaItem -> !metaItem.getValueAsBoolean().orElse(false)).orElse(true);}- public void setEnabled(boolean enabled) {- if (!enabled) {- replaceMetaByName(getMeta(), ENABLED, Values.create(false));+ public void setDisabled(boolean disabled) {+ if (disabled) {+ replaceMetaByName(getMeta(), DISABLED, Values.create(true));} else {- getMeta().removeIf(isMetaNameEqualTo(ENABLED));+ getMeta().removeIf(isMetaNameEqualTo(DISABLED));}}@@ -392,7 +392,7 @@ public class AssetAttribute extends Attribute {// ---------------------------------------------------public static Optional<AssetAttribute> attributeFromJson(ObjectValue objectValue, String assetId, String name) {- if (objectValue == null || objectValue.keys().length == 0) {+ if (objectValue == null) {return Optional.empty();}diff --git a/model/src/main/java/org/openremote/model/asset/AssetMeta.java b/model/src/main/java/org/openremote/model/asset/AssetMeta.javaindex 580fffef1..d227b1a14 100644--- a/model/src/main/java/org/openremote/model/asset/AssetMeta.java+++ b/model/src/main/java/org/openremote/model/asset/AssetMeta.java@@ -26,6 +26,7 @@ import org.openremote.model.attribute.MetaItem;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.ArrayList;import java.util.Comparator;@@ -48,7 +49,7 @@ public enum AssetMeta implements HasUniqueResourceName {* 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),+ PROTOCOL_CONFIGURATION(ASSET_META_NAMESPACE + ":protocolConfiguration", new Access(false, false, true), ValueType.BOOLEAN, Values.create(true), true),/*** Links the attribute to an agent's {@link org.openremote.model.asset.agent.ProtocolConfiguration}, connecting it@@ -70,7 +71,7 @@ public enum AssetMeta implements HasUniqueResourceName {/*** 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),+ SHOW_ON_DASHBOARD(ASSET_META_NAMESPACE + ":showOnDashboard", new Access(true, true, true), ValueType.BOOLEAN, Values.create(true), true),/*** Format string that can be used to render the attribute value, see https://github.com/alexei/sprintf.js.@@ -91,17 +92,21 @@ public enum AssetMeta implements HasUniqueResourceName {* 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),+ READ_ONLY(ASSET_META_NAMESPACE + ":readOnly", new Access(true, false, true), ValueType.BOOLEAN, 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),+ 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.*/- DEFAULT(ASSET_META_NAMESPACE + ":default", new Access(false, false, false), ValueType.STRING),+ //DEFAULT(ASSET_META_NAMESPACE + ":default", new Access(false, false, false), ValueType.STRING),/*** Minimum range constraint for numeric attribute values.@@ -126,7 +131,7 @@ public enum AssetMeta implements HasUniqueResourceName {/*** Should attribute values be stored in time series database*/- STORE_DATA_POINTS(ASSET_META_NAMESPACE + ":storeDataPoints", new Access(true, false, true), ValueType.BOOLEAN),+ STORE_DATA_POINTS(ASSET_META_NAMESPACE + ":storeDataPoints", new Access(true, false, true), ValueType.BOOLEAN, Values.create(true), true),/*** Should attribute writes be processed by the rules engines as {@link AssetState} facts in knowledge sessions,@@ -135,7 +140,7 @@ 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),+ RULE_STATE(ASSET_META_NAMESPACE + ":ruleState", new Access(true, false, true), ValueType.BOOLEAN, Values.create(true), true),/*** Should attribute writes be processed by the rules engines as events in knowledge sessions. Any attribute@@ -144,7 +149,7 @@ 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),+ RULE_EVENT(ASSET_META_NAMESPACE + ":ruleEvent", new Access(true, false, true), ValueType.BOOLEAN, Values.create(true), true),/*** Set maximum lifetime of {@link AssetEvent} facts in knowledge sessions, for example "1h30m". The rules@@ -154,14 +159,14 @@ public enum AssetMeta implements HasUniqueResourceName {RULE_EVENT_EXPIRES(ASSET_META_NAMESPACE + ":ruleEventExpires", new Access(true, false, true), ValueType.STRING),/**- * Enable flag to be used by asset attributes that could require this functionality (e.g. {@link org.openremote.model.asset.agent.ProtocolConfiguration})+ * Disabled flag to be used by asset attributes that could require this functionality (e.g. {@link org.openremote.model.asset.agent.ProtocolConfiguration})*/- ENABLED(ASSET_META_NAMESPACE + ":enabled", new Access(true, false, true), ValueType.BOOLEAN),+ DISABLED(ASSET_META_NAMESPACE + ":disabled", new Access(true, false, true), ValueType.BOOLEAN, 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);+ 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@@ -170,11 +175,22 @@ public enum AssetMeta implements HasUniqueResourceName {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);+ }++ AssetMeta(String urn, Access access, ValueType valueType, Value initialValue, boolean valueFixed) {+ if (initialValue != null && initialValue.getType() != valueType) {+ throw new IllegalStateException("Initial asset meta value must be of the same type as the asset meta");+ }this.urn = urn;this.access = access;this.valueType = valueType;+ this.initialValue = initialValue;+ this.valueFixed = valueFixed;}public String getUrn() {@@ -189,6 +205,21 @@ public enum AssetMeta implements HasUniqueResourceName {return valueType;}+ public Value getInitialValue() {+ return initialValue;+ }++ /**+ * Indicates that the value of this asset meta should not be changed.+ */+ public boolean isValueFixed() {+ return valueFixed;+ }++ public boolean isRestricted() {+ 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.@@ -203,10 +234,10 @@ public enum AssetMeta implements HasUniqueResourceName {return Optional.empty();}- public static AssetMeta[] editable() {+ public static AssetMeta[] unRestricted() {List<AssetMeta> list = new ArrayList<>();for (AssetMeta meta : values()) {- if (meta.getAccess().editable)+ if (!meta.getAccess().restricted)list.add(meta);}@@ -215,12 +246,24 @@ public enum AssetMeta implements HasUniqueResourceName {return list.toArray(new AssetMeta[list.size()]);}- public static boolean isEditable(String urn) {- for (AssetMeta assetMeta : editable()) {+ public static AssetMeta[] restricted() {+ List<AssetMeta> list = new ArrayList<>();+ for (AssetMeta meta : values()) {+ if (meta.getAccess().restricted)+ list.add(meta);+ }++ list.sort(Comparator.comparing(Enum::name));++ return list.toArray(new AssetMeta[list.size()]);+ }++ public static boolean isRestricted(String urn) {+ for (AssetMeta assetMeta : restricted()) {if (assetMeta.getUrn().equals(urn))- return assetMeta.getAccess().editable;+ return assetMeta.getAccess().restricted;}- return true;+ return false;}public static Optional<AssetMeta> getAssetMeta(String urn) {@@ -264,32 +307,6 @@ public enum AssetMeta implements HasUniqueResourceName {.orElse(false);}- /**- * In theory, meta item values can be of any {@link ValueType}. In practice, these- * are the types we can edit/have editor UI for.- */- public enum EditableType {- STRING("Text", ValueType.STRING),- NUMBER("Number", ValueType.NUMBER),- BOOLEAN("On/Off toggle", ValueType.BOOLEAN);-- EditableType(String label, ValueType valueType) {- this.label = label;- this.valueType = valueType;- }-- public final String label;- public final ValueType valueType;-- public static EditableType byValueType(ValueType valueType) {- for (EditableType vt : values()) {- if (vt.valueType == valueType)- return vt;- }- return null;- }- }-public static class Access {/**@@ -305,12 +322,12 @@ public enum AssetMeta implements HasUniqueResourceName {/*** Can a user add this meta item when editing an asset?*/- final public boolean editable;+ final public boolean restricted;- public Access(boolean protectedRead, boolean protectedWrite, boolean editable) {+ public Access(boolean protectedRead, boolean protectedWrite, boolean restricted) {this.protectedRead = protectedRead;this.protectedWrite = protectedWrite;- this.editable = editable;+ this.restricted = restricted;}}diff --git a/model/src/main/java/org/openremote/model/asset/AssetQuery.java b/model/src/main/java/org/openremote/model/asset/AssetQuery.javaindex 99c852451..86ee3bc1a 100644--- a/model/src/main/java/org/openremote/model/asset/AssetQuery.java+++ b/model/src/main/java/org/openremote/model/asset/AssetQuery.java@@ -19,437 +19,11 @@*/package org.openremote.model.asset;-import org.openremote.model.attribute.AttributeRef;--import java.util.Locale;-/**- * Encapsulate asset query restriction, projection, and ordering of results.+ * This was only done to allow GWT jackson to compile it; don't think GWT jackson+ * likes self referencing generic type parameters but hard to tell as the errors+ * generated are not helpful.*/-public class AssetQuery<CHILD extends AssetQuery<CHILD>> {-- public static class Select {- public boolean loadComplete;- public boolean filterProtected;- public String[] attributeNames;-- public Select() {- }-- public Select(boolean loadComplete) {- this.loadComplete = loadComplete;- }-- public Select(boolean loadComplete, boolean filterProtected) {- this.loadComplete = loadComplete;- this.filterProtected = filterProtected;- }-- public Select(String... attributeNames) {- this.attributeNames = attributeNames;- }-- public Select loadComplete(boolean loadComplete) {- this.loadComplete = loadComplete;- return this;- }-- public Select filterProtected(boolean filterProtected) {- this.filterProtected = filterProtected;- return this;- }-- public Select attributesByName(String... attributeNames) {- this.attributeNames = attributeNames;- return this;- }- }-- public enum Match {- EXACT,- BEGIN,- END,- CONTAINS;-- public String prepare(String string) {- if (string == null)- return null;- switch (this) {- case BEGIN:- return string + "%";- case CONTAINS:- return "%" + string + "%";- case END:- return "%" + string;- }- return string;- }- }-- public interface ValuePredicate {- }-- public static class StringPredicate implements ValuePredicate {- public Match match = Match.EXACT;- public boolean caseSensitive = true;- public String value;-- public StringPredicate() {- }-- public StringPredicate(String value) {- this.value = value;- }-- public StringPredicate(Match match, String value) {- this.match = match;- this.value = value;- }-- public StringPredicate(Match match, boolean caseSensitive, String value) {- this.match = match;- this.caseSensitive = caseSensitive;- this.value = value;- }-- public StringPredicate match(Match match) {- this.match = match;- return this;- }-- public StringPredicate caseSensitive(boolean caseSensitive) {- this.caseSensitive = caseSensitive;- return this;- }-- public StringPredicate value(String value) {- this.value = value;- return this;- }-- public String prepareValue() {- String s = match.prepare(this.value);- if (!caseSensitive)- s = s.toUpperCase(Locale.ROOT);- return s;- }- }-- public static class BooleanPredicate implements ValuePredicate {- public boolean predicate;-- public BooleanPredicate() {- }-- public BooleanPredicate(boolean predicate) {- this.predicate = predicate;- }-- public BooleanPredicate predicate(boolean predicate) {- this.predicate = predicate;- return this;- }- }-- public static class StringArrayPredicate implements ValuePredicate {- public StringPredicate[] predicates = new StringPredicate[0];-- public StringArrayPredicate() {- }-- public StringArrayPredicate(StringPredicate... predicates) {- this.predicates = predicates;- }-- public StringArrayPredicate predicates(StringPredicate... predicates) {- this.predicates = predicates;- return this;- }- }-- public static class ParentPredicate {- public String id;- public String type;- public boolean noParent;-- public ParentPredicate() {- }-- public ParentPredicate(String id) {- this.id = id;- }-- public ParentPredicate(boolean noParent) {- this.noParent = noParent;- }-- public ParentPredicate id(String id) {- this.id = id;- return this;- }-- public ParentPredicate type(String type) {- this.type = type;- return this;- }-- public ParentPredicate type(AssetType type) {- return type(type.getValue());- }-- public ParentPredicate noParent(boolean noParent) {- this.noParent = noParent;- return this;- }- }-- public static class PathPredicate {- public String[] path;-- public PathPredicate() {- }-- public PathPredicate(String[] path) {- this.path = path;- }-- public PathPredicate path(String[] path) {- this.path = path;- return this;- }-- public boolean hasPath() {- return path != null && path.length > 0;- }- }-- public static class TenantPredicate {- public String realmId;- public String realm;-- public TenantPredicate() {- }-- public TenantPredicate(String realmId) {- this.realmId = realmId;- }-- public TenantPredicate realmId(String id) {- this.realmId = id;- return this;- }-- public TenantPredicate realm(String name) {- this.realm = name;- return this;- }- }-- public static class AttributeMetaPredicate {- public StringPredicate itemNamePredicate;- public ValuePredicate itemValuePredicate;-- public AttributeMetaPredicate() {- }-- public AttributeMetaPredicate(StringPredicate itemNamePredicate) {- this.itemNamePredicate = itemNamePredicate;- }-- public AttributeMetaPredicate(AssetMeta assetMeta) {- this.itemNamePredicate = new StringPredicate(assetMeta.getUrn());- }-- public AttributeMetaPredicate(ValuePredicate itemValuePredicate) {- this.itemValuePredicate = itemValuePredicate;- }-- public AttributeMetaPredicate(StringPredicate itemNamePredicate, ValuePredicate itemValuePredicate) {- this.itemNamePredicate = itemNamePredicate;- this.itemValuePredicate = itemValuePredicate;- }-- public AttributeMetaPredicate(AssetMeta assetMeta, ValuePredicate itemValuePredicate) {- this(new StringPredicate(assetMeta.getUrn()), itemValuePredicate);- }-- public AttributeMetaPredicate itemName(StringPredicate itemNamePredicate) {- this.itemNamePredicate = itemNamePredicate;- return this;- }-- public AttributeMetaPredicate itemName(AssetMeta assetMeta) {- return itemName(new StringPredicate(assetMeta.getUrn()));- }-- public AttributeMetaPredicate itemValue(ValuePredicate itemValuePredicate) {- this.itemValuePredicate = itemValuePredicate;- return this;- }- }-- public static class AttributeRefPredicate extends AttributeMetaPredicate {-- public AttributeRefPredicate() {- }-- public AttributeRefPredicate(AttributeRef attributeRef) {- this(attributeRef.getEntityId(), attributeRef.getAttributeName());- }-- public AttributeRefPredicate(String entityId, String attributeName) {- super(- new StringArrayPredicate(- new StringPredicate(entityId),- new StringPredicate(attributeName)- ));- }-- public AttributeRefPredicate(String name, String entityId, String attributeName) {- super(- new StringPredicate(name),- new StringArrayPredicate(- new StringPredicate(entityId),- new StringPredicate(attributeName)- ));- }-- public AttributeRefPredicate(AssetMeta assetMeta, String entityId, String attributeName) {- this(assetMeta.getUrn(), entityId, attributeName);- }-- public AttributeRefPredicate(StringPredicate name, AttributeRef attributeRef) {- super(- name,- new StringArrayPredicate(- new StringPredicate(attributeRef.getEntityId()),- new StringPredicate(attributeRef.getAttributeName())- ));- }-- public AttributeRefPredicate(AssetMeta assetMeta, AttributeRef attributeRef) {- this(new StringPredicate(assetMeta.getUrn()), attributeRef);- }- }-- public static class OrderBy {-- public enum Property {- CREATED_ON,- NAME,- ASSET_TYPE,- PARENT_ID,- REALM_ID- }-- public Property property;- public boolean descending;-- public OrderBy() {- }-- public OrderBy(Property property) {- this.property = property;- }-- public OrderBy(Property property, boolean descending) {- this.property = property;- this.descending = descending;- }-- public OrderBy property(Property property) {- this.property = property;- return this;- }-- public OrderBy descending(boolean descending) {- this.descending = descending;- return this;- }- }-- // Projection- public Select select = new Select(false, false);-- // Restriction predicates- public String id;- public StringPredicate name;- public ParentPredicate parentPredicate;- public PathPredicate pathPredicate;- public TenantPredicate tenantPredicate;- public String userId;- public StringPredicate type;- public AttributeMetaPredicate attributeMetaPredicate;-- // Ordering- public OrderBy orderBy = new OrderBy(OrderBy.Property.CREATED_ON);-- public AssetQuery() {- }-- public CHILD select(Select select) {- this.select = select;- return (CHILD) this;- }-- public CHILD id(String id) {- this.id = id;- return (CHILD) this;- }-- public CHILD name(String name) {- return name(new StringPredicate(name));- }-- public CHILD name(StringPredicate name) {- this.name = name;- return (CHILD) this;- }-- public CHILD parent(String id) {- return parent(new ParentPredicate(id));- }-- public CHILD parent(AssetType assetType) {- return parent(new ParentPredicate().type(assetType));- }-- public CHILD parent(ParentPredicate parentPredicate) {- this.parentPredicate = parentPredicate;- return (CHILD) this;- }-- public CHILD path(PathPredicate pathPredicate) {- this.pathPredicate = pathPredicate;- return (CHILD) this;- }-- public CHILD tenant(TenantPredicate tenantPredicate) {- this.tenantPredicate = tenantPredicate;- return (CHILD) this;- }-- public CHILD userId(String userId) {- this.userId = userId;- return (CHILD) this;- }-- public CHILD type(StringPredicate type) {- this.type = type;- return (CHILD) this;- }-- public CHILD type(AssetType assetType) {- return type(new StringPredicate(assetType.getValue()));- }-- public CHILD attributeMeta(AttributeMetaPredicate attributeMetaPredicate) {- this.attributeMetaPredicate = attributeMetaPredicate;- return (CHILD) this;- }+public class AssetQuery extends AbstractAssetQuery<AssetQuery> {- public CHILD orderBy(OrderBy orderBy) {- this.orderBy = orderBy;- return (CHILD) this;- }}diff --git a/model/src/main/java/org/openremote/model/asset/agent/ProtocolConfiguration.java b/model/src/main/java/org/openremote/model/asset/agent/ProtocolConfiguration.javaindex c6b0b55f5..43f24ffdd 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@@ -50,7 +50,6 @@ final public class ProtocolConfiguration {return null;}isValidProtocolNameOrThrow(protocolName);- attribute.setEnabled(true);attribute.setReadOnly(true);attribute.setType(AttributeType.STRING);attribute.setValue(Values.create(protocolName));diff --git a/model/src/main/java/org/openremote/model/attribute/MetaItem.java b/model/src/main/java/org/openremote/model/attribute/MetaItem.javaindex c618957e2..26dbb9fe9 100644--- a/model/src/main/java/org/openremote/model/attribute/MetaItem.java+++ b/model/src/main/java/org/openremote/model/attribute/MetaItem.java@@ -22,6 +22,7 @@ package org.openremote.model.attribute;import org.openremote.model.AbstractValueHolder;import org.openremote.model.HasUniqueResourceName;import org.openremote.model.ValidationFailure;+import org.openremote.model.asset.AssetMeta;import org.openremote.model.util.TextUtil;import org.openremote.model.value.ObjectValue;import org.openremote.model.value.Value;@@ -61,6 +62,12 @@ public class MetaItem extends AbstractValueHolder {setValue(value);}+ public MetaItem(AssetMeta assetMeta) {+ super(Values.createObject());+ setName(assetMeta.getUrn());+ setValue(assetMeta.getInitialValue());+ }+public MetaItem(HasUniqueResourceName hasUniqueResourceName, Value value) {this(hasUniqueResourceName.getUrn(), value);}@@ -69,10 +76,26 @@ public class MetaItem extends AbstractValueHolder {return getObjectValue().getString("name");}+ public boolean hasRestrictedFlag() {+ return getObjectValue().hasKey("restricted");+ }++ public boolean isRestricted() {+ return getObjectValue().getBoolean("restricted").orElse(false);+ }++ public void setRestricted(boolean restricted) {+ getObjectValue().put("restricted", Values.create(restricted));+ }+public void setName(String name) {getObjectValue().put("name", TextUtil.requireNonNullAndNonEmpty(name));}+ public void clearName() {+ getObjectValue().remove("name");+ }+@Overridepublic List<ValidationFailure> getValidationFailures() {List<ValidationFailure> failures = super.getValidationFailures();diff --git a/model/src/main/java/org/openremote/model/geo/GeoJSON.java b/model/src/main/java/org/openremote/model/geo/GeoJSON.javaindex b99cb67af..a48876529 100644--- a/model/src/main/java/org/openremote/model/geo/GeoJSON.java+++ b/model/src/main/java/org/openremote/model/geo/GeoJSON.java@@ -25,7 +25,7 @@ import org.openremote.model.value.Values;public class GeoJSON extends AbstractTypeHolder {- public static final GeoJSON EMPTY_FEATURE_COLLECTION = new GeoJSON("FeatureCollection").setEmptyFeatures();;+ public static final GeoJSON EMPTY_FEATURE_COLLECTION = new GeoJSON("FeatureCollection").setEmptyFeatures();public GeoJSON(String type) {super(type);diff --git a/model/src/main/java/org/openremote/model/rules/Assets.java b/model/src/main/java/org/openremote/model/rules/Assets.javaindex aad23ade9..94337e213 100644--- a/model/src/main/java/org/openremote/model/rules/Assets.java+++ b/model/src/main/java/org/openremote/model/rules/Assets.java@@ -20,7 +20,7 @@package org.openremote.model.rules;import org.openremote.model.attribute.AttributeEvent;-import org.openremote.model.asset.AssetQuery;+import org.openremote.model.asset.AbstractAssetQuery;import java.util.List;import java.util.function.Consumer;@@ -31,7 +31,7 @@ import java.util.function.Consumer;*/public abstract class Assets {- public abstract class RestrictedQuery extends AssetQuery<RestrictedQuery> {+ public abstract class RestrictedQuery extends AbstractAssetQuery<RestrictedQuery> {abstract public String getResult();diff --git a/model/src/main/java/org/openremote/model/util/EnumUtil.java b/model/src/main/java/org/openremote/model/util/EnumUtil.javanew file mode 100644index 000000000..21a890a8f--- /dev/null+++ b/model/src/main/java/org/openremote/model/util/EnumUtil.java@@ -0,0 +1,92 @@+/*+ * 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 org.openremote.model.value.Value;+import org.openremote.model.value.ValueType;+import org.openremote.model.value.Values;++import java.util.Optional;++public final class EnumUtil {+ private EnumUtil() {}+++ public static Value enumToValue(Enum<?> enumValue, ValueType valueType) {++ switch (valueType) {+ case OBJECT:+ return null;+ case ARRAY:+ return null;+ case STRING:+ return Values.create(enumValue.name());+ case NUMBER:+ return Values.create(enumValue.ordinal());+ case BOOLEAN:+ return null;+ }++ return null;+ }++ public static <T extends Enum<T>> Optional<T> enumFromValue(Class<T> enumClazz, Value value) {+ if (value == null) {+ return Optional.empty();+ }++ switch (value.getType()) {+ case OBJECT:+ return Optional.empty();+ case ARRAY:+ return Optional.empty();+ case STRING:+ return enumFromString(enumClazz, value.toString());+ case NUMBER:+ return Values+ .getNumber(value)+ .map(Double::intValue)+ .flatMap(ordinal -> enumFromInteger(enumClazz, ordinal));+ case BOOLEAN:+ return Optional.empty();+ }++ return Optional.empty();+ }++ public static <T extends Enum<T>> Optional<T> enumFromString(Class<T> enumClazz, String value) {+ for (T enumValue : enumClazz.getEnumConstants()) {+ if (enumValue.name().equalsIgnoreCase(value)) {+ return Optional.of(enumValue);+ }+ }++ return Optional.empty();+ }++ public static <T extends Enum<T>> Optional<T> enumFromInteger(Class<T> enumClazz, int ordinal) {+ for (T enumValue : enumClazz.getEnumConstants()) {+ if (enumValue.ordinal() == ordinal) {+ return Optional.of(enumValue);+ }+ }+ return Optional.empty();+ }+}